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/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFrameInfo.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/RuntimeLibcalls.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/CodeGen/SelectionDAGNodes.h"
46 #include "llvm/CodeGen/TargetCallingConv.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/ValueTypes.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GetElementPtrTypeIterator.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Instruction.h"
59 #include "llvm/IR/Instructions.h"
60 #include "llvm/IR/IntrinsicInst.h"
61 #include "llvm/IR/Intrinsics.h"
62 #include "llvm/IR/IntrinsicsAArch64.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/IR/OperandTraits.h"
65 #include "llvm/IR/PatternMatch.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/IR/Use.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/MC/MCRegisterInfo.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/KnownBits.h"
77 #include "llvm/Support/MachineValueType.h"
78 #include "llvm/Support/MathExtras.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Target/TargetMachine.h"
81 #include "llvm/Target/TargetOptions.h"
82 #include <algorithm>
83 #include <bitset>
84 #include <cassert>
85 #include <cctype>
86 #include <cstdint>
87 #include <cstdlib>
88 #include <iterator>
89 #include <limits>
90 #include <tuple>
91 #include <utility>
92 #include <vector>
93 
94 using namespace llvm;
95 using namespace llvm::PatternMatch;
96 
97 #define DEBUG_TYPE "aarch64-lower"
98 
99 STATISTIC(NumTailCalls, "Number of tail calls");
100 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
101 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
102 
103 // FIXME: The necessary dtprel relocations don't seem to be supported
104 // well in the GNU bfd and gold linkers at the moment. Therefore, by
105 // default, for now, fall back to GeneralDynamic code generation.
106 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
107     "aarch64-elf-ldtls-generation", cl::Hidden,
108     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
109     cl::init(false));
110 
111 static cl::opt<bool>
112 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
113                          cl::desc("Enable AArch64 logical imm instruction "
114                                   "optimization"),
115                          cl::init(true));
116 
117 // Temporary option added for the purpose of testing functionality added
118 // to DAGCombiner.cpp in D92230. It is expected that this can be removed
119 // in future when both implementations will be based off MGATHER rather
120 // than the GLD1 nodes added for the SVE gather load intrinsics.
121 static cl::opt<bool>
122 EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
123                                 cl::desc("Combine extends of AArch64 masked "
124                                          "gather intrinsics"),
125                                 cl::init(true));
126 
127 /// Value type used for condition codes.
128 static const MVT MVT_CC = MVT::i32;
129 
130 static inline EVT getPackedSVEVectorVT(EVT VT) {
131   switch (VT.getSimpleVT().SimpleTy) {
132   default:
133     llvm_unreachable("unexpected element type for vector");
134   case MVT::i8:
135     return MVT::nxv16i8;
136   case MVT::i16:
137     return MVT::nxv8i16;
138   case MVT::i32:
139     return MVT::nxv4i32;
140   case MVT::i64:
141     return MVT::nxv2i64;
142   case MVT::f16:
143     return MVT::nxv8f16;
144   case MVT::f32:
145     return MVT::nxv4f32;
146   case MVT::f64:
147     return MVT::nxv2f64;
148   case MVT::bf16:
149     return MVT::nxv8bf16;
150   }
151 }
152 
153 // NOTE: Currently there's only a need to return integer vector types. If this
154 // changes then just add an extra "type" parameter.
155 static inline EVT getPackedSVEVectorVT(ElementCount EC) {
156   switch (EC.getKnownMinValue()) {
157   default:
158     llvm_unreachable("unexpected element count for vector");
159   case 16:
160     return MVT::nxv16i8;
161   case 8:
162     return MVT::nxv8i16;
163   case 4:
164     return MVT::nxv4i32;
165   case 2:
166     return MVT::nxv2i64;
167   }
168 }
169 
170 static inline EVT getPromotedVTForPredicate(EVT VT) {
171   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
172          "Expected scalable predicate vector type!");
173   switch (VT.getVectorMinNumElements()) {
174   default:
175     llvm_unreachable("unexpected element count for vector");
176   case 2:
177     return MVT::nxv2i64;
178   case 4:
179     return MVT::nxv4i32;
180   case 8:
181     return MVT::nxv8i16;
182   case 16:
183     return MVT::nxv16i8;
184   }
185 }
186 
187 /// Returns true if VT's elements occupy the lowest bit positions of its
188 /// associated register class without any intervening space.
189 ///
190 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
191 /// same register class, but only nxv8f16 can be treated as a packed vector.
192 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
193   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
194          "Expected legal vector type!");
195   return VT.isFixedLengthVector() ||
196          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
197 }
198 
199 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
200 // predicate and end with a passthru value matching the result type.
201 static bool isMergePassthruOpcode(unsigned Opc) {
202   switch (Opc) {
203   default:
204     return false;
205   case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
206   case AArch64ISD::BSWAP_MERGE_PASSTHRU:
207   case AArch64ISD::CTLZ_MERGE_PASSTHRU:
208   case AArch64ISD::CTPOP_MERGE_PASSTHRU:
209   case AArch64ISD::DUP_MERGE_PASSTHRU:
210   case AArch64ISD::ABS_MERGE_PASSTHRU:
211   case AArch64ISD::NEG_MERGE_PASSTHRU:
212   case AArch64ISD::FNEG_MERGE_PASSTHRU:
213   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
214   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
215   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
216   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
217   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
218   case AArch64ISD::FRINT_MERGE_PASSTHRU:
219   case AArch64ISD::FROUND_MERGE_PASSTHRU:
220   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
221   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
222   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
223   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
224   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
225   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
226   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
227   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
228   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
229   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
230   case AArch64ISD::FABS_MERGE_PASSTHRU:
231     return true;
232   }
233 }
234 
235 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
236                                              const AArch64Subtarget &STI)
237     : TargetLowering(TM), Subtarget(&STI) {
238   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
239   // we have to make something up. Arbitrarily, choose ZeroOrOne.
240   setBooleanContents(ZeroOrOneBooleanContent);
241   // When comparing vectors the result sets the different elements in the
242   // vector to all-one or all-zero.
243   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
244 
245   // Set up the register classes.
246   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
247   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
248 
249   if (Subtarget->hasLS64()) {
250     addRegisterClass(MVT::i64x8, &AArch64::GPR64x8ClassRegClass);
251     setOperationAction(ISD::LOAD, MVT::i64x8, Custom);
252     setOperationAction(ISD::STORE, MVT::i64x8, Custom);
253   }
254 
255   if (Subtarget->hasFPARMv8()) {
256     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
257     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
258     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
259     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
260     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
261   }
262 
263   if (Subtarget->hasNEON()) {
264     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
265     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
266     // Someone set us up the NEON.
267     addDRTypeForNEON(MVT::v2f32);
268     addDRTypeForNEON(MVT::v8i8);
269     addDRTypeForNEON(MVT::v4i16);
270     addDRTypeForNEON(MVT::v2i32);
271     addDRTypeForNEON(MVT::v1i64);
272     addDRTypeForNEON(MVT::v1f64);
273     addDRTypeForNEON(MVT::v4f16);
274     if (Subtarget->hasBF16())
275       addDRTypeForNEON(MVT::v4bf16);
276 
277     addQRTypeForNEON(MVT::v4f32);
278     addQRTypeForNEON(MVT::v2f64);
279     addQRTypeForNEON(MVT::v16i8);
280     addQRTypeForNEON(MVT::v8i16);
281     addQRTypeForNEON(MVT::v4i32);
282     addQRTypeForNEON(MVT::v2i64);
283     addQRTypeForNEON(MVT::v8f16);
284     if (Subtarget->hasBF16())
285       addQRTypeForNEON(MVT::v8bf16);
286   }
287 
288   if (Subtarget->hasSVE()) {
289     // Add legal sve predicate types
290     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
291     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
292     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
293     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
294 
295     // Add legal sve data types
296     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
297     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
298     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
299     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
300 
301     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
302     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
303     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
304     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
305     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
306     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
307 
308     if (Subtarget->hasBF16()) {
309       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
310       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
311       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
312     }
313 
314     if (Subtarget->useSVEForFixedLengthVectors()) {
315       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
316         if (useSVEForFixedLengthVectorVT(VT))
317           addRegisterClass(VT, &AArch64::ZPRRegClass);
318 
319       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
320         if (useSVEForFixedLengthVectorVT(VT))
321           addRegisterClass(VT, &AArch64::ZPRRegClass);
322     }
323 
324     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
325       setOperationAction(ISD::SADDSAT, VT, Legal);
326       setOperationAction(ISD::UADDSAT, VT, Legal);
327       setOperationAction(ISD::SSUBSAT, VT, Legal);
328       setOperationAction(ISD::USUBSAT, VT, Legal);
329       setOperationAction(ISD::UREM, VT, Expand);
330       setOperationAction(ISD::SREM, VT, Expand);
331       setOperationAction(ISD::SDIVREM, VT, Expand);
332       setOperationAction(ISD::UDIVREM, VT, Expand);
333     }
334 
335     for (auto VT :
336          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
337            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
338       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
339 
340     for (auto VT :
341          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
342            MVT::nxv2f64 }) {
343       setCondCodeAction(ISD::SETO, VT, Expand);
344       setCondCodeAction(ISD::SETOLT, VT, Expand);
345       setCondCodeAction(ISD::SETLT, VT, Expand);
346       setCondCodeAction(ISD::SETOLE, VT, Expand);
347       setCondCodeAction(ISD::SETLE, VT, Expand);
348       setCondCodeAction(ISD::SETULT, VT, Expand);
349       setCondCodeAction(ISD::SETULE, VT, Expand);
350       setCondCodeAction(ISD::SETUGE, VT, Expand);
351       setCondCodeAction(ISD::SETUGT, VT, Expand);
352       setCondCodeAction(ISD::SETUEQ, VT, Expand);
353       setCondCodeAction(ISD::SETUNE, VT, Expand);
354 
355       setOperationAction(ISD::FREM, VT, Expand);
356       setOperationAction(ISD::FPOW, VT, Expand);
357       setOperationAction(ISD::FPOWI, VT, Expand);
358       setOperationAction(ISD::FCOS, VT, Expand);
359       setOperationAction(ISD::FSIN, VT, Expand);
360       setOperationAction(ISD::FSINCOS, VT, Expand);
361       setOperationAction(ISD::FEXP, VT, Expand);
362       setOperationAction(ISD::FEXP2, VT, Expand);
363       setOperationAction(ISD::FLOG, VT, Expand);
364       setOperationAction(ISD::FLOG2, VT, Expand);
365       setOperationAction(ISD::FLOG10, VT, Expand);
366     }
367   }
368 
369   // Compute derived properties from the register classes
370   computeRegisterProperties(Subtarget->getRegisterInfo());
371 
372   // Provide all sorts of operation actions
373   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
374   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
375   setOperationAction(ISD::SETCC, MVT::i32, Custom);
376   setOperationAction(ISD::SETCC, MVT::i64, Custom);
377   setOperationAction(ISD::SETCC, MVT::f16, Custom);
378   setOperationAction(ISD::SETCC, MVT::f32, Custom);
379   setOperationAction(ISD::SETCC, MVT::f64, Custom);
380   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
381   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
382   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
383   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
384   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
385   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
386   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
387   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
388   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
389   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
390   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
391   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
392   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
393   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
394   setOperationAction(ISD::SELECT, MVT::i32, Custom);
395   setOperationAction(ISD::SELECT, MVT::i64, Custom);
396   setOperationAction(ISD::SELECT, MVT::f16, Custom);
397   setOperationAction(ISD::SELECT, MVT::f32, Custom);
398   setOperationAction(ISD::SELECT, MVT::f64, Custom);
399   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
400   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
401   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
402   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
403   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
404   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
405   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
406 
407   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
408   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
409   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
410 
411   setOperationAction(ISD::FREM, MVT::f32, Expand);
412   setOperationAction(ISD::FREM, MVT::f64, Expand);
413   setOperationAction(ISD::FREM, MVT::f80, Expand);
414 
415   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
416 
417   // Custom lowering hooks are needed for XOR
418   // to fold it into CSINC/CSINV.
419   setOperationAction(ISD::XOR, MVT::i32, Custom);
420   setOperationAction(ISD::XOR, MVT::i64, Custom);
421 
422   // Virtually no operation on f128 is legal, but LLVM can't expand them when
423   // there's a valid register class, so we need custom operations in most cases.
424   setOperationAction(ISD::FABS, MVT::f128, Expand);
425   setOperationAction(ISD::FADD, MVT::f128, LibCall);
426   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
427   setOperationAction(ISD::FCOS, MVT::f128, Expand);
428   setOperationAction(ISD::FDIV, MVT::f128, LibCall);
429   setOperationAction(ISD::FMA, MVT::f128, Expand);
430   setOperationAction(ISD::FMUL, MVT::f128, LibCall);
431   setOperationAction(ISD::FNEG, MVT::f128, Expand);
432   setOperationAction(ISD::FPOW, MVT::f128, Expand);
433   setOperationAction(ISD::FREM, MVT::f128, Expand);
434   setOperationAction(ISD::FRINT, MVT::f128, Expand);
435   setOperationAction(ISD::FSIN, MVT::f128, Expand);
436   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
437   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
438   setOperationAction(ISD::FSUB, MVT::f128, LibCall);
439   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
440   setOperationAction(ISD::SETCC, MVT::f128, Custom);
441   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
442   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
443   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
444   setOperationAction(ISD::SELECT, MVT::f128, Custom);
445   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
446   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
447 
448   // Lowering for many of the conversions is actually specified by the non-f128
449   // type. The LowerXXX function will be trivial when f128 isn't involved.
450   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
451   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
452   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
453   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
454   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
455   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
456   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
457   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
458   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
459   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
460   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
461   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
462   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
463   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
464   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
465   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
466   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
467   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
468   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
469   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
470   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
471   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
472   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
473   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
474   setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
475   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
476   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
477   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
478   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
479   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
480 
481   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
482   setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
483   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
484   setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
485 
486   // Variable arguments.
487   setOperationAction(ISD::VASTART, MVT::Other, Custom);
488   setOperationAction(ISD::VAARG, MVT::Other, Custom);
489   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
490   setOperationAction(ISD::VAEND, MVT::Other, Expand);
491 
492   // Variable-sized objects.
493   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
494   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
495 
496   if (Subtarget->isTargetWindows())
497     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
498   else
499     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
500 
501   // Constant pool entries
502   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
503 
504   // BlockAddress
505   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
506 
507   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
508   setOperationAction(ISD::ADDC, MVT::i32, Custom);
509   setOperationAction(ISD::ADDE, MVT::i32, Custom);
510   setOperationAction(ISD::SUBC, MVT::i32, Custom);
511   setOperationAction(ISD::SUBE, MVT::i32, Custom);
512   setOperationAction(ISD::ADDC, MVT::i64, Custom);
513   setOperationAction(ISD::ADDE, MVT::i64, Custom);
514   setOperationAction(ISD::SUBC, MVT::i64, Custom);
515   setOperationAction(ISD::SUBE, MVT::i64, Custom);
516 
517   // AArch64 lacks both left-rotate and popcount instructions.
518   setOperationAction(ISD::ROTL, MVT::i32, Expand);
519   setOperationAction(ISD::ROTL, MVT::i64, Expand);
520   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
521     setOperationAction(ISD::ROTL, VT, Expand);
522     setOperationAction(ISD::ROTR, VT, Expand);
523   }
524 
525   // AArch64 doesn't have i32 MULH{S|U}.
526   setOperationAction(ISD::MULHU, MVT::i32, Expand);
527   setOperationAction(ISD::MULHS, MVT::i32, Expand);
528 
529   // AArch64 doesn't have {U|S}MUL_LOHI.
530   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
531   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
532 
533   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
534   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
535   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
536 
537   setOperationAction(ISD::ABS, MVT::i32, Custom);
538   setOperationAction(ISD::ABS, MVT::i64, Custom);
539 
540   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
541   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
542   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
543     setOperationAction(ISD::SDIVREM, VT, Expand);
544     setOperationAction(ISD::UDIVREM, VT, Expand);
545   }
546   setOperationAction(ISD::SREM, MVT::i32, Expand);
547   setOperationAction(ISD::SREM, MVT::i64, Expand);
548   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
549   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
550   setOperationAction(ISD::UREM, MVT::i32, Expand);
551   setOperationAction(ISD::UREM, MVT::i64, Expand);
552 
553   // Custom lower Add/Sub/Mul with overflow.
554   setOperationAction(ISD::SADDO, MVT::i32, Custom);
555   setOperationAction(ISD::SADDO, MVT::i64, Custom);
556   setOperationAction(ISD::UADDO, MVT::i32, Custom);
557   setOperationAction(ISD::UADDO, MVT::i64, Custom);
558   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
559   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
560   setOperationAction(ISD::USUBO, MVT::i32, Custom);
561   setOperationAction(ISD::USUBO, MVT::i64, Custom);
562   setOperationAction(ISD::SMULO, MVT::i32, Custom);
563   setOperationAction(ISD::SMULO, MVT::i64, Custom);
564   setOperationAction(ISD::UMULO, MVT::i32, Custom);
565   setOperationAction(ISD::UMULO, MVT::i64, Custom);
566 
567   setOperationAction(ISD::FSIN, MVT::f32, Expand);
568   setOperationAction(ISD::FSIN, MVT::f64, Expand);
569   setOperationAction(ISD::FCOS, MVT::f32, Expand);
570   setOperationAction(ISD::FCOS, MVT::f64, Expand);
571   setOperationAction(ISD::FPOW, MVT::f32, Expand);
572   setOperationAction(ISD::FPOW, MVT::f64, Expand);
573   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
574   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
575   if (Subtarget->hasFullFP16())
576     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
577   else
578     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
579 
580   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
581   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
582   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
583   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
584   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
585   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
586   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
587   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
588   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
589   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
590   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
591   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
592   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
593   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
594   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
595   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
596   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
597   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
598   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
599   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
600   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
601   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
602   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
603   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
604   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
605   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
606   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
607   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
608   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
609   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
610   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
611   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
612   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
613 
614   if (!Subtarget->hasFullFP16()) {
615     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
616     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
617     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
618     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
619     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
620     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
621     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
622     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
623     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
624     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
625     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
626     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
627     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
628     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
629     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
630     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
631     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
632     setOperationAction(ISD::FROUNDEVEN,  MVT::f16,  Promote);
633     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
634     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
635     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
636     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
637     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
638 
639     // promote v4f16 to v4f32 when that is known to be safe.
640     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
641     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
642     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
643     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
644     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
645     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
646     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
647     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
648 
649     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
650     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
651     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
652     setOperationAction(ISD::FROUNDEVEN,  MVT::v4f16, Expand);
653     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
654     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
655     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
656     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
657     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
658     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
659     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
660     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
661     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
662     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
663     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
664     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
665 
666     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
667     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
668     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
669     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
670     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
671     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
672     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
673     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
674     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
675     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
676     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
677     setOperationAction(ISD::FROUNDEVEN,  MVT::v8f16, Expand);
678     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
679     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
680     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
681     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
682     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
683     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
684     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
685     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
686     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
687   }
688 
689   // AArch64 has implementations of a lot of rounding-like FP operations.
690   for (MVT Ty : {MVT::f32, MVT::f64}) {
691     setOperationAction(ISD::FFLOOR, Ty, Legal);
692     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
693     setOperationAction(ISD::FCEIL, Ty, Legal);
694     setOperationAction(ISD::FRINT, Ty, Legal);
695     setOperationAction(ISD::FTRUNC, Ty, Legal);
696     setOperationAction(ISD::FROUND, Ty, Legal);
697     setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
698     setOperationAction(ISD::FMINNUM, Ty, Legal);
699     setOperationAction(ISD::FMAXNUM, Ty, Legal);
700     setOperationAction(ISD::FMINIMUM, Ty, Legal);
701     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
702     setOperationAction(ISD::LROUND, Ty, Legal);
703     setOperationAction(ISD::LLROUND, Ty, Legal);
704     setOperationAction(ISD::LRINT, Ty, Legal);
705     setOperationAction(ISD::LLRINT, Ty, Legal);
706   }
707 
708   if (Subtarget->hasFullFP16()) {
709     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
710     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
711     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
712     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
713     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
714     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
715     setOperationAction(ISD::FROUNDEVEN,  MVT::f16, Legal);
716     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
717     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
718     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
719     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
720   }
721 
722   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
723 
724   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
725   setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
726 
727   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
728   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
729   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
730   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
731   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
732 
733   // Generate outline atomics library calls only if LSE was not specified for
734   // subtarget
735   if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
736     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
737     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
738     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
739     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
740     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
741     setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
742     setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
743     setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
744     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
745     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
746     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
747     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
748     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
749     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
750     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
751     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
752     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
753     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
754     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
755     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
756     setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
757     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
758     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
759     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
760     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
761 #define LCALLNAMES(A, B, N)                                                    \
762   setLibcallName(A##N##_RELAX, #B #N "_relax");                                \
763   setLibcallName(A##N##_ACQ, #B #N "_acq");                                    \
764   setLibcallName(A##N##_REL, #B #N "_rel");                                    \
765   setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
766 #define LCALLNAME4(A, B)                                                       \
767   LCALLNAMES(A, B, 1)                                                          \
768   LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
769 #define LCALLNAME5(A, B)                                                       \
770   LCALLNAMES(A, B, 1)                                                          \
771   LCALLNAMES(A, B, 2)                                                          \
772   LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
773     LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
774     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
775     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
776     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
777     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
778     LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
779 #undef LCALLNAMES
780 #undef LCALLNAME4
781 #undef LCALLNAME5
782   }
783 
784   // 128-bit loads and stores can be done without expanding
785   setOperationAction(ISD::LOAD, MVT::i128, Custom);
786   setOperationAction(ISD::STORE, MVT::i128, Custom);
787 
788   // Aligned 128-bit loads and stores are single-copy atomic according to the
789   // v8.4a spec.
790   if (Subtarget->hasLSE2()) {
791     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
792     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
793   }
794 
795   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
796   // custom lowering, as there are no un-paired non-temporal stores and
797   // legalization will break up 256 bit inputs.
798   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
799   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
800   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
801   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
802   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
803   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
804   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
805 
806   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
807   // This requires the Performance Monitors extension.
808   if (Subtarget->hasPerfMon())
809     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
810 
811   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
812       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
813     // Issue __sincos_stret if available.
814     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
815     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
816   } else {
817     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
818     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
819   }
820 
821   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
822     // MSVCRT doesn't have powi; fall back to pow
823     setLibcallName(RTLIB::POWI_F32, nullptr);
824     setLibcallName(RTLIB::POWI_F64, nullptr);
825   }
826 
827   // Make floating-point constants legal for the large code model, so they don't
828   // become loads from the constant pool.
829   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
830     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
831     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
832   }
833 
834   // AArch64 does not have floating-point extending loads, i1 sign-extending
835   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
836   for (MVT VT : MVT::fp_valuetypes()) {
837     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
838     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
839     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
840     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
841   }
842   for (MVT VT : MVT::integer_valuetypes())
843     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
844 
845   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
846   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
847   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
848   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
849   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
850   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
851   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
852 
853   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
854   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
855   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
856 
857   // Indexed loads and stores are supported.
858   for (unsigned im = (unsigned)ISD::PRE_INC;
859        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
860     setIndexedLoadAction(im, MVT::i8, Legal);
861     setIndexedLoadAction(im, MVT::i16, Legal);
862     setIndexedLoadAction(im, MVT::i32, Legal);
863     setIndexedLoadAction(im, MVT::i64, Legal);
864     setIndexedLoadAction(im, MVT::f64, Legal);
865     setIndexedLoadAction(im, MVT::f32, Legal);
866     setIndexedLoadAction(im, MVT::f16, Legal);
867     setIndexedLoadAction(im, MVT::bf16, Legal);
868     setIndexedStoreAction(im, MVT::i8, Legal);
869     setIndexedStoreAction(im, MVT::i16, Legal);
870     setIndexedStoreAction(im, MVT::i32, Legal);
871     setIndexedStoreAction(im, MVT::i64, Legal);
872     setIndexedStoreAction(im, MVT::f64, Legal);
873     setIndexedStoreAction(im, MVT::f32, Legal);
874     setIndexedStoreAction(im, MVT::f16, Legal);
875     setIndexedStoreAction(im, MVT::bf16, Legal);
876   }
877 
878   // Trap.
879   setOperationAction(ISD::TRAP, MVT::Other, Legal);
880   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
881   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
882 
883   // We combine OR nodes for bitfield operations.
884   setTargetDAGCombine(ISD::OR);
885   // Try to create BICs for vector ANDs.
886   setTargetDAGCombine(ISD::AND);
887 
888   // Vector add and sub nodes may conceal a high-half opportunity.
889   // Also, try to fold ADD into CSINC/CSINV..
890   setTargetDAGCombine(ISD::ADD);
891   setTargetDAGCombine(ISD::ABS);
892   setTargetDAGCombine(ISD::SUB);
893   setTargetDAGCombine(ISD::SRL);
894   setTargetDAGCombine(ISD::XOR);
895   setTargetDAGCombine(ISD::SINT_TO_FP);
896   setTargetDAGCombine(ISD::UINT_TO_FP);
897 
898   // TODO: Do the same for FP_TO_*INT_SAT.
899   setTargetDAGCombine(ISD::FP_TO_SINT);
900   setTargetDAGCombine(ISD::FP_TO_UINT);
901   setTargetDAGCombine(ISD::FDIV);
902 
903   // Try and combine setcc with csel
904   setTargetDAGCombine(ISD::SETCC);
905 
906   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
907 
908   setTargetDAGCombine(ISD::ANY_EXTEND);
909   setTargetDAGCombine(ISD::ZERO_EXTEND);
910   setTargetDAGCombine(ISD::SIGN_EXTEND);
911   setTargetDAGCombine(ISD::VECTOR_SPLICE);
912   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
913   setTargetDAGCombine(ISD::TRUNCATE);
914   setTargetDAGCombine(ISD::CONCAT_VECTORS);
915   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
916   setTargetDAGCombine(ISD::STORE);
917   if (Subtarget->supportsAddressTopByteIgnored())
918     setTargetDAGCombine(ISD::LOAD);
919 
920   setTargetDAGCombine(ISD::MUL);
921 
922   setTargetDAGCombine(ISD::SELECT);
923   setTargetDAGCombine(ISD::VSELECT);
924 
925   setTargetDAGCombine(ISD::INTRINSIC_VOID);
926   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
927   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
928   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
929   setTargetDAGCombine(ISD::VECREDUCE_ADD);
930   setTargetDAGCombine(ISD::STEP_VECTOR);
931 
932   setTargetDAGCombine(ISD::GlobalAddress);
933 
934   // In case of strict alignment, avoid an excessive number of byte wide stores.
935   MaxStoresPerMemsetOptSize = 8;
936   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
937                        ? MaxStoresPerMemsetOptSize : 32;
938 
939   MaxGluedStoresPerMemcpy = 4;
940   MaxStoresPerMemcpyOptSize = 4;
941   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
942                        ? MaxStoresPerMemcpyOptSize : 16;
943 
944   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
945 
946   MaxLoadsPerMemcmpOptSize = 4;
947   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
948                       ? MaxLoadsPerMemcmpOptSize : 8;
949 
950   setStackPointerRegisterToSaveRestore(AArch64::SP);
951 
952   setSchedulingPreference(Sched::Hybrid);
953 
954   EnableExtLdPromotion = true;
955 
956   // Set required alignment.
957   setMinFunctionAlignment(Align(4));
958   // Set preferred alignments.
959   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
960   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
961 
962   // Only change the limit for entries in a jump table if specified by
963   // the sub target, but not at the command line.
964   unsigned MaxJT = STI.getMaximumJumpTableSize();
965   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
966     setMaximumJumpTableSize(MaxJT);
967 
968   setHasExtractBitsInsn(true);
969 
970   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
971 
972   if (Subtarget->hasNEON()) {
973     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
974     // silliness like this:
975     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
976     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
977     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
978     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
979     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
980     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
981     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
982     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
983     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
984     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
985     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
986     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
987     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
988     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
989     setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand);
990     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
991     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
992     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
993     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
994     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
995     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
996     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
997     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
998     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
999     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
1000     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
1001 
1002     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
1003     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
1004     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
1005     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
1006     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
1007 
1008     setOperationAction(ISD::FP_TO_SINT_SAT, MVT::v1i64, Expand);
1009     setOperationAction(ISD::FP_TO_UINT_SAT, MVT::v1i64, Expand);
1010 
1011     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
1012 
1013     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
1014     // elements smaller than i32, so promote the input to i32 first.
1015     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
1016     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
1017     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
1018     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
1019     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v16i8, MVT::v16i32);
1020     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v16i8, MVT::v16i32);
1021 
1022     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
1023     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
1024     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
1025     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
1026     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
1027     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
1028     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
1029     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
1030     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
1031 
1032     if (Subtarget->hasFullFP16()) {
1033       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1034       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1035       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
1036       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1037     } else {
1038       // when AArch64 doesn't have fullfp16 support, promote the input
1039       // to i32 first.
1040       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
1041       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
1042       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
1043       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
1044     }
1045 
1046     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
1047     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
1048     setOperationAction(ISD::BITREVERSE, MVT::v8i8, Legal);
1049     setOperationAction(ISD::BITREVERSE, MVT::v16i8, Legal);
1050     setOperationAction(ISD::BITREVERSE, MVT::v2i32, Custom);
1051     setOperationAction(ISD::BITREVERSE, MVT::v4i32, Custom);
1052     setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1053     setOperationAction(ISD::BITREVERSE, MVT::v2i64, Custom);
1054     for (auto VT : {MVT::v1i64, MVT::v2i64}) {
1055       setOperationAction(ISD::UMAX, VT, Custom);
1056       setOperationAction(ISD::SMAX, VT, Custom);
1057       setOperationAction(ISD::UMIN, VT, Custom);
1058       setOperationAction(ISD::SMIN, VT, Custom);
1059     }
1060 
1061     // AArch64 doesn't have MUL.2d:
1062     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
1063     // Custom handling for some quad-vector types to detect MULL.
1064     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
1065     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1066     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1067 
1068     // Saturates
1069     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1070                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1071       setOperationAction(ISD::SADDSAT, VT, Legal);
1072       setOperationAction(ISD::UADDSAT, VT, Legal);
1073       setOperationAction(ISD::SSUBSAT, VT, Legal);
1074       setOperationAction(ISD::USUBSAT, VT, Legal);
1075     }
1076 
1077     for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
1078                    MVT::v4i32}) {
1079       setOperationAction(ISD::ABDS, VT, Legal);
1080       setOperationAction(ISD::ABDU, VT, Legal);
1081     }
1082 
1083     // Vector reductions
1084     for (MVT VT : { MVT::v4f16, MVT::v2f32,
1085                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1086       if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
1087         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1088         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1089 
1090         setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
1091       }
1092     }
1093     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
1094                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1095       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1096       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1097       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1098       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1099       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1100     }
1101     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
1102 
1103     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
1104     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
1105     // Likewise, narrowing and extending vector loads/stores aren't handled
1106     // directly.
1107     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1108       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
1109 
1110       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
1111         setOperationAction(ISD::MULHS, VT, Legal);
1112         setOperationAction(ISD::MULHU, VT, Legal);
1113       } else {
1114         setOperationAction(ISD::MULHS, VT, Expand);
1115         setOperationAction(ISD::MULHU, VT, Expand);
1116       }
1117       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1118       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1119 
1120       setOperationAction(ISD::BSWAP, VT, Expand);
1121       setOperationAction(ISD::CTTZ, VT, Expand);
1122 
1123       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
1124         setTruncStoreAction(VT, InnerVT, Expand);
1125         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1126         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1127         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1128       }
1129     }
1130 
1131     // AArch64 has implementations of a lot of rounding-like FP operations.
1132     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
1133       setOperationAction(ISD::FFLOOR, Ty, Legal);
1134       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1135       setOperationAction(ISD::FCEIL, Ty, Legal);
1136       setOperationAction(ISD::FRINT, Ty, Legal);
1137       setOperationAction(ISD::FTRUNC, Ty, Legal);
1138       setOperationAction(ISD::FROUND, Ty, Legal);
1139       setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1140     }
1141 
1142     if (Subtarget->hasFullFP16()) {
1143       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
1144         setOperationAction(ISD::FFLOOR, Ty, Legal);
1145         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
1146         setOperationAction(ISD::FCEIL, Ty, Legal);
1147         setOperationAction(ISD::FRINT, Ty, Legal);
1148         setOperationAction(ISD::FTRUNC, Ty, Legal);
1149         setOperationAction(ISD::FROUND, Ty, Legal);
1150         setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
1151       }
1152     }
1153 
1154     if (Subtarget->hasSVE())
1155       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
1156 
1157     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
1158 
1159     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i16, MVT::v4i8, Custom);
1160     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1161     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
1162     setLoadExtAction(ISD::EXTLOAD,  MVT::v4i32, MVT::v4i8, Custom);
1163     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1164     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
1165   }
1166 
1167   if (Subtarget->hasSVE()) {
1168     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
1169       setOperationAction(ISD::BITREVERSE, VT, Custom);
1170       setOperationAction(ISD::BSWAP, VT, Custom);
1171       setOperationAction(ISD::CTLZ, VT, Custom);
1172       setOperationAction(ISD::CTPOP, VT, Custom);
1173       setOperationAction(ISD::CTTZ, VT, Custom);
1174       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1175       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1176       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1177       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1178       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1179       setOperationAction(ISD::MGATHER, VT, Custom);
1180       setOperationAction(ISD::MSCATTER, VT, Custom);
1181       setOperationAction(ISD::MLOAD, VT, Custom);
1182       setOperationAction(ISD::MUL, VT, Custom);
1183       setOperationAction(ISD::MULHS, VT, Custom);
1184       setOperationAction(ISD::MULHU, VT, Custom);
1185       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1186       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1187       setOperationAction(ISD::SELECT, VT, Custom);
1188       setOperationAction(ISD::SETCC, VT, Custom);
1189       setOperationAction(ISD::SDIV, VT, Custom);
1190       setOperationAction(ISD::UDIV, VT, Custom);
1191       setOperationAction(ISD::SMIN, VT, Custom);
1192       setOperationAction(ISD::UMIN, VT, Custom);
1193       setOperationAction(ISD::SMAX, VT, Custom);
1194       setOperationAction(ISD::UMAX, VT, Custom);
1195       setOperationAction(ISD::SHL, VT, Custom);
1196       setOperationAction(ISD::SRL, VT, Custom);
1197       setOperationAction(ISD::SRA, VT, Custom);
1198       setOperationAction(ISD::ABS, VT, Custom);
1199       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1200       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1201       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1202       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1203       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1204       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1205       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1206       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1207 
1208       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
1209       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
1210       setOperationAction(ISD::SELECT_CC, VT, Expand);
1211       setOperationAction(ISD::ROTL, VT, Expand);
1212       setOperationAction(ISD::ROTR, VT, Expand);
1213     }
1214 
1215     // Illegal unpacked integer vector types.
1216     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1217       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1218       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1219     }
1220 
1221     // Legalize unpacked bitcasts to REINTERPRET_CAST.
1222     for (auto VT : {MVT::nxv2i16, MVT::nxv4i16, MVT::nxv2i32, MVT::nxv2bf16,
1223                     MVT::nxv2f16, MVT::nxv4f16, MVT::nxv2f32})
1224       setOperationAction(ISD::BITCAST, VT, Custom);
1225 
1226     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1227       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1228       setOperationAction(ISD::SELECT, VT, Custom);
1229       setOperationAction(ISD::SETCC, VT, Custom);
1230       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1231       setOperationAction(ISD::TRUNCATE, VT, Custom);
1232       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1233       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1234       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1235 
1236       setOperationAction(ISD::SELECT_CC, VT, Expand);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1239 
1240       // There are no legal MVT::nxv16f## based types.
1241       if (VT != MVT::nxv16i1) {
1242         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1243         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1244       }
1245     }
1246 
1247     // NEON doesn't support masked loads/stores/gathers/scatters, but SVE does
1248     for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v1f64,
1249                     MVT::v2f64, MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1250                     MVT::v2i32, MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
1251       setOperationAction(ISD::MLOAD, VT, Custom);
1252       setOperationAction(ISD::MSTORE, VT, Custom);
1253       setOperationAction(ISD::MGATHER, VT, Custom);
1254       setOperationAction(ISD::MSCATTER, VT, Custom);
1255     }
1256 
1257     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
1258       for (MVT InnerVT : MVT::fp_scalable_vector_valuetypes()) {
1259         // Avoid marking truncating FP stores as legal to prevent the
1260         // DAGCombiner from creating unsupported truncating stores.
1261         setTruncStoreAction(VT, InnerVT, Expand);
1262         // SVE does not have floating-point extending loads.
1263         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
1264         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
1265         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
1266       }
1267     }
1268 
1269     // SVE supports truncating stores of 64 and 128-bit vectors
1270     setTruncStoreAction(MVT::v2i64, MVT::v2i8, Custom);
1271     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Custom);
1272     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Custom);
1273     setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
1274     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
1275 
1276     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1277                     MVT::nxv4f32, MVT::nxv2f64}) {
1278       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1280       setOperationAction(ISD::MGATHER, VT, Custom);
1281       setOperationAction(ISD::MSCATTER, VT, Custom);
1282       setOperationAction(ISD::MLOAD, VT, Custom);
1283       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1284       setOperationAction(ISD::SELECT, VT, Custom);
1285       setOperationAction(ISD::FADD, VT, Custom);
1286       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1287       setOperationAction(ISD::FDIV, VT, Custom);
1288       setOperationAction(ISD::FMA, VT, Custom);
1289       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1290       setOperationAction(ISD::FMAXNUM, VT, Custom);
1291       setOperationAction(ISD::FMINIMUM, VT, Custom);
1292       setOperationAction(ISD::FMINNUM, VT, Custom);
1293       setOperationAction(ISD::FMUL, VT, Custom);
1294       setOperationAction(ISD::FNEG, VT, Custom);
1295       setOperationAction(ISD::FSUB, VT, Custom);
1296       setOperationAction(ISD::FCEIL, VT, Custom);
1297       setOperationAction(ISD::FFLOOR, VT, Custom);
1298       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1299       setOperationAction(ISD::FRINT, VT, Custom);
1300       setOperationAction(ISD::FROUND, VT, Custom);
1301       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1302       setOperationAction(ISD::FTRUNC, VT, Custom);
1303       setOperationAction(ISD::FSQRT, VT, Custom);
1304       setOperationAction(ISD::FABS, VT, Custom);
1305       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1306       setOperationAction(ISD::FP_ROUND, VT, Custom);
1307       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1308       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1309       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1310       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1311       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1312 
1313       setOperationAction(ISD::SELECT_CC, VT, Expand);
1314     }
1315 
1316     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
1317       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1318       setOperationAction(ISD::MGATHER, VT, Custom);
1319       setOperationAction(ISD::MSCATTER, VT, Custom);
1320       setOperationAction(ISD::MLOAD, VT, Custom);
1321     }
1322 
1323     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1324 
1325     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1326     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1327 
1328     // NOTE: Currently this has to happen after computeRegisterProperties rather
1329     // than the preferred option of combining it with the addRegisterClass call.
1330     if (Subtarget->useSVEForFixedLengthVectors()) {
1331       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1332         if (useSVEForFixedLengthVectorVT(VT))
1333           addTypeForFixedLengthSVE(VT);
1334       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1335         if (useSVEForFixedLengthVectorVT(VT))
1336           addTypeForFixedLengthSVE(VT);
1337 
1338       // 64bit results can mean a bigger than NEON input.
1339       for (auto VT : {MVT::v8i8, MVT::v4i16})
1340         setOperationAction(ISD::TRUNCATE, VT, Custom);
1341       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1342 
1343       // 128bit results imply a bigger than NEON input.
1344       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1345         setOperationAction(ISD::TRUNCATE, VT, Custom);
1346       for (auto VT : {MVT::v8f16, MVT::v4f32})
1347         setOperationAction(ISD::FP_ROUND, VT, Custom);
1348 
1349       // These operations are not supported on NEON but SVE can do them.
1350       setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
1351       setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
1352       setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1353       setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
1354       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1355       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1356       setOperationAction(ISD::MULHS, MVT::v1i64, Custom);
1357       setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
1358       setOperationAction(ISD::MULHU, MVT::v1i64, Custom);
1359       setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
1360       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1361       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1362       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1363       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1364       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1365       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1366       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1367       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1368       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1369       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1370       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1371       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1372       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1373       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1374       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1375       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1376       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1377       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1378       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1379       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1380       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1381       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1382       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1383       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1384       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1385       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1386       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1387       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1388 
1389       // Int operations with no NEON support.
1390       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1391                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1392         setOperationAction(ISD::BITREVERSE, VT, Custom);
1393         setOperationAction(ISD::CTTZ, VT, Custom);
1394         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1395         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1396         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1397       }
1398 
1399       // FP operations with no NEON support.
1400       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
1401                       MVT::v1f64, MVT::v2f64})
1402         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1403 
1404       // Use SVE for vectors with more than 2 elements.
1405       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1406         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1407     }
1408 
1409     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64);
1410     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32);
1411     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16);
1412     setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8);
1413   }
1414 
1415   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1416 }
1417 
1418 void AArch64TargetLowering::addTypeForNEON(MVT VT) {
1419   assert(VT.isVector() && "VT should be a vector type");
1420 
1421   if (VT.isFloatingPoint()) {
1422     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1423     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1424     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1425   }
1426 
1427   // Mark vector float intrinsics as expand.
1428   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1429     setOperationAction(ISD::FSIN, VT, Expand);
1430     setOperationAction(ISD::FCOS, VT, Expand);
1431     setOperationAction(ISD::FPOW, VT, Expand);
1432     setOperationAction(ISD::FLOG, VT, Expand);
1433     setOperationAction(ISD::FLOG2, VT, Expand);
1434     setOperationAction(ISD::FLOG10, VT, Expand);
1435     setOperationAction(ISD::FEXP, VT, Expand);
1436     setOperationAction(ISD::FEXP2, VT, Expand);
1437   }
1438 
1439   // But we do support custom-lowering for FCOPYSIGN.
1440   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
1441       ((VT == MVT::v4f16 || VT == MVT::v8f16) && Subtarget->hasFullFP16()))
1442     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1443 
1444   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1445   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1447   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1448   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1449   setOperationAction(ISD::SRA, VT, Custom);
1450   setOperationAction(ISD::SRL, VT, Custom);
1451   setOperationAction(ISD::SHL, VT, Custom);
1452   setOperationAction(ISD::OR, VT, Custom);
1453   setOperationAction(ISD::SETCC, VT, Custom);
1454   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1455 
1456   setOperationAction(ISD::SELECT, VT, Expand);
1457   setOperationAction(ISD::SELECT_CC, VT, Expand);
1458   setOperationAction(ISD::VSELECT, VT, Expand);
1459   for (MVT InnerVT : MVT::all_valuetypes())
1460     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1461 
1462   // CNT supports only B element sizes, then use UADDLP to widen.
1463   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1464     setOperationAction(ISD::CTPOP, VT, Custom);
1465 
1466   setOperationAction(ISD::UDIV, VT, Expand);
1467   setOperationAction(ISD::SDIV, VT, Expand);
1468   setOperationAction(ISD::UREM, VT, Expand);
1469   setOperationAction(ISD::SREM, VT, Expand);
1470   setOperationAction(ISD::FREM, VT, Expand);
1471 
1472   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1473   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1474   setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
1475   setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
1476 
1477   if (!VT.isFloatingPoint())
1478     setOperationAction(ISD::ABS, VT, Legal);
1479 
1480   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1481   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1482     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1483       setOperationAction(Opcode, VT, Legal);
1484 
1485   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1486   if (VT.isFloatingPoint() &&
1487       VT.getVectorElementType() != MVT::bf16 &&
1488       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1489     for (unsigned Opcode :
1490          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1491       setOperationAction(Opcode, VT, Legal);
1492 
1493   if (Subtarget->isLittleEndian()) {
1494     for (unsigned im = (unsigned)ISD::PRE_INC;
1495          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1496       setIndexedLoadAction(im, VT, Legal);
1497       setIndexedStoreAction(im, VT, Legal);
1498     }
1499   }
1500 }
1501 
1502 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1503   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1504 
1505   // By default everything must be expanded.
1506   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1507     setOperationAction(Op, VT, Expand);
1508 
1509   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1510   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1511 
1512   if (VT.isFloatingPoint()) {
1513     setCondCodeAction(ISD::SETO, VT, Expand);
1514     setCondCodeAction(ISD::SETOLT, VT, Expand);
1515     setCondCodeAction(ISD::SETLT, VT, Expand);
1516     setCondCodeAction(ISD::SETOLE, VT, Expand);
1517     setCondCodeAction(ISD::SETLE, VT, Expand);
1518     setCondCodeAction(ISD::SETULT, VT, Expand);
1519     setCondCodeAction(ISD::SETULE, VT, Expand);
1520     setCondCodeAction(ISD::SETUGE, VT, Expand);
1521     setCondCodeAction(ISD::SETUGT, VT, Expand);
1522     setCondCodeAction(ISD::SETUEQ, VT, Expand);
1523     setCondCodeAction(ISD::SETUNE, VT, Expand);
1524   }
1525 
1526   // Mark integer truncating stores as having custom lowering
1527   if (VT.isInteger()) {
1528     MVT InnerVT = VT.changeVectorElementType(MVT::i8);
1529     while (InnerVT != VT) {
1530       setTruncStoreAction(VT, InnerVT, Custom);
1531       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Custom);
1532       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Custom);
1533       InnerVT = InnerVT.changeVectorElementType(
1534           MVT::getIntegerVT(2 * InnerVT.getScalarSizeInBits()));
1535     }
1536   }
1537 
1538   // Lower fixed length vector operations to scalable equivalents.
1539   setOperationAction(ISD::ABS, VT, Custom);
1540   setOperationAction(ISD::ADD, VT, Custom);
1541   setOperationAction(ISD::AND, VT, Custom);
1542   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1543   setOperationAction(ISD::BITCAST, VT, Custom);
1544   setOperationAction(ISD::BITREVERSE, VT, Custom);
1545   setOperationAction(ISD::BSWAP, VT, Custom);
1546   setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1547   setOperationAction(ISD::CTLZ, VT, Custom);
1548   setOperationAction(ISD::CTPOP, VT, Custom);
1549   setOperationAction(ISD::CTTZ, VT, Custom);
1550   setOperationAction(ISD::FABS, VT, Custom);
1551   setOperationAction(ISD::FADD, VT, Custom);
1552   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1553   setOperationAction(ISD::FCEIL, VT, Custom);
1554   setOperationAction(ISD::FDIV, VT, Custom);
1555   setOperationAction(ISD::FFLOOR, VT, Custom);
1556   setOperationAction(ISD::FMA, VT, Custom);
1557   setOperationAction(ISD::FMAXIMUM, VT, Custom);
1558   setOperationAction(ISD::FMAXNUM, VT, Custom);
1559   setOperationAction(ISD::FMINIMUM, VT, Custom);
1560   setOperationAction(ISD::FMINNUM, VT, Custom);
1561   setOperationAction(ISD::FMUL, VT, Custom);
1562   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1563   setOperationAction(ISD::FNEG, VT, Custom);
1564   setOperationAction(ISD::FP_EXTEND, VT, Custom);
1565   setOperationAction(ISD::FP_ROUND, VT, Custom);
1566   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1567   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1568   setOperationAction(ISD::FRINT, VT, Custom);
1569   setOperationAction(ISD::FROUND, VT, Custom);
1570   setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1571   setOperationAction(ISD::FSQRT, VT, Custom);
1572   setOperationAction(ISD::FSUB, VT, Custom);
1573   setOperationAction(ISD::FTRUNC, VT, Custom);
1574   setOperationAction(ISD::LOAD, VT, Custom);
1575   setOperationAction(ISD::MGATHER, VT, Custom);
1576   setOperationAction(ISD::MLOAD, VT, Custom);
1577   setOperationAction(ISD::MSCATTER, VT, Custom);
1578   setOperationAction(ISD::MSTORE, VT, Custom);
1579   setOperationAction(ISD::MUL, VT, Custom);
1580   setOperationAction(ISD::MULHS, VT, Custom);
1581   setOperationAction(ISD::MULHU, VT, Custom);
1582   setOperationAction(ISD::OR, VT, Custom);
1583   setOperationAction(ISD::SDIV, VT, Custom);
1584   setOperationAction(ISD::SELECT, VT, Custom);
1585   setOperationAction(ISD::SETCC, VT, Custom);
1586   setOperationAction(ISD::SHL, VT, Custom);
1587   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1588   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1589   setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1590   setOperationAction(ISD::SMAX, VT, Custom);
1591   setOperationAction(ISD::SMIN, VT, Custom);
1592   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1593   setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
1594   setOperationAction(ISD::SRA, VT, Custom);
1595   setOperationAction(ISD::SRL, VT, Custom);
1596   setOperationAction(ISD::STORE, VT, Custom);
1597   setOperationAction(ISD::SUB, VT, Custom);
1598   setOperationAction(ISD::TRUNCATE, VT, Custom);
1599   setOperationAction(ISD::UDIV, VT, Custom);
1600   setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1601   setOperationAction(ISD::UMAX, VT, Custom);
1602   setOperationAction(ISD::UMIN, VT, Custom);
1603   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1604   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1605   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1606   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1607   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1608   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1609   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1610   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1611   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1612   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1613   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1614   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1615   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1616   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1617   setOperationAction(ISD::VSELECT, VT, Custom);
1618   setOperationAction(ISD::XOR, VT, Custom);
1619   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1620 }
1621 
1622 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1623   addRegisterClass(VT, &AArch64::FPR64RegClass);
1624   addTypeForNEON(VT);
1625 }
1626 
1627 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1628   addRegisterClass(VT, &AArch64::FPR128RegClass);
1629   addTypeForNEON(VT);
1630 }
1631 
1632 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1633                                               LLVMContext &C, EVT VT) const {
1634   if (!VT.isVector())
1635     return MVT::i32;
1636   if (VT.isScalableVector())
1637     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1638   return VT.changeVectorElementTypeToInteger();
1639 }
1640 
1641 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1642                                const APInt &Demanded,
1643                                TargetLowering::TargetLoweringOpt &TLO,
1644                                unsigned NewOpc) {
1645   uint64_t OldImm = Imm, NewImm, Enc;
1646   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1647 
1648   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1649   // bimm64.
1650   if (Imm == 0 || Imm == Mask ||
1651       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1652     return false;
1653 
1654   unsigned EltSize = Size;
1655   uint64_t DemandedBits = Demanded.getZExtValue();
1656 
1657   // Clear bits that are not demanded.
1658   Imm &= DemandedBits;
1659 
1660   while (true) {
1661     // The goal here is to set the non-demanded bits in a way that minimizes
1662     // the number of switching between 0 and 1. In order to achieve this goal,
1663     // we set the non-demanded bits to the value of the preceding demanded bits.
1664     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1665     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1666     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1667     // The final result is 0b11000011.
1668     uint64_t NonDemandedBits = ~DemandedBits;
1669     uint64_t InvertedImm = ~Imm & DemandedBits;
1670     uint64_t RotatedImm =
1671         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1672         NonDemandedBits;
1673     uint64_t Sum = RotatedImm + NonDemandedBits;
1674     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1675     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1676     NewImm = (Imm | Ones) & Mask;
1677 
1678     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1679     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1680     // we halve the element size and continue the search.
1681     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1682       break;
1683 
1684     // We cannot shrink the element size any further if it is 2-bits.
1685     if (EltSize == 2)
1686       return false;
1687 
1688     EltSize /= 2;
1689     Mask >>= EltSize;
1690     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1691 
1692     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1693     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1694       return false;
1695 
1696     // Merge the upper and lower halves of Imm and DemandedBits.
1697     Imm |= Hi;
1698     DemandedBits |= DemandedBitsHi;
1699   }
1700 
1701   ++NumOptimizedImms;
1702 
1703   // Replicate the element across the register width.
1704   while (EltSize < Size) {
1705     NewImm |= NewImm << EltSize;
1706     EltSize *= 2;
1707   }
1708 
1709   (void)OldImm;
1710   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1711          "demanded bits should never be altered");
1712   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1713 
1714   // Create the new constant immediate node.
1715   EVT VT = Op.getValueType();
1716   SDLoc DL(Op);
1717   SDValue New;
1718 
1719   // If the new constant immediate is all-zeros or all-ones, let the target
1720   // independent DAG combine optimize this node.
1721   if (NewImm == 0 || NewImm == OrigMask) {
1722     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1723                           TLO.DAG.getConstant(NewImm, DL, VT));
1724   // Otherwise, create a machine node so that target independent DAG combine
1725   // doesn't undo this optimization.
1726   } else {
1727     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1728     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1729     New = SDValue(
1730         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1731   }
1732 
1733   return TLO.CombineTo(Op, New);
1734 }
1735 
1736 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1737     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1738     TargetLoweringOpt &TLO) const {
1739   // Delay this optimization to as late as possible.
1740   if (!TLO.LegalOps)
1741     return false;
1742 
1743   if (!EnableOptimizeLogicalImm)
1744     return false;
1745 
1746   EVT VT = Op.getValueType();
1747   if (VT.isVector())
1748     return false;
1749 
1750   unsigned Size = VT.getSizeInBits();
1751   assert((Size == 32 || Size == 64) &&
1752          "i32 or i64 is expected after legalization.");
1753 
1754   // Exit early if we demand all bits.
1755   if (DemandedBits.countPopulation() == Size)
1756     return false;
1757 
1758   unsigned NewOpc;
1759   switch (Op.getOpcode()) {
1760   default:
1761     return false;
1762   case ISD::AND:
1763     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1764     break;
1765   case ISD::OR:
1766     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1767     break;
1768   case ISD::XOR:
1769     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1770     break;
1771   }
1772   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1773   if (!C)
1774     return false;
1775   uint64_t Imm = C->getZExtValue();
1776   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1777 }
1778 
1779 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1780 /// Mask are known to be either zero or one and return them Known.
1781 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1782     const SDValue Op, KnownBits &Known,
1783     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1784   switch (Op.getOpcode()) {
1785   default:
1786     break;
1787   case AArch64ISD::CSEL: {
1788     KnownBits Known2;
1789     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1790     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1791     Known = KnownBits::commonBits(Known, Known2);
1792     break;
1793   }
1794   case AArch64ISD::LOADgot:
1795   case AArch64ISD::ADDlow: {
1796     if (!Subtarget->isTargetILP32())
1797       break;
1798     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1799     Known.Zero = APInt::getHighBitsSet(64, 32);
1800     break;
1801   }
1802   case AArch64ISD::ASSERT_ZEXT_BOOL: {
1803     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1804     Known.Zero |= APInt(Known.getBitWidth(), 0xFE);
1805     break;
1806   }
1807   case ISD::INTRINSIC_W_CHAIN: {
1808     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1809     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1810     switch (IntID) {
1811     default: return;
1812     case Intrinsic::aarch64_ldaxr:
1813     case Intrinsic::aarch64_ldxr: {
1814       unsigned BitWidth = Known.getBitWidth();
1815       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1816       unsigned MemBits = VT.getScalarSizeInBits();
1817       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1818       return;
1819     }
1820     }
1821     break;
1822   }
1823   case ISD::INTRINSIC_WO_CHAIN:
1824   case ISD::INTRINSIC_VOID: {
1825     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1826     switch (IntNo) {
1827     default:
1828       break;
1829     case Intrinsic::aarch64_neon_umaxv:
1830     case Intrinsic::aarch64_neon_uminv: {
1831       // Figure out the datatype of the vector operand. The UMINV instruction
1832       // will zero extend the result, so we can mark as known zero all the
1833       // bits larger than the element datatype. 32-bit or larget doesn't need
1834       // this as those are legal types and will be handled by isel directly.
1835       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1836       unsigned BitWidth = Known.getBitWidth();
1837       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1838         assert(BitWidth >= 8 && "Unexpected width!");
1839         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1840         Known.Zero |= Mask;
1841       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1842         assert(BitWidth >= 16 && "Unexpected width!");
1843         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1844         Known.Zero |= Mask;
1845       }
1846       break;
1847     } break;
1848     }
1849   }
1850   }
1851 }
1852 
1853 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1854                                                   EVT) const {
1855   return MVT::i64;
1856 }
1857 
1858 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1859     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1860     bool *Fast) const {
1861   if (Subtarget->requiresStrictAlign())
1862     return false;
1863 
1864   if (Fast) {
1865     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1866     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1867             // See comments in performSTORECombine() for more details about
1868             // these conditions.
1869 
1870             // Code that uses clang vector extensions can mark that it
1871             // wants unaligned accesses to be treated as fast by
1872             // underspecifying alignment to be 1 or 2.
1873             Alignment <= 2 ||
1874 
1875             // Disregard v2i64. Memcpy lowering produces those and splitting
1876             // them regresses performance on micro-benchmarks and olden/bh.
1877             VT == MVT::v2i64;
1878   }
1879   return true;
1880 }
1881 
1882 // Same as above but handling LLTs instead.
1883 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1884     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1885     bool *Fast) const {
1886   if (Subtarget->requiresStrictAlign())
1887     return false;
1888 
1889   if (Fast) {
1890     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1891     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1892             Ty.getSizeInBytes() != 16 ||
1893             // See comments in performSTORECombine() for more details about
1894             // these conditions.
1895 
1896             // Code that uses clang vector extensions can mark that it
1897             // wants unaligned accesses to be treated as fast by
1898             // underspecifying alignment to be 1 or 2.
1899             Alignment <= 2 ||
1900 
1901             // Disregard v2i64. Memcpy lowering produces those and splitting
1902             // them regresses performance on micro-benchmarks and olden/bh.
1903             Ty == LLT::fixed_vector(2, 64);
1904   }
1905   return true;
1906 }
1907 
1908 FastISel *
1909 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1910                                       const TargetLibraryInfo *libInfo) const {
1911   return AArch64::createFastISel(funcInfo, libInfo);
1912 }
1913 
1914 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1915 #define MAKE_CASE(V)                                                           \
1916   case V:                                                                      \
1917     return #V;
1918   switch ((AArch64ISD::NodeType)Opcode) {
1919   case AArch64ISD::FIRST_NUMBER:
1920     break;
1921     MAKE_CASE(AArch64ISD::CALL)
1922     MAKE_CASE(AArch64ISD::ADRP)
1923     MAKE_CASE(AArch64ISD::ADR)
1924     MAKE_CASE(AArch64ISD::ADDlow)
1925     MAKE_CASE(AArch64ISD::LOADgot)
1926     MAKE_CASE(AArch64ISD::RET_FLAG)
1927     MAKE_CASE(AArch64ISD::BRCOND)
1928     MAKE_CASE(AArch64ISD::CSEL)
1929     MAKE_CASE(AArch64ISD::CSINV)
1930     MAKE_CASE(AArch64ISD::CSNEG)
1931     MAKE_CASE(AArch64ISD::CSINC)
1932     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1933     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1934     MAKE_CASE(AArch64ISD::ADD_PRED)
1935     MAKE_CASE(AArch64ISD::MUL_PRED)
1936     MAKE_CASE(AArch64ISD::MULHS_PRED)
1937     MAKE_CASE(AArch64ISD::MULHU_PRED)
1938     MAKE_CASE(AArch64ISD::SDIV_PRED)
1939     MAKE_CASE(AArch64ISD::SHL_PRED)
1940     MAKE_CASE(AArch64ISD::SMAX_PRED)
1941     MAKE_CASE(AArch64ISD::SMIN_PRED)
1942     MAKE_CASE(AArch64ISD::SRA_PRED)
1943     MAKE_CASE(AArch64ISD::SRL_PRED)
1944     MAKE_CASE(AArch64ISD::SUB_PRED)
1945     MAKE_CASE(AArch64ISD::UDIV_PRED)
1946     MAKE_CASE(AArch64ISD::UMAX_PRED)
1947     MAKE_CASE(AArch64ISD::UMIN_PRED)
1948     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
1949     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1950     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1951     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
1952     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
1953     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
1954     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
1955     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
1956     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
1957     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
1958     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
1959     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
1960     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
1961     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
1962     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
1963     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
1964     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
1965     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
1966     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
1967     MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
1968     MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
1969     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1970     MAKE_CASE(AArch64ISD::ADC)
1971     MAKE_CASE(AArch64ISD::SBC)
1972     MAKE_CASE(AArch64ISD::ADDS)
1973     MAKE_CASE(AArch64ISD::SUBS)
1974     MAKE_CASE(AArch64ISD::ADCS)
1975     MAKE_CASE(AArch64ISD::SBCS)
1976     MAKE_CASE(AArch64ISD::ANDS)
1977     MAKE_CASE(AArch64ISD::CCMP)
1978     MAKE_CASE(AArch64ISD::CCMN)
1979     MAKE_CASE(AArch64ISD::FCCMP)
1980     MAKE_CASE(AArch64ISD::FCMP)
1981     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1982     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1983     MAKE_CASE(AArch64ISD::DUP)
1984     MAKE_CASE(AArch64ISD::DUPLANE8)
1985     MAKE_CASE(AArch64ISD::DUPLANE16)
1986     MAKE_CASE(AArch64ISD::DUPLANE32)
1987     MAKE_CASE(AArch64ISD::DUPLANE64)
1988     MAKE_CASE(AArch64ISD::MOVI)
1989     MAKE_CASE(AArch64ISD::MOVIshift)
1990     MAKE_CASE(AArch64ISD::MOVIedit)
1991     MAKE_CASE(AArch64ISD::MOVImsl)
1992     MAKE_CASE(AArch64ISD::FMOV)
1993     MAKE_CASE(AArch64ISD::MVNIshift)
1994     MAKE_CASE(AArch64ISD::MVNImsl)
1995     MAKE_CASE(AArch64ISD::BICi)
1996     MAKE_CASE(AArch64ISD::ORRi)
1997     MAKE_CASE(AArch64ISD::BSP)
1998     MAKE_CASE(AArch64ISD::EXTR)
1999     MAKE_CASE(AArch64ISD::ZIP1)
2000     MAKE_CASE(AArch64ISD::ZIP2)
2001     MAKE_CASE(AArch64ISD::UZP1)
2002     MAKE_CASE(AArch64ISD::UZP2)
2003     MAKE_CASE(AArch64ISD::TRN1)
2004     MAKE_CASE(AArch64ISD::TRN2)
2005     MAKE_CASE(AArch64ISD::REV16)
2006     MAKE_CASE(AArch64ISD::REV32)
2007     MAKE_CASE(AArch64ISD::REV64)
2008     MAKE_CASE(AArch64ISD::EXT)
2009     MAKE_CASE(AArch64ISD::SPLICE)
2010     MAKE_CASE(AArch64ISD::VSHL)
2011     MAKE_CASE(AArch64ISD::VLSHR)
2012     MAKE_CASE(AArch64ISD::VASHR)
2013     MAKE_CASE(AArch64ISD::VSLI)
2014     MAKE_CASE(AArch64ISD::VSRI)
2015     MAKE_CASE(AArch64ISD::CMEQ)
2016     MAKE_CASE(AArch64ISD::CMGE)
2017     MAKE_CASE(AArch64ISD::CMGT)
2018     MAKE_CASE(AArch64ISD::CMHI)
2019     MAKE_CASE(AArch64ISD::CMHS)
2020     MAKE_CASE(AArch64ISD::FCMEQ)
2021     MAKE_CASE(AArch64ISD::FCMGE)
2022     MAKE_CASE(AArch64ISD::FCMGT)
2023     MAKE_CASE(AArch64ISD::CMEQz)
2024     MAKE_CASE(AArch64ISD::CMGEz)
2025     MAKE_CASE(AArch64ISD::CMGTz)
2026     MAKE_CASE(AArch64ISD::CMLEz)
2027     MAKE_CASE(AArch64ISD::CMLTz)
2028     MAKE_CASE(AArch64ISD::FCMEQz)
2029     MAKE_CASE(AArch64ISD::FCMGEz)
2030     MAKE_CASE(AArch64ISD::FCMGTz)
2031     MAKE_CASE(AArch64ISD::FCMLEz)
2032     MAKE_CASE(AArch64ISD::FCMLTz)
2033     MAKE_CASE(AArch64ISD::SADDV)
2034     MAKE_CASE(AArch64ISD::UADDV)
2035     MAKE_CASE(AArch64ISD::SRHADD)
2036     MAKE_CASE(AArch64ISD::URHADD)
2037     MAKE_CASE(AArch64ISD::SHADD)
2038     MAKE_CASE(AArch64ISD::UHADD)
2039     MAKE_CASE(AArch64ISD::SDOT)
2040     MAKE_CASE(AArch64ISD::UDOT)
2041     MAKE_CASE(AArch64ISD::SMINV)
2042     MAKE_CASE(AArch64ISD::UMINV)
2043     MAKE_CASE(AArch64ISD::SMAXV)
2044     MAKE_CASE(AArch64ISD::UMAXV)
2045     MAKE_CASE(AArch64ISD::SADDV_PRED)
2046     MAKE_CASE(AArch64ISD::UADDV_PRED)
2047     MAKE_CASE(AArch64ISD::SMAXV_PRED)
2048     MAKE_CASE(AArch64ISD::UMAXV_PRED)
2049     MAKE_CASE(AArch64ISD::SMINV_PRED)
2050     MAKE_CASE(AArch64ISD::UMINV_PRED)
2051     MAKE_CASE(AArch64ISD::ORV_PRED)
2052     MAKE_CASE(AArch64ISD::EORV_PRED)
2053     MAKE_CASE(AArch64ISD::ANDV_PRED)
2054     MAKE_CASE(AArch64ISD::CLASTA_N)
2055     MAKE_CASE(AArch64ISD::CLASTB_N)
2056     MAKE_CASE(AArch64ISD::LASTA)
2057     MAKE_CASE(AArch64ISD::LASTB)
2058     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
2059     MAKE_CASE(AArch64ISD::LS64_BUILD)
2060     MAKE_CASE(AArch64ISD::LS64_EXTRACT)
2061     MAKE_CASE(AArch64ISD::TBL)
2062     MAKE_CASE(AArch64ISD::FADD_PRED)
2063     MAKE_CASE(AArch64ISD::FADDA_PRED)
2064     MAKE_CASE(AArch64ISD::FADDV_PRED)
2065     MAKE_CASE(AArch64ISD::FDIV_PRED)
2066     MAKE_CASE(AArch64ISD::FMA_PRED)
2067     MAKE_CASE(AArch64ISD::FMAX_PRED)
2068     MAKE_CASE(AArch64ISD::FMAXV_PRED)
2069     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
2070     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
2071     MAKE_CASE(AArch64ISD::FMIN_PRED)
2072     MAKE_CASE(AArch64ISD::FMINV_PRED)
2073     MAKE_CASE(AArch64ISD::FMINNM_PRED)
2074     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
2075     MAKE_CASE(AArch64ISD::FMUL_PRED)
2076     MAKE_CASE(AArch64ISD::FSUB_PRED)
2077     MAKE_CASE(AArch64ISD::BIC)
2078     MAKE_CASE(AArch64ISD::BIT)
2079     MAKE_CASE(AArch64ISD::CBZ)
2080     MAKE_CASE(AArch64ISD::CBNZ)
2081     MAKE_CASE(AArch64ISD::TBZ)
2082     MAKE_CASE(AArch64ISD::TBNZ)
2083     MAKE_CASE(AArch64ISD::TC_RETURN)
2084     MAKE_CASE(AArch64ISD::PREFETCH)
2085     MAKE_CASE(AArch64ISD::SITOF)
2086     MAKE_CASE(AArch64ISD::UITOF)
2087     MAKE_CASE(AArch64ISD::NVCAST)
2088     MAKE_CASE(AArch64ISD::MRS)
2089     MAKE_CASE(AArch64ISD::SQSHL_I)
2090     MAKE_CASE(AArch64ISD::UQSHL_I)
2091     MAKE_CASE(AArch64ISD::SRSHR_I)
2092     MAKE_CASE(AArch64ISD::URSHR_I)
2093     MAKE_CASE(AArch64ISD::SQSHLU_I)
2094     MAKE_CASE(AArch64ISD::WrapperLarge)
2095     MAKE_CASE(AArch64ISD::LD2post)
2096     MAKE_CASE(AArch64ISD::LD3post)
2097     MAKE_CASE(AArch64ISD::LD4post)
2098     MAKE_CASE(AArch64ISD::ST2post)
2099     MAKE_CASE(AArch64ISD::ST3post)
2100     MAKE_CASE(AArch64ISD::ST4post)
2101     MAKE_CASE(AArch64ISD::LD1x2post)
2102     MAKE_CASE(AArch64ISD::LD1x3post)
2103     MAKE_CASE(AArch64ISD::LD1x4post)
2104     MAKE_CASE(AArch64ISD::ST1x2post)
2105     MAKE_CASE(AArch64ISD::ST1x3post)
2106     MAKE_CASE(AArch64ISD::ST1x4post)
2107     MAKE_CASE(AArch64ISD::LD1DUPpost)
2108     MAKE_CASE(AArch64ISD::LD2DUPpost)
2109     MAKE_CASE(AArch64ISD::LD3DUPpost)
2110     MAKE_CASE(AArch64ISD::LD4DUPpost)
2111     MAKE_CASE(AArch64ISD::LD1LANEpost)
2112     MAKE_CASE(AArch64ISD::LD2LANEpost)
2113     MAKE_CASE(AArch64ISD::LD3LANEpost)
2114     MAKE_CASE(AArch64ISD::LD4LANEpost)
2115     MAKE_CASE(AArch64ISD::ST2LANEpost)
2116     MAKE_CASE(AArch64ISD::ST3LANEpost)
2117     MAKE_CASE(AArch64ISD::ST4LANEpost)
2118     MAKE_CASE(AArch64ISD::SMULL)
2119     MAKE_CASE(AArch64ISD::UMULL)
2120     MAKE_CASE(AArch64ISD::FRECPE)
2121     MAKE_CASE(AArch64ISD::FRECPS)
2122     MAKE_CASE(AArch64ISD::FRSQRTE)
2123     MAKE_CASE(AArch64ISD::FRSQRTS)
2124     MAKE_CASE(AArch64ISD::STG)
2125     MAKE_CASE(AArch64ISD::STZG)
2126     MAKE_CASE(AArch64ISD::ST2G)
2127     MAKE_CASE(AArch64ISD::STZ2G)
2128     MAKE_CASE(AArch64ISD::SUNPKHI)
2129     MAKE_CASE(AArch64ISD::SUNPKLO)
2130     MAKE_CASE(AArch64ISD::UUNPKHI)
2131     MAKE_CASE(AArch64ISD::UUNPKLO)
2132     MAKE_CASE(AArch64ISD::INSR)
2133     MAKE_CASE(AArch64ISD::PTEST)
2134     MAKE_CASE(AArch64ISD::PTRUE)
2135     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
2136     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
2137     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
2138     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
2139     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
2140     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
2141     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
2142     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
2143     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
2144     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
2145     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
2146     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
2147     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
2148     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
2149     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
2150     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
2151     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
2152     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
2153     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
2154     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
2155     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
2156     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
2157     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
2158     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
2159     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
2160     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
2161     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
2162     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
2163     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
2164     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
2165     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
2166     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
2167     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
2168     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
2169     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
2170     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
2171     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
2172     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
2173     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
2174     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
2175     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
2176     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
2177     MAKE_CASE(AArch64ISD::ST1_PRED)
2178     MAKE_CASE(AArch64ISD::SST1_PRED)
2179     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
2180     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
2181     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
2182     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
2183     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
2184     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
2185     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
2186     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
2187     MAKE_CASE(AArch64ISD::LDP)
2188     MAKE_CASE(AArch64ISD::STP)
2189     MAKE_CASE(AArch64ISD::STNP)
2190     MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
2191     MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
2192     MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
2193     MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
2194     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
2195     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
2196     MAKE_CASE(AArch64ISD::UADDLP)
2197     MAKE_CASE(AArch64ISD::CALL_RVMARKER)
2198     MAKE_CASE(AArch64ISD::ASSERT_ZEXT_BOOL)
2199   }
2200 #undef MAKE_CASE
2201   return nullptr;
2202 }
2203 
2204 MachineBasicBlock *
2205 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
2206                                     MachineBasicBlock *MBB) const {
2207   // We materialise the F128CSEL pseudo-instruction as some control flow and a
2208   // phi node:
2209 
2210   // OrigBB:
2211   //     [... previous instrs leading to comparison ...]
2212   //     b.ne TrueBB
2213   //     b EndBB
2214   // TrueBB:
2215   //     ; Fallthrough
2216   // EndBB:
2217   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
2218 
2219   MachineFunction *MF = MBB->getParent();
2220   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2221   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
2222   DebugLoc DL = MI.getDebugLoc();
2223   MachineFunction::iterator It = ++MBB->getIterator();
2224 
2225   Register DestReg = MI.getOperand(0).getReg();
2226   Register IfTrueReg = MI.getOperand(1).getReg();
2227   Register IfFalseReg = MI.getOperand(2).getReg();
2228   unsigned CondCode = MI.getOperand(3).getImm();
2229   bool NZCVKilled = MI.getOperand(4).isKill();
2230 
2231   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
2232   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
2233   MF->insert(It, TrueBB);
2234   MF->insert(It, EndBB);
2235 
2236   // Transfer rest of current basic-block to EndBB
2237   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
2238                 MBB->end());
2239   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
2240 
2241   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
2242   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
2243   MBB->addSuccessor(TrueBB);
2244   MBB->addSuccessor(EndBB);
2245 
2246   // TrueBB falls through to the end.
2247   TrueBB->addSuccessor(EndBB);
2248 
2249   if (!NZCVKilled) {
2250     TrueBB->addLiveIn(AArch64::NZCV);
2251     EndBB->addLiveIn(AArch64::NZCV);
2252   }
2253 
2254   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
2255       .addReg(IfTrueReg)
2256       .addMBB(TrueBB)
2257       .addReg(IfFalseReg)
2258       .addMBB(MBB);
2259 
2260   MI.eraseFromParent();
2261   return EndBB;
2262 }
2263 
2264 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
2265        MachineInstr &MI, MachineBasicBlock *BB) const {
2266   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2267              BB->getParent()->getFunction().getPersonalityFn())) &&
2268          "SEH does not use catchret!");
2269   return BB;
2270 }
2271 
2272 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
2273     MachineInstr &MI, MachineBasicBlock *BB) const {
2274   switch (MI.getOpcode()) {
2275   default:
2276 #ifndef NDEBUG
2277     MI.dump();
2278 #endif
2279     llvm_unreachable("Unexpected instruction for custom inserter!");
2280 
2281   case AArch64::F128CSEL:
2282     return EmitF128CSEL(MI, BB);
2283 
2284   case TargetOpcode::STACKMAP:
2285   case TargetOpcode::PATCHPOINT:
2286   case TargetOpcode::STATEPOINT:
2287     return emitPatchPoint(MI, BB);
2288 
2289   case AArch64::CATCHRET:
2290     return EmitLoweredCatchRet(MI, BB);
2291   }
2292 }
2293 
2294 //===----------------------------------------------------------------------===//
2295 // AArch64 Lowering private implementation.
2296 //===----------------------------------------------------------------------===//
2297 
2298 //===----------------------------------------------------------------------===//
2299 // Lowering Code
2300 //===----------------------------------------------------------------------===//
2301 
2302 // Forward declarations of SVE fixed length lowering helpers
2303 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT);
2304 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2305 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
2306 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
2307                                                 SelectionDAG &DAG);
2308 
2309 /// isZerosVector - Check whether SDNode N is a zero-filled vector.
2310 static bool isZerosVector(const SDNode *N) {
2311   // Look through a bit convert.
2312   while (N->getOpcode() == ISD::BITCAST)
2313     N = N->getOperand(0).getNode();
2314 
2315   if (ISD::isConstantSplatVectorAllZeros(N))
2316     return true;
2317 
2318   if (N->getOpcode() != AArch64ISD::DUP)
2319     return false;
2320 
2321   auto Opnd0 = N->getOperand(0);
2322   auto *CINT = dyn_cast<ConstantSDNode>(Opnd0);
2323   auto *CFP = dyn_cast<ConstantFPSDNode>(Opnd0);
2324   return (CINT && CINT->isZero()) || (CFP && CFP->isZero());
2325 }
2326 
2327 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
2328 /// CC
2329 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
2330   switch (CC) {
2331   default:
2332     llvm_unreachable("Unknown condition code!");
2333   case ISD::SETNE:
2334     return AArch64CC::NE;
2335   case ISD::SETEQ:
2336     return AArch64CC::EQ;
2337   case ISD::SETGT:
2338     return AArch64CC::GT;
2339   case ISD::SETGE:
2340     return AArch64CC::GE;
2341   case ISD::SETLT:
2342     return AArch64CC::LT;
2343   case ISD::SETLE:
2344     return AArch64CC::LE;
2345   case ISD::SETUGT:
2346     return AArch64CC::HI;
2347   case ISD::SETUGE:
2348     return AArch64CC::HS;
2349   case ISD::SETULT:
2350     return AArch64CC::LO;
2351   case ISD::SETULE:
2352     return AArch64CC::LS;
2353   }
2354 }
2355 
2356 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
2357 static void changeFPCCToAArch64CC(ISD::CondCode CC,
2358                                   AArch64CC::CondCode &CondCode,
2359                                   AArch64CC::CondCode &CondCode2) {
2360   CondCode2 = AArch64CC::AL;
2361   switch (CC) {
2362   default:
2363     llvm_unreachable("Unknown FP condition!");
2364   case ISD::SETEQ:
2365   case ISD::SETOEQ:
2366     CondCode = AArch64CC::EQ;
2367     break;
2368   case ISD::SETGT:
2369   case ISD::SETOGT:
2370     CondCode = AArch64CC::GT;
2371     break;
2372   case ISD::SETGE:
2373   case ISD::SETOGE:
2374     CondCode = AArch64CC::GE;
2375     break;
2376   case ISD::SETOLT:
2377     CondCode = AArch64CC::MI;
2378     break;
2379   case ISD::SETOLE:
2380     CondCode = AArch64CC::LS;
2381     break;
2382   case ISD::SETONE:
2383     CondCode = AArch64CC::MI;
2384     CondCode2 = AArch64CC::GT;
2385     break;
2386   case ISD::SETO:
2387     CondCode = AArch64CC::VC;
2388     break;
2389   case ISD::SETUO:
2390     CondCode = AArch64CC::VS;
2391     break;
2392   case ISD::SETUEQ:
2393     CondCode = AArch64CC::EQ;
2394     CondCode2 = AArch64CC::VS;
2395     break;
2396   case ISD::SETUGT:
2397     CondCode = AArch64CC::HI;
2398     break;
2399   case ISD::SETUGE:
2400     CondCode = AArch64CC::PL;
2401     break;
2402   case ISD::SETLT:
2403   case ISD::SETULT:
2404     CondCode = AArch64CC::LT;
2405     break;
2406   case ISD::SETLE:
2407   case ISD::SETULE:
2408     CondCode = AArch64CC::LE;
2409     break;
2410   case ISD::SETNE:
2411   case ISD::SETUNE:
2412     CondCode = AArch64CC::NE;
2413     break;
2414   }
2415 }
2416 
2417 /// Convert a DAG fp condition code to an AArch64 CC.
2418 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2419 /// should be AND'ed instead of OR'ed.
2420 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2421                                      AArch64CC::CondCode &CondCode,
2422                                      AArch64CC::CondCode &CondCode2) {
2423   CondCode2 = AArch64CC::AL;
2424   switch (CC) {
2425   default:
2426     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2427     assert(CondCode2 == AArch64CC::AL);
2428     break;
2429   case ISD::SETONE:
2430     // (a one b)
2431     // == ((a olt b) || (a ogt b))
2432     // == ((a ord b) && (a une b))
2433     CondCode = AArch64CC::VC;
2434     CondCode2 = AArch64CC::NE;
2435     break;
2436   case ISD::SETUEQ:
2437     // (a ueq b)
2438     // == ((a uno b) || (a oeq b))
2439     // == ((a ule b) && (a uge b))
2440     CondCode = AArch64CC::PL;
2441     CondCode2 = AArch64CC::LE;
2442     break;
2443   }
2444 }
2445 
2446 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2447 /// CC usable with the vector instructions. Fewer operations are available
2448 /// without a real NZCV register, so we have to use less efficient combinations
2449 /// to get the same effect.
2450 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2451                                         AArch64CC::CondCode &CondCode,
2452                                         AArch64CC::CondCode &CondCode2,
2453                                         bool &Invert) {
2454   Invert = false;
2455   switch (CC) {
2456   default:
2457     // Mostly the scalar mappings work fine.
2458     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2459     break;
2460   case ISD::SETUO:
2461     Invert = true;
2462     LLVM_FALLTHROUGH;
2463   case ISD::SETO:
2464     CondCode = AArch64CC::MI;
2465     CondCode2 = AArch64CC::GE;
2466     break;
2467   case ISD::SETUEQ:
2468   case ISD::SETULT:
2469   case ISD::SETULE:
2470   case ISD::SETUGT:
2471   case ISD::SETUGE:
2472     // All of the compare-mask comparisons are ordered, but we can switch
2473     // between the two by a double inversion. E.g. ULE == !OGT.
2474     Invert = true;
2475     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2476                           CondCode, CondCode2);
2477     break;
2478   }
2479 }
2480 
2481 static bool isLegalArithImmed(uint64_t C) {
2482   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2483   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2484   LLVM_DEBUG(dbgs() << "Is imm " << C
2485                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2486   return IsLegal;
2487 }
2488 
2489 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2490 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2491 // can be set differently by this operation. It comes down to whether
2492 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2493 // everything is fine. If not then the optimization is wrong. Thus general
2494 // comparisons are only valid if op2 != 0.
2495 //
2496 // So, finally, the only LLVM-native comparisons that don't mention C and V
2497 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2498 // the absence of information about op2.
2499 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2500   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2501          (CC == ISD::SETEQ || CC == ISD::SETNE);
2502 }
2503 
2504 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2505                                       SelectionDAG &DAG, SDValue Chain,
2506                                       bool IsSignaling) {
2507   EVT VT = LHS.getValueType();
2508   assert(VT != MVT::f128);
2509   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2510   unsigned Opcode =
2511       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2512   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2513 }
2514 
2515 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2516                               const SDLoc &dl, SelectionDAG &DAG) {
2517   EVT VT = LHS.getValueType();
2518   const bool FullFP16 =
2519     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2520 
2521   if (VT.isFloatingPoint()) {
2522     assert(VT != MVT::f128);
2523     if (VT == MVT::f16 && !FullFP16) {
2524       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2525       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2526       VT = MVT::f32;
2527     }
2528     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2529   }
2530 
2531   // The CMP instruction is just an alias for SUBS, and representing it as
2532   // SUBS means that it's possible to get CSE with subtract operations.
2533   // A later phase can perform the optimization of setting the destination
2534   // register to WZR/XZR if it ends up being unused.
2535   unsigned Opcode = AArch64ISD::SUBS;
2536 
2537   if (isCMN(RHS, CC)) {
2538     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2539     Opcode = AArch64ISD::ADDS;
2540     RHS = RHS.getOperand(1);
2541   } else if (isCMN(LHS, CC)) {
2542     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2543     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2544     Opcode = AArch64ISD::ADDS;
2545     LHS = LHS.getOperand(1);
2546   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2547     if (LHS.getOpcode() == ISD::AND) {
2548       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2549       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2550       // of the signed comparisons.
2551       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2552                                            DAG.getVTList(VT, MVT_CC),
2553                                            LHS.getOperand(0),
2554                                            LHS.getOperand(1));
2555       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2556       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2557       return ANDSNode.getValue(1);
2558     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2559       // Use result of ANDS
2560       return LHS.getValue(1);
2561     }
2562   }
2563 
2564   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2565       .getValue(1);
2566 }
2567 
2568 /// \defgroup AArch64CCMP CMP;CCMP matching
2569 ///
2570 /// These functions deal with the formation of CMP;CCMP;... sequences.
2571 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2572 /// a comparison. They set the NZCV flags to a predefined value if their
2573 /// predicate is false. This allows to express arbitrary conjunctions, for
2574 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2575 /// expressed as:
2576 ///   cmp A
2577 ///   ccmp B, inv(CB), CA
2578 ///   check for CB flags
2579 ///
2580 /// This naturally lets us implement chains of AND operations with SETCC
2581 /// operands. And we can even implement some other situations by transforming
2582 /// them:
2583 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2584 ///     negating the flags used in a CCMP/FCCMP operations.
2585 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2586 ///     by negating the flags we test for afterwards. i.e.
2587 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2588 ///   - Note that we can only ever negate all previously processed results.
2589 ///     What we can not implement by flipping the flags to test is a negation
2590 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2591 ///     far, so the 2nd sub-tree we emit would also affect the first).
2592 /// With those tools we can implement some OR operations:
2593 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2594 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2595 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2596 ///     elimination rules from earlier to implement the whole thing as a
2597 ///     CCMP/FCCMP chain.
2598 ///
2599 /// As complete example:
2600 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2601 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2602 /// can be reassociated to:
2603 ///     or (and (setCC (cmp C)) setCD (cmp D))
2604 //         (or (setCA (cmp A)) (setCB (cmp B)))
2605 /// can be transformed to:
2606 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2607 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2608 /// which can be implemented as:
2609 ///   cmp C
2610 ///   ccmp D, inv(CD), CC
2611 ///   ccmp A, CA, inv(CD)
2612 ///   ccmp B, CB, inv(CA)
2613 ///   check for CB flags
2614 ///
2615 /// A counterexample is "or (and A B) (and C D)" which translates to
2616 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2617 /// can only implement 1 of the inner (not) operations, but not both!
2618 /// @{
2619 
2620 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2621 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2622                                          ISD::CondCode CC, SDValue CCOp,
2623                                          AArch64CC::CondCode Predicate,
2624                                          AArch64CC::CondCode OutCC,
2625                                          const SDLoc &DL, SelectionDAG &DAG) {
2626   unsigned Opcode = 0;
2627   const bool FullFP16 =
2628     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2629 
2630   if (LHS.getValueType().isFloatingPoint()) {
2631     assert(LHS.getValueType() != MVT::f128);
2632     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2633       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2634       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2635     }
2636     Opcode = AArch64ISD::FCCMP;
2637   } else if (RHS.getOpcode() == ISD::SUB) {
2638     SDValue SubOp0 = RHS.getOperand(0);
2639     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2640       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2641       Opcode = AArch64ISD::CCMN;
2642       RHS = RHS.getOperand(1);
2643     }
2644   }
2645   if (Opcode == 0)
2646     Opcode = AArch64ISD::CCMP;
2647 
2648   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2649   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2650   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2651   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2652   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2653 }
2654 
2655 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2656 /// expressed as a conjunction. See \ref AArch64CCMP.
2657 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2658 ///                     changing the conditions on the SETCC tests.
2659 ///                     (this means we can call emitConjunctionRec() with
2660 ///                      Negate==true on this sub-tree)
2661 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2662 ///                     cannot do the negation naturally. We are required to
2663 ///                     emit the subtree first in this case.
2664 /// \param WillNegate   Is true if are called when the result of this
2665 ///                     subexpression must be negated. This happens when the
2666 ///                     outer expression is an OR. We can use this fact to know
2667 ///                     that we have a double negation (or (or ...) ...) that
2668 ///                     can be implemented for free.
2669 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2670                                bool &MustBeFirst, bool WillNegate,
2671                                unsigned Depth = 0) {
2672   if (!Val.hasOneUse())
2673     return false;
2674   unsigned Opcode = Val->getOpcode();
2675   if (Opcode == ISD::SETCC) {
2676     if (Val->getOperand(0).getValueType() == MVT::f128)
2677       return false;
2678     CanNegate = true;
2679     MustBeFirst = false;
2680     return true;
2681   }
2682   // Protect against exponential runtime and stack overflow.
2683   if (Depth > 6)
2684     return false;
2685   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2686     bool IsOR = Opcode == ISD::OR;
2687     SDValue O0 = Val->getOperand(0);
2688     SDValue O1 = Val->getOperand(1);
2689     bool CanNegateL;
2690     bool MustBeFirstL;
2691     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2692       return false;
2693     bool CanNegateR;
2694     bool MustBeFirstR;
2695     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2696       return false;
2697 
2698     if (MustBeFirstL && MustBeFirstR)
2699       return false;
2700 
2701     if (IsOR) {
2702       // For an OR expression we need to be able to naturally negate at least
2703       // one side or we cannot do the transformation at all.
2704       if (!CanNegateL && !CanNegateR)
2705         return false;
2706       // If we the result of the OR will be negated and we can naturally negate
2707       // the leafs, then this sub-tree as a whole negates naturally.
2708       CanNegate = WillNegate && CanNegateL && CanNegateR;
2709       // If we cannot naturally negate the whole sub-tree, then this must be
2710       // emitted first.
2711       MustBeFirst = !CanNegate;
2712     } else {
2713       assert(Opcode == ISD::AND && "Must be OR or AND");
2714       // We cannot naturally negate an AND operation.
2715       CanNegate = false;
2716       MustBeFirst = MustBeFirstL || MustBeFirstR;
2717     }
2718     return true;
2719   }
2720   return false;
2721 }
2722 
2723 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2724 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2725 /// Tries to transform the given i1 producing node @p Val to a series compare
2726 /// and conditional compare operations. @returns an NZCV flags producing node
2727 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2728 /// transformation was not possible.
2729 /// \p Negate is true if we want this sub-tree being negated just by changing
2730 /// SETCC conditions.
2731 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2732     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2733     AArch64CC::CondCode Predicate) {
2734   // We're at a tree leaf, produce a conditional comparison operation.
2735   unsigned Opcode = Val->getOpcode();
2736   if (Opcode == ISD::SETCC) {
2737     SDValue LHS = Val->getOperand(0);
2738     SDValue RHS = Val->getOperand(1);
2739     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2740     bool isInteger = LHS.getValueType().isInteger();
2741     if (Negate)
2742       CC = getSetCCInverse(CC, LHS.getValueType());
2743     SDLoc DL(Val);
2744     // Determine OutCC and handle FP special case.
2745     if (isInteger) {
2746       OutCC = changeIntCCToAArch64CC(CC);
2747     } else {
2748       assert(LHS.getValueType().isFloatingPoint());
2749       AArch64CC::CondCode ExtraCC;
2750       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2751       // Some floating point conditions can't be tested with a single condition
2752       // code. Construct an additional comparison in this case.
2753       if (ExtraCC != AArch64CC::AL) {
2754         SDValue ExtraCmp;
2755         if (!CCOp.getNode())
2756           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2757         else
2758           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2759                                                ExtraCC, DL, DAG);
2760         CCOp = ExtraCmp;
2761         Predicate = ExtraCC;
2762       }
2763     }
2764 
2765     // Produce a normal comparison if we are first in the chain
2766     if (!CCOp)
2767       return emitComparison(LHS, RHS, CC, DL, DAG);
2768     // Otherwise produce a ccmp.
2769     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2770                                      DAG);
2771   }
2772   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2773 
2774   bool IsOR = Opcode == ISD::OR;
2775 
2776   SDValue LHS = Val->getOperand(0);
2777   bool CanNegateL;
2778   bool MustBeFirstL;
2779   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2780   assert(ValidL && "Valid conjunction/disjunction tree");
2781   (void)ValidL;
2782 
2783   SDValue RHS = Val->getOperand(1);
2784   bool CanNegateR;
2785   bool MustBeFirstR;
2786   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2787   assert(ValidR && "Valid conjunction/disjunction tree");
2788   (void)ValidR;
2789 
2790   // Swap sub-tree that must come first to the right side.
2791   if (MustBeFirstL) {
2792     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2793     std::swap(LHS, RHS);
2794     std::swap(CanNegateL, CanNegateR);
2795     std::swap(MustBeFirstL, MustBeFirstR);
2796   }
2797 
2798   bool NegateR;
2799   bool NegateAfterR;
2800   bool NegateL;
2801   bool NegateAfterAll;
2802   if (Opcode == ISD::OR) {
2803     // Swap the sub-tree that we can negate naturally to the left.
2804     if (!CanNegateL) {
2805       assert(CanNegateR && "at least one side must be negatable");
2806       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2807       assert(!Negate);
2808       std::swap(LHS, RHS);
2809       NegateR = false;
2810       NegateAfterR = true;
2811     } else {
2812       // Negate the left sub-tree if possible, otherwise negate the result.
2813       NegateR = CanNegateR;
2814       NegateAfterR = !CanNegateR;
2815     }
2816     NegateL = true;
2817     NegateAfterAll = !Negate;
2818   } else {
2819     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2820     assert(!Negate && "Valid conjunction/disjunction tree");
2821 
2822     NegateL = false;
2823     NegateR = false;
2824     NegateAfterR = false;
2825     NegateAfterAll = false;
2826   }
2827 
2828   // Emit sub-trees.
2829   AArch64CC::CondCode RHSCC;
2830   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2831   if (NegateAfterR)
2832     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2833   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2834   if (NegateAfterAll)
2835     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2836   return CmpL;
2837 }
2838 
2839 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2840 /// In some cases this is even possible with OR operations in the expression.
2841 /// See \ref AArch64CCMP.
2842 /// \see emitConjunctionRec().
2843 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2844                                AArch64CC::CondCode &OutCC) {
2845   bool DummyCanNegate;
2846   bool DummyMustBeFirst;
2847   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2848     return SDValue();
2849 
2850   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2851 }
2852 
2853 /// @}
2854 
2855 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2856 /// extension operations.
2857 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2858   auto isSupportedExtend = [&](SDValue V) {
2859     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2860       return true;
2861 
2862     if (V.getOpcode() == ISD::AND)
2863       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2864         uint64_t Mask = MaskCst->getZExtValue();
2865         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2866       }
2867 
2868     return false;
2869   };
2870 
2871   if (!Op.hasOneUse())
2872     return 0;
2873 
2874   if (isSupportedExtend(Op))
2875     return 1;
2876 
2877   unsigned Opc = Op.getOpcode();
2878   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2879     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2880       uint64_t Shift = ShiftCst->getZExtValue();
2881       if (isSupportedExtend(Op.getOperand(0)))
2882         return (Shift <= 4) ? 2 : 1;
2883       EVT VT = Op.getValueType();
2884       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2885         return 1;
2886     }
2887 
2888   return 0;
2889 }
2890 
2891 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2892                              SDValue &AArch64cc, SelectionDAG &DAG,
2893                              const SDLoc &dl) {
2894   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2895     EVT VT = RHS.getValueType();
2896     uint64_t C = RHSC->getZExtValue();
2897     if (!isLegalArithImmed(C)) {
2898       // Constant does not fit, try adjusting it by one?
2899       switch (CC) {
2900       default:
2901         break;
2902       case ISD::SETLT:
2903       case ISD::SETGE:
2904         if ((VT == MVT::i32 && C != 0x80000000 &&
2905              isLegalArithImmed((uint32_t)(C - 1))) ||
2906             (VT == MVT::i64 && C != 0x80000000ULL &&
2907              isLegalArithImmed(C - 1ULL))) {
2908           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2909           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2910           RHS = DAG.getConstant(C, dl, VT);
2911         }
2912         break;
2913       case ISD::SETULT:
2914       case ISD::SETUGE:
2915         if ((VT == MVT::i32 && C != 0 &&
2916              isLegalArithImmed((uint32_t)(C - 1))) ||
2917             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2918           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2919           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2920           RHS = DAG.getConstant(C, dl, VT);
2921         }
2922         break;
2923       case ISD::SETLE:
2924       case ISD::SETGT:
2925         if ((VT == MVT::i32 && C != INT32_MAX &&
2926              isLegalArithImmed((uint32_t)(C + 1))) ||
2927             (VT == MVT::i64 && C != INT64_MAX &&
2928              isLegalArithImmed(C + 1ULL))) {
2929           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2930           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2931           RHS = DAG.getConstant(C, dl, VT);
2932         }
2933         break;
2934       case ISD::SETULE:
2935       case ISD::SETUGT:
2936         if ((VT == MVT::i32 && C != UINT32_MAX &&
2937              isLegalArithImmed((uint32_t)(C + 1))) ||
2938             (VT == MVT::i64 && C != UINT64_MAX &&
2939              isLegalArithImmed(C + 1ULL))) {
2940           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2941           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2942           RHS = DAG.getConstant(C, dl, VT);
2943         }
2944         break;
2945       }
2946     }
2947   }
2948 
2949   // Comparisons are canonicalized so that the RHS operand is simpler than the
2950   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2951   // can fold some shift+extend operations on the RHS operand, so swap the
2952   // operands if that can be done.
2953   //
2954   // For example:
2955   //    lsl     w13, w11, #1
2956   //    cmp     w13, w12
2957   // can be turned into:
2958   //    cmp     w12, w11, lsl #1
2959   if (!isa<ConstantSDNode>(RHS) ||
2960       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2961     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2962 
2963     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2964       std::swap(LHS, RHS);
2965       CC = ISD::getSetCCSwappedOperands(CC);
2966     }
2967   }
2968 
2969   SDValue Cmp;
2970   AArch64CC::CondCode AArch64CC;
2971   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2972     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2973 
2974     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2975     // For the i8 operand, the largest immediate is 255, so this can be easily
2976     // encoded in the compare instruction. For the i16 operand, however, the
2977     // largest immediate cannot be encoded in the compare.
2978     // Therefore, use a sign extending load and cmn to avoid materializing the
2979     // -1 constant. For example,
2980     // movz w1, #65535
2981     // ldrh w0, [x0, #0]
2982     // cmp w0, w1
2983     // >
2984     // ldrsh w0, [x0, #0]
2985     // cmn w0, #1
2986     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2987     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2988     // ensure both the LHS and RHS are truly zero extended and to make sure the
2989     // transformation is profitable.
2990     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2991         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2992         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2993         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2994       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2995       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2996         SDValue SExt =
2997             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2998                         DAG.getValueType(MVT::i16));
2999         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
3000                                                    RHS.getValueType()),
3001                              CC, dl, DAG);
3002         AArch64CC = changeIntCCToAArch64CC(CC);
3003       }
3004     }
3005 
3006     if (!Cmp && (RHSC->isZero() || RHSC->isOne())) {
3007       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
3008         if ((CC == ISD::SETNE) ^ RHSC->isZero())
3009           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
3010       }
3011     }
3012   }
3013 
3014   if (!Cmp) {
3015     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3016     AArch64CC = changeIntCCToAArch64CC(CC);
3017   }
3018   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
3019   return Cmp;
3020 }
3021 
3022 static std::pair<SDValue, SDValue>
3023 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
3024   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
3025          "Unsupported value type");
3026   SDValue Value, Overflow;
3027   SDLoc DL(Op);
3028   SDValue LHS = Op.getOperand(0);
3029   SDValue RHS = Op.getOperand(1);
3030   unsigned Opc = 0;
3031   switch (Op.getOpcode()) {
3032   default:
3033     llvm_unreachable("Unknown overflow instruction!");
3034   case ISD::SADDO:
3035     Opc = AArch64ISD::ADDS;
3036     CC = AArch64CC::VS;
3037     break;
3038   case ISD::UADDO:
3039     Opc = AArch64ISD::ADDS;
3040     CC = AArch64CC::HS;
3041     break;
3042   case ISD::SSUBO:
3043     Opc = AArch64ISD::SUBS;
3044     CC = AArch64CC::VS;
3045     break;
3046   case ISD::USUBO:
3047     Opc = AArch64ISD::SUBS;
3048     CC = AArch64CC::LO;
3049     break;
3050   // Multiply needs a little bit extra work.
3051   case ISD::SMULO:
3052   case ISD::UMULO: {
3053     CC = AArch64CC::NE;
3054     bool IsSigned = Op.getOpcode() == ISD::SMULO;
3055     if (Op.getValueType() == MVT::i32) {
3056       // Extend to 64-bits, then perform a 64-bit multiply.
3057       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3058       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
3059       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
3060       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3061       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3062 
3063       // Check that the result fits into a 32-bit integer.
3064       SDVTList VTs = DAG.getVTList(MVT::i64, MVT_CC);
3065       if (IsSigned) {
3066         // cmp xreg, wreg, sxtw
3067         SDValue SExtMul = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Value);
3068         Overflow =
3069             DAG.getNode(AArch64ISD::SUBS, DL, VTs, Mul, SExtMul).getValue(1);
3070       } else {
3071         // tst xreg, #0xffffffff00000000
3072         SDValue UpperBits = DAG.getConstant(0xFFFFFFFF00000000, DL, MVT::i64);
3073         Overflow =
3074             DAG.getNode(AArch64ISD::ANDS, DL, VTs, Mul, UpperBits).getValue(1);
3075       }
3076       break;
3077     }
3078     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
3079     // For the 64 bit multiply
3080     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
3081     if (IsSigned) {
3082       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
3083       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
3084                                       DAG.getConstant(63, DL, MVT::i64));
3085       // It is important that LowerBits is last, otherwise the arithmetic
3086       // shift will not be folded into the compare (SUBS).
3087       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3088       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
3089                      .getValue(1);
3090     } else {
3091       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
3092       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
3093       Overflow =
3094           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
3095                       DAG.getConstant(0, DL, MVT::i64),
3096                       UpperBits).getValue(1);
3097     }
3098     break;
3099   }
3100   } // switch (...)
3101 
3102   if (Opc) {
3103     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
3104 
3105     // Emit the AArch64 operation with overflow check.
3106     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
3107     Overflow = Value.getValue(1);
3108   }
3109   return std::make_pair(Value, Overflow);
3110 }
3111 
3112 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
3113   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3114     return LowerToScalableOp(Op, DAG);
3115 
3116   SDValue Sel = Op.getOperand(0);
3117   SDValue Other = Op.getOperand(1);
3118   SDLoc dl(Sel);
3119 
3120   // If the operand is an overflow checking operation, invert the condition
3121   // code and kill the Not operation. I.e., transform:
3122   // (xor (overflow_op_bool, 1))
3123   //   -->
3124   // (csel 1, 0, invert(cc), overflow_op_bool)
3125   // ... which later gets transformed to just a cset instruction with an
3126   // inverted condition code, rather than a cset + eor sequence.
3127   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
3128     // Only lower legal XALUO ops.
3129     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
3130       return SDValue();
3131 
3132     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3133     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3134     AArch64CC::CondCode CC;
3135     SDValue Value, Overflow;
3136     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
3137     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3138     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
3139                        CCVal, Overflow);
3140   }
3141   // If neither operand is a SELECT_CC, give up.
3142   if (Sel.getOpcode() != ISD::SELECT_CC)
3143     std::swap(Sel, Other);
3144   if (Sel.getOpcode() != ISD::SELECT_CC)
3145     return Op;
3146 
3147   // The folding we want to perform is:
3148   // (xor x, (select_cc a, b, cc, 0, -1) )
3149   //   -->
3150   // (csel x, (xor x, -1), cc ...)
3151   //
3152   // The latter will get matched to a CSINV instruction.
3153 
3154   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
3155   SDValue LHS = Sel.getOperand(0);
3156   SDValue RHS = Sel.getOperand(1);
3157   SDValue TVal = Sel.getOperand(2);
3158   SDValue FVal = Sel.getOperand(3);
3159 
3160   // FIXME: This could be generalized to non-integer comparisons.
3161   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
3162     return Op;
3163 
3164   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3165   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3166 
3167   // The values aren't constants, this isn't the pattern we're looking for.
3168   if (!CFVal || !CTVal)
3169     return Op;
3170 
3171   // We can commute the SELECT_CC by inverting the condition.  This
3172   // might be needed to make this fit into a CSINV pattern.
3173   if (CTVal->isAllOnes() && CFVal->isZero()) {
3174     std::swap(TVal, FVal);
3175     std::swap(CTVal, CFVal);
3176     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
3177   }
3178 
3179   // If the constants line up, perform the transform!
3180   if (CTVal->isZero() && CFVal->isAllOnes()) {
3181     SDValue CCVal;
3182     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3183 
3184     FVal = Other;
3185     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
3186                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
3187 
3188     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
3189                        CCVal, Cmp);
3190   }
3191 
3192   return Op;
3193 }
3194 
3195 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
3196   EVT VT = Op.getValueType();
3197 
3198   // Let legalize expand this if it isn't a legal type yet.
3199   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3200     return SDValue();
3201 
3202   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3203 
3204   unsigned Opc;
3205   bool ExtraOp = false;
3206   switch (Op.getOpcode()) {
3207   default:
3208     llvm_unreachable("Invalid code");
3209   case ISD::ADDC:
3210     Opc = AArch64ISD::ADDS;
3211     break;
3212   case ISD::SUBC:
3213     Opc = AArch64ISD::SUBS;
3214     break;
3215   case ISD::ADDE:
3216     Opc = AArch64ISD::ADCS;
3217     ExtraOp = true;
3218     break;
3219   case ISD::SUBE:
3220     Opc = AArch64ISD::SBCS;
3221     ExtraOp = true;
3222     break;
3223   }
3224 
3225   if (!ExtraOp)
3226     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
3227   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
3228                      Op.getOperand(2));
3229 }
3230 
3231 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
3232   // Let legalize expand this if it isn't a legal type yet.
3233   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3234     return SDValue();
3235 
3236   SDLoc dl(Op);
3237   AArch64CC::CondCode CC;
3238   // The actual operation that sets the overflow or carry flag.
3239   SDValue Value, Overflow;
3240   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
3241 
3242   // We use 0 and 1 as false and true values.
3243   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3244   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3245 
3246   // We use an inverted condition, because the conditional select is inverted
3247   // too. This will allow it to be selected to a single instruction:
3248   // CSINC Wd, WZR, WZR, invert(cond).
3249   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
3250   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
3251                          CCVal, Overflow);
3252 
3253   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3254   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3255 }
3256 
3257 // Prefetch operands are:
3258 // 1: Address to prefetch
3259 // 2: bool isWrite
3260 // 3: int locality (0 = no locality ... 3 = extreme locality)
3261 // 4: bool isDataCache
3262 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
3263   SDLoc DL(Op);
3264   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3265   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
3266   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3267 
3268   bool IsStream = !Locality;
3269   // When the locality number is set
3270   if (Locality) {
3271     // The front-end should have filtered out the out-of-range values
3272     assert(Locality <= 3 && "Prefetch locality out-of-range");
3273     // The locality degree is the opposite of the cache speed.
3274     // Put the number the other way around.
3275     // The encoding starts at 0 for level 1
3276     Locality = 3 - Locality;
3277   }
3278 
3279   // built the mask value encoding the expected behavior.
3280   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
3281                    (!IsData << 3) |     // IsDataCache bit
3282                    (Locality << 1) |    // Cache level bits
3283                    (unsigned)IsStream;  // Stream bit
3284   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
3285                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
3286 }
3287 
3288 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
3289                                               SelectionDAG &DAG) const {
3290   EVT VT = Op.getValueType();
3291   if (VT.isScalableVector())
3292     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
3293 
3294   if (useSVEForFixedLengthVectorVT(VT))
3295     return LowerFixedLengthFPExtendToSVE(Op, DAG);
3296 
3297   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
3298   return SDValue();
3299 }
3300 
3301 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
3302                                              SelectionDAG &DAG) const {
3303   if (Op.getValueType().isScalableVector())
3304     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
3305 
3306   bool IsStrict = Op->isStrictFPOpcode();
3307   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3308   EVT SrcVT = SrcVal.getValueType();
3309 
3310   if (useSVEForFixedLengthVectorVT(SrcVT))
3311     return LowerFixedLengthFPRoundToSVE(Op, DAG);
3312 
3313   if (SrcVT != MVT::f128) {
3314     // Expand cases where the input is a vector bigger than NEON.
3315     if (useSVEForFixedLengthVectorVT(SrcVT))
3316       return SDValue();
3317 
3318     // It's legal except when f128 is involved
3319     return Op;
3320   }
3321 
3322   return SDValue();
3323 }
3324 
3325 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3326                                                     SelectionDAG &DAG) const {
3327   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3328   // Any additional optimization in this function should be recorded
3329   // in the cost tables.
3330   EVT InVT = Op.getOperand(0).getValueType();
3331   EVT VT = Op.getValueType();
3332 
3333   if (VT.isScalableVector()) {
3334     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3335                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3336                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3337     return LowerToPredicatedOp(Op, DAG, Opcode);
3338   }
3339 
3340   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3341     return LowerFixedLengthFPToIntToSVE(Op, DAG);
3342 
3343   unsigned NumElts = InVT.getVectorNumElements();
3344 
3345   // f16 conversions are promoted to f32 when full fp16 is not supported.
3346   if (InVT.getVectorElementType() == MVT::f16 &&
3347       !Subtarget->hasFullFP16()) {
3348     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3349     SDLoc dl(Op);
3350     return DAG.getNode(
3351         Op.getOpcode(), dl, Op.getValueType(),
3352         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3353   }
3354 
3355   uint64_t VTSize = VT.getFixedSizeInBits();
3356   uint64_t InVTSize = InVT.getFixedSizeInBits();
3357   if (VTSize < InVTSize) {
3358     SDLoc dl(Op);
3359     SDValue Cv =
3360         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3361                     Op.getOperand(0));
3362     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3363   }
3364 
3365   if (VTSize > InVTSize) {
3366     SDLoc dl(Op);
3367     MVT ExtVT =
3368         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3369                          VT.getVectorNumElements());
3370     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3371     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3372   }
3373 
3374   // Type changing conversions are illegal.
3375   return Op;
3376 }
3377 
3378 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3379                                               SelectionDAG &DAG) const {
3380   bool IsStrict = Op->isStrictFPOpcode();
3381   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3382 
3383   if (SrcVal.getValueType().isVector())
3384     return LowerVectorFP_TO_INT(Op, DAG);
3385 
3386   // f16 conversions are promoted to f32 when full fp16 is not supported.
3387   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3388     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3389     SDLoc dl(Op);
3390     return DAG.getNode(
3391         Op.getOpcode(), dl, Op.getValueType(),
3392         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3393   }
3394 
3395   if (SrcVal.getValueType() != MVT::f128) {
3396     // It's legal except when f128 is involved
3397     return Op;
3398   }
3399 
3400   return SDValue();
3401 }
3402 
3403 SDValue
3404 AArch64TargetLowering::LowerVectorFP_TO_INT_SAT(SDValue Op,
3405                                                 SelectionDAG &DAG) const {
3406   // AArch64 FP-to-int conversions saturate to the destination element size, so
3407   // we can lower common saturating conversions to simple instructions.
3408   SDValue SrcVal = Op.getOperand(0);
3409   EVT SrcVT = SrcVal.getValueType();
3410   EVT DstVT = Op.getValueType();
3411   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3412 
3413   uint64_t SrcElementWidth = SrcVT.getScalarSizeInBits();
3414   uint64_t DstElementWidth = DstVT.getScalarSizeInBits();
3415   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3416   assert(SatWidth <= DstElementWidth &&
3417          "Saturation width cannot exceed result width");
3418 
3419   // TODO: Consider lowering to SVE operations, as in LowerVectorFP_TO_INT.
3420   // Currently, the `llvm.fpto[su]i.sat.*` instrinsics don't accept scalable
3421   // types, so this is hard to reach.
3422   if (DstVT.isScalableVector())
3423     return SDValue();
3424 
3425   EVT SrcElementVT = SrcVT.getVectorElementType();
3426 
3427   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
3428   if (SrcElementVT == MVT::f16 &&
3429       (!Subtarget->hasFullFP16() || DstElementWidth > 16)) {
3430     MVT F32VT = MVT::getVectorVT(MVT::f32, SrcVT.getVectorNumElements());
3431     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), F32VT, SrcVal);
3432     SrcVT = F32VT;
3433     SrcElementVT = MVT::f32;
3434     SrcElementWidth = 32;
3435   } else if (SrcElementVT != MVT::f64 && SrcElementVT != MVT::f32 &&
3436              SrcElementVT != MVT::f16)
3437     return SDValue();
3438 
3439   SDLoc DL(Op);
3440   // Cases that we can emit directly.
3441   if (SrcElementWidth == DstElementWidth && SrcElementWidth == SatWidth)
3442     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
3443                        DAG.getValueType(DstVT.getScalarType()));
3444 
3445   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
3446   // result. This is only valid if the legal cvt is larger than the saturate
3447   // width. For double, as we don't have MIN/MAX, it can be simpler to scalarize
3448   // (at least until sqxtn is selected).
3449   if (SrcElementWidth < SatWidth || SrcElementVT == MVT::f64)
3450     return SDValue();
3451 
3452   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
3453   SDValue NativeCvt = DAG.getNode(Op.getOpcode(), DL, IntVT, SrcVal,
3454                                   DAG.getValueType(IntVT.getScalarType()));
3455   SDValue Sat;
3456   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
3457     SDValue MinC = DAG.getConstant(
3458         APInt::getSignedMaxValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
3459         IntVT);
3460     SDValue Min = DAG.getNode(ISD::SMIN, DL, IntVT, NativeCvt, MinC);
3461     SDValue MaxC = DAG.getConstant(
3462         APInt::getSignedMinValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
3463         IntVT);
3464     Sat = DAG.getNode(ISD::SMAX, DL, IntVT, Min, MaxC);
3465   } else {
3466     SDValue MinC = DAG.getConstant(
3467         APInt::getAllOnesValue(SatWidth).zextOrSelf(SrcElementWidth), DL,
3468         IntVT);
3469     Sat = DAG.getNode(ISD::UMIN, DL, IntVT, NativeCvt, MinC);
3470   }
3471 
3472   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
3473 }
3474 
3475 SDValue AArch64TargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
3476                                                   SelectionDAG &DAG) const {
3477   // AArch64 FP-to-int conversions saturate to the destination register size, so
3478   // we can lower common saturating conversions to simple instructions.
3479   SDValue SrcVal = Op.getOperand(0);
3480   EVT SrcVT = SrcVal.getValueType();
3481 
3482   if (SrcVT.isVector())
3483     return LowerVectorFP_TO_INT_SAT(Op, DAG);
3484 
3485   EVT DstVT = Op.getValueType();
3486   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3487   uint64_t SatWidth = SatVT.getScalarSizeInBits();
3488   uint64_t DstWidth = DstVT.getScalarSizeInBits();
3489   assert(SatWidth <= DstWidth && "Saturation width cannot exceed result width");
3490 
3491   // In the absence of FP16 support, promote f16 to f32 and saturate the result.
3492   if (SrcVT == MVT::f16 && !Subtarget->hasFullFP16()) {
3493     SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, SrcVal);
3494     SrcVT = MVT::f32;
3495   } else if (SrcVT != MVT::f64 && SrcVT != MVT::f32 && SrcVT != MVT::f16)
3496     return SDValue();
3497 
3498   SDLoc DL(Op);
3499   // Cases that we can emit directly.
3500   if ((SrcVT == MVT::f64 || SrcVT == MVT::f32 ||
3501        (SrcVT == MVT::f16 && Subtarget->hasFullFP16())) &&
3502       DstVT == SatVT && (DstVT == MVT::i64 || DstVT == MVT::i32))
3503     return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
3504                        DAG.getValueType(DstVT));
3505 
3506   // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
3507   // result. This is only valid if the legal cvt is larger than the saturate
3508   // width.
3509   if (DstWidth < SatWidth)
3510     return SDValue();
3511 
3512   SDValue NativeCvt =
3513       DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal, DAG.getValueType(DstVT));
3514   SDValue Sat;
3515   if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
3516     SDValue MinC = DAG.getConstant(
3517         APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
3518     SDValue Min = DAG.getNode(ISD::SMIN, DL, DstVT, NativeCvt, MinC);
3519     SDValue MaxC = DAG.getConstant(
3520         APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
3521     Sat = DAG.getNode(ISD::SMAX, DL, DstVT, Min, MaxC);
3522   } else {
3523     SDValue MinC = DAG.getConstant(
3524         APInt::getAllOnesValue(SatWidth).zextOrSelf(DstWidth), DL, DstVT);
3525     Sat = DAG.getNode(ISD::UMIN, DL, DstVT, NativeCvt, MinC);
3526   }
3527 
3528   return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
3529 }
3530 
3531 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3532                                                     SelectionDAG &DAG) const {
3533   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3534   // Any additional optimization in this function should be recorded
3535   // in the cost tables.
3536   EVT VT = Op.getValueType();
3537   SDLoc dl(Op);
3538   SDValue In = Op.getOperand(0);
3539   EVT InVT = In.getValueType();
3540   unsigned Opc = Op.getOpcode();
3541   bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
3542 
3543   if (VT.isScalableVector()) {
3544     if (InVT.getVectorElementType() == MVT::i1) {
3545       // We can't directly extend an SVE predicate; extend it first.
3546       unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3547       EVT CastVT = getPromotedVTForPredicate(InVT);
3548       In = DAG.getNode(CastOpc, dl, CastVT, In);
3549       return DAG.getNode(Opc, dl, VT, In);
3550     }
3551 
3552     unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
3553                                : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
3554     return LowerToPredicatedOp(Op, DAG, Opcode);
3555   }
3556 
3557   if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
3558     return LowerFixedLengthIntToFPToSVE(Op, DAG);
3559 
3560   uint64_t VTSize = VT.getFixedSizeInBits();
3561   uint64_t InVTSize = InVT.getFixedSizeInBits();
3562   if (VTSize < InVTSize) {
3563     MVT CastVT =
3564         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3565                          InVT.getVectorNumElements());
3566     In = DAG.getNode(Opc, dl, CastVT, In);
3567     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3568   }
3569 
3570   if (VTSize > InVTSize) {
3571     unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3572     EVT CastVT = VT.changeVectorElementTypeToInteger();
3573     In = DAG.getNode(CastOpc, dl, CastVT, In);
3574     return DAG.getNode(Opc, dl, VT, In);
3575   }
3576 
3577   return Op;
3578 }
3579 
3580 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3581                                             SelectionDAG &DAG) const {
3582   if (Op.getValueType().isVector())
3583     return LowerVectorINT_TO_FP(Op, DAG);
3584 
3585   bool IsStrict = Op->isStrictFPOpcode();
3586   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3587 
3588   // f16 conversions are promoted to f32 when full fp16 is not supported.
3589   if (Op.getValueType() == MVT::f16 &&
3590       !Subtarget->hasFullFP16()) {
3591     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3592     SDLoc dl(Op);
3593     return DAG.getNode(
3594         ISD::FP_ROUND, dl, MVT::f16,
3595         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3596         DAG.getIntPtrConstant(0, dl));
3597   }
3598 
3599   // i128 conversions are libcalls.
3600   if (SrcVal.getValueType() == MVT::i128)
3601     return SDValue();
3602 
3603   // Other conversions are legal, unless it's to the completely software-based
3604   // fp128.
3605   if (Op.getValueType() != MVT::f128)
3606     return Op;
3607   return SDValue();
3608 }
3609 
3610 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3611                                             SelectionDAG &DAG) const {
3612   // For iOS, we want to call an alternative entry point: __sincos_stret,
3613   // which returns the values in two S / D registers.
3614   SDLoc dl(Op);
3615   SDValue Arg = Op.getOperand(0);
3616   EVT ArgVT = Arg.getValueType();
3617   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3618 
3619   ArgListTy Args;
3620   ArgListEntry Entry;
3621 
3622   Entry.Node = Arg;
3623   Entry.Ty = ArgTy;
3624   Entry.IsSExt = false;
3625   Entry.IsZExt = false;
3626   Args.push_back(Entry);
3627 
3628   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3629                                         : RTLIB::SINCOS_STRET_F32;
3630   const char *LibcallName = getLibcallName(LC);
3631   SDValue Callee =
3632       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3633 
3634   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3635   TargetLowering::CallLoweringInfo CLI(DAG);
3636   CLI.setDebugLoc(dl)
3637       .setChain(DAG.getEntryNode())
3638       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3639 
3640   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3641   return CallResult.first;
3642 }
3643 
3644 static MVT getSVEContainerType(EVT ContentTy);
3645 
3646 SDValue AArch64TargetLowering::LowerBITCAST(SDValue Op,
3647                                             SelectionDAG &DAG) const {
3648   EVT OpVT = Op.getValueType();
3649   EVT ArgVT = Op.getOperand(0).getValueType();
3650 
3651   if (useSVEForFixedLengthVectorVT(OpVT))
3652     return LowerFixedLengthBitcastToSVE(Op, DAG);
3653 
3654   if (OpVT.isScalableVector()) {
3655     if (isTypeLegal(OpVT) && !isTypeLegal(ArgVT)) {
3656       assert(OpVT.isFloatingPoint() && !ArgVT.isFloatingPoint() &&
3657              "Expected int->fp bitcast!");
3658       SDValue ExtResult =
3659           DAG.getNode(ISD::ANY_EXTEND, SDLoc(Op), getSVEContainerType(ArgVT),
3660                       Op.getOperand(0));
3661       return getSVESafeBitCast(OpVT, ExtResult, DAG);
3662     }
3663     return getSVESafeBitCast(OpVT, Op.getOperand(0), DAG);
3664   }
3665 
3666   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3667     return SDValue();
3668 
3669   assert(ArgVT == MVT::i16);
3670   SDLoc DL(Op);
3671 
3672   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3673   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3674   return SDValue(
3675       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3676                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3677       0);
3678 }
3679 
3680 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3681   if (OrigVT.getSizeInBits() >= 64)
3682     return OrigVT;
3683 
3684   assert(OrigVT.isSimple() && "Expecting a simple value type");
3685 
3686   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3687   switch (OrigSimpleTy) {
3688   default: llvm_unreachable("Unexpected Vector Type");
3689   case MVT::v2i8:
3690   case MVT::v2i16:
3691      return MVT::v2i32;
3692   case MVT::v4i8:
3693     return  MVT::v4i16;
3694   }
3695 }
3696 
3697 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3698                                                  const EVT &OrigTy,
3699                                                  const EVT &ExtTy,
3700                                                  unsigned ExtOpcode) {
3701   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3702   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3703   // 64-bits we need to insert a new extension so that it will be 64-bits.
3704   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3705   if (OrigTy.getSizeInBits() >= 64)
3706     return N;
3707 
3708   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3709   EVT NewVT = getExtensionTo64Bits(OrigTy);
3710 
3711   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3712 }
3713 
3714 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3715                                    bool isSigned) {
3716   EVT VT = N->getValueType(0);
3717 
3718   if (N->getOpcode() != ISD::BUILD_VECTOR)
3719     return false;
3720 
3721   for (const SDValue &Elt : N->op_values()) {
3722     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3723       unsigned EltSize = VT.getScalarSizeInBits();
3724       unsigned HalfSize = EltSize / 2;
3725       if (isSigned) {
3726         if (!isIntN(HalfSize, C->getSExtValue()))
3727           return false;
3728       } else {
3729         if (!isUIntN(HalfSize, C->getZExtValue()))
3730           return false;
3731       }
3732       continue;
3733     }
3734     return false;
3735   }
3736 
3737   return true;
3738 }
3739 
3740 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3741   if (N->getOpcode() == ISD::SIGN_EXTEND ||
3742       N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
3743     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3744                                              N->getOperand(0)->getValueType(0),
3745                                              N->getValueType(0),
3746                                              N->getOpcode());
3747 
3748   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3749   EVT VT = N->getValueType(0);
3750   SDLoc dl(N);
3751   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3752   unsigned NumElts = VT.getVectorNumElements();
3753   MVT TruncVT = MVT::getIntegerVT(EltSize);
3754   SmallVector<SDValue, 8> Ops;
3755   for (unsigned i = 0; i != NumElts; ++i) {
3756     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3757     const APInt &CInt = C->getAPIntValue();
3758     // Element types smaller than 32 bits are not legal, so use i32 elements.
3759     // The values are implicitly truncated so sext vs. zext doesn't matter.
3760     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3761   }
3762   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3763 }
3764 
3765 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3766   return N->getOpcode() == ISD::SIGN_EXTEND ||
3767          N->getOpcode() == ISD::ANY_EXTEND ||
3768          isExtendedBUILD_VECTOR(N, DAG, true);
3769 }
3770 
3771 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3772   return N->getOpcode() == ISD::ZERO_EXTEND ||
3773          N->getOpcode() == ISD::ANY_EXTEND ||
3774          isExtendedBUILD_VECTOR(N, DAG, false);
3775 }
3776 
3777 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3778   unsigned Opcode = N->getOpcode();
3779   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3780     SDNode *N0 = N->getOperand(0).getNode();
3781     SDNode *N1 = N->getOperand(1).getNode();
3782     return N0->hasOneUse() && N1->hasOneUse() &&
3783       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3784   }
3785   return false;
3786 }
3787 
3788 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3789   unsigned Opcode = N->getOpcode();
3790   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3791     SDNode *N0 = N->getOperand(0).getNode();
3792     SDNode *N1 = N->getOperand(1).getNode();
3793     return N0->hasOneUse() && N1->hasOneUse() &&
3794       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3795   }
3796   return false;
3797 }
3798 
3799 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3800                                                 SelectionDAG &DAG) const {
3801   // The rounding mode is in bits 23:22 of the FPSCR.
3802   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3803   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3804   // so that the shift + and get folded into a bitfield extract.
3805   SDLoc dl(Op);
3806 
3807   SDValue Chain = Op.getOperand(0);
3808   SDValue FPCR_64 = DAG.getNode(
3809       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3810       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3811   Chain = FPCR_64.getValue(1);
3812   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3813   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3814                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3815   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3816                               DAG.getConstant(22, dl, MVT::i32));
3817   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3818                             DAG.getConstant(3, dl, MVT::i32));
3819   return DAG.getMergeValues({AND, Chain}, dl);
3820 }
3821 
3822 SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op,
3823                                                  SelectionDAG &DAG) const {
3824   SDLoc DL(Op);
3825   SDValue Chain = Op->getOperand(0);
3826   SDValue RMValue = Op->getOperand(1);
3827 
3828   // The rounding mode is in bits 23:22 of the FPCR.
3829   // The llvm.set.rounding argument value to the rounding mode in FPCR mapping
3830   // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
3831   // ((arg - 1) & 3) << 22).
3832   //
3833   // The argument of llvm.set.rounding must be within the segment [0, 3], so
3834   // NearestTiesToAway (4) is not handled here. It is responsibility of the code
3835   // generated llvm.set.rounding to ensure this condition.
3836 
3837   // Calculate new value of FPCR[23:22].
3838   RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
3839                         DAG.getConstant(1, DL, MVT::i32));
3840   RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
3841                         DAG.getConstant(0x3, DL, MVT::i32));
3842   RMValue =
3843       DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
3844                   DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32));
3845   RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue);
3846 
3847   // Get current value of FPCR.
3848   SDValue Ops[] = {
3849       Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)};
3850   SDValue FPCR =
3851       DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops);
3852   Chain = FPCR.getValue(1);
3853   FPCR = FPCR.getValue(0);
3854 
3855   // Put new rounding mode into FPSCR[23:22].
3856   const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos);
3857   FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR,
3858                      DAG.getConstant(RMMask, DL, MVT::i64));
3859   FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue);
3860   SDValue Ops2[] = {
3861       Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64),
3862       FPCR};
3863   return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
3864 }
3865 
3866 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3867   EVT VT = Op.getValueType();
3868 
3869   // If SVE is available then i64 vector multiplications can also be made legal.
3870   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3871 
3872   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3873     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3874 
3875   // Multiplications are only custom-lowered for 128-bit vectors so that
3876   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3877   assert(VT.is128BitVector() && VT.isInteger() &&
3878          "unexpected type for custom-lowering ISD::MUL");
3879   SDNode *N0 = Op.getOperand(0).getNode();
3880   SDNode *N1 = Op.getOperand(1).getNode();
3881   unsigned NewOpc = 0;
3882   bool isMLA = false;
3883   bool isN0SExt = isSignExtended(N0, DAG);
3884   bool isN1SExt = isSignExtended(N1, DAG);
3885   if (isN0SExt && isN1SExt)
3886     NewOpc = AArch64ISD::SMULL;
3887   else {
3888     bool isN0ZExt = isZeroExtended(N0, DAG);
3889     bool isN1ZExt = isZeroExtended(N1, DAG);
3890     if (isN0ZExt && isN1ZExt)
3891       NewOpc = AArch64ISD::UMULL;
3892     else if (isN1SExt || isN1ZExt) {
3893       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3894       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3895       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3896         NewOpc = AArch64ISD::SMULL;
3897         isMLA = true;
3898       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3899         NewOpc =  AArch64ISD::UMULL;
3900         isMLA = true;
3901       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3902         std::swap(N0, N1);
3903         NewOpc =  AArch64ISD::UMULL;
3904         isMLA = true;
3905       }
3906     }
3907 
3908     if (!NewOpc) {
3909       if (VT == MVT::v2i64)
3910         // Fall through to expand this.  It is not legal.
3911         return SDValue();
3912       else
3913         // Other vector multiplications are legal.
3914         return Op;
3915     }
3916   }
3917 
3918   // Legalize to a S/UMULL instruction
3919   SDLoc DL(Op);
3920   SDValue Op0;
3921   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3922   if (!isMLA) {
3923     Op0 = skipExtensionForVectorMULL(N0, DAG);
3924     assert(Op0.getValueType().is64BitVector() &&
3925            Op1.getValueType().is64BitVector() &&
3926            "unexpected types for extended operands to VMULL");
3927     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3928   }
3929   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3930   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3931   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3932   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3933   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3934   EVT Op1VT = Op1.getValueType();
3935   return DAG.getNode(N0->getOpcode(), DL, VT,
3936                      DAG.getNode(NewOpc, DL, VT,
3937                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3938                      DAG.getNode(NewOpc, DL, VT,
3939                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3940 }
3941 
3942 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3943                                int Pattern) {
3944   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3945                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3946 }
3947 
3948 static SDValue lowerConvertToSVBool(SDValue Op, SelectionDAG &DAG) {
3949   SDLoc DL(Op);
3950   EVT OutVT = Op.getValueType();
3951   SDValue InOp = Op.getOperand(1);
3952   EVT InVT = InOp.getValueType();
3953 
3954   // Return the operand if the cast isn't changing type,
3955   // i.e. <n x 16 x i1> -> <n x 16 x i1>
3956   if (InVT == OutVT)
3957     return InOp;
3958 
3959   SDValue Reinterpret =
3960       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, InOp);
3961 
3962   // If the argument converted to an svbool is a ptrue or a comparison, the
3963   // lanes introduced by the widening are zero by construction.
3964   switch (InOp.getOpcode()) {
3965   case AArch64ISD::SETCC_MERGE_ZERO:
3966     return Reinterpret;
3967   case ISD::INTRINSIC_WO_CHAIN:
3968     if (InOp.getConstantOperandVal(0) == Intrinsic::aarch64_sve_ptrue)
3969       return Reinterpret;
3970   }
3971 
3972   // Otherwise, zero the newly introduced lanes.
3973   SDValue Mask = getPTrue(DAG, DL, InVT, AArch64SVEPredPattern::all);
3974   SDValue MaskReinterpret =
3975       DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, Mask);
3976   return DAG.getNode(ISD::AND, DL, OutVT, Reinterpret, MaskReinterpret);
3977 }
3978 
3979 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3980                                                      SelectionDAG &DAG) const {
3981   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3982   SDLoc dl(Op);
3983   switch (IntNo) {
3984   default: return SDValue();    // Don't custom lower most intrinsics.
3985   case Intrinsic::thread_pointer: {
3986     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3987     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3988   }
3989   case Intrinsic::aarch64_neon_abs: {
3990     EVT Ty = Op.getValueType();
3991     if (Ty == MVT::i64) {
3992       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3993                                    Op.getOperand(1));
3994       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3995       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3996     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3997       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3998     } else {
3999       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
4000     }
4001   }
4002   case Intrinsic::aarch64_neon_smax:
4003     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
4004                        Op.getOperand(1), Op.getOperand(2));
4005   case Intrinsic::aarch64_neon_umax:
4006     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
4007                        Op.getOperand(1), Op.getOperand(2));
4008   case Intrinsic::aarch64_neon_smin:
4009     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
4010                        Op.getOperand(1), Op.getOperand(2));
4011   case Intrinsic::aarch64_neon_umin:
4012     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
4013                        Op.getOperand(1), Op.getOperand(2));
4014 
4015   case Intrinsic::aarch64_sve_sunpkhi:
4016     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
4017                        Op.getOperand(1));
4018   case Intrinsic::aarch64_sve_sunpklo:
4019     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
4020                        Op.getOperand(1));
4021   case Intrinsic::aarch64_sve_uunpkhi:
4022     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
4023                        Op.getOperand(1));
4024   case Intrinsic::aarch64_sve_uunpklo:
4025     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
4026                        Op.getOperand(1));
4027   case Intrinsic::aarch64_sve_clasta_n:
4028     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
4029                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4030   case Intrinsic::aarch64_sve_clastb_n:
4031     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
4032                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4033   case Intrinsic::aarch64_sve_lasta:
4034     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
4035                        Op.getOperand(1), Op.getOperand(2));
4036   case Intrinsic::aarch64_sve_lastb:
4037     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
4038                        Op.getOperand(1), Op.getOperand(2));
4039   case Intrinsic::aarch64_sve_rev:
4040     return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
4041                        Op.getOperand(1));
4042   case Intrinsic::aarch64_sve_tbl:
4043     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
4044                        Op.getOperand(1), Op.getOperand(2));
4045   case Intrinsic::aarch64_sve_trn1:
4046     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
4047                        Op.getOperand(1), Op.getOperand(2));
4048   case Intrinsic::aarch64_sve_trn2:
4049     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
4050                        Op.getOperand(1), Op.getOperand(2));
4051   case Intrinsic::aarch64_sve_uzp1:
4052     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
4053                        Op.getOperand(1), Op.getOperand(2));
4054   case Intrinsic::aarch64_sve_uzp2:
4055     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
4056                        Op.getOperand(1), Op.getOperand(2));
4057   case Intrinsic::aarch64_sve_zip1:
4058     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
4059                        Op.getOperand(1), Op.getOperand(2));
4060   case Intrinsic::aarch64_sve_zip2:
4061     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
4062                        Op.getOperand(1), Op.getOperand(2));
4063   case Intrinsic::aarch64_sve_splice:
4064     return DAG.getNode(AArch64ISD::SPLICE, dl, Op.getValueType(),
4065                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4066   case Intrinsic::aarch64_sve_ptrue:
4067     return getPTrue(DAG, dl, Op.getValueType(),
4068                     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
4069   case Intrinsic::aarch64_sve_clz:
4070     return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
4071                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4072   case Intrinsic::aarch64_sve_cnt: {
4073     SDValue Data = Op.getOperand(3);
4074     // CTPOP only supports integer operands.
4075     if (Data.getValueType().isFloatingPoint())
4076       Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
4077     return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
4078                        Op.getOperand(2), Data, Op.getOperand(1));
4079   }
4080   case Intrinsic::aarch64_sve_dupq_lane:
4081     return LowerDUPQLane(Op, DAG);
4082   case Intrinsic::aarch64_sve_convert_from_svbool:
4083     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
4084                        Op.getOperand(1));
4085   case Intrinsic::aarch64_sve_convert_to_svbool:
4086     return lowerConvertToSVBool(Op, DAG);
4087   case Intrinsic::aarch64_sve_fneg:
4088     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4089                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4090   case Intrinsic::aarch64_sve_frintp:
4091     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
4092                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4093   case Intrinsic::aarch64_sve_frintm:
4094     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
4095                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4096   case Intrinsic::aarch64_sve_frinti:
4097     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4098                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4099   case Intrinsic::aarch64_sve_frintx:
4100     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
4101                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4102   case Intrinsic::aarch64_sve_frinta:
4103     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
4104                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4105   case Intrinsic::aarch64_sve_frintn:
4106     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
4107                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4108   case Intrinsic::aarch64_sve_frintz:
4109     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
4110                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4111   case Intrinsic::aarch64_sve_ucvtf:
4112     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
4113                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4114                        Op.getOperand(1));
4115   case Intrinsic::aarch64_sve_scvtf:
4116     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
4117                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4118                        Op.getOperand(1));
4119   case Intrinsic::aarch64_sve_fcvtzu:
4120     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
4121                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4122                        Op.getOperand(1));
4123   case Intrinsic::aarch64_sve_fcvtzs:
4124     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
4125                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4126                        Op.getOperand(1));
4127   case Intrinsic::aarch64_sve_fsqrt:
4128     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
4129                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4130   case Intrinsic::aarch64_sve_frecpx:
4131     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
4132                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4133   case Intrinsic::aarch64_sve_frecpe_x:
4134     return DAG.getNode(AArch64ISD::FRECPE, dl, Op.getValueType(),
4135                        Op.getOperand(1));
4136   case Intrinsic::aarch64_sve_frecps_x:
4137     return DAG.getNode(AArch64ISD::FRECPS, dl, Op.getValueType(),
4138                        Op.getOperand(1), Op.getOperand(2));
4139   case Intrinsic::aarch64_sve_frsqrte_x:
4140     return DAG.getNode(AArch64ISD::FRSQRTE, dl, Op.getValueType(),
4141                        Op.getOperand(1));
4142   case Intrinsic::aarch64_sve_frsqrts_x:
4143     return DAG.getNode(AArch64ISD::FRSQRTS, dl, Op.getValueType(),
4144                        Op.getOperand(1), Op.getOperand(2));
4145   case Intrinsic::aarch64_sve_fabs:
4146     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4147                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4148   case Intrinsic::aarch64_sve_abs:
4149     return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
4150                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4151   case Intrinsic::aarch64_sve_neg:
4152     return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
4153                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4154   case Intrinsic::aarch64_sve_insr: {
4155     SDValue Scalar = Op.getOperand(2);
4156     EVT ScalarTy = Scalar.getValueType();
4157     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
4158       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
4159 
4160     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
4161                        Op.getOperand(1), Scalar);
4162   }
4163   case Intrinsic::aarch64_sve_rbit:
4164     return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
4165                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
4166                        Op.getOperand(1));
4167   case Intrinsic::aarch64_sve_revb:
4168     return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
4169                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
4170   case Intrinsic::aarch64_sve_sxtb:
4171     return DAG.getNode(
4172         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4173         Op.getOperand(2), Op.getOperand(3),
4174         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4175         Op.getOperand(1));
4176   case Intrinsic::aarch64_sve_sxth:
4177     return DAG.getNode(
4178         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4179         Op.getOperand(2), Op.getOperand(3),
4180         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4181         Op.getOperand(1));
4182   case Intrinsic::aarch64_sve_sxtw:
4183     return DAG.getNode(
4184         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4185         Op.getOperand(2), Op.getOperand(3),
4186         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4187         Op.getOperand(1));
4188   case Intrinsic::aarch64_sve_uxtb:
4189     return DAG.getNode(
4190         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4191         Op.getOperand(2), Op.getOperand(3),
4192         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
4193         Op.getOperand(1));
4194   case Intrinsic::aarch64_sve_uxth:
4195     return DAG.getNode(
4196         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4197         Op.getOperand(2), Op.getOperand(3),
4198         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
4199         Op.getOperand(1));
4200   case Intrinsic::aarch64_sve_uxtw:
4201     return DAG.getNode(
4202         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
4203         Op.getOperand(2), Op.getOperand(3),
4204         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
4205         Op.getOperand(1));
4206 
4207   case Intrinsic::localaddress: {
4208     const auto &MF = DAG.getMachineFunction();
4209     const auto *RegInfo = Subtarget->getRegisterInfo();
4210     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
4211     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
4212                               Op.getSimpleValueType());
4213   }
4214 
4215   case Intrinsic::eh_recoverfp: {
4216     // FIXME: This needs to be implemented to correctly handle highly aligned
4217     // stack objects. For now we simply return the incoming FP. Refer D53541
4218     // for more details.
4219     SDValue FnOp = Op.getOperand(1);
4220     SDValue IncomingFPOp = Op.getOperand(2);
4221     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
4222     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
4223     if (!Fn)
4224       report_fatal_error(
4225           "llvm.eh.recoverfp must take a function as the first argument");
4226     return IncomingFPOp;
4227   }
4228 
4229   case Intrinsic::aarch64_neon_vsri:
4230   case Intrinsic::aarch64_neon_vsli: {
4231     EVT Ty = Op.getValueType();
4232 
4233     if (!Ty.isVector())
4234       report_fatal_error("Unexpected type for aarch64_neon_vsli");
4235 
4236     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
4237 
4238     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
4239     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
4240     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
4241                        Op.getOperand(3));
4242   }
4243 
4244   case Intrinsic::aarch64_neon_srhadd:
4245   case Intrinsic::aarch64_neon_urhadd:
4246   case Intrinsic::aarch64_neon_shadd:
4247   case Intrinsic::aarch64_neon_uhadd: {
4248     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4249                         IntNo == Intrinsic::aarch64_neon_shadd);
4250     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
4251                           IntNo == Intrinsic::aarch64_neon_urhadd);
4252     unsigned Opcode =
4253         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
4254                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
4255     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4256                        Op.getOperand(2));
4257   }
4258   case Intrinsic::aarch64_neon_sabd:
4259   case Intrinsic::aarch64_neon_uabd: {
4260     unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? ISD::ABDU
4261                                                             : ISD::ABDS;
4262     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4263                        Op.getOperand(2));
4264   }
4265   case Intrinsic::aarch64_neon_uaddlp: {
4266     unsigned Opcode = AArch64ISD::UADDLP;
4267     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1));
4268   }
4269   case Intrinsic::aarch64_neon_sdot:
4270   case Intrinsic::aarch64_neon_udot:
4271   case Intrinsic::aarch64_sve_sdot:
4272   case Intrinsic::aarch64_sve_udot: {
4273     unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot ||
4274                        IntNo == Intrinsic::aarch64_sve_udot)
4275                           ? AArch64ISD::UDOT
4276                           : AArch64ISD::SDOT;
4277     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
4278                        Op.getOperand(2), Op.getOperand(3));
4279   }
4280   }
4281 }
4282 
4283 bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
4284   if (VT.getVectorElementType() == MVT::i8 ||
4285       VT.getVectorElementType() == MVT::i16) {
4286     EltTy = MVT::i32;
4287     return true;
4288   }
4289   return false;
4290 }
4291 
4292 bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
4293   if (VT.getVectorElementType() == MVT::i32 &&
4294       VT.getVectorElementCount().getKnownMinValue() >= 4 &&
4295       !VT.isFixedLengthVector())
4296     return true;
4297 
4298   return false;
4299 }
4300 
4301 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
4302   return ExtVal.getValueType().isScalableVector() ||
4303          useSVEForFixedLengthVectorVT(ExtVal.getValueType(),
4304                                       /*OverrideNEON=*/true);
4305 }
4306 
4307 unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4308   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4309       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4310        AArch64ISD::GLD1_MERGE_ZERO},
4311       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4312        AArch64ISD::GLD1_UXTW_MERGE_ZERO},
4313       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4314        AArch64ISD::GLD1_MERGE_ZERO},
4315       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4316        AArch64ISD::GLD1_SXTW_MERGE_ZERO},
4317       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4318        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4319       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4320        AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
4321       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4322        AArch64ISD::GLD1_SCALED_MERGE_ZERO},
4323       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4324        AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
4325   };
4326   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4327   return AddrModes.find(Key)->second;
4328 }
4329 
4330 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
4331   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
4332       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
4333        AArch64ISD::SST1_PRED},
4334       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
4335        AArch64ISD::SST1_UXTW_PRED},
4336       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
4337        AArch64ISD::SST1_PRED},
4338       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
4339        AArch64ISD::SST1_SXTW_PRED},
4340       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
4341        AArch64ISD::SST1_SCALED_PRED},
4342       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
4343        AArch64ISD::SST1_UXTW_SCALED_PRED},
4344       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
4345        AArch64ISD::SST1_SCALED_PRED},
4346       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
4347        AArch64ISD::SST1_SXTW_SCALED_PRED},
4348   };
4349   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
4350   return AddrModes.find(Key)->second;
4351 }
4352 
4353 unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
4354   switch (Opcode) {
4355   default:
4356     llvm_unreachable("unimplemented opcode");
4357     return Opcode;
4358   case AArch64ISD::GLD1_MERGE_ZERO:
4359     return AArch64ISD::GLD1S_MERGE_ZERO;
4360   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
4361     return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
4362   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
4363     return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
4364   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
4365     return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
4366   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
4367     return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
4368   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
4369     return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
4370   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
4371     return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
4372   }
4373 }
4374 
4375 bool getGatherScatterIndexIsExtended(SDValue Index) {
4376   unsigned Opcode = Index.getOpcode();
4377   if (Opcode == ISD::SIGN_EXTEND_INREG)
4378     return true;
4379 
4380   if (Opcode == ISD::AND) {
4381     SDValue Splat = Index.getOperand(1);
4382     if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
4383       return false;
4384     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
4385     if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
4386       return false;
4387     return true;
4388   }
4389 
4390   return false;
4391 }
4392 
4393 // If the base pointer of a masked gather or scatter is null, we
4394 // may be able to swap BasePtr & Index and use the vector + register
4395 // or vector + immediate addressing mode, e.g.
4396 // VECTOR + REGISTER:
4397 //    getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
4398 // -> getelementptr %offset, <vscale x N x T> %indices
4399 // VECTOR + IMMEDIATE:
4400 //    getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
4401 // -> getelementptr #x, <vscale x N x T> %indices
4402 void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
4403                                  unsigned &Opcode, bool IsGather,
4404                                  SelectionDAG &DAG) {
4405   if (!isNullConstant(BasePtr))
4406     return;
4407 
4408   // FIXME: This will not match for fixed vector type codegen as the nodes in
4409   // question will have fixed<->scalable conversions around them. This should be
4410   // moved to a DAG combine or complex pattern so that is executes after all of
4411   // the fixed vector insert and extracts have been removed. This deficiency
4412   // will result in a sub-optimal addressing mode being used, i.e. an ADD not
4413   // being folded into the scatter/gather.
4414   ConstantSDNode *Offset = nullptr;
4415   if (Index.getOpcode() == ISD::ADD)
4416     if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
4417       if (isa<ConstantSDNode>(SplatVal))
4418         Offset = cast<ConstantSDNode>(SplatVal);
4419       else {
4420         BasePtr = SplatVal;
4421         Index = Index->getOperand(0);
4422         return;
4423       }
4424     }
4425 
4426   unsigned NewOp =
4427       IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
4428 
4429   if (!Offset) {
4430     std::swap(BasePtr, Index);
4431     Opcode = NewOp;
4432     return;
4433   }
4434 
4435   uint64_t OffsetVal = Offset->getZExtValue();
4436   unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
4437   auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
4438 
4439   if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
4440     // Index is out of range for the immediate addressing mode
4441     BasePtr = ConstOffset;
4442     Index = Index->getOperand(0);
4443     return;
4444   }
4445 
4446   // Immediate is in range
4447   Opcode = NewOp;
4448   BasePtr = Index->getOperand(0);
4449   Index = ConstOffset;
4450 }
4451 
4452 SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
4453                                             SelectionDAG &DAG) const {
4454   SDLoc DL(Op);
4455   MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
4456   assert(MGT && "Can only custom lower gather load nodes");
4457 
4458   bool IsFixedLength = MGT->getMemoryVT().isFixedLengthVector();
4459 
4460   SDValue Index = MGT->getIndex();
4461   SDValue Chain = MGT->getChain();
4462   SDValue PassThru = MGT->getPassThru();
4463   SDValue Mask = MGT->getMask();
4464   SDValue BasePtr = MGT->getBasePtr();
4465   ISD::LoadExtType ExtTy = MGT->getExtensionType();
4466 
4467   ISD::MemIndexType IndexType = MGT->getIndexType();
4468   bool IsScaled =
4469       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4470   bool IsSigned =
4471       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4472   bool IdxNeedsExtend =
4473       getGatherScatterIndexIsExtended(Index) ||
4474       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4475   bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
4476 
4477   EVT VT = PassThru.getSimpleValueType();
4478   EVT IndexVT = Index.getSimpleValueType();
4479   EVT MemVT = MGT->getMemoryVT();
4480   SDValue InputVT = DAG.getValueType(MemVT);
4481 
4482   if (VT.getVectorElementType() == MVT::bf16 &&
4483       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4484     return SDValue();
4485 
4486   if (IsFixedLength) {
4487     assert(Subtarget->useSVEForFixedLengthVectors() &&
4488            "Cannot lower when not using SVE for fixed vectors");
4489     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4490       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4491       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4492     } else {
4493       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4494       IndexVT = MemVT.changeTypeToInteger();
4495     }
4496     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4497     Mask = DAG.getNode(
4498         ISD::ZERO_EXTEND, DL,
4499         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4500   }
4501 
4502   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4503     PassThru = SDValue();
4504 
4505   if (VT.isFloatingPoint() && !IsFixedLength) {
4506     // Handle FP data by using an integer gather and casting the result.
4507     if (PassThru) {
4508       EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4509       PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
4510     }
4511     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4512   }
4513 
4514   SDVTList VTs = DAG.getVTList(IndexVT, MVT::Other);
4515 
4516   if (getGatherScatterIndexIsExtended(Index))
4517     Index = Index.getOperand(0);
4518 
4519   unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
4520   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4521                               /*isGather=*/true, DAG);
4522 
4523   if (ResNeedsSignExtend)
4524     Opcode = getSignExtendedGatherOpcode(Opcode);
4525 
4526   if (IsFixedLength) {
4527     if (Index.getSimpleValueType().isFixedLengthVector())
4528       Index = convertToScalableVector(DAG, IndexVT, Index);
4529     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4530       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4531     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4532   }
4533 
4534   SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT};
4535   SDValue Result = DAG.getNode(Opcode, DL, VTs, Ops);
4536   Chain = Result.getValue(1);
4537 
4538   if (IsFixedLength) {
4539     Result = convertFromScalableVector(
4540         DAG, VT.changeVectorElementType(IndexVT.getVectorElementType()),
4541         Result);
4542     Result = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Result);
4543     Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
4544 
4545     if (PassThru)
4546       Result = DAG.getSelect(DL, VT, MGT->getMask(), Result, PassThru);
4547   } else {
4548     if (PassThru)
4549       Result = DAG.getSelect(DL, IndexVT, Mask, Result, PassThru);
4550 
4551     if (VT.isFloatingPoint())
4552       Result = getSVESafeBitCast(VT, Result, DAG);
4553   }
4554 
4555   return DAG.getMergeValues({Result, Chain}, DL);
4556 }
4557 
4558 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
4559                                              SelectionDAG &DAG) const {
4560   SDLoc DL(Op);
4561   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
4562   assert(MSC && "Can only custom lower scatter store nodes");
4563 
4564   bool IsFixedLength = MSC->getMemoryVT().isFixedLengthVector();
4565 
4566   SDValue Index = MSC->getIndex();
4567   SDValue Chain = MSC->getChain();
4568   SDValue StoreVal = MSC->getValue();
4569   SDValue Mask = MSC->getMask();
4570   SDValue BasePtr = MSC->getBasePtr();
4571 
4572   ISD::MemIndexType IndexType = MSC->getIndexType();
4573   bool IsScaled =
4574       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
4575   bool IsSigned =
4576       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
4577   bool NeedsExtend =
4578       getGatherScatterIndexIsExtended(Index) ||
4579       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
4580 
4581   EVT VT = StoreVal.getSimpleValueType();
4582   EVT IndexVT = Index.getSimpleValueType();
4583   SDVTList VTs = DAG.getVTList(MVT::Other);
4584   EVT MemVT = MSC->getMemoryVT();
4585   SDValue InputVT = DAG.getValueType(MemVT);
4586 
4587   if (VT.getVectorElementType() == MVT::bf16 &&
4588       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
4589     return SDValue();
4590 
4591   if (IsFixedLength) {
4592     assert(Subtarget->useSVEForFixedLengthVectors() &&
4593            "Cannot lower when not using SVE for fixed vectors");
4594     if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
4595       IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
4596       MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
4597     } else {
4598       MemVT = getContainerForFixedLengthVector(DAG, MemVT);
4599       IndexVT = MemVT.changeTypeToInteger();
4600     }
4601     InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
4602 
4603     StoreVal =
4604         DAG.getNode(ISD::BITCAST, DL, VT.changeTypeToInteger(), StoreVal);
4605     StoreVal = DAG.getNode(
4606         ISD::ANY_EXTEND, DL,
4607         VT.changeVectorElementType(IndexVT.getVectorElementType()), StoreVal);
4608     StoreVal = convertToScalableVector(DAG, IndexVT, StoreVal);
4609     Mask = DAG.getNode(
4610         ISD::ZERO_EXTEND, DL,
4611         VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
4612   } else if (VT.isFloatingPoint()) {
4613     // Handle FP data by casting the data so an integer scatter can be used.
4614     EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
4615     StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
4616     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
4617   }
4618 
4619   if (getGatherScatterIndexIsExtended(Index))
4620     Index = Index.getOperand(0);
4621 
4622   unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
4623   selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
4624                               /*isGather=*/false, DAG);
4625 
4626   if (IsFixedLength) {
4627     if (Index.getSimpleValueType().isFixedLengthVector())
4628       Index = convertToScalableVector(DAG, IndexVT, Index);
4629     if (BasePtr.getSimpleValueType().isFixedLengthVector())
4630       BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
4631     Mask = convertFixedMaskToScalableVector(Mask, DAG);
4632   }
4633 
4634   SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
4635   return DAG.getNode(Opcode, DL, VTs, Ops);
4636 }
4637 
4638 SDValue AArch64TargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
4639   SDLoc DL(Op);
4640   MaskedLoadSDNode *LoadNode = cast<MaskedLoadSDNode>(Op);
4641   assert(LoadNode && "Expected custom lowering of a masked load node");
4642   EVT VT = Op->getValueType(0);
4643 
4644   if (useSVEForFixedLengthVectorVT(VT, true))
4645     return LowerFixedLengthVectorMLoadToSVE(Op, DAG);
4646 
4647   SDValue PassThru = LoadNode->getPassThru();
4648   SDValue Mask = LoadNode->getMask();
4649 
4650   if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
4651     return Op;
4652 
4653   SDValue Load = DAG.getMaskedLoad(
4654       VT, DL, LoadNode->getChain(), LoadNode->getBasePtr(),
4655       LoadNode->getOffset(), Mask, DAG.getUNDEF(VT), LoadNode->getMemoryVT(),
4656       LoadNode->getMemOperand(), LoadNode->getAddressingMode(),
4657       LoadNode->getExtensionType());
4658 
4659   SDValue Result = DAG.getSelect(DL, VT, Mask, Load, PassThru);
4660 
4661   return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
4662 }
4663 
4664 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
4665 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
4666                                         EVT VT, EVT MemVT,
4667                                         SelectionDAG &DAG) {
4668   assert(VT.isVector() && "VT should be a vector type");
4669   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
4670 
4671   SDValue Value = ST->getValue();
4672 
4673   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
4674   // the word lane which represent the v4i8 subvector.  It optimizes the store
4675   // to:
4676   //
4677   //   xtn  v0.8b, v0.8h
4678   //   str  s0, [x0]
4679 
4680   SDValue Undef = DAG.getUNDEF(MVT::i16);
4681   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
4682                                         {Undef, Undef, Undef, Undef});
4683 
4684   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
4685                                  Value, UndefVec);
4686   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
4687 
4688   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
4689   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
4690                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
4691 
4692   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
4693                       ST->getBasePtr(), ST->getMemOperand());
4694 }
4695 
4696 // Custom lowering for any store, vector or scalar and/or default or with
4697 // a truncate operations.  Currently only custom lower truncate operation
4698 // from vector v4i16 to v4i8 or volatile stores of i128.
4699 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
4700                                           SelectionDAG &DAG) const {
4701   SDLoc Dl(Op);
4702   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
4703   assert (StoreNode && "Can only custom lower store nodes");
4704 
4705   SDValue Value = StoreNode->getValue();
4706 
4707   EVT VT = Value.getValueType();
4708   EVT MemVT = StoreNode->getMemoryVT();
4709 
4710   if (VT.isVector()) {
4711     if (useSVEForFixedLengthVectorVT(VT, true))
4712       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
4713 
4714     unsigned AS = StoreNode->getAddressSpace();
4715     Align Alignment = StoreNode->getAlign();
4716     if (Alignment < MemVT.getStoreSize() &&
4717         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
4718                                         StoreNode->getMemOperand()->getFlags(),
4719                                         nullptr)) {
4720       return scalarizeVectorStore(StoreNode, DAG);
4721     }
4722 
4723     if (StoreNode->isTruncatingStore() && VT == MVT::v4i16 &&
4724         MemVT == MVT::v4i8) {
4725       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
4726     }
4727     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
4728     // the custom lowering, as there are no un-paired non-temporal stores and
4729     // legalization will break up 256 bit inputs.
4730     ElementCount EC = MemVT.getVectorElementCount();
4731     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
4732         EC.isKnownEven() &&
4733         ((MemVT.getScalarSizeInBits() == 8u ||
4734           MemVT.getScalarSizeInBits() == 16u ||
4735           MemVT.getScalarSizeInBits() == 32u ||
4736           MemVT.getScalarSizeInBits() == 64u))) {
4737       SDValue Lo =
4738           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4739                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4740                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
4741       SDValue Hi =
4742           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
4743                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
4744                       StoreNode->getValue(),
4745                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
4746       SDValue Result = DAG.getMemIntrinsicNode(
4747           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
4748           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4749           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4750       return Result;
4751     }
4752   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
4753     return LowerStore128(Op, DAG);
4754   } else if (MemVT == MVT::i64x8) {
4755     SDValue Value = StoreNode->getValue();
4756     assert(Value->getValueType(0) == MVT::i64x8);
4757     SDValue Chain = StoreNode->getChain();
4758     SDValue Base = StoreNode->getBasePtr();
4759     EVT PtrVT = Base.getValueType();
4760     for (unsigned i = 0; i < 8; i++) {
4761       SDValue Part = DAG.getNode(AArch64ISD::LS64_EXTRACT, Dl, MVT::i64,
4762                                  Value, DAG.getConstant(i, Dl, MVT::i32));
4763       SDValue Ptr = DAG.getNode(ISD::ADD, Dl, PtrVT, Base,
4764                                 DAG.getConstant(i * 8, Dl, PtrVT));
4765       Chain = DAG.getStore(Chain, Dl, Part, Ptr, StoreNode->getPointerInfo(),
4766                            StoreNode->getOriginalAlign());
4767     }
4768     return Chain;
4769   }
4770 
4771   return SDValue();
4772 }
4773 
4774 /// Lower atomic or volatile 128-bit stores to a single STP instruction.
4775 SDValue AArch64TargetLowering::LowerStore128(SDValue Op,
4776                                              SelectionDAG &DAG) const {
4777   MemSDNode *StoreNode = cast<MemSDNode>(Op);
4778   assert(StoreNode->getMemoryVT() == MVT::i128);
4779   assert(StoreNode->isVolatile() || StoreNode->isAtomic());
4780   assert(!StoreNode->isAtomic() ||
4781          StoreNode->getMergedOrdering() == AtomicOrdering::Unordered ||
4782          StoreNode->getMergedOrdering() == AtomicOrdering::Monotonic);
4783 
4784   SDValue Value = StoreNode->getOpcode() == ISD::STORE
4785                       ? StoreNode->getOperand(1)
4786                       : StoreNode->getOperand(2);
4787   SDLoc DL(Op);
4788   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4789                            DAG.getConstant(0, DL, MVT::i64));
4790   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
4791                            DAG.getConstant(1, DL, MVT::i64));
4792   SDValue Result = DAG.getMemIntrinsicNode(
4793       AArch64ISD::STP, DL, DAG.getVTList(MVT::Other),
4794       {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
4795       StoreNode->getMemoryVT(), StoreNode->getMemOperand());
4796   return Result;
4797 }
4798 
4799 SDValue AArch64TargetLowering::LowerLOAD(SDValue Op,
4800                                          SelectionDAG &DAG) const {
4801   SDLoc DL(Op);
4802   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
4803   assert(LoadNode && "Expected custom lowering of a load node");
4804 
4805   if (LoadNode->getMemoryVT() == MVT::i64x8) {
4806     SmallVector<SDValue, 8> Ops;
4807     SDValue Base = LoadNode->getBasePtr();
4808     SDValue Chain = LoadNode->getChain();
4809     EVT PtrVT = Base.getValueType();
4810     for (unsigned i = 0; i < 8; i++) {
4811       SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
4812                                 DAG.getConstant(i * 8, DL, PtrVT));
4813       SDValue Part = DAG.getLoad(MVT::i64, DL, Chain, Ptr,
4814                                  LoadNode->getPointerInfo(),
4815                                  LoadNode->getOriginalAlign());
4816       Ops.push_back(Part);
4817       Chain = SDValue(Part.getNode(), 1);
4818     }
4819     SDValue Loaded = DAG.getNode(AArch64ISD::LS64_BUILD, DL, MVT::i64x8, Ops);
4820     return DAG.getMergeValues({Loaded, Chain}, DL);
4821   }
4822 
4823   // Custom lowering for extending v4i8 vector loads.
4824   EVT VT = Op->getValueType(0);
4825   assert((VT == MVT::v4i16 || VT == MVT::v4i32) && "Expected v4i16 or v4i32");
4826 
4827   if (LoadNode->getMemoryVT() != MVT::v4i8)
4828     return SDValue();
4829 
4830   unsigned ExtType;
4831   if (LoadNode->getExtensionType() == ISD::SEXTLOAD)
4832     ExtType = ISD::SIGN_EXTEND;
4833   else if (LoadNode->getExtensionType() == ISD::ZEXTLOAD ||
4834            LoadNode->getExtensionType() == ISD::EXTLOAD)
4835     ExtType = ISD::ZERO_EXTEND;
4836   else
4837     return SDValue();
4838 
4839   SDValue Load = DAG.getLoad(MVT::f32, DL, LoadNode->getChain(),
4840                              LoadNode->getBasePtr(), MachinePointerInfo());
4841   SDValue Chain = Load.getValue(1);
4842   SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f32, Load);
4843   SDValue BC = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Vec);
4844   SDValue Ext = DAG.getNode(ExtType, DL, MVT::v8i16, BC);
4845   Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Ext,
4846                     DAG.getConstant(0, DL, MVT::i64));
4847   if (VT == MVT::v4i32)
4848     Ext = DAG.getNode(ExtType, DL, MVT::v4i32, Ext);
4849   return DAG.getMergeValues({Ext, Chain}, DL);
4850 }
4851 
4852 // Generate SUBS and CSEL for integer abs.
4853 SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
4854   MVT VT = Op.getSimpleValueType();
4855 
4856   if (VT.isVector())
4857     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
4858 
4859   SDLoc DL(Op);
4860   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
4861                             Op.getOperand(0));
4862   // Generate SUBS & CSEL.
4863   SDValue Cmp =
4864       DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
4865                   Op.getOperand(0), DAG.getConstant(0, DL, VT));
4866   return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
4867                      DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
4868                      Cmp.getValue(1));
4869 }
4870 
4871 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
4872                                               SelectionDAG &DAG) const {
4873   LLVM_DEBUG(dbgs() << "Custom lowering: ");
4874   LLVM_DEBUG(Op.dump());
4875 
4876   switch (Op.getOpcode()) {
4877   default:
4878     llvm_unreachable("unimplemented operand");
4879     return SDValue();
4880   case ISD::BITCAST:
4881     return LowerBITCAST(Op, DAG);
4882   case ISD::GlobalAddress:
4883     return LowerGlobalAddress(Op, DAG);
4884   case ISD::GlobalTLSAddress:
4885     return LowerGlobalTLSAddress(Op, DAG);
4886   case ISD::SETCC:
4887   case ISD::STRICT_FSETCC:
4888   case ISD::STRICT_FSETCCS:
4889     return LowerSETCC(Op, DAG);
4890   case ISD::BR_CC:
4891     return LowerBR_CC(Op, DAG);
4892   case ISD::SELECT:
4893     return LowerSELECT(Op, DAG);
4894   case ISD::SELECT_CC:
4895     return LowerSELECT_CC(Op, DAG);
4896   case ISD::JumpTable:
4897     return LowerJumpTable(Op, DAG);
4898   case ISD::BR_JT:
4899     return LowerBR_JT(Op, DAG);
4900   case ISD::ConstantPool:
4901     return LowerConstantPool(Op, DAG);
4902   case ISD::BlockAddress:
4903     return LowerBlockAddress(Op, DAG);
4904   case ISD::VASTART:
4905     return LowerVASTART(Op, DAG);
4906   case ISD::VACOPY:
4907     return LowerVACOPY(Op, DAG);
4908   case ISD::VAARG:
4909     return LowerVAARG(Op, DAG);
4910   case ISD::ADDC:
4911   case ISD::ADDE:
4912   case ISD::SUBC:
4913   case ISD::SUBE:
4914     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
4915   case ISD::SADDO:
4916   case ISD::UADDO:
4917   case ISD::SSUBO:
4918   case ISD::USUBO:
4919   case ISD::SMULO:
4920   case ISD::UMULO:
4921     return LowerXALUO(Op, DAG);
4922   case ISD::FADD:
4923     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
4924   case ISD::FSUB:
4925     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
4926   case ISD::FMUL:
4927     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
4928   case ISD::FMA:
4929     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
4930   case ISD::FDIV:
4931     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
4932   case ISD::FNEG:
4933     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
4934   case ISD::FCEIL:
4935     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
4936   case ISD::FFLOOR:
4937     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
4938   case ISD::FNEARBYINT:
4939     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
4940   case ISD::FRINT:
4941     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
4942   case ISD::FROUND:
4943     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
4944   case ISD::FROUNDEVEN:
4945     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
4946   case ISD::FTRUNC:
4947     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
4948   case ISD::FSQRT:
4949     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
4950   case ISD::FABS:
4951     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
4952   case ISD::FP_ROUND:
4953   case ISD::STRICT_FP_ROUND:
4954     return LowerFP_ROUND(Op, DAG);
4955   case ISD::FP_EXTEND:
4956     return LowerFP_EXTEND(Op, DAG);
4957   case ISD::FRAMEADDR:
4958     return LowerFRAMEADDR(Op, DAG);
4959   case ISD::SPONENTRY:
4960     return LowerSPONENTRY(Op, DAG);
4961   case ISD::RETURNADDR:
4962     return LowerRETURNADDR(Op, DAG);
4963   case ISD::ADDROFRETURNADDR:
4964     return LowerADDROFRETURNADDR(Op, DAG);
4965   case ISD::CONCAT_VECTORS:
4966     return LowerCONCAT_VECTORS(Op, DAG);
4967   case ISD::INSERT_VECTOR_ELT:
4968     return LowerINSERT_VECTOR_ELT(Op, DAG);
4969   case ISD::EXTRACT_VECTOR_ELT:
4970     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4971   case ISD::BUILD_VECTOR:
4972     return LowerBUILD_VECTOR(Op, DAG);
4973   case ISD::VECTOR_SHUFFLE:
4974     return LowerVECTOR_SHUFFLE(Op, DAG);
4975   case ISD::SPLAT_VECTOR:
4976     return LowerSPLAT_VECTOR(Op, DAG);
4977   case ISD::EXTRACT_SUBVECTOR:
4978     return LowerEXTRACT_SUBVECTOR(Op, DAG);
4979   case ISD::INSERT_SUBVECTOR:
4980     return LowerINSERT_SUBVECTOR(Op, DAG);
4981   case ISD::SDIV:
4982   case ISD::UDIV:
4983     return LowerDIV(Op, DAG);
4984   case ISD::SMIN:
4985   case ISD::UMIN:
4986   case ISD::SMAX:
4987   case ISD::UMAX:
4988     return LowerMinMax(Op, DAG);
4989   case ISD::SRA:
4990   case ISD::SRL:
4991   case ISD::SHL:
4992     return LowerVectorSRA_SRL_SHL(Op, DAG);
4993   case ISD::SHL_PARTS:
4994   case ISD::SRL_PARTS:
4995   case ISD::SRA_PARTS:
4996     return LowerShiftParts(Op, DAG);
4997   case ISD::CTPOP:
4998     return LowerCTPOP(Op, DAG);
4999   case ISD::FCOPYSIGN:
5000     return LowerFCOPYSIGN(Op, DAG);
5001   case ISD::OR:
5002     return LowerVectorOR(Op, DAG);
5003   case ISD::XOR:
5004     return LowerXOR(Op, DAG);
5005   case ISD::PREFETCH:
5006     return LowerPREFETCH(Op, DAG);
5007   case ISD::SINT_TO_FP:
5008   case ISD::UINT_TO_FP:
5009   case ISD::STRICT_SINT_TO_FP:
5010   case ISD::STRICT_UINT_TO_FP:
5011     return LowerINT_TO_FP(Op, DAG);
5012   case ISD::FP_TO_SINT:
5013   case ISD::FP_TO_UINT:
5014   case ISD::STRICT_FP_TO_SINT:
5015   case ISD::STRICT_FP_TO_UINT:
5016     return LowerFP_TO_INT(Op, DAG);
5017   case ISD::FP_TO_SINT_SAT:
5018   case ISD::FP_TO_UINT_SAT:
5019     return LowerFP_TO_INT_SAT(Op, DAG);
5020   case ISD::FSINCOS:
5021     return LowerFSINCOS(Op, DAG);
5022   case ISD::FLT_ROUNDS_:
5023     return LowerFLT_ROUNDS_(Op, DAG);
5024   case ISD::SET_ROUNDING:
5025     return LowerSET_ROUNDING(Op, DAG);
5026   case ISD::MUL:
5027     return LowerMUL(Op, DAG);
5028   case ISD::MULHS:
5029     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHS_PRED,
5030                                /*OverrideNEON=*/true);
5031   case ISD::MULHU:
5032     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHU_PRED,
5033                                /*OverrideNEON=*/true);
5034   case ISD::INTRINSIC_WO_CHAIN:
5035     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5036   case ISD::ATOMIC_STORE:
5037     if (cast<MemSDNode>(Op)->getMemoryVT() == MVT::i128) {
5038       assert(Subtarget->hasLSE2());
5039       return LowerStore128(Op, DAG);
5040     }
5041     return SDValue();
5042   case ISD::STORE:
5043     return LowerSTORE(Op, DAG);
5044   case ISD::MSTORE:
5045     return LowerFixedLengthVectorMStoreToSVE(Op, DAG);
5046   case ISD::MGATHER:
5047     return LowerMGATHER(Op, DAG);
5048   case ISD::MSCATTER:
5049     return LowerMSCATTER(Op, DAG);
5050   case ISD::VECREDUCE_SEQ_FADD:
5051     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
5052   case ISD::VECREDUCE_ADD:
5053   case ISD::VECREDUCE_AND:
5054   case ISD::VECREDUCE_OR:
5055   case ISD::VECREDUCE_XOR:
5056   case ISD::VECREDUCE_SMAX:
5057   case ISD::VECREDUCE_SMIN:
5058   case ISD::VECREDUCE_UMAX:
5059   case ISD::VECREDUCE_UMIN:
5060   case ISD::VECREDUCE_FADD:
5061   case ISD::VECREDUCE_FMAX:
5062   case ISD::VECREDUCE_FMIN:
5063     return LowerVECREDUCE(Op, DAG);
5064   case ISD::ATOMIC_LOAD_SUB:
5065     return LowerATOMIC_LOAD_SUB(Op, DAG);
5066   case ISD::ATOMIC_LOAD_AND:
5067     return LowerATOMIC_LOAD_AND(Op, DAG);
5068   case ISD::DYNAMIC_STACKALLOC:
5069     return LowerDYNAMIC_STACKALLOC(Op, DAG);
5070   case ISD::VSCALE:
5071     return LowerVSCALE(Op, DAG);
5072   case ISD::ANY_EXTEND:
5073   case ISD::SIGN_EXTEND:
5074   case ISD::ZERO_EXTEND:
5075     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
5076   case ISD::SIGN_EXTEND_INREG: {
5077     // Only custom lower when ExtraVT has a legal byte based element type.
5078     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
5079     EVT ExtraEltVT = ExtraVT.getVectorElementType();
5080     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
5081         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
5082       return SDValue();
5083 
5084     return LowerToPredicatedOp(Op, DAG,
5085                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
5086   }
5087   case ISD::TRUNCATE:
5088     return LowerTRUNCATE(Op, DAG);
5089   case ISD::MLOAD:
5090     return LowerMLOAD(Op, DAG);
5091   case ISD::LOAD:
5092     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
5093       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
5094     return LowerLOAD(Op, DAG);
5095   case ISD::ADD:
5096     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
5097   case ISD::AND:
5098     return LowerToScalableOp(Op, DAG);
5099   case ISD::SUB:
5100     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
5101   case ISD::FMAXIMUM:
5102     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED);
5103   case ISD::FMAXNUM:
5104     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
5105   case ISD::FMINIMUM:
5106     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED);
5107   case ISD::FMINNUM:
5108     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
5109   case ISD::VSELECT:
5110     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
5111   case ISD::ABS:
5112     return LowerABS(Op, DAG);
5113   case ISD::BITREVERSE:
5114     return LowerBitreverse(Op, DAG);
5115   case ISD::BSWAP:
5116     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
5117   case ISD::CTLZ:
5118     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
5119                                /*OverrideNEON=*/true);
5120   case ISD::CTTZ:
5121     return LowerCTTZ(Op, DAG);
5122   case ISD::VECTOR_SPLICE:
5123     return LowerVECTOR_SPLICE(Op, DAG);
5124   }
5125 }
5126 
5127 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
5128   return !Subtarget->useSVEForFixedLengthVectors();
5129 }
5130 
5131 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
5132     EVT VT, bool OverrideNEON) const {
5133   if (!Subtarget->useSVEForFixedLengthVectors())
5134     return false;
5135 
5136   if (!VT.isFixedLengthVector())
5137     return false;
5138 
5139   // Don't use SVE for vectors we cannot scalarize if required.
5140   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
5141   // Fixed length predicates should be promoted to i8.
5142   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
5143   case MVT::i1:
5144   default:
5145     return false;
5146   case MVT::i8:
5147   case MVT::i16:
5148   case MVT::i32:
5149   case MVT::i64:
5150   case MVT::f16:
5151   case MVT::f32:
5152   case MVT::f64:
5153     break;
5154   }
5155 
5156   // All SVE implementations support NEON sized vectors.
5157   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
5158     return true;
5159 
5160   // Ensure NEON MVTs only belong to a single register class.
5161   if (VT.getFixedSizeInBits() <= 128)
5162     return false;
5163 
5164   // Don't use SVE for types that don't fit.
5165   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
5166     return false;
5167 
5168   // TODO: Perhaps an artificial restriction, but worth having whilst getting
5169   // the base fixed length SVE support in place.
5170   if (!VT.isPow2VectorType())
5171     return false;
5172 
5173   return true;
5174 }
5175 
5176 //===----------------------------------------------------------------------===//
5177 //                      Calling Convention Implementation
5178 //===----------------------------------------------------------------------===//
5179 
5180 /// Selects the correct CCAssignFn for a given CallingConvention value.
5181 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
5182                                                      bool IsVarArg) const {
5183   switch (CC) {
5184   default:
5185     report_fatal_error("Unsupported calling convention.");
5186   case CallingConv::WebKit_JS:
5187     return CC_AArch64_WebKit_JS;
5188   case CallingConv::GHC:
5189     return CC_AArch64_GHC;
5190   case CallingConv::C:
5191   case CallingConv::Fast:
5192   case CallingConv::PreserveMost:
5193   case CallingConv::CXX_FAST_TLS:
5194   case CallingConv::Swift:
5195   case CallingConv::SwiftTail:
5196   case CallingConv::Tail:
5197     if (Subtarget->isTargetWindows() && IsVarArg)
5198       return CC_AArch64_Win64_VarArg;
5199     if (!Subtarget->isTargetDarwin())
5200       return CC_AArch64_AAPCS;
5201     if (!IsVarArg)
5202       return CC_AArch64_DarwinPCS;
5203     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
5204                                       : CC_AArch64_DarwinPCS_VarArg;
5205    case CallingConv::Win64:
5206     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
5207    case CallingConv::CFGuard_Check:
5208      return CC_AArch64_Win64_CFGuard_Check;
5209    case CallingConv::AArch64_VectorCall:
5210    case CallingConv::AArch64_SVE_VectorCall:
5211      return CC_AArch64_AAPCS;
5212   }
5213 }
5214 
5215 CCAssignFn *
5216 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
5217   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
5218                                       : RetCC_AArch64_AAPCS;
5219 }
5220 
5221 SDValue AArch64TargetLowering::LowerFormalArguments(
5222     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
5223     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5224     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5225   MachineFunction &MF = DAG.getMachineFunction();
5226   MachineFrameInfo &MFI = MF.getFrameInfo();
5227   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5228 
5229   // Assign locations to all of the incoming arguments.
5230   SmallVector<CCValAssign, 16> ArgLocs;
5231   DenseMap<unsigned, SDValue> CopiedRegs;
5232   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5233 
5234   // At this point, Ins[].VT may already be promoted to i32. To correctly
5235   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5236   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5237   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
5238   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
5239   // LocVT.
5240   unsigned NumArgs = Ins.size();
5241   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
5242   unsigned CurArgIdx = 0;
5243   for (unsigned i = 0; i != NumArgs; ++i) {
5244     MVT ValVT = Ins[i].VT;
5245     if (Ins[i].isOrigArg()) {
5246       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
5247       CurArgIdx = Ins[i].getOrigArgIndex();
5248 
5249       // Get type of the original argument.
5250       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
5251                                   /*AllowUnknown*/ true);
5252       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
5253       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5254       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
5255         ValVT = MVT::i8;
5256       else if (ActualMVT == MVT::i16)
5257         ValVT = MVT::i16;
5258     }
5259     bool UseVarArgCC = false;
5260     if (IsWin64)
5261       UseVarArgCC = isVarArg;
5262     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
5263     bool Res =
5264         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
5265     assert(!Res && "Call operand has unhandled type");
5266     (void)Res;
5267   }
5268   SmallVector<SDValue, 16> ArgValues;
5269   unsigned ExtraArgLocs = 0;
5270   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5271     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
5272 
5273     if (Ins[i].Flags.isByVal()) {
5274       // Byval is used for HFAs in the PCS, but the system should work in a
5275       // non-compliant manner for larger structs.
5276       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5277       int Size = Ins[i].Flags.getByValSize();
5278       unsigned NumRegs = (Size + 7) / 8;
5279 
5280       // FIXME: This works on big-endian for composite byvals, which are the common
5281       // case. It should also work for fundamental types too.
5282       unsigned FrameIdx =
5283         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
5284       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
5285       InVals.push_back(FrameIdxN);
5286 
5287       continue;
5288     }
5289 
5290     if (Ins[i].Flags.isSwiftAsync())
5291       MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
5292 
5293     SDValue ArgValue;
5294     if (VA.isRegLoc()) {
5295       // Arguments stored in registers.
5296       EVT RegVT = VA.getLocVT();
5297       const TargetRegisterClass *RC;
5298 
5299       if (RegVT == MVT::i32)
5300         RC = &AArch64::GPR32RegClass;
5301       else if (RegVT == MVT::i64)
5302         RC = &AArch64::GPR64RegClass;
5303       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
5304         RC = &AArch64::FPR16RegClass;
5305       else if (RegVT == MVT::f32)
5306         RC = &AArch64::FPR32RegClass;
5307       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
5308         RC = &AArch64::FPR64RegClass;
5309       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
5310         RC = &AArch64::FPR128RegClass;
5311       else if (RegVT.isScalableVector() &&
5312                RegVT.getVectorElementType() == MVT::i1)
5313         RC = &AArch64::PPRRegClass;
5314       else if (RegVT.isScalableVector())
5315         RC = &AArch64::ZPRRegClass;
5316       else
5317         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
5318 
5319       // Transform the arguments in physical registers into virtual ones.
5320       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
5321       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
5322 
5323       // If this is an 8, 16 or 32-bit value, it is really passed promoted
5324       // to 64 bits.  Insert an assert[sz]ext to capture this, then
5325       // truncate to the right size.
5326       switch (VA.getLocInfo()) {
5327       default:
5328         llvm_unreachable("Unknown loc info!");
5329       case CCValAssign::Full:
5330         break;
5331       case CCValAssign::Indirect:
5332         assert(VA.getValVT().isScalableVector() &&
5333                "Only scalable vectors can be passed indirectly");
5334         break;
5335       case CCValAssign::BCvt:
5336         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
5337         break;
5338       case CCValAssign::AExt:
5339       case CCValAssign::SExt:
5340       case CCValAssign::ZExt:
5341         break;
5342       case CCValAssign::AExtUpper:
5343         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
5344                                DAG.getConstant(32, DL, RegVT));
5345         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
5346         break;
5347       }
5348     } else { // VA.isRegLoc()
5349       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
5350       unsigned ArgOffset = VA.getLocMemOffset();
5351       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
5352                               ? VA.getLocVT().getSizeInBits()
5353                               : VA.getValVT().getSizeInBits()) / 8;
5354 
5355       uint32_t BEAlign = 0;
5356       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
5357           !Ins[i].Flags.isInConsecutiveRegs())
5358         BEAlign = 8 - ArgSize;
5359 
5360       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
5361 
5362       // Create load nodes to retrieve arguments from the stack.
5363       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
5364 
5365       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
5366       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5367       MVT MemVT = VA.getValVT();
5368 
5369       switch (VA.getLocInfo()) {
5370       default:
5371         break;
5372       case CCValAssign::Trunc:
5373       case CCValAssign::BCvt:
5374         MemVT = VA.getLocVT();
5375         break;
5376       case CCValAssign::Indirect:
5377         assert(VA.getValVT().isScalableVector() &&
5378                "Only scalable vectors can be passed indirectly");
5379         MemVT = VA.getLocVT();
5380         break;
5381       case CCValAssign::SExt:
5382         ExtType = ISD::SEXTLOAD;
5383         break;
5384       case CCValAssign::ZExt:
5385         ExtType = ISD::ZEXTLOAD;
5386         break;
5387       case CCValAssign::AExt:
5388         ExtType = ISD::EXTLOAD;
5389         break;
5390       }
5391 
5392       ArgValue =
5393           DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
5394                          MachinePointerInfo::getFixedStack(MF, FI), MemVT);
5395     }
5396 
5397     if (VA.getLocInfo() == CCValAssign::Indirect) {
5398       assert(VA.getValVT().isScalableVector() &&
5399            "Only scalable vectors can be passed indirectly");
5400 
5401       uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
5402       unsigned NumParts = 1;
5403       if (Ins[i].Flags.isInConsecutiveRegs()) {
5404         assert(!Ins[i].Flags.isInConsecutiveRegsLast());
5405         while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
5406           ++NumParts;
5407       }
5408 
5409       MVT PartLoad = VA.getValVT();
5410       SDValue Ptr = ArgValue;
5411 
5412       // Ensure we generate all loads for each tuple part, whilst updating the
5413       // pointer after each load correctly using vscale.
5414       while (NumParts > 0) {
5415         ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
5416         InVals.push_back(ArgValue);
5417         NumParts--;
5418         if (NumParts > 0) {
5419           SDValue BytesIncrement = DAG.getVScale(
5420               DL, Ptr.getValueType(),
5421               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
5422           SDNodeFlags Flags;
5423           Flags.setNoUnsignedWrap(true);
5424           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5425                             BytesIncrement, Flags);
5426           ExtraArgLocs++;
5427           i++;
5428         }
5429       }
5430     } else {
5431       if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
5432         ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
5433                                ArgValue, DAG.getValueType(MVT::i32));
5434 
5435       // i1 arguments are zero-extended to i8 by the caller. Emit a
5436       // hint to reflect this.
5437       if (Ins[i].isOrigArg()) {
5438         Argument *OrigArg = MF.getFunction().getArg(Ins[i].getOrigArgIndex());
5439         if (OrigArg->getType()->isIntegerTy(1)) {
5440           if (!Ins[i].Flags.isZExt()) {
5441             ArgValue = DAG.getNode(AArch64ISD::ASSERT_ZEXT_BOOL, DL,
5442                                    ArgValue.getValueType(), ArgValue);
5443           }
5444         }
5445       }
5446 
5447       InVals.push_back(ArgValue);
5448     }
5449   }
5450   assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
5451 
5452   // varargs
5453   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5454   if (isVarArg) {
5455     if (!Subtarget->isTargetDarwin() || IsWin64) {
5456       // The AAPCS variadic function ABI is identical to the non-variadic
5457       // one. As a result there may be more arguments in registers and we should
5458       // save them for future reference.
5459       // Win64 variadic functions also pass arguments in registers, but all float
5460       // arguments are passed in integer registers.
5461       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
5462     }
5463 
5464     // This will point to the next argument passed via stack.
5465     unsigned StackOffset = CCInfo.getNextStackOffset();
5466     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
5467     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
5468     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
5469 
5470     if (MFI.hasMustTailInVarArgFunc()) {
5471       SmallVector<MVT, 2> RegParmTypes;
5472       RegParmTypes.push_back(MVT::i64);
5473       RegParmTypes.push_back(MVT::f128);
5474       // Compute the set of forwarded registers. The rest are scratch.
5475       SmallVectorImpl<ForwardedRegister> &Forwards =
5476                                        FuncInfo->getForwardedMustTailRegParms();
5477       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
5478                                                CC_AArch64_AAPCS);
5479 
5480       // Conservatively forward X8, since it might be used for aggregate return.
5481       if (!CCInfo.isAllocated(AArch64::X8)) {
5482         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
5483         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
5484       }
5485     }
5486   }
5487 
5488   // On Windows, InReg pointers must be returned, so record the pointer in a
5489   // virtual register at the start of the function so it can be returned in the
5490   // epilogue.
5491   if (IsWin64) {
5492     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
5493       if (Ins[I].Flags.isInReg()) {
5494         assert(!FuncInfo->getSRetReturnReg());
5495 
5496         MVT PtrTy = getPointerTy(DAG.getDataLayout());
5497         Register Reg =
5498             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
5499         FuncInfo->setSRetReturnReg(Reg);
5500 
5501         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
5502         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
5503         break;
5504       }
5505     }
5506   }
5507 
5508   unsigned StackArgSize = CCInfo.getNextStackOffset();
5509   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5510   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
5511     // This is a non-standard ABI so by fiat I say we're allowed to make full
5512     // use of the stack area to be popped, which must be aligned to 16 bytes in
5513     // any case:
5514     StackArgSize = alignTo(StackArgSize, 16);
5515 
5516     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
5517     // a multiple of 16.
5518     FuncInfo->setArgumentStackToRestore(StackArgSize);
5519 
5520     // This realignment carries over to the available bytes below. Our own
5521     // callers will guarantee the space is free by giving an aligned value to
5522     // CALLSEQ_START.
5523   }
5524   // Even if we're not expected to free up the space, it's useful to know how
5525   // much is there while considering tail calls (because we can reuse it).
5526   FuncInfo->setBytesInStackArgArea(StackArgSize);
5527 
5528   if (Subtarget->hasCustomCallingConv())
5529     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
5530 
5531   return Chain;
5532 }
5533 
5534 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
5535                                                 SelectionDAG &DAG,
5536                                                 const SDLoc &DL,
5537                                                 SDValue &Chain) const {
5538   MachineFunction &MF = DAG.getMachineFunction();
5539   MachineFrameInfo &MFI = MF.getFrameInfo();
5540   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5541   auto PtrVT = getPointerTy(DAG.getDataLayout());
5542   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
5543 
5544   SmallVector<SDValue, 8> MemOps;
5545 
5546   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
5547                                           AArch64::X3, AArch64::X4, AArch64::X5,
5548                                           AArch64::X6, AArch64::X7 };
5549   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
5550   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
5551 
5552   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
5553   int GPRIdx = 0;
5554   if (GPRSaveSize != 0) {
5555     if (IsWin64) {
5556       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
5557       if (GPRSaveSize & 15)
5558         // The extra size here, if triggered, will always be 8.
5559         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
5560     } else
5561       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
5562 
5563     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
5564 
5565     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
5566       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
5567       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
5568       SDValue Store =
5569           DAG.getStore(Val.getValue(1), DL, Val, FIN,
5570                        IsWin64 ? MachinePointerInfo::getFixedStack(
5571                                      MF, GPRIdx, (i - FirstVariadicGPR) * 8)
5572                                : MachinePointerInfo::getStack(MF, i * 8));
5573       MemOps.push_back(Store);
5574       FIN =
5575           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
5576     }
5577   }
5578   FuncInfo->setVarArgsGPRIndex(GPRIdx);
5579   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
5580 
5581   if (Subtarget->hasFPARMv8() && !IsWin64) {
5582     static const MCPhysReg FPRArgRegs[] = {
5583         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
5584         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
5585     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
5586     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
5587 
5588     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
5589     int FPRIdx = 0;
5590     if (FPRSaveSize != 0) {
5591       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
5592 
5593       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
5594 
5595       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
5596         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
5597         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
5598 
5599         SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
5600                                      MachinePointerInfo::getStack(MF, i * 16));
5601         MemOps.push_back(Store);
5602         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
5603                           DAG.getConstant(16, DL, PtrVT));
5604       }
5605     }
5606     FuncInfo->setVarArgsFPRIndex(FPRIdx);
5607     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
5608   }
5609 
5610   if (!MemOps.empty()) {
5611     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5612   }
5613 }
5614 
5615 /// LowerCallResult - Lower the result values of a call into the
5616 /// appropriate copies out of appropriate physical registers.
5617 SDValue AArch64TargetLowering::LowerCallResult(
5618     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5619     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
5620     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
5621     SDValue ThisVal) const {
5622   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5623   // Assign locations to each value returned by this call.
5624   SmallVector<CCValAssign, 16> RVLocs;
5625   DenseMap<unsigned, SDValue> CopiedRegs;
5626   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5627                  *DAG.getContext());
5628   CCInfo.AnalyzeCallResult(Ins, RetCC);
5629 
5630   // Copy all of the result registers out of their specified physreg.
5631   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5632     CCValAssign VA = RVLocs[i];
5633 
5634     // Pass 'this' value directly from the argument to return value, to avoid
5635     // reg unit interference
5636     if (i == 0 && isThisReturn) {
5637       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
5638              "unexpected return calling convention register assignment");
5639       InVals.push_back(ThisVal);
5640       continue;
5641     }
5642 
5643     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
5644     // allows one use of a physreg per block.
5645     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
5646     if (!Val) {
5647       Val =
5648           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
5649       Chain = Val.getValue(1);
5650       InFlag = Val.getValue(2);
5651       CopiedRegs[VA.getLocReg()] = Val;
5652     }
5653 
5654     switch (VA.getLocInfo()) {
5655     default:
5656       llvm_unreachable("Unknown loc info!");
5657     case CCValAssign::Full:
5658       break;
5659     case CCValAssign::BCvt:
5660       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
5661       break;
5662     case CCValAssign::AExtUpper:
5663       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
5664                         DAG.getConstant(32, DL, VA.getLocVT()));
5665       LLVM_FALLTHROUGH;
5666     case CCValAssign::AExt:
5667       LLVM_FALLTHROUGH;
5668     case CCValAssign::ZExt:
5669       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
5670       break;
5671     }
5672 
5673     InVals.push_back(Val);
5674   }
5675 
5676   return Chain;
5677 }
5678 
5679 /// Return true if the calling convention is one that we can guarantee TCO for.
5680 static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
5681   return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
5682          CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
5683 }
5684 
5685 /// Return true if we might ever do TCO for calls with this calling convention.
5686 static bool mayTailCallThisCC(CallingConv::ID CC) {
5687   switch (CC) {
5688   case CallingConv::C:
5689   case CallingConv::AArch64_SVE_VectorCall:
5690   case CallingConv::PreserveMost:
5691   case CallingConv::Swift:
5692   case CallingConv::SwiftTail:
5693   case CallingConv::Tail:
5694   case CallingConv::Fast:
5695     return true;
5696   default:
5697     return false;
5698   }
5699 }
5700 
5701 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
5702     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
5703     const SmallVectorImpl<ISD::OutputArg> &Outs,
5704     const SmallVectorImpl<SDValue> &OutVals,
5705     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
5706   if (!mayTailCallThisCC(CalleeCC))
5707     return false;
5708 
5709   MachineFunction &MF = DAG.getMachineFunction();
5710   const Function &CallerF = MF.getFunction();
5711   CallingConv::ID CallerCC = CallerF.getCallingConv();
5712 
5713   // Functions using the C or Fast calling convention that have an SVE signature
5714   // preserve more registers and should assume the SVE_VectorCall CC.
5715   // The check for matching callee-saved regs will determine whether it is
5716   // eligible for TCO.
5717   if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) &&
5718       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
5719     CallerCC = CallingConv::AArch64_SVE_VectorCall;
5720 
5721   bool CCMatch = CallerCC == CalleeCC;
5722 
5723   // When using the Windows calling convention on a non-windows OS, we want
5724   // to back up and restore X18 in such functions; we can't do a tail call
5725   // from those functions.
5726   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
5727       CalleeCC != CallingConv::Win64)
5728     return false;
5729 
5730   // Byval parameters hand the function a pointer directly into the stack area
5731   // we want to reuse during a tail call. Working around this *is* possible (see
5732   // X86) but less efficient and uglier in LowerCall.
5733   for (Function::const_arg_iterator i = CallerF.arg_begin(),
5734                                     e = CallerF.arg_end();
5735        i != e; ++i) {
5736     if (i->hasByValAttr())
5737       return false;
5738 
5739     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
5740     // In this case, it is necessary to save/restore X0 in the callee. Tail
5741     // call opt interferes with this. So we disable tail call opt when the
5742     // caller has an argument with "inreg" attribute.
5743 
5744     // FIXME: Check whether the callee also has an "inreg" argument.
5745     if (i->hasInRegAttr())
5746       return false;
5747   }
5748 
5749   if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
5750     return CCMatch;
5751 
5752   // Externally-defined functions with weak linkage should not be
5753   // tail-called on AArch64 when the OS does not support dynamic
5754   // pre-emption of symbols, as the AAELF spec requires normal calls
5755   // to undefined weak functions to be replaced with a NOP or jump to the
5756   // next instruction. The behaviour of branch instructions in this
5757   // situation (as used for tail calls) is implementation-defined, so we
5758   // cannot rely on the linker replacing the tail call with a return.
5759   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5760     const GlobalValue *GV = G->getGlobal();
5761     const Triple &TT = getTargetMachine().getTargetTriple();
5762     if (GV->hasExternalWeakLinkage() &&
5763         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
5764       return false;
5765   }
5766 
5767   // Now we search for cases where we can use a tail call without changing the
5768   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
5769   // concept.
5770 
5771   // I want anyone implementing a new calling convention to think long and hard
5772   // about this assert.
5773   assert((!isVarArg || CalleeCC == CallingConv::C) &&
5774          "Unexpected variadic calling convention");
5775 
5776   LLVMContext &C = *DAG.getContext();
5777   if (isVarArg && !Outs.empty()) {
5778     // At least two cases here: if caller is fastcc then we can't have any
5779     // memory arguments (we'd be expected to clean up the stack afterwards). If
5780     // caller is C then we could potentially use its argument area.
5781 
5782     // FIXME: for now we take the most conservative of these in both cases:
5783     // disallow all variadic memory operands.
5784     SmallVector<CCValAssign, 16> ArgLocs;
5785     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5786 
5787     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
5788     for (const CCValAssign &ArgLoc : ArgLocs)
5789       if (!ArgLoc.isRegLoc())
5790         return false;
5791   }
5792 
5793   // Check that the call results are passed in the same way.
5794   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
5795                                   CCAssignFnForCall(CalleeCC, isVarArg),
5796                                   CCAssignFnForCall(CallerCC, isVarArg)))
5797     return false;
5798   // The callee has to preserve all registers the caller needs to preserve.
5799   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5800   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
5801   if (!CCMatch) {
5802     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
5803     if (Subtarget->hasCustomCallingConv()) {
5804       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
5805       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
5806     }
5807     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
5808       return false;
5809   }
5810 
5811   // Nothing more to check if the callee is taking no arguments
5812   if (Outs.empty())
5813     return true;
5814 
5815   SmallVector<CCValAssign, 16> ArgLocs;
5816   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
5817 
5818   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
5819 
5820   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5821 
5822   // If any of the arguments is passed indirectly, it must be SVE, so the
5823   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
5824   // allocate space on the stack. That is why we determine this explicitly here
5825   // the call cannot be a tailcall.
5826   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
5827         assert((A.getLocInfo() != CCValAssign::Indirect ||
5828                 A.getValVT().isScalableVector()) &&
5829                "Expected value to be scalable");
5830         return A.getLocInfo() == CCValAssign::Indirect;
5831       }))
5832     return false;
5833 
5834   // If the stack arguments for this call do not fit into our own save area then
5835   // the call cannot be made tail.
5836   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
5837     return false;
5838 
5839   const MachineRegisterInfo &MRI = MF.getRegInfo();
5840   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
5841     return false;
5842 
5843   return true;
5844 }
5845 
5846 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
5847                                                    SelectionDAG &DAG,
5848                                                    MachineFrameInfo &MFI,
5849                                                    int ClobberedFI) const {
5850   SmallVector<SDValue, 8> ArgChains;
5851   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
5852   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
5853 
5854   // Include the original chain at the beginning of the list. When this is
5855   // used by target LowerCall hooks, this helps legalize find the
5856   // CALLSEQ_BEGIN node.
5857   ArgChains.push_back(Chain);
5858 
5859   // Add a chain value for each stack argument corresponding
5860   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
5861                             UE = DAG.getEntryNode().getNode()->use_end();
5862        U != UE; ++U)
5863     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5864       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5865         if (FI->getIndex() < 0) {
5866           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
5867           int64_t InLastByte = InFirstByte;
5868           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
5869 
5870           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
5871               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
5872             ArgChains.push_back(SDValue(L, 1));
5873         }
5874 
5875   // Build a tokenfactor for all the chains.
5876   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5877 }
5878 
5879 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
5880                                                    bool TailCallOpt) const {
5881   return (CallCC == CallingConv::Fast && TailCallOpt) ||
5882          CallCC == CallingConv::Tail || CallCC == CallingConv::SwiftTail;
5883 }
5884 
5885 // Check if the value is zero-extended from i1 to i8
5886 static bool checkZExtBool(SDValue Arg, const SelectionDAG &DAG) {
5887   unsigned SizeInBits = Arg.getValueType().getSizeInBits();
5888   if (SizeInBits < 8)
5889     return false;
5890 
5891   APInt LowBits(SizeInBits, 0xFF);
5892   APInt RequredZero(SizeInBits, 0xFE);
5893   KnownBits Bits = DAG.computeKnownBits(Arg, LowBits, 4);
5894   bool ZExtBool = (Bits.Zero & RequredZero) == RequredZero;
5895   return ZExtBool;
5896 }
5897 
5898 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
5899 /// and add input and output parameter nodes.
5900 SDValue
5901 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
5902                                  SmallVectorImpl<SDValue> &InVals) const {
5903   SelectionDAG &DAG = CLI.DAG;
5904   SDLoc &DL = CLI.DL;
5905   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
5906   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
5907   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
5908   SDValue Chain = CLI.Chain;
5909   SDValue Callee = CLI.Callee;
5910   bool &IsTailCall = CLI.IsTailCall;
5911   CallingConv::ID CallConv = CLI.CallConv;
5912   bool IsVarArg = CLI.IsVarArg;
5913 
5914   MachineFunction &MF = DAG.getMachineFunction();
5915   MachineFunction::CallSiteInfo CSInfo;
5916   bool IsThisReturn = false;
5917 
5918   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5919   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
5920   bool IsSibCall = false;
5921   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CallConv);
5922 
5923   // Check callee args/returns for SVE registers and set calling convention
5924   // accordingly.
5925   if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) {
5926     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
5927       return Out.VT.isScalableVector();
5928     });
5929     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
5930       return In.VT.isScalableVector();
5931     });
5932 
5933     if (CalleeInSVE || CalleeOutSVE)
5934       CallConv = CallingConv::AArch64_SVE_VectorCall;
5935   }
5936 
5937   if (IsTailCall) {
5938     // Check if it's really possible to do a tail call.
5939     IsTailCall = isEligibleForTailCallOptimization(
5940         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
5941 
5942     // A sibling call is one where we're under the usual C ABI and not planning
5943     // to change that but can still do a tail call:
5944     if (!TailCallOpt && IsTailCall && CallConv != CallingConv::Tail &&
5945         CallConv != CallingConv::SwiftTail)
5946       IsSibCall = true;
5947 
5948     if (IsTailCall)
5949       ++NumTailCalls;
5950   }
5951 
5952   if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
5953     report_fatal_error("failed to perform tail call elimination on a call "
5954                        "site marked musttail");
5955 
5956   // Analyze operands of the call, assigning locations to each operand.
5957   SmallVector<CCValAssign, 16> ArgLocs;
5958   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5959 
5960   if (IsVarArg) {
5961     // Handle fixed and variable vector arguments differently.
5962     // Variable vector arguments always go into memory.
5963     unsigned NumArgs = Outs.size();
5964 
5965     for (unsigned i = 0; i != NumArgs; ++i) {
5966       MVT ArgVT = Outs[i].VT;
5967       if (!Outs[i].IsFixed && ArgVT.isScalableVector())
5968         report_fatal_error("Passing SVE types to variadic functions is "
5969                            "currently not supported");
5970 
5971       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5972       bool UseVarArgCC = !Outs[i].IsFixed;
5973       // On Windows, the fixed arguments in a vararg call are passed in GPRs
5974       // too, so use the vararg CC to force them to integer registers.
5975       if (IsCalleeWin64)
5976         UseVarArgCC = true;
5977       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
5978       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
5979       assert(!Res && "Call operand has unhandled type");
5980       (void)Res;
5981     }
5982   } else {
5983     // At this point, Outs[].VT may already be promoted to i32. To correctly
5984     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
5985     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
5986     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
5987     // we use a special version of AnalyzeCallOperands to pass in ValVT and
5988     // LocVT.
5989     unsigned NumArgs = Outs.size();
5990     for (unsigned i = 0; i != NumArgs; ++i) {
5991       MVT ValVT = Outs[i].VT;
5992       // Get type of the original argument.
5993       EVT ActualVT = getValueType(DAG.getDataLayout(),
5994                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
5995                                   /*AllowUnknown*/ true);
5996       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
5997       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5998       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
5999       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
6000         ValVT = MVT::i8;
6001       else if (ActualMVT == MVT::i16)
6002         ValVT = MVT::i16;
6003 
6004       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
6005       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
6006       assert(!Res && "Call operand has unhandled type");
6007       (void)Res;
6008     }
6009   }
6010 
6011   // Get a count of how many bytes are to be pushed on the stack.
6012   unsigned NumBytes = CCInfo.getNextStackOffset();
6013 
6014   if (IsSibCall) {
6015     // Since we're not changing the ABI to make this a tail call, the memory
6016     // operands are already available in the caller's incoming argument space.
6017     NumBytes = 0;
6018   }
6019 
6020   // FPDiff is the byte offset of the call's argument area from the callee's.
6021   // Stores to callee stack arguments will be placed in FixedStackSlots offset
6022   // by this amount for a tail call. In a sibling call it must be 0 because the
6023   // caller will deallocate the entire stack and the callee still expects its
6024   // arguments to begin at SP+0. Completely unused for non-tail calls.
6025   int FPDiff = 0;
6026 
6027   if (IsTailCall && !IsSibCall) {
6028     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
6029 
6030     // Since callee will pop argument stack as a tail call, we must keep the
6031     // popped size 16-byte aligned.
6032     NumBytes = alignTo(NumBytes, 16);
6033 
6034     // FPDiff will be negative if this tail call requires more space than we
6035     // would automatically have in our incoming argument space. Positive if we
6036     // can actually shrink the stack.
6037     FPDiff = NumReusableBytes - NumBytes;
6038 
6039     // Update the required reserved area if this is the tail call requiring the
6040     // most argument stack space.
6041     if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
6042       FuncInfo->setTailCallReservedStack(-FPDiff);
6043 
6044     // The stack pointer must be 16-byte aligned at all times it's used for a
6045     // memory operation, which in practice means at *all* times and in
6046     // particular across call boundaries. Therefore our own arguments started at
6047     // a 16-byte aligned SP and the delta applied for the tail call should
6048     // satisfy the same constraint.
6049     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
6050   }
6051 
6052   // Adjust the stack pointer for the new arguments...
6053   // These operations are automatically eliminated by the prolog/epilog pass
6054   if (!IsSibCall)
6055     Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
6056 
6057   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
6058                                         getPointerTy(DAG.getDataLayout()));
6059 
6060   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6061   SmallSet<unsigned, 8> RegsUsed;
6062   SmallVector<SDValue, 8> MemOpChains;
6063   auto PtrVT = getPointerTy(DAG.getDataLayout());
6064 
6065   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
6066     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
6067     for (const auto &F : Forwards) {
6068       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
6069        RegsToPass.emplace_back(F.PReg, Val);
6070     }
6071   }
6072 
6073   // Walk the register/memloc assignments, inserting copies/loads.
6074   unsigned ExtraArgLocs = 0;
6075   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
6076     CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
6077     SDValue Arg = OutVals[i];
6078     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6079 
6080     // Promote the value if needed.
6081     switch (VA.getLocInfo()) {
6082     default:
6083       llvm_unreachable("Unknown loc info!");
6084     case CCValAssign::Full:
6085       break;
6086     case CCValAssign::SExt:
6087       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
6088       break;
6089     case CCValAssign::ZExt:
6090       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6091       break;
6092     case CCValAssign::AExt:
6093       if (Outs[i].ArgVT == MVT::i1) {
6094         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
6095         //
6096         // Check if we actually have to do this, because the value may
6097         // already be zero-extended.
6098         //
6099         // We cannot just emit a (zext i8 (trunc (assert-zext i8)))
6100         // and rely on DAGCombiner to fold this, because the following
6101         // (anyext i32) is combined with (zext i8) in DAG.getNode:
6102         //
6103         //   (ext (zext x)) -> (zext x)
6104         //
6105         // This will give us (zext i32), which we cannot remove, so
6106         // try to check this beforehand.
6107         if (!checkZExtBool(Arg, DAG)) {
6108           Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6109           Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
6110         }
6111       }
6112       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6113       break;
6114     case CCValAssign::AExtUpper:
6115       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6116       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
6117       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6118                         DAG.getConstant(32, DL, VA.getLocVT()));
6119       break;
6120     case CCValAssign::BCvt:
6121       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
6122       break;
6123     case CCValAssign::Trunc:
6124       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6125       break;
6126     case CCValAssign::FPExt:
6127       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
6128       break;
6129     case CCValAssign::Indirect:
6130       assert(VA.getValVT().isScalableVector() &&
6131              "Only scalable vectors can be passed indirectly");
6132 
6133       uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
6134       uint64_t PartSize = StoreSize;
6135       unsigned NumParts = 1;
6136       if (Outs[i].Flags.isInConsecutiveRegs()) {
6137         assert(!Outs[i].Flags.isInConsecutiveRegsLast());
6138         while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
6139           ++NumParts;
6140         StoreSize *= NumParts;
6141       }
6142 
6143       MachineFrameInfo &MFI = MF.getFrameInfo();
6144       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
6145       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
6146       int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
6147       MFI.setStackID(FI, TargetStackID::ScalableVector);
6148 
6149       MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6150       SDValue Ptr = DAG.getFrameIndex(
6151           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
6152       SDValue SpillSlot = Ptr;
6153 
6154       // Ensure we generate all stores for each tuple part, whilst updating the
6155       // pointer after each store correctly using vscale.
6156       while (NumParts) {
6157         Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
6158         NumParts--;
6159         if (NumParts > 0) {
6160           SDValue BytesIncrement = DAG.getVScale(
6161               DL, Ptr.getValueType(),
6162               APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
6163           SDNodeFlags Flags;
6164           Flags.setNoUnsignedWrap(true);
6165 
6166           MPI = MachinePointerInfo(MPI.getAddrSpace());
6167           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6168                             BytesIncrement, Flags);
6169           ExtraArgLocs++;
6170           i++;
6171         }
6172       }
6173 
6174       Arg = SpillSlot;
6175       break;
6176     }
6177 
6178     if (VA.isRegLoc()) {
6179       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
6180           Outs[0].VT == MVT::i64) {
6181         assert(VA.getLocVT() == MVT::i64 &&
6182                "unexpected calling convention register assignment");
6183         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
6184                "unexpected use of 'returned'");
6185         IsThisReturn = true;
6186       }
6187       if (RegsUsed.count(VA.getLocReg())) {
6188         // If this register has already been used then we're trying to pack
6189         // parts of an [N x i32] into an X-register. The extension type will
6190         // take care of putting the two halves in the right place but we have to
6191         // combine them.
6192         SDValue &Bits =
6193             llvm::find_if(RegsToPass,
6194                           [=](const std::pair<unsigned, SDValue> &Elt) {
6195                             return Elt.first == VA.getLocReg();
6196                           })
6197                 ->second;
6198         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6199         // Call site info is used for function's parameter entry value
6200         // tracking. For now we track only simple cases when parameter
6201         // is transferred through whole register.
6202         llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
6203           return ArgReg.Reg == VA.getLocReg();
6204         });
6205       } else {
6206         RegsToPass.emplace_back(VA.getLocReg(), Arg);
6207         RegsUsed.insert(VA.getLocReg());
6208         const TargetOptions &Options = DAG.getTarget().Options;
6209         if (Options.EmitCallSiteInfo)
6210           CSInfo.emplace_back(VA.getLocReg(), i);
6211       }
6212     } else {
6213       assert(VA.isMemLoc());
6214 
6215       SDValue DstAddr;
6216       MachinePointerInfo DstInfo;
6217 
6218       // FIXME: This works on big-endian for composite byvals, which are the
6219       // common case. It should also work for fundamental types too.
6220       uint32_t BEAlign = 0;
6221       unsigned OpSize;
6222       if (VA.getLocInfo() == CCValAssign::Indirect ||
6223           VA.getLocInfo() == CCValAssign::Trunc)
6224         OpSize = VA.getLocVT().getFixedSizeInBits();
6225       else
6226         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
6227                                  : VA.getValVT().getSizeInBits();
6228       OpSize = (OpSize + 7) / 8;
6229       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
6230           !Flags.isInConsecutiveRegs()) {
6231         if (OpSize < 8)
6232           BEAlign = 8 - OpSize;
6233       }
6234       unsigned LocMemOffset = VA.getLocMemOffset();
6235       int32_t Offset = LocMemOffset + BEAlign;
6236       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6237       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6238 
6239       if (IsTailCall) {
6240         Offset = Offset + FPDiff;
6241         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
6242 
6243         DstAddr = DAG.getFrameIndex(FI, PtrVT);
6244         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
6245 
6246         // Make sure any stack arguments overlapping with where we're storing
6247         // are loaded before this eventual operation. Otherwise they'll be
6248         // clobbered.
6249         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
6250       } else {
6251         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
6252 
6253         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
6254         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
6255       }
6256 
6257       if (Outs[i].Flags.isByVal()) {
6258         SDValue SizeNode =
6259             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
6260         SDValue Cpy = DAG.getMemcpy(
6261             Chain, DL, DstAddr, Arg, SizeNode,
6262             Outs[i].Flags.getNonZeroByValAlign(),
6263             /*isVol = */ false, /*AlwaysInline = */ false,
6264             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
6265 
6266         MemOpChains.push_back(Cpy);
6267       } else {
6268         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
6269         // promoted to a legal register type i32, we should truncate Arg back to
6270         // i1/i8/i16.
6271         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
6272             VA.getValVT() == MVT::i16)
6273           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
6274 
6275         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
6276         MemOpChains.push_back(Store);
6277       }
6278     }
6279   }
6280 
6281   if (!MemOpChains.empty())
6282     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
6283 
6284   // Build a sequence of copy-to-reg nodes chained together with token chain
6285   // and flag operands which copy the outgoing args into the appropriate regs.
6286   SDValue InFlag;
6287   for (auto &RegToPass : RegsToPass) {
6288     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
6289                              RegToPass.second, InFlag);
6290     InFlag = Chain.getValue(1);
6291   }
6292 
6293   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
6294   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
6295   // node so that legalize doesn't hack it.
6296   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
6297     auto GV = G->getGlobal();
6298     unsigned OpFlags =
6299         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
6300     if (OpFlags & AArch64II::MO_GOT) {
6301       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
6302       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6303     } else {
6304       const GlobalValue *GV = G->getGlobal();
6305       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
6306     }
6307   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
6308     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6309         Subtarget->isTargetMachO()) {
6310       const char *Sym = S->getSymbol();
6311       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
6312       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
6313     } else {
6314       const char *Sym = S->getSymbol();
6315       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
6316     }
6317   }
6318 
6319   // We don't usually want to end the call-sequence here because we would tidy
6320   // the frame up *after* the call, however in the ABI-changing tail-call case
6321   // we've carefully laid out the parameters so that when sp is reset they'll be
6322   // in the correct location.
6323   if (IsTailCall && !IsSibCall) {
6324     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
6325                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
6326     InFlag = Chain.getValue(1);
6327   }
6328 
6329   std::vector<SDValue> Ops;
6330   Ops.push_back(Chain);
6331   Ops.push_back(Callee);
6332 
6333   if (IsTailCall) {
6334     // Each tail call may have to adjust the stack by a different amount, so
6335     // this information must travel along with the operation for eventual
6336     // consumption by emitEpilogue.
6337     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
6338   }
6339 
6340   // Add argument registers to the end of the list so that they are known live
6341   // into the call.
6342   for (auto &RegToPass : RegsToPass)
6343     Ops.push_back(DAG.getRegister(RegToPass.first,
6344                                   RegToPass.second.getValueType()));
6345 
6346   // Add a register mask operand representing the call-preserved registers.
6347   const uint32_t *Mask;
6348   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6349   if (IsThisReturn) {
6350     // For 'this' returns, use the X0-preserving mask if applicable
6351     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
6352     if (!Mask) {
6353       IsThisReturn = false;
6354       Mask = TRI->getCallPreservedMask(MF, CallConv);
6355     }
6356   } else
6357     Mask = TRI->getCallPreservedMask(MF, CallConv);
6358 
6359   if (Subtarget->hasCustomCallingConv())
6360     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
6361 
6362   if (TRI->isAnyArgRegReserved(MF))
6363     TRI->emitReservedArgRegCallError(MF);
6364 
6365   assert(Mask && "Missing call preserved mask for calling convention");
6366   Ops.push_back(DAG.getRegisterMask(Mask));
6367 
6368   if (InFlag.getNode())
6369     Ops.push_back(InFlag);
6370 
6371   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6372 
6373   // If we're doing a tall call, use a TC_RETURN here rather than an
6374   // actual call instruction.
6375   if (IsTailCall) {
6376     MF.getFrameInfo().setHasTailCall();
6377     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
6378     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
6379     return Ret;
6380   }
6381 
6382   unsigned CallOpc = AArch64ISD::CALL;
6383   // Calls with operand bundle "clang.arc.attachedcall" are special. They should
6384   // be expanded to the call, directly followed by a special marker sequence.
6385   // Use the CALL_RVMARKER to do that.
6386   if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
6387     assert(!IsTailCall &&
6388            "tail calls cannot be marked with clang.arc.attachedcall");
6389     CallOpc = AArch64ISD::CALL_RVMARKER;
6390   }
6391 
6392   // Returns a chain and a flag for retval copy to use.
6393   Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
6394   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
6395   InFlag = Chain.getValue(1);
6396   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
6397 
6398   uint64_t CalleePopBytes =
6399       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
6400 
6401   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
6402                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
6403                              InFlag, DL);
6404   if (!Ins.empty())
6405     InFlag = Chain.getValue(1);
6406 
6407   // Handle result values, copying them out of physregs into vregs that we
6408   // return.
6409   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
6410                          InVals, IsThisReturn,
6411                          IsThisReturn ? OutVals[0] : SDValue());
6412 }
6413 
6414 bool AArch64TargetLowering::CanLowerReturn(
6415     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
6416     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
6417   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6418   SmallVector<CCValAssign, 16> RVLocs;
6419   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6420   return CCInfo.CheckReturn(Outs, RetCC);
6421 }
6422 
6423 SDValue
6424 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6425                                    bool isVarArg,
6426                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
6427                                    const SmallVectorImpl<SDValue> &OutVals,
6428                                    const SDLoc &DL, SelectionDAG &DAG) const {
6429   auto &MF = DAG.getMachineFunction();
6430   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6431 
6432   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
6433   SmallVector<CCValAssign, 16> RVLocs;
6434   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
6435   CCInfo.AnalyzeReturn(Outs, RetCC);
6436 
6437   // Copy the result values into the output registers.
6438   SDValue Flag;
6439   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
6440   SmallSet<unsigned, 4> RegsUsed;
6441   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
6442        ++i, ++realRVLocIdx) {
6443     CCValAssign &VA = RVLocs[i];
6444     assert(VA.isRegLoc() && "Can only return in registers!");
6445     SDValue Arg = OutVals[realRVLocIdx];
6446 
6447     switch (VA.getLocInfo()) {
6448     default:
6449       llvm_unreachable("Unknown loc info!");
6450     case CCValAssign::Full:
6451       if (Outs[i].ArgVT == MVT::i1) {
6452         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
6453         // value. This is strictly redundant on Darwin (which uses "zeroext
6454         // i1"), but will be optimised out before ISel.
6455         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
6456         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
6457       }
6458       break;
6459     case CCValAssign::BCvt:
6460       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
6461       break;
6462     case CCValAssign::AExt:
6463     case CCValAssign::ZExt:
6464       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6465       break;
6466     case CCValAssign::AExtUpper:
6467       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
6468       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
6469       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
6470                         DAG.getConstant(32, DL, VA.getLocVT()));
6471       break;
6472     }
6473 
6474     if (RegsUsed.count(VA.getLocReg())) {
6475       SDValue &Bits =
6476           llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
6477             return Elt.first == VA.getLocReg();
6478           })->second;
6479       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
6480     } else {
6481       RetVals.emplace_back(VA.getLocReg(), Arg);
6482       RegsUsed.insert(VA.getLocReg());
6483     }
6484   }
6485 
6486   SmallVector<SDValue, 4> RetOps(1, Chain);
6487   for (auto &RetVal : RetVals) {
6488     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
6489     Flag = Chain.getValue(1);
6490     RetOps.push_back(
6491         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
6492   }
6493 
6494   // Windows AArch64 ABIs require that for returning structs by value we copy
6495   // the sret argument into X0 for the return.
6496   // We saved the argument into a virtual register in the entry block,
6497   // so now we copy the value out and into X0.
6498   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
6499     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
6500                                      getPointerTy(MF.getDataLayout()));
6501 
6502     unsigned RetValReg = AArch64::X0;
6503     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
6504     Flag = Chain.getValue(1);
6505 
6506     RetOps.push_back(
6507       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
6508   }
6509 
6510   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6511   const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&MF);
6512   if (I) {
6513     for (; *I; ++I) {
6514       if (AArch64::GPR64RegClass.contains(*I))
6515         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6516       else if (AArch64::FPR64RegClass.contains(*I))
6517         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6518       else
6519         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6520     }
6521   }
6522 
6523   RetOps[0] = Chain; // Update chain.
6524 
6525   // Add the flag if we have it.
6526   if (Flag.getNode())
6527     RetOps.push_back(Flag);
6528 
6529   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
6530 }
6531 
6532 //===----------------------------------------------------------------------===//
6533 //  Other Lowering Code
6534 //===----------------------------------------------------------------------===//
6535 
6536 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
6537                                              SelectionDAG &DAG,
6538                                              unsigned Flag) const {
6539   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
6540                                     N->getOffset(), Flag);
6541 }
6542 
6543 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
6544                                              SelectionDAG &DAG,
6545                                              unsigned Flag) const {
6546   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
6547 }
6548 
6549 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
6550                                              SelectionDAG &DAG,
6551                                              unsigned Flag) const {
6552   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
6553                                    N->getOffset(), Flag);
6554 }
6555 
6556 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
6557                                              SelectionDAG &DAG,
6558                                              unsigned Flag) const {
6559   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
6560 }
6561 
6562 // (loadGOT sym)
6563 template <class NodeTy>
6564 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
6565                                       unsigned Flags) const {
6566   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
6567   SDLoc DL(N);
6568   EVT Ty = getPointerTy(DAG.getDataLayout());
6569   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
6570   // FIXME: Once remat is capable of dealing with instructions with register
6571   // operands, expand this into two nodes instead of using a wrapper node.
6572   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
6573 }
6574 
6575 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
6576 template <class NodeTy>
6577 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
6578                                             unsigned Flags) const {
6579   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
6580   SDLoc DL(N);
6581   EVT Ty = getPointerTy(DAG.getDataLayout());
6582   const unsigned char MO_NC = AArch64II::MO_NC;
6583   return DAG.getNode(
6584       AArch64ISD::WrapperLarge, DL, Ty,
6585       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
6586       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
6587       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
6588       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
6589 }
6590 
6591 // (addlow (adrp %hi(sym)) %lo(sym))
6592 template <class NodeTy>
6593 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
6594                                        unsigned Flags) const {
6595   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
6596   SDLoc DL(N);
6597   EVT Ty = getPointerTy(DAG.getDataLayout());
6598   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
6599   SDValue Lo = getTargetNode(N, Ty, DAG,
6600                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
6601   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
6602   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
6603 }
6604 
6605 // (adr sym)
6606 template <class NodeTy>
6607 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
6608                                            unsigned Flags) const {
6609   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
6610   SDLoc DL(N);
6611   EVT Ty = getPointerTy(DAG.getDataLayout());
6612   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
6613   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
6614 }
6615 
6616 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
6617                                                   SelectionDAG &DAG) const {
6618   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
6619   const GlobalValue *GV = GN->getGlobal();
6620   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6621 
6622   if (OpFlags != AArch64II::MO_NO_FLAG)
6623     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
6624            "unexpected offset in global node");
6625 
6626   // This also catches the large code model case for Darwin, and tiny code
6627   // model with got relocations.
6628   if ((OpFlags & AArch64II::MO_GOT) != 0) {
6629     return getGOT(GN, DAG, OpFlags);
6630   }
6631 
6632   SDValue Result;
6633   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6634     Result = getAddrLarge(GN, DAG, OpFlags);
6635   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6636     Result = getAddrTiny(GN, DAG, OpFlags);
6637   } else {
6638     Result = getAddr(GN, DAG, OpFlags);
6639   }
6640   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6641   SDLoc DL(GN);
6642   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
6643     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
6644                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
6645   return Result;
6646 }
6647 
6648 /// Convert a TLS address reference into the correct sequence of loads
6649 /// and calls to compute the variable's address (for Darwin, currently) and
6650 /// return an SDValue containing the final node.
6651 
6652 /// Darwin only has one TLS scheme which must be capable of dealing with the
6653 /// fully general situation, in the worst case. This means:
6654 ///     + "extern __thread" declaration.
6655 ///     + Defined in a possibly unknown dynamic library.
6656 ///
6657 /// The general system is that each __thread variable has a [3 x i64] descriptor
6658 /// which contains information used by the runtime to calculate the address. The
6659 /// only part of this the compiler needs to know about is the first xword, which
6660 /// contains a function pointer that must be called with the address of the
6661 /// entire descriptor in "x0".
6662 ///
6663 /// Since this descriptor may be in a different unit, in general even the
6664 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
6665 /// is:
6666 ///     adrp x0, _var@TLVPPAGE
6667 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
6668 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
6669 ///                                      ; the function pointer
6670 ///     blr x1                           ; Uses descriptor address in x0
6671 ///     ; Address of _var is now in x0.
6672 ///
6673 /// If the address of _var's descriptor *is* known to the linker, then it can
6674 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
6675 /// a slight efficiency gain.
6676 SDValue
6677 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
6678                                                    SelectionDAG &DAG) const {
6679   assert(Subtarget->isTargetDarwin() &&
6680          "This function expects a Darwin target");
6681 
6682   SDLoc DL(Op);
6683   MVT PtrVT = getPointerTy(DAG.getDataLayout());
6684   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6685   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6686 
6687   SDValue TLVPAddr =
6688       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6689   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
6690 
6691   // The first entry in the descriptor is a function pointer that we must call
6692   // to obtain the address of the variable.
6693   SDValue Chain = DAG.getEntryNode();
6694   SDValue FuncTLVGet = DAG.getLoad(
6695       PtrMemVT, DL, Chain, DescAddr,
6696       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
6697       Align(PtrMemVT.getSizeInBits() / 8),
6698       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6699   Chain = FuncTLVGet.getValue(1);
6700 
6701   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
6702   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
6703 
6704   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6705   MFI.setAdjustsStack(true);
6706 
6707   // TLS calls preserve all registers except those that absolutely must be
6708   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
6709   // silly).
6710   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
6711   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
6712   if (Subtarget->hasCustomCallingConv())
6713     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
6714 
6715   // Finally, we can make the call. This is just a degenerate version of a
6716   // normal AArch64 call node: x0 takes the address of the descriptor, and
6717   // returns the address of the variable in this thread.
6718   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
6719   Chain =
6720       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
6721                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
6722                   DAG.getRegisterMask(Mask), Chain.getValue(1));
6723   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
6724 }
6725 
6726 /// Convert a thread-local variable reference into a sequence of instructions to
6727 /// compute the variable's address for the local exec TLS model of ELF targets.
6728 /// The sequence depends on the maximum TLS area size.
6729 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
6730                                                     SDValue ThreadBase,
6731                                                     const SDLoc &DL,
6732                                                     SelectionDAG &DAG) const {
6733   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6734   SDValue TPOff, Addr;
6735 
6736   switch (DAG.getTarget().Options.TLSSize) {
6737   default:
6738     llvm_unreachable("Unexpected TLS size");
6739 
6740   case 12: {
6741     // mrs   x0, TPIDR_EL0
6742     // add   x0, x0, :tprel_lo12:a
6743     SDValue Var = DAG.getTargetGlobalAddress(
6744         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
6745     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6746                                       Var,
6747                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6748                    0);
6749   }
6750 
6751   case 24: {
6752     // mrs   x0, TPIDR_EL0
6753     // add   x0, x0, :tprel_hi12:a
6754     // add   x0, x0, :tprel_lo12_nc:a
6755     SDValue HiVar = DAG.getTargetGlobalAddress(
6756         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6757     SDValue LoVar = DAG.getTargetGlobalAddress(
6758         GV, DL, PtrVT, 0,
6759         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6760     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
6761                                       HiVar,
6762                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6763                    0);
6764     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
6765                                       LoVar,
6766                                       DAG.getTargetConstant(0, DL, MVT::i32)),
6767                    0);
6768   }
6769 
6770   case 32: {
6771     // mrs   x1, TPIDR_EL0
6772     // movz  x0, #:tprel_g1:a
6773     // movk  x0, #:tprel_g0_nc:a
6774     // add   x0, x1, x0
6775     SDValue HiVar = DAG.getTargetGlobalAddress(
6776         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
6777     SDValue LoVar = DAG.getTargetGlobalAddress(
6778         GV, DL, PtrVT, 0,
6779         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6780     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6781                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6782                     0);
6783     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6784                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6785                     0);
6786     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6787   }
6788 
6789   case 48: {
6790     // mrs   x1, TPIDR_EL0
6791     // movz  x0, #:tprel_g2:a
6792     // movk  x0, #:tprel_g1_nc:a
6793     // movk  x0, #:tprel_g0_nc:a
6794     // add   x0, x1, x0
6795     SDValue HiVar = DAG.getTargetGlobalAddress(
6796         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
6797     SDValue MiVar = DAG.getTargetGlobalAddress(
6798         GV, DL, PtrVT, 0,
6799         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
6800     SDValue LoVar = DAG.getTargetGlobalAddress(
6801         GV, DL, PtrVT, 0,
6802         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
6803     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
6804                                        DAG.getTargetConstant(32, DL, MVT::i32)),
6805                     0);
6806     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
6807                                        DAG.getTargetConstant(16, DL, MVT::i32)),
6808                     0);
6809     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
6810                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6811                     0);
6812     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6813   }
6814   }
6815 }
6816 
6817 /// When accessing thread-local variables under either the general-dynamic or
6818 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
6819 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
6820 /// is a function pointer to carry out the resolution.
6821 ///
6822 /// The sequence is:
6823 ///    adrp  x0, :tlsdesc:var
6824 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
6825 ///    add   x0, x0, #:tlsdesc_lo12:var
6826 ///    .tlsdesccall var
6827 ///    blr   x1
6828 ///    (TPIDR_EL0 offset now in x0)
6829 ///
6830 ///  The above sequence must be produced unscheduled, to enable the linker to
6831 ///  optimize/relax this sequence.
6832 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
6833 ///  above sequence, and expanded really late in the compilation flow, to ensure
6834 ///  the sequence is produced as per above.
6835 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
6836                                                       const SDLoc &DL,
6837                                                       SelectionDAG &DAG) const {
6838   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6839 
6840   SDValue Chain = DAG.getEntryNode();
6841   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6842 
6843   Chain =
6844       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
6845   SDValue Glue = Chain.getValue(1);
6846 
6847   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
6848 }
6849 
6850 SDValue
6851 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
6852                                                 SelectionDAG &DAG) const {
6853   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
6854 
6855   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6856 
6857   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
6858 
6859   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
6860     if (Model == TLSModel::LocalDynamic)
6861       Model = TLSModel::GeneralDynamic;
6862   }
6863 
6864   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6865       Model != TLSModel::LocalExec)
6866     report_fatal_error("ELF TLS only supported in small memory model or "
6867                        "in local exec TLS model");
6868   // Different choices can be made for the maximum size of the TLS area for a
6869   // module. For the small address model, the default TLS size is 16MiB and the
6870   // maximum TLS size is 4GiB.
6871   // FIXME: add tiny and large code model support for TLS access models other
6872   // than local exec. We currently generate the same code as small for tiny,
6873   // which may be larger than needed.
6874 
6875   SDValue TPOff;
6876   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6877   SDLoc DL(Op);
6878   const GlobalValue *GV = GA->getGlobal();
6879 
6880   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
6881 
6882   if (Model == TLSModel::LocalExec) {
6883     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
6884   } else if (Model == TLSModel::InitialExec) {
6885     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6886     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
6887   } else if (Model == TLSModel::LocalDynamic) {
6888     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
6889     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
6890     // the beginning of the module's TLS region, followed by a DTPREL offset
6891     // calculation.
6892 
6893     // These accesses will need deduplicating if there's more than one.
6894     AArch64FunctionInfo *MFI =
6895         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6896     MFI->incNumLocalDynamicTLSAccesses();
6897 
6898     // The call needs a relocation too for linker relaxation. It doesn't make
6899     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6900     // the address.
6901     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
6902                                                   AArch64II::MO_TLS);
6903 
6904     // Now we can calculate the offset from TPIDR_EL0 to this module's
6905     // thread-local area.
6906     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6907 
6908     // Now use :dtprel_whatever: operations to calculate this variable's offset
6909     // in its thread-storage area.
6910     SDValue HiVar = DAG.getTargetGlobalAddress(
6911         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6912     SDValue LoVar = DAG.getTargetGlobalAddress(
6913         GV, DL, MVT::i64, 0,
6914         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6915 
6916     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
6917                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6918                     0);
6919     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
6920                                        DAG.getTargetConstant(0, DL, MVT::i32)),
6921                     0);
6922   } else if (Model == TLSModel::GeneralDynamic) {
6923     // The call needs a relocation too for linker relaxation. It doesn't make
6924     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
6925     // the address.
6926     SDValue SymAddr =
6927         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
6928 
6929     // Finally we can make a call to calculate the offset from tpidr_el0.
6930     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
6931   } else
6932     llvm_unreachable("Unsupported ELF TLS access model");
6933 
6934   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
6935 }
6936 
6937 SDValue
6938 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
6939                                                     SelectionDAG &DAG) const {
6940   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
6941 
6942   SDValue Chain = DAG.getEntryNode();
6943   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6944   SDLoc DL(Op);
6945 
6946   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
6947 
6948   // Load the ThreadLocalStoragePointer from the TEB
6949   // A pointer to the TLS array is located at offset 0x58 from the TEB.
6950   SDValue TLSArray =
6951       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
6952   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
6953   Chain = TLSArray.getValue(1);
6954 
6955   // Load the TLS index from the C runtime;
6956   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
6957   // This also does the same as LOADgot, but using a generic i32 load,
6958   // while LOADgot only loads i64.
6959   SDValue TLSIndexHi =
6960       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
6961   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
6962       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6963   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
6964   SDValue TLSIndex =
6965       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
6966   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
6967   Chain = TLSIndex.getValue(1);
6968 
6969   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
6970   // offset into the TLSArray.
6971   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
6972   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
6973                              DAG.getConstant(3, DL, PtrVT));
6974   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
6975                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
6976                             MachinePointerInfo());
6977   Chain = TLS.getValue(1);
6978 
6979   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6980   const GlobalValue *GV = GA->getGlobal();
6981   SDValue TGAHi = DAG.getTargetGlobalAddress(
6982       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
6983   SDValue TGALo = DAG.getTargetGlobalAddress(
6984       GV, DL, PtrVT, 0,
6985       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
6986 
6987   // Add the offset from the start of the .tls section (section base).
6988   SDValue Addr =
6989       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
6990                                  DAG.getTargetConstant(0, DL, MVT::i32)),
6991               0);
6992   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
6993   return Addr;
6994 }
6995 
6996 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
6997                                                      SelectionDAG &DAG) const {
6998   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6999   if (DAG.getTarget().useEmulatedTLS())
7000     return LowerToTLSEmulatedModel(GA, DAG);
7001 
7002   if (Subtarget->isTargetDarwin())
7003     return LowerDarwinGlobalTLSAddress(Op, DAG);
7004   if (Subtarget->isTargetELF())
7005     return LowerELFGlobalTLSAddress(Op, DAG);
7006   if (Subtarget->isTargetWindows())
7007     return LowerWindowsGlobalTLSAddress(Op, DAG);
7008 
7009   llvm_unreachable("Unexpected platform trying to use TLS");
7010 }
7011 
7012 // Looks through \param Val to determine the bit that can be used to
7013 // check the sign of the value. It returns the unextended value and
7014 // the sign bit position.
7015 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
7016   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
7017     return {Val.getOperand(0),
7018             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
7019                 1};
7020 
7021   if (Val.getOpcode() == ISD::SIGN_EXTEND)
7022     return {Val.getOperand(0),
7023             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
7024 
7025   return {Val, Val.getValueSizeInBits() - 1};
7026 }
7027 
7028 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
7029   SDValue Chain = Op.getOperand(0);
7030   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
7031   SDValue LHS = Op.getOperand(2);
7032   SDValue RHS = Op.getOperand(3);
7033   SDValue Dest = Op.getOperand(4);
7034   SDLoc dl(Op);
7035 
7036   MachineFunction &MF = DAG.getMachineFunction();
7037   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
7038   // will not be produced, as they are conditional branch instructions that do
7039   // not set flags.
7040   bool ProduceNonFlagSettingCondBr =
7041       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
7042 
7043   // Handle f128 first, since lowering it will result in comparing the return
7044   // value of a libcall against zero, which is just what the rest of LowerBR_CC
7045   // is expecting to deal with.
7046   if (LHS.getValueType() == MVT::f128) {
7047     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
7048 
7049     // If softenSetCCOperands returned a scalar, we need to compare the result
7050     // against zero to select between true and false values.
7051     if (!RHS.getNode()) {
7052       RHS = DAG.getConstant(0, dl, LHS.getValueType());
7053       CC = ISD::SETNE;
7054     }
7055   }
7056 
7057   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
7058   // instruction.
7059   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
7060       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7061     // Only lower legal XALUO ops.
7062     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
7063       return SDValue();
7064 
7065     // The actual operation with overflow check.
7066     AArch64CC::CondCode OFCC;
7067     SDValue Value, Overflow;
7068     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
7069 
7070     if (CC == ISD::SETNE)
7071       OFCC = getInvertedCondCode(OFCC);
7072     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
7073 
7074     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7075                        Overflow);
7076   }
7077 
7078   if (LHS.getValueType().isInteger()) {
7079     assert((LHS.getValueType() == RHS.getValueType()) &&
7080            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7081 
7082     // If the RHS of the comparison is zero, we can potentially fold this
7083     // to a specialized branch.
7084     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7085     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
7086       if (CC == ISD::SETEQ) {
7087         // See if we can use a TBZ to fold in an AND as well.
7088         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7089         // out of bounds, a late MI-layer pass rewrites branches.
7090         // 403.gcc is an example that hits this case.
7091         if (LHS.getOpcode() == ISD::AND &&
7092             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7093             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7094           SDValue Test = LHS.getOperand(0);
7095           uint64_t Mask = LHS.getConstantOperandVal(1);
7096           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
7097                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7098                              Dest);
7099         }
7100 
7101         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
7102       } else if (CC == ISD::SETNE) {
7103         // See if we can use a TBZ to fold in an AND as well.
7104         // TBZ has a smaller branch displacement than CBZ.  If the offset is
7105         // out of bounds, a late MI-layer pass rewrites branches.
7106         // 403.gcc is an example that hits this case.
7107         if (LHS.getOpcode() == ISD::AND &&
7108             isa<ConstantSDNode>(LHS.getOperand(1)) &&
7109             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
7110           SDValue Test = LHS.getOperand(0);
7111           uint64_t Mask = LHS.getConstantOperandVal(1);
7112           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
7113                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
7114                              Dest);
7115         }
7116 
7117         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
7118       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
7119         // Don't combine AND since emitComparison converts the AND to an ANDS
7120         // (a.k.a. TST) and the test in the test bit and branch instruction
7121         // becomes redundant.  This would also increase register pressure.
7122         uint64_t SignBitPos;
7123         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7124         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
7125                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7126       }
7127     }
7128     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
7129         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
7130       // Don't combine AND since emitComparison converts the AND to an ANDS
7131       // (a.k.a. TST) and the test in the test bit and branch instruction
7132       // becomes redundant.  This would also increase register pressure.
7133       uint64_t SignBitPos;
7134       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
7135       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
7136                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
7137     }
7138 
7139     SDValue CCVal;
7140     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7141     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
7142                        Cmp);
7143   }
7144 
7145   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
7146          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
7147 
7148   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7149   // clean.  Some of them require two branches to implement.
7150   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7151   AArch64CC::CondCode CC1, CC2;
7152   changeFPCCToAArch64CC(CC, CC1, CC2);
7153   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7154   SDValue BR1 =
7155       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
7156   if (CC2 != AArch64CC::AL) {
7157     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7158     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
7159                        Cmp);
7160   }
7161 
7162   return BR1;
7163 }
7164 
7165 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
7166                                               SelectionDAG &DAG) const {
7167   EVT VT = Op.getValueType();
7168   SDLoc DL(Op);
7169 
7170   SDValue In1 = Op.getOperand(0);
7171   SDValue In2 = Op.getOperand(1);
7172   EVT SrcVT = In2.getValueType();
7173 
7174   if (VT.isScalableVector()) {
7175     if (VT != SrcVT)
7176       return SDValue();
7177 
7178     // copysign(x,y) -> (y & SIGN_MASK) | (x & ~SIGN_MASK)
7179     //
7180     // A possible alternative sequence involves using FNEG_MERGE_PASSTHRU;
7181     // maybe useful for copysign operations with mismatched VTs.
7182     //
7183     // IntVT here is chosen so it's a legal type with the same element width
7184     // as the input.
7185     EVT IntVT =
7186         getPackedSVEVectorVT(VT.getVectorElementType().changeTypeToInteger());
7187     unsigned NumBits = VT.getScalarSizeInBits();
7188     SDValue SignMask = DAG.getConstant(APInt::getSignMask(NumBits), DL, IntVT);
7189     SDValue InvSignMask = DAG.getNOT(DL, SignMask, IntVT);
7190     SDValue Sign = DAG.getNode(ISD::AND, DL, IntVT, SignMask,
7191                                getSVESafeBitCast(IntVT, In2, DAG));
7192     SDValue Magnitude = DAG.getNode(ISD::AND, DL, IntVT, InvSignMask,
7193                                     getSVESafeBitCast(IntVT, In1, DAG));
7194     SDValue IntResult = DAG.getNode(ISD::OR, DL, IntVT, Sign, Magnitude);
7195     return getSVESafeBitCast(VT, IntResult, DAG);
7196   }
7197 
7198   if (SrcVT.bitsLT(VT))
7199     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
7200   else if (SrcVT.bitsGT(VT))
7201     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
7202 
7203   EVT VecVT;
7204   uint64_t EltMask;
7205   SDValue VecVal1, VecVal2;
7206 
7207   auto setVecVal = [&] (int Idx) {
7208     if (!VT.isVector()) {
7209       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7210                                           DAG.getUNDEF(VecVT), In1);
7211       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
7212                                           DAG.getUNDEF(VecVT), In2);
7213     } else {
7214       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
7215       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
7216     }
7217   };
7218 
7219   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
7220     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
7221     EltMask = 0x80000000ULL;
7222     setVecVal(AArch64::ssub);
7223   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
7224     VecVT = MVT::v2i64;
7225 
7226     // We want to materialize a mask with the high bit set, but the AdvSIMD
7227     // immediate moves cannot materialize that in a single instruction for
7228     // 64-bit elements. Instead, materialize zero and then negate it.
7229     EltMask = 0;
7230 
7231     setVecVal(AArch64::dsub);
7232   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
7233     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
7234     EltMask = 0x8000ULL;
7235     setVecVal(AArch64::hsub);
7236   } else {
7237     llvm_unreachable("Invalid type for copysign!");
7238   }
7239 
7240   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
7241 
7242   // If we couldn't materialize the mask above, then the mask vector will be
7243   // the zero vector, and we need to negate it here.
7244   if (VT == MVT::f64 || VT == MVT::v2f64) {
7245     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
7246     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
7247     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
7248   }
7249 
7250   SDValue Sel =
7251       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
7252 
7253   if (VT == MVT::f16)
7254     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
7255   if (VT == MVT::f32)
7256     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
7257   else if (VT == MVT::f64)
7258     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
7259   else
7260     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
7261 }
7262 
7263 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
7264   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
7265           Attribute::NoImplicitFloat))
7266     return SDValue();
7267 
7268   if (!Subtarget->hasNEON())
7269     return SDValue();
7270 
7271   // While there is no integer popcount instruction, it can
7272   // be more efficiently lowered to the following sequence that uses
7273   // AdvSIMD registers/instructions as long as the copies to/from
7274   // the AdvSIMD registers are cheap.
7275   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
7276   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
7277   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
7278   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
7279   SDValue Val = Op.getOperand(0);
7280   SDLoc DL(Op);
7281   EVT VT = Op.getValueType();
7282 
7283   if (VT == MVT::i32 || VT == MVT::i64) {
7284     if (VT == MVT::i32)
7285       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
7286     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
7287 
7288     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
7289     SDValue UaddLV = DAG.getNode(
7290         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7291         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7292 
7293     if (VT == MVT::i64)
7294       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
7295     return UaddLV;
7296   } else if (VT == MVT::i128) {
7297     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
7298 
7299     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
7300     SDValue UaddLV = DAG.getNode(
7301         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
7302         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
7303 
7304     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
7305   }
7306 
7307   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
7308     return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
7309 
7310   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
7311           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
7312          "Unexpected type for custom ctpop lowering");
7313 
7314   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
7315   Val = DAG.getBitcast(VT8Bit, Val);
7316   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
7317 
7318   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
7319   unsigned EltSize = 8;
7320   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
7321   while (EltSize != VT.getScalarSizeInBits()) {
7322     EltSize *= 2;
7323     NumElts /= 2;
7324     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
7325     Val = DAG.getNode(
7326         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
7327         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
7328   }
7329 
7330   return Val;
7331 }
7332 
7333 SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7334   EVT VT = Op.getValueType();
7335   assert(VT.isScalableVector() ||
7336          useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
7337 
7338   SDLoc DL(Op);
7339   SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
7340   return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
7341 }
7342 
7343 SDValue AArch64TargetLowering::LowerMinMax(SDValue Op,
7344                                            SelectionDAG &DAG) const {
7345 
7346   EVT VT = Op.getValueType();
7347   SDLoc DL(Op);
7348   unsigned Opcode = Op.getOpcode();
7349   ISD::CondCode CC;
7350   switch (Opcode) {
7351   default:
7352     llvm_unreachable("Wrong instruction");
7353   case ISD::SMAX:
7354     CC = ISD::SETGT;
7355     break;
7356   case ISD::SMIN:
7357     CC = ISD::SETLT;
7358     break;
7359   case ISD::UMAX:
7360     CC = ISD::SETUGT;
7361     break;
7362   case ISD::UMIN:
7363     CC = ISD::SETULT;
7364     break;
7365   }
7366 
7367   if (VT.isScalableVector() ||
7368       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) {
7369     switch (Opcode) {
7370     default:
7371       llvm_unreachable("Wrong instruction");
7372     case ISD::SMAX:
7373       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
7374                                  /*OverrideNEON=*/true);
7375     case ISD::SMIN:
7376       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
7377                                  /*OverrideNEON=*/true);
7378     case ISD::UMAX:
7379       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
7380                                  /*OverrideNEON=*/true);
7381     case ISD::UMIN:
7382       return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
7383                                  /*OverrideNEON=*/true);
7384     }
7385   }
7386 
7387   SDValue Op0 = Op.getOperand(0);
7388   SDValue Op1 = Op.getOperand(1);
7389   SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
7390   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
7391 }
7392 
7393 SDValue AArch64TargetLowering::LowerBitreverse(SDValue Op,
7394                                                SelectionDAG &DAG) const {
7395   EVT VT = Op.getValueType();
7396 
7397   if (VT.isScalableVector() ||
7398       useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
7399     return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
7400                                true);
7401 
7402   SDLoc DL(Op);
7403   SDValue REVB;
7404   MVT VST;
7405 
7406   switch (VT.getSimpleVT().SimpleTy) {
7407   default:
7408     llvm_unreachable("Invalid type for bitreverse!");
7409 
7410   case MVT::v2i32: {
7411     VST = MVT::v8i8;
7412     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7413 
7414     break;
7415   }
7416 
7417   case MVT::v4i32: {
7418     VST = MVT::v16i8;
7419     REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
7420 
7421     break;
7422   }
7423 
7424   case MVT::v1i64: {
7425     VST = MVT::v8i8;
7426     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7427 
7428     break;
7429   }
7430 
7431   case MVT::v2i64: {
7432     VST = MVT::v16i8;
7433     REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
7434 
7435     break;
7436   }
7437   }
7438 
7439   return DAG.getNode(AArch64ISD::NVCAST, DL, VT,
7440                      DAG.getNode(ISD::BITREVERSE, DL, VST, REVB));
7441 }
7442 
7443 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7444 
7445   if (Op.getValueType().isVector())
7446     return LowerVSETCC(Op, DAG);
7447 
7448   bool IsStrict = Op->isStrictFPOpcode();
7449   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
7450   unsigned OpNo = IsStrict ? 1 : 0;
7451   SDValue Chain;
7452   if (IsStrict)
7453     Chain = Op.getOperand(0);
7454   SDValue LHS = Op.getOperand(OpNo + 0);
7455   SDValue RHS = Op.getOperand(OpNo + 1);
7456   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
7457   SDLoc dl(Op);
7458 
7459   // We chose ZeroOrOneBooleanContents, so use zero and one.
7460   EVT VT = Op.getValueType();
7461   SDValue TVal = DAG.getConstant(1, dl, VT);
7462   SDValue FVal = DAG.getConstant(0, dl, VT);
7463 
7464   // Handle f128 first, since one possible outcome is a normal integer
7465   // comparison which gets picked up by the next if statement.
7466   if (LHS.getValueType() == MVT::f128) {
7467     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
7468                         IsSignaling);
7469 
7470     // If softenSetCCOperands returned a scalar, use it.
7471     if (!RHS.getNode()) {
7472       assert(LHS.getValueType() == Op.getValueType() &&
7473              "Unexpected setcc expansion!");
7474       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
7475     }
7476   }
7477 
7478   if (LHS.getValueType().isInteger()) {
7479     SDValue CCVal;
7480     SDValue Cmp = getAArch64Cmp(
7481         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
7482 
7483     // Note that we inverted the condition above, so we reverse the order of
7484     // the true and false operands here.  This will allow the setcc to be
7485     // matched to a single CSINC instruction.
7486     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
7487     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
7488   }
7489 
7490   // Now we know we're dealing with FP values.
7491   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7492          LHS.getValueType() == MVT::f64);
7493 
7494   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
7495   // and do the comparison.
7496   SDValue Cmp;
7497   if (IsStrict)
7498     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
7499   else
7500     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7501 
7502   AArch64CC::CondCode CC1, CC2;
7503   changeFPCCToAArch64CC(CC, CC1, CC2);
7504   SDValue Res;
7505   if (CC2 == AArch64CC::AL) {
7506     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
7507                           CC2);
7508     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7509 
7510     // Note that we inverted the condition above, so we reverse the order of
7511     // the true and false operands here.  This will allow the setcc to be
7512     // matched to a single CSINC instruction.
7513     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
7514   } else {
7515     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
7516     // totally clean.  Some of them require two CSELs to implement.  As is in
7517     // this case, we emit the first CSEL and then emit a second using the output
7518     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
7519 
7520     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
7521     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7522     SDValue CS1 =
7523         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7524 
7525     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7526     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7527   }
7528   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
7529 }
7530 
7531 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
7532                                               SDValue RHS, SDValue TVal,
7533                                               SDValue FVal, const SDLoc &dl,
7534                                               SelectionDAG &DAG) const {
7535   // Handle f128 first, because it will result in a comparison of some RTLIB
7536   // call result against zero.
7537   if (LHS.getValueType() == MVT::f128) {
7538     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
7539 
7540     // If softenSetCCOperands returned a scalar, we need to compare the result
7541     // against zero to select between true and false values.
7542     if (!RHS.getNode()) {
7543       RHS = DAG.getConstant(0, dl, LHS.getValueType());
7544       CC = ISD::SETNE;
7545     }
7546   }
7547 
7548   // Also handle f16, for which we need to do a f32 comparison.
7549   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
7550     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
7551     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
7552   }
7553 
7554   // Next, handle integers.
7555   if (LHS.getValueType().isInteger()) {
7556     assert((LHS.getValueType() == RHS.getValueType()) &&
7557            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
7558 
7559     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
7560     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
7561     ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
7562     // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
7563     // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
7564     // supported types.
7565     if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
7566         CTVal->isOne() && CFVal->isAllOnes() &&
7567         LHS.getValueType() == TVal.getValueType()) {
7568       EVT VT = LHS.getValueType();
7569       SDValue Shift =
7570           DAG.getNode(ISD::SRA, dl, VT, LHS,
7571                       DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
7572       return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
7573     }
7574 
7575     unsigned Opcode = AArch64ISD::CSEL;
7576 
7577     // If both the TVal and the FVal are constants, see if we can swap them in
7578     // order to for a CSINV or CSINC out of them.
7579     if (CTVal && CFVal && CTVal->isAllOnes() && CFVal->isZero()) {
7580       std::swap(TVal, FVal);
7581       std::swap(CTVal, CFVal);
7582       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7583     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isZero()) {
7584       std::swap(TVal, FVal);
7585       std::swap(CTVal, CFVal);
7586       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7587     } else if (TVal.getOpcode() == ISD::XOR) {
7588       // If TVal is a NOT we want to swap TVal and FVal so that we can match
7589       // with a CSINV rather than a CSEL.
7590       if (isAllOnesConstant(TVal.getOperand(1))) {
7591         std::swap(TVal, FVal);
7592         std::swap(CTVal, CFVal);
7593         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7594       }
7595     } else if (TVal.getOpcode() == ISD::SUB) {
7596       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
7597       // that we can match with a CSNEG rather than a CSEL.
7598       if (isNullConstant(TVal.getOperand(0))) {
7599         std::swap(TVal, FVal);
7600         std::swap(CTVal, CFVal);
7601         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7602       }
7603     } else if (CTVal && CFVal) {
7604       const int64_t TrueVal = CTVal->getSExtValue();
7605       const int64_t FalseVal = CFVal->getSExtValue();
7606       bool Swap = false;
7607 
7608       // If both TVal and FVal are constants, see if FVal is the
7609       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
7610       // instead of a CSEL in that case.
7611       if (TrueVal == ~FalseVal) {
7612         Opcode = AArch64ISD::CSINV;
7613       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
7614                  TrueVal == -FalseVal) {
7615         Opcode = AArch64ISD::CSNEG;
7616       } else if (TVal.getValueType() == MVT::i32) {
7617         // If our operands are only 32-bit wide, make sure we use 32-bit
7618         // arithmetic for the check whether we can use CSINC. This ensures that
7619         // the addition in the check will wrap around properly in case there is
7620         // an overflow (which would not be the case if we do the check with
7621         // 64-bit arithmetic).
7622         const uint32_t TrueVal32 = CTVal->getZExtValue();
7623         const uint32_t FalseVal32 = CFVal->getZExtValue();
7624 
7625         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
7626           Opcode = AArch64ISD::CSINC;
7627 
7628           if (TrueVal32 > FalseVal32) {
7629             Swap = true;
7630           }
7631         }
7632         // 64-bit check whether we can use CSINC.
7633       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
7634         Opcode = AArch64ISD::CSINC;
7635 
7636         if (TrueVal > FalseVal) {
7637           Swap = true;
7638         }
7639       }
7640 
7641       // Swap TVal and FVal if necessary.
7642       if (Swap) {
7643         std::swap(TVal, FVal);
7644         std::swap(CTVal, CFVal);
7645         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
7646       }
7647 
7648       if (Opcode != AArch64ISD::CSEL) {
7649         // Drop FVal since we can get its value by simply inverting/negating
7650         // TVal.
7651         FVal = TVal;
7652       }
7653     }
7654 
7655     // Avoid materializing a constant when possible by reusing a known value in
7656     // a register.  However, don't perform this optimization if the known value
7657     // is one, zero or negative one in the case of a CSEL.  We can always
7658     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
7659     // FVal, respectively.
7660     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
7661     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
7662         !RHSVal->isZero() && !RHSVal->isAllOnes()) {
7663       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7664       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
7665       // "a != C ? x : a" to avoid materializing C.
7666       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
7667         TVal = LHS;
7668       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
7669         FVal = LHS;
7670     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
7671       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
7672       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
7673       // avoid materializing C.
7674       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7675       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
7676         Opcode = AArch64ISD::CSINV;
7677         TVal = LHS;
7678         FVal = DAG.getConstant(0, dl, FVal.getValueType());
7679       }
7680     }
7681 
7682     SDValue CCVal;
7683     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
7684     EVT VT = TVal.getValueType();
7685     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
7686   }
7687 
7688   // Now we know we're dealing with FP values.
7689   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
7690          LHS.getValueType() == MVT::f64);
7691   assert(LHS.getValueType() == RHS.getValueType());
7692   EVT VT = TVal.getValueType();
7693   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
7694 
7695   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7696   // clean.  Some of them require two CSELs to implement.
7697   AArch64CC::CondCode CC1, CC2;
7698   changeFPCCToAArch64CC(CC, CC1, CC2);
7699 
7700   if (DAG.getTarget().Options.UnsafeFPMath) {
7701     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
7702     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
7703     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
7704     if (RHSVal && RHSVal->isZero()) {
7705       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
7706       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
7707 
7708       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
7709           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
7710         TVal = LHS;
7711       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
7712                CFVal && CFVal->isZero() &&
7713                FVal.getValueType() == LHS.getValueType())
7714         FVal = LHS;
7715     }
7716   }
7717 
7718   // Emit first, and possibly only, CSEL.
7719   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
7720   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
7721 
7722   // If we need a second CSEL, emit it, using the output of the first as the
7723   // RHS.  We're effectively OR'ing the two CC's together.
7724   if (CC2 != AArch64CC::AL) {
7725     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
7726     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
7727   }
7728 
7729   // Otherwise, return the output of the first CSEL.
7730   return CS1;
7731 }
7732 
7733 SDValue AArch64TargetLowering::LowerVECTOR_SPLICE(SDValue Op,
7734                                                   SelectionDAG &DAG) const {
7735   EVT Ty = Op.getValueType();
7736   auto Idx = Op.getConstantOperandAPInt(2);
7737 
7738   // This will select to an EXT instruction, which has a maximum immediate
7739   // value of 255, hence 2048-bits is the maximum value we can lower.
7740   if (Idx.sge(-1) && Idx.slt(2048 / Ty.getVectorElementType().getSizeInBits()))
7741     return Op;
7742 
7743   return SDValue();
7744 }
7745 
7746 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
7747                                               SelectionDAG &DAG) const {
7748   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7749   SDValue LHS = Op.getOperand(0);
7750   SDValue RHS = Op.getOperand(1);
7751   SDValue TVal = Op.getOperand(2);
7752   SDValue FVal = Op.getOperand(3);
7753   SDLoc DL(Op);
7754   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
7755 }
7756 
7757 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
7758                                            SelectionDAG &DAG) const {
7759   SDValue CCVal = Op->getOperand(0);
7760   SDValue TVal = Op->getOperand(1);
7761   SDValue FVal = Op->getOperand(2);
7762   SDLoc DL(Op);
7763 
7764   EVT Ty = Op.getValueType();
7765   if (Ty.isScalableVector()) {
7766     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
7767     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
7768     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
7769     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7770   }
7771 
7772   if (useSVEForFixedLengthVectorVT(Ty)) {
7773     // FIXME: Ideally this would be the same as above using i1 types, however
7774     // for the moment we can't deal with fixed i1 vector types properly, so
7775     // instead extend the predicate to a result type sized integer vector.
7776     MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits());
7777     MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount());
7778     SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT);
7779     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal);
7780     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
7781   }
7782 
7783   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
7784   // instruction.
7785   if (ISD::isOverflowIntrOpRes(CCVal)) {
7786     // Only lower legal XALUO ops.
7787     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
7788       return SDValue();
7789 
7790     AArch64CC::CondCode OFCC;
7791     SDValue Value, Overflow;
7792     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
7793     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
7794 
7795     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
7796                        CCVal, Overflow);
7797   }
7798 
7799   // Lower it the same way as we would lower a SELECT_CC node.
7800   ISD::CondCode CC;
7801   SDValue LHS, RHS;
7802   if (CCVal.getOpcode() == ISD::SETCC) {
7803     LHS = CCVal.getOperand(0);
7804     RHS = CCVal.getOperand(1);
7805     CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
7806   } else {
7807     LHS = CCVal;
7808     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
7809     CC = ISD::SETNE;
7810   }
7811   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
7812 }
7813 
7814 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
7815                                               SelectionDAG &DAG) const {
7816   // Jump table entries as PC relative offsets. No additional tweaking
7817   // is necessary here. Just get the address of the jump table.
7818   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7819 
7820   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7821       !Subtarget->isTargetMachO()) {
7822     return getAddrLarge(JT, DAG);
7823   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7824     return getAddrTiny(JT, DAG);
7825   }
7826   return getAddr(JT, DAG);
7827 }
7828 
7829 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
7830                                           SelectionDAG &DAG) const {
7831   // Jump table entries as PC relative offsets. No additional tweaking
7832   // is necessary here. Just get the address of the jump table.
7833   SDLoc DL(Op);
7834   SDValue JT = Op.getOperand(1);
7835   SDValue Entry = Op.getOperand(2);
7836   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
7837 
7838   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7839   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
7840 
7841   SDNode *Dest =
7842       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
7843                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
7844   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
7845                      SDValue(Dest, 0));
7846 }
7847 
7848 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
7849                                                  SelectionDAG &DAG) const {
7850   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7851 
7852   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
7853     // Use the GOT for the large code model on iOS.
7854     if (Subtarget->isTargetMachO()) {
7855       return getGOT(CP, DAG);
7856     }
7857     return getAddrLarge(CP, DAG);
7858   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7859     return getAddrTiny(CP, DAG);
7860   } else {
7861     return getAddr(CP, DAG);
7862   }
7863 }
7864 
7865 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
7866                                                SelectionDAG &DAG) const {
7867   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
7868   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
7869       !Subtarget->isTargetMachO()) {
7870     return getAddrLarge(BA, DAG);
7871   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
7872     return getAddrTiny(BA, DAG);
7873   }
7874   return getAddr(BA, DAG);
7875 }
7876 
7877 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
7878                                                  SelectionDAG &DAG) const {
7879   AArch64FunctionInfo *FuncInfo =
7880       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7881 
7882   SDLoc DL(Op);
7883   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
7884                                  getPointerTy(DAG.getDataLayout()));
7885   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
7886   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7887   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7888                       MachinePointerInfo(SV));
7889 }
7890 
7891 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
7892                                                   SelectionDAG &DAG) const {
7893   AArch64FunctionInfo *FuncInfo =
7894       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
7895 
7896   SDLoc DL(Op);
7897   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
7898                                      ? FuncInfo->getVarArgsGPRIndex()
7899                                      : FuncInfo->getVarArgsStackIndex(),
7900                                  getPointerTy(DAG.getDataLayout()));
7901   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7902   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7903                       MachinePointerInfo(SV));
7904 }
7905 
7906 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
7907                                                   SelectionDAG &DAG) const {
7908   // The layout of the va_list struct is specified in the AArch64 Procedure Call
7909   // Standard, section B.3.
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
7912   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
7913   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
7914   auto PtrVT = getPointerTy(DAG.getDataLayout());
7915   SDLoc DL(Op);
7916 
7917   SDValue Chain = Op.getOperand(0);
7918   SDValue VAList = Op.getOperand(1);
7919   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7920   SmallVector<SDValue, 4> MemOps;
7921 
7922   // void *__stack at offset 0
7923   unsigned Offset = 0;
7924   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
7925   Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
7926   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
7927                                 MachinePointerInfo(SV), Align(PtrSize)));
7928 
7929   // void *__gr_top at offset 8 (4 on ILP32)
7930   Offset += PtrSize;
7931   int GPRSize = FuncInfo->getVarArgsGPRSize();
7932   if (GPRSize > 0) {
7933     SDValue GRTop, GRTopAddr;
7934 
7935     GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7936                             DAG.getConstant(Offset, DL, PtrVT));
7937 
7938     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
7939     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
7940                         DAG.getConstant(GPRSize, DL, PtrVT));
7941     GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
7942 
7943     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
7944                                   MachinePointerInfo(SV, Offset),
7945                                   Align(PtrSize)));
7946   }
7947 
7948   // void *__vr_top at offset 16 (8 on ILP32)
7949   Offset += PtrSize;
7950   int FPRSize = FuncInfo->getVarArgsFPRSize();
7951   if (FPRSize > 0) {
7952     SDValue VRTop, VRTopAddr;
7953     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7954                             DAG.getConstant(Offset, DL, PtrVT));
7955 
7956     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
7957     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
7958                         DAG.getConstant(FPRSize, DL, PtrVT));
7959     VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
7960 
7961     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
7962                                   MachinePointerInfo(SV, Offset),
7963                                   Align(PtrSize)));
7964   }
7965 
7966   // int __gr_offs at offset 24 (12 on ILP32)
7967   Offset += PtrSize;
7968   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7969                                    DAG.getConstant(Offset, DL, PtrVT));
7970   MemOps.push_back(
7971       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
7972                    GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7973 
7974   // int __vr_offs at offset 28 (16 on ILP32)
7975   Offset += 4;
7976   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
7977                                    DAG.getConstant(Offset, DL, PtrVT));
7978   MemOps.push_back(
7979       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
7980                    VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
7981 
7982   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
7983 }
7984 
7985 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
7986                                             SelectionDAG &DAG) const {
7987   MachineFunction &MF = DAG.getMachineFunction();
7988 
7989   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
7990     return LowerWin64_VASTART(Op, DAG);
7991   else if (Subtarget->isTargetDarwin())
7992     return LowerDarwin_VASTART(Op, DAG);
7993   else
7994     return LowerAAPCS_VASTART(Op, DAG);
7995 }
7996 
7997 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
7998                                            SelectionDAG &DAG) const {
7999   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
8000   // pointer.
8001   SDLoc DL(Op);
8002   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
8003   unsigned VaListSize =
8004       (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
8005           ? PtrSize
8006           : Subtarget->isTargetILP32() ? 20 : 32;
8007   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
8008   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8009 
8010   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
8011                        DAG.getConstant(VaListSize, DL, MVT::i32),
8012                        Align(PtrSize), false, false, false,
8013                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
8014 }
8015 
8016 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
8017   assert(Subtarget->isTargetDarwin() &&
8018          "automatic va_arg instruction only works on Darwin");
8019 
8020   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8021   EVT VT = Op.getValueType();
8022   SDLoc DL(Op);
8023   SDValue Chain = Op.getOperand(0);
8024   SDValue Addr = Op.getOperand(1);
8025   MaybeAlign Align(Op.getConstantOperandVal(3));
8026   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
8027   auto PtrVT = getPointerTy(DAG.getDataLayout());
8028   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
8029   SDValue VAList =
8030       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
8031   Chain = VAList.getValue(1);
8032   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
8033 
8034   if (VT.isScalableVector())
8035     report_fatal_error("Passing SVE types to variadic functions is "
8036                        "currently not supported");
8037 
8038   if (Align && *Align > MinSlotSize) {
8039     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8040                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
8041     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
8042                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
8043   }
8044 
8045   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
8046   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
8047 
8048   // Scalar integer and FP values smaller than 64 bits are implicitly extended
8049   // up to 64 bits.  At the very least, we have to increase the striding of the
8050   // vaargs list to match this, and for FP values we need to introduce
8051   // FP_ROUND nodes as well.
8052   if (VT.isInteger() && !VT.isVector())
8053     ArgSize = std::max(ArgSize, MinSlotSize);
8054   bool NeedFPTrunc = false;
8055   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
8056     ArgSize = 8;
8057     NeedFPTrunc = true;
8058   }
8059 
8060   // Increment the pointer, VAList, to the next vaarg
8061   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
8062                                DAG.getConstant(ArgSize, DL, PtrVT));
8063   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
8064 
8065   // Store the incremented VAList to the legalized pointer
8066   SDValue APStore =
8067       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
8068 
8069   // Load the actual argument out of the pointer VAList
8070   if (NeedFPTrunc) {
8071     // Load the value as an f64.
8072     SDValue WideFP =
8073         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
8074     // Round the value down to an f32.
8075     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
8076                                    DAG.getIntPtrConstant(1, DL));
8077     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
8078     // Merge the rounded value with the chain output of the load.
8079     return DAG.getMergeValues(Ops, DL);
8080   }
8081 
8082   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
8083 }
8084 
8085 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
8086                                               SelectionDAG &DAG) const {
8087   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8088   MFI.setFrameAddressIsTaken(true);
8089 
8090   EVT VT = Op.getValueType();
8091   SDLoc DL(Op);
8092   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8093   SDValue FrameAddr =
8094       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
8095   while (Depth--)
8096     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
8097                             MachinePointerInfo());
8098 
8099   if (Subtarget->isTargetILP32())
8100     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
8101                             DAG.getValueType(VT));
8102 
8103   return FrameAddr;
8104 }
8105 
8106 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
8107                                               SelectionDAG &DAG) const {
8108   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8109 
8110   EVT VT = getPointerTy(DAG.getDataLayout());
8111   SDLoc DL(Op);
8112   int FI = MFI.CreateFixedObject(4, 0, false);
8113   return DAG.getFrameIndex(FI, VT);
8114 }
8115 
8116 #define GET_REGISTER_MATCHER
8117 #include "AArch64GenAsmMatcher.inc"
8118 
8119 // FIXME? Maybe this could be a TableGen attribute on some registers and
8120 // this table could be generated automatically from RegInfo.
8121 Register AArch64TargetLowering::
8122 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
8123   Register Reg = MatchRegisterName(RegName);
8124   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
8125     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
8126     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
8127     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
8128       Reg = 0;
8129   }
8130   if (Reg)
8131     return Reg;
8132   report_fatal_error(Twine("Invalid register name \""
8133                               + StringRef(RegName)  + "\"."));
8134 }
8135 
8136 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
8137                                                      SelectionDAG &DAG) const {
8138   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
8139 
8140   EVT VT = Op.getValueType();
8141   SDLoc DL(Op);
8142 
8143   SDValue FrameAddr =
8144       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
8145   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8146 
8147   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
8148 }
8149 
8150 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
8151                                                SelectionDAG &DAG) const {
8152   MachineFunction &MF = DAG.getMachineFunction();
8153   MachineFrameInfo &MFI = MF.getFrameInfo();
8154   MFI.setReturnAddressIsTaken(true);
8155 
8156   EVT VT = Op.getValueType();
8157   SDLoc DL(Op);
8158   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8159   SDValue ReturnAddress;
8160   if (Depth) {
8161     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8162     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
8163     ReturnAddress = DAG.getLoad(
8164         VT, DL, DAG.getEntryNode(),
8165         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
8166   } else {
8167     // Return LR, which contains the return address. Mark it an implicit
8168     // live-in.
8169     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
8170     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
8171   }
8172 
8173   // The XPACLRI instruction assembles to a hint-space instruction before
8174   // Armv8.3-A therefore this instruction can be safely used for any pre
8175   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
8176   // that instead.
8177   SDNode *St;
8178   if (Subtarget->hasPAuth()) {
8179     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
8180   } else {
8181     // XPACLRI operates on LR therefore we must move the operand accordingly.
8182     SDValue Chain =
8183         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
8184     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
8185   }
8186   return SDValue(St, 0);
8187 }
8188 
8189 /// LowerShiftParts - Lower SHL_PARTS/SRA_PARTS/SRL_PARTS, which returns two
8190 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
8191 SDValue AArch64TargetLowering::LowerShiftParts(SDValue Op,
8192                                                SelectionDAG &DAG) const {
8193   SDValue Lo, Hi;
8194   expandShiftParts(Op.getNode(), Lo, Hi, DAG);
8195   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
8196 }
8197 
8198 bool AArch64TargetLowering::isOffsetFoldingLegal(
8199     const GlobalAddressSDNode *GA) const {
8200   // Offsets are folded in the DAG combine rather than here so that we can
8201   // intelligently choose an offset based on the uses.
8202   return false;
8203 }
8204 
8205 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
8206                                          bool OptForSize) const {
8207   bool IsLegal = false;
8208   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
8209   // 16-bit case when target has full fp16 support.
8210   // FIXME: We should be able to handle f128 as well with a clever lowering.
8211   const APInt ImmInt = Imm.bitcastToAPInt();
8212   if (VT == MVT::f64)
8213     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
8214   else if (VT == MVT::f32)
8215     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
8216   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
8217     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
8218   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
8219   //       generate that fmov.
8220 
8221   // If we can not materialize in immediate field for fmov, check if the
8222   // value can be encoded as the immediate operand of a logical instruction.
8223   // The immediate value will be created with either MOVZ, MOVN, or ORR.
8224   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
8225     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
8226     // however the mov+fmov sequence is always better because of the reduced
8227     // cache pressure. The timings are still the same if you consider
8228     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
8229     // movw+movk is fused). So we limit up to 2 instrdduction at most.
8230     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
8231     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
8232 			      Insn);
8233     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
8234     IsLegal = Insn.size() <= Limit;
8235   }
8236 
8237   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
8238                     << " imm value: "; Imm.dump(););
8239   return IsLegal;
8240 }
8241 
8242 //===----------------------------------------------------------------------===//
8243 //                          AArch64 Optimization Hooks
8244 //===----------------------------------------------------------------------===//
8245 
8246 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
8247                            SDValue Operand, SelectionDAG &DAG,
8248                            int &ExtraSteps) {
8249   EVT VT = Operand.getValueType();
8250   if ((ST->hasNEON() &&
8251        (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
8252         VT == MVT::f32 || VT == MVT::v1f32 || VT == MVT::v2f32 ||
8253         VT == MVT::v4f32)) ||
8254       (ST->hasSVE() &&
8255        (VT == MVT::nxv8f16 || VT == MVT::nxv4f32 || VT == MVT::nxv2f64))) {
8256     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
8257       // For the reciprocal estimates, convergence is quadratic, so the number
8258       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
8259       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
8260       // the result for float (23 mantissa bits) is 2 and for double (52
8261       // mantissa bits) is 3.
8262       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
8263 
8264     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
8265   }
8266 
8267   return SDValue();
8268 }
8269 
8270 SDValue
8271 AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
8272                                         const DenormalMode &Mode) const {
8273   SDLoc DL(Op);
8274   EVT VT = Op.getValueType();
8275   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8276   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
8277   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
8278 }
8279 
8280 SDValue
8281 AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
8282                                                    SelectionDAG &DAG) const {
8283   return Op;
8284 }
8285 
8286 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
8287                                                SelectionDAG &DAG, int Enabled,
8288                                                int &ExtraSteps,
8289                                                bool &UseOneConst,
8290                                                bool Reciprocal) const {
8291   if (Enabled == ReciprocalEstimate::Enabled ||
8292       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
8293     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
8294                                        DAG, ExtraSteps)) {
8295       SDLoc DL(Operand);
8296       EVT VT = Operand.getValueType();
8297 
8298       SDNodeFlags Flags;
8299       Flags.setAllowReassociation(true);
8300 
8301       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
8302       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
8303       for (int i = ExtraSteps; i > 0; --i) {
8304         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
8305                                    Flags);
8306         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
8307         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8308       }
8309       if (!Reciprocal)
8310         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
8311 
8312       ExtraSteps = 0;
8313       return Estimate;
8314     }
8315 
8316   return SDValue();
8317 }
8318 
8319 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
8320                                                 SelectionDAG &DAG, int Enabled,
8321                                                 int &ExtraSteps) const {
8322   if (Enabled == ReciprocalEstimate::Enabled)
8323     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
8324                                        DAG, ExtraSteps)) {
8325       SDLoc DL(Operand);
8326       EVT VT = Operand.getValueType();
8327 
8328       SDNodeFlags Flags;
8329       Flags.setAllowReassociation(true);
8330 
8331       // Newton reciprocal iteration: E * (2 - X * E)
8332       // AArch64 reciprocal iteration instruction: (2 - M * N)
8333       for (int i = ExtraSteps; i > 0; --i) {
8334         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
8335                                    Estimate, Flags);
8336         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
8337       }
8338 
8339       ExtraSteps = 0;
8340       return Estimate;
8341     }
8342 
8343   return SDValue();
8344 }
8345 
8346 //===----------------------------------------------------------------------===//
8347 //                          AArch64 Inline Assembly Support
8348 //===----------------------------------------------------------------------===//
8349 
8350 // Table of Constraints
8351 // TODO: This is the current set of constraints supported by ARM for the
8352 // compiler, not all of them may make sense.
8353 //
8354 // r - A general register
8355 // w - An FP/SIMD register of some size in the range v0-v31
8356 // x - An FP/SIMD register of some size in the range v0-v15
8357 // I - Constant that can be used with an ADD instruction
8358 // J - Constant that can be used with a SUB instruction
8359 // K - Constant that can be used with a 32-bit logical instruction
8360 // L - Constant that can be used with a 64-bit logical instruction
8361 // M - Constant that can be used as a 32-bit MOV immediate
8362 // N - Constant that can be used as a 64-bit MOV immediate
8363 // Q - A memory reference with base register and no offset
8364 // S - A symbolic address
8365 // Y - Floating point constant zero
8366 // Z - Integer constant zero
8367 //
8368 //   Note that general register operands will be output using their 64-bit x
8369 // register name, whatever the size of the variable, unless the asm operand
8370 // is prefixed by the %w modifier. Floating-point and SIMD register operands
8371 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
8372 // %q modifier.
8373 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
8374   // At this point, we have to lower this constraint to something else, so we
8375   // lower it to an "r" or "w". However, by doing this we will force the result
8376   // to be in register, while the X constraint is much more permissive.
8377   //
8378   // Although we are correct (we are free to emit anything, without
8379   // constraints), we might break use cases that would expect us to be more
8380   // efficient and emit something else.
8381   if (!Subtarget->hasFPARMv8())
8382     return "r";
8383 
8384   if (ConstraintVT.isFloatingPoint())
8385     return "w";
8386 
8387   if (ConstraintVT.isVector() &&
8388      (ConstraintVT.getSizeInBits() == 64 ||
8389       ConstraintVT.getSizeInBits() == 128))
8390     return "w";
8391 
8392   return "r";
8393 }
8394 
8395 enum PredicateConstraint {
8396   Upl,
8397   Upa,
8398   Invalid
8399 };
8400 
8401 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
8402   PredicateConstraint P = PredicateConstraint::Invalid;
8403   if (Constraint == "Upa")
8404     P = PredicateConstraint::Upa;
8405   if (Constraint == "Upl")
8406     P = PredicateConstraint::Upl;
8407   return P;
8408 }
8409 
8410 /// getConstraintType - Given a constraint letter, return the type of
8411 /// constraint it is for this target.
8412 AArch64TargetLowering::ConstraintType
8413 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
8414   if (Constraint.size() == 1) {
8415     switch (Constraint[0]) {
8416     default:
8417       break;
8418     case 'x':
8419     case 'w':
8420     case 'y':
8421       return C_RegisterClass;
8422     // An address with a single base register. Due to the way we
8423     // currently handle addresses it is the same as 'r'.
8424     case 'Q':
8425       return C_Memory;
8426     case 'I':
8427     case 'J':
8428     case 'K':
8429     case 'L':
8430     case 'M':
8431     case 'N':
8432     case 'Y':
8433     case 'Z':
8434       return C_Immediate;
8435     case 'z':
8436     case 'S': // A symbolic address
8437       return C_Other;
8438     }
8439   } else if (parsePredicateConstraint(Constraint) !=
8440              PredicateConstraint::Invalid)
8441       return C_RegisterClass;
8442   return TargetLowering::getConstraintType(Constraint);
8443 }
8444 
8445 /// Examine constraint type and operand type and determine a weight value.
8446 /// This object must already have been set up with the operand type
8447 /// and the current alternative constraint selected.
8448 TargetLowering::ConstraintWeight
8449 AArch64TargetLowering::getSingleConstraintMatchWeight(
8450     AsmOperandInfo &info, const char *constraint) const {
8451   ConstraintWeight weight = CW_Invalid;
8452   Value *CallOperandVal = info.CallOperandVal;
8453   // If we don't have a value, we can't do a match,
8454   // but allow it at the lowest weight.
8455   if (!CallOperandVal)
8456     return CW_Default;
8457   Type *type = CallOperandVal->getType();
8458   // Look at the constraint type.
8459   switch (*constraint) {
8460   default:
8461     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8462     break;
8463   case 'x':
8464   case 'w':
8465   case 'y':
8466     if (type->isFloatingPointTy() || type->isVectorTy())
8467       weight = CW_Register;
8468     break;
8469   case 'z':
8470     weight = CW_Constant;
8471     break;
8472   case 'U':
8473     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
8474       weight = CW_Register;
8475     break;
8476   }
8477   return weight;
8478 }
8479 
8480 std::pair<unsigned, const TargetRegisterClass *>
8481 AArch64TargetLowering::getRegForInlineAsmConstraint(
8482     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
8483   if (Constraint.size() == 1) {
8484     switch (Constraint[0]) {
8485     case 'r':
8486       if (VT.isScalableVector())
8487         return std::make_pair(0U, nullptr);
8488       if (Subtarget->hasLS64() && VT.getSizeInBits() == 512)
8489         return std::make_pair(0U, &AArch64::GPR64x8ClassRegClass);
8490       if (VT.getFixedSizeInBits() == 64)
8491         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
8492       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
8493     case 'w': {
8494       if (!Subtarget->hasFPARMv8())
8495         break;
8496       if (VT.isScalableVector()) {
8497         if (VT.getVectorElementType() != MVT::i1)
8498           return std::make_pair(0U, &AArch64::ZPRRegClass);
8499         return std::make_pair(0U, nullptr);
8500       }
8501       uint64_t VTSize = VT.getFixedSizeInBits();
8502       if (VTSize == 16)
8503         return std::make_pair(0U, &AArch64::FPR16RegClass);
8504       if (VTSize == 32)
8505         return std::make_pair(0U, &AArch64::FPR32RegClass);
8506       if (VTSize == 64)
8507         return std::make_pair(0U, &AArch64::FPR64RegClass);
8508       if (VTSize == 128)
8509         return std::make_pair(0U, &AArch64::FPR128RegClass);
8510       break;
8511     }
8512     // The instructions that this constraint is designed for can
8513     // only take 128-bit registers so just use that regclass.
8514     case 'x':
8515       if (!Subtarget->hasFPARMv8())
8516         break;
8517       if (VT.isScalableVector())
8518         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
8519       if (VT.getSizeInBits() == 128)
8520         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
8521       break;
8522     case 'y':
8523       if (!Subtarget->hasFPARMv8())
8524         break;
8525       if (VT.isScalableVector())
8526         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
8527       break;
8528     }
8529   } else {
8530     PredicateConstraint PC = parsePredicateConstraint(Constraint);
8531     if (PC != PredicateConstraint::Invalid) {
8532       if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
8533         return std::make_pair(0U, nullptr);
8534       bool restricted = (PC == PredicateConstraint::Upl);
8535       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
8536                         : std::make_pair(0U, &AArch64::PPRRegClass);
8537     }
8538   }
8539   if (StringRef("{cc}").equals_insensitive(Constraint))
8540     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
8541 
8542   // Use the default implementation in TargetLowering to convert the register
8543   // constraint into a member of a register class.
8544   std::pair<unsigned, const TargetRegisterClass *> Res;
8545   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8546 
8547   // Not found as a standard register?
8548   if (!Res.second) {
8549     unsigned Size = Constraint.size();
8550     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
8551         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
8552       int RegNo;
8553       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
8554       if (!Failed && RegNo >= 0 && RegNo <= 31) {
8555         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
8556         // By default we'll emit v0-v31 for this unless there's a modifier where
8557         // we'll emit the correct register as well.
8558         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
8559           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
8560           Res.second = &AArch64::FPR64RegClass;
8561         } else {
8562           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
8563           Res.second = &AArch64::FPR128RegClass;
8564         }
8565       }
8566     }
8567   }
8568 
8569   if (Res.second && !Subtarget->hasFPARMv8() &&
8570       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
8571       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
8572     return std::make_pair(0U, nullptr);
8573 
8574   return Res;
8575 }
8576 
8577 EVT AArch64TargetLowering::getAsmOperandValueType(const DataLayout &DL,
8578                                                   llvm::Type *Ty,
8579                                                   bool AllowUnknown) const {
8580   if (Subtarget->hasLS64() && Ty->isIntegerTy(512))
8581     return EVT(MVT::i64x8);
8582 
8583   return TargetLowering::getAsmOperandValueType(DL, Ty, AllowUnknown);
8584 }
8585 
8586 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8587 /// vector.  If it is invalid, don't add anything to Ops.
8588 void AArch64TargetLowering::LowerAsmOperandForConstraint(
8589     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8590     SelectionDAG &DAG) const {
8591   SDValue Result;
8592 
8593   // Currently only support length 1 constraints.
8594   if (Constraint.length() != 1)
8595     return;
8596 
8597   char ConstraintLetter = Constraint[0];
8598   switch (ConstraintLetter) {
8599   default:
8600     break;
8601 
8602   // This set of constraints deal with valid constants for various instructions.
8603   // Validate and return a target constant for them if we can.
8604   case 'z': {
8605     // 'z' maps to xzr or wzr so it needs an input of 0.
8606     if (!isNullConstant(Op))
8607       return;
8608 
8609     if (Op.getValueType() == MVT::i64)
8610       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
8611     else
8612       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
8613     break;
8614   }
8615   case 'S': {
8616     // An absolute symbolic address or label reference.
8617     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8618       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8619                                           GA->getValueType(0));
8620     } else if (const BlockAddressSDNode *BA =
8621                    dyn_cast<BlockAddressSDNode>(Op)) {
8622       Result =
8623           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
8624     } else
8625       return;
8626     break;
8627   }
8628 
8629   case 'I':
8630   case 'J':
8631   case 'K':
8632   case 'L':
8633   case 'M':
8634   case 'N':
8635     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8636     if (!C)
8637       return;
8638 
8639     // Grab the value and do some validation.
8640     uint64_t CVal = C->getZExtValue();
8641     switch (ConstraintLetter) {
8642     // The I constraint applies only to simple ADD or SUB immediate operands:
8643     // i.e. 0 to 4095 with optional shift by 12
8644     // The J constraint applies only to ADD or SUB immediates that would be
8645     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
8646     // instruction [or vice versa], in other words -1 to -4095 with optional
8647     // left shift by 12.
8648     case 'I':
8649       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
8650         break;
8651       return;
8652     case 'J': {
8653       uint64_t NVal = -C->getSExtValue();
8654       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
8655         CVal = C->getSExtValue();
8656         break;
8657       }
8658       return;
8659     }
8660     // The K and L constraints apply *only* to logical immediates, including
8661     // what used to be the MOVI alias for ORR (though the MOVI alias has now
8662     // been removed and MOV should be used). So these constraints have to
8663     // distinguish between bit patterns that are valid 32-bit or 64-bit
8664     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
8665     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
8666     // versa.
8667     case 'K':
8668       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8669         break;
8670       return;
8671     case 'L':
8672       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8673         break;
8674       return;
8675     // The M and N constraints are a superset of K and L respectively, for use
8676     // with the MOV (immediate) alias. As well as the logical immediates they
8677     // also match 32 or 64-bit immediates that can be loaded either using a
8678     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
8679     // (M) or 64-bit 0x1234000000000000 (N) etc.
8680     // As a note some of this code is liberally stolen from the asm parser.
8681     case 'M': {
8682       if (!isUInt<32>(CVal))
8683         return;
8684       if (AArch64_AM::isLogicalImmediate(CVal, 32))
8685         break;
8686       if ((CVal & 0xFFFF) == CVal)
8687         break;
8688       if ((CVal & 0xFFFF0000ULL) == CVal)
8689         break;
8690       uint64_t NCVal = ~(uint32_t)CVal;
8691       if ((NCVal & 0xFFFFULL) == NCVal)
8692         break;
8693       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8694         break;
8695       return;
8696     }
8697     case 'N': {
8698       if (AArch64_AM::isLogicalImmediate(CVal, 64))
8699         break;
8700       if ((CVal & 0xFFFFULL) == CVal)
8701         break;
8702       if ((CVal & 0xFFFF0000ULL) == CVal)
8703         break;
8704       if ((CVal & 0xFFFF00000000ULL) == CVal)
8705         break;
8706       if ((CVal & 0xFFFF000000000000ULL) == CVal)
8707         break;
8708       uint64_t NCVal = ~CVal;
8709       if ((NCVal & 0xFFFFULL) == NCVal)
8710         break;
8711       if ((NCVal & 0xFFFF0000ULL) == NCVal)
8712         break;
8713       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
8714         break;
8715       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
8716         break;
8717       return;
8718     }
8719     default:
8720       return;
8721     }
8722 
8723     // All assembler immediates are 64-bit integers.
8724     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
8725     break;
8726   }
8727 
8728   if (Result.getNode()) {
8729     Ops.push_back(Result);
8730     return;
8731   }
8732 
8733   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8734 }
8735 
8736 //===----------------------------------------------------------------------===//
8737 //                     AArch64 Advanced SIMD Support
8738 //===----------------------------------------------------------------------===//
8739 
8740 /// WidenVector - Given a value in the V64 register class, produce the
8741 /// equivalent value in the V128 register class.
8742 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
8743   EVT VT = V64Reg.getValueType();
8744   unsigned NarrowSize = VT.getVectorNumElements();
8745   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8746   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
8747   SDLoc DL(V64Reg);
8748 
8749   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
8750                      V64Reg, DAG.getConstant(0, DL, MVT::i64));
8751 }
8752 
8753 /// getExtFactor - Determine the adjustment factor for the position when
8754 /// generating an "extract from vector registers" instruction.
8755 static unsigned getExtFactor(SDValue &V) {
8756   EVT EltType = V.getValueType().getVectorElementType();
8757   return EltType.getSizeInBits() / 8;
8758 }
8759 
8760 /// NarrowVector - Given a value in the V128 register class, produce the
8761 /// equivalent value in the V64 register class.
8762 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
8763   EVT VT = V128Reg.getValueType();
8764   unsigned WideSize = VT.getVectorNumElements();
8765   MVT EltTy = VT.getVectorElementType().getSimpleVT();
8766   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
8767   SDLoc DL(V128Reg);
8768 
8769   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
8770 }
8771 
8772 // Gather data to see if the operation can be modelled as a
8773 // shuffle in combination with VEXTs.
8774 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
8775                                                   SelectionDAG &DAG) const {
8776   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8777   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
8778   SDLoc dl(Op);
8779   EVT VT = Op.getValueType();
8780   assert(!VT.isScalableVector() &&
8781          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
8782   unsigned NumElts = VT.getVectorNumElements();
8783 
8784   struct ShuffleSourceInfo {
8785     SDValue Vec;
8786     unsigned MinElt;
8787     unsigned MaxElt;
8788 
8789     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
8790     // be compatible with the shuffle we intend to construct. As a result
8791     // ShuffleVec will be some sliding window into the original Vec.
8792     SDValue ShuffleVec;
8793 
8794     // Code should guarantee that element i in Vec starts at element "WindowBase
8795     // + i * WindowScale in ShuffleVec".
8796     int WindowBase;
8797     int WindowScale;
8798 
8799     ShuffleSourceInfo(SDValue Vec)
8800       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
8801           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
8802 
8803     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
8804   };
8805 
8806   // First gather all vectors used as an immediate source for this BUILD_VECTOR
8807   // node.
8808   SmallVector<ShuffleSourceInfo, 2> Sources;
8809   for (unsigned i = 0; i < NumElts; ++i) {
8810     SDValue V = Op.getOperand(i);
8811     if (V.isUndef())
8812       continue;
8813     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8814              !isa<ConstantSDNode>(V.getOperand(1))) {
8815       LLVM_DEBUG(
8816           dbgs() << "Reshuffle failed: "
8817                     "a shuffle can only come from building a vector from "
8818                     "various elements of other vectors, provided their "
8819                     "indices are constant\n");
8820       return SDValue();
8821     }
8822 
8823     // Add this element source to the list if it's not already there.
8824     SDValue SourceVec = V.getOperand(0);
8825     auto Source = find(Sources, SourceVec);
8826     if (Source == Sources.end())
8827       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
8828 
8829     // Update the minimum and maximum lane number seen.
8830     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
8831     Source->MinElt = std::min(Source->MinElt, EltNo);
8832     Source->MaxElt = std::max(Source->MaxElt, EltNo);
8833   }
8834 
8835   if (Sources.size() > 2) {
8836     LLVM_DEBUG(
8837         dbgs() << "Reshuffle failed: currently only do something sane when at "
8838                   "most two source vectors are involved\n");
8839     return SDValue();
8840   }
8841 
8842   // Find out the smallest element size among result and two sources, and use
8843   // it as element size to build the shuffle_vector.
8844   EVT SmallestEltTy = VT.getVectorElementType();
8845   for (auto &Source : Sources) {
8846     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
8847     if (SrcEltTy.bitsLT(SmallestEltTy)) {
8848       SmallestEltTy = SrcEltTy;
8849     }
8850   }
8851   unsigned ResMultiplier =
8852       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8853   uint64_t VTSize = VT.getFixedSizeInBits();
8854   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
8855   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
8856 
8857   // If the source vector is too wide or too narrow, we may nevertheless be able
8858   // to construct a compatible shuffle either by concatenating it with UNDEF or
8859   // extracting a suitable range of elements.
8860   for (auto &Src : Sources) {
8861     EVT SrcVT = Src.ShuffleVec.getValueType();
8862 
8863     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
8864     if (SrcVTSize == VTSize)
8865       continue;
8866 
8867     // This stage of the search produces a source with the same element type as
8868     // the original, but with a total width matching the BUILD_VECTOR output.
8869     EVT EltVT = SrcVT.getVectorElementType();
8870     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
8871     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
8872 
8873     if (SrcVTSize < VTSize) {
8874       assert(2 * SrcVTSize == VTSize);
8875       // We can pad out the smaller vector for free, so if it's part of a
8876       // shuffle...
8877       Src.ShuffleVec =
8878           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
8879                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
8880       continue;
8881     }
8882 
8883     if (SrcVTSize != 2 * VTSize) {
8884       LLVM_DEBUG(
8885           dbgs() << "Reshuffle failed: result vector too small to extract\n");
8886       return SDValue();
8887     }
8888 
8889     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
8890       LLVM_DEBUG(
8891           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
8892       return SDValue();
8893     }
8894 
8895     if (Src.MinElt >= NumSrcElts) {
8896       // The extraction can just take the second half
8897       Src.ShuffleVec =
8898           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8899                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8900       Src.WindowBase = -NumSrcElts;
8901     } else if (Src.MaxElt < NumSrcElts) {
8902       // The extraction can just take the first half
8903       Src.ShuffleVec =
8904           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8905                       DAG.getConstant(0, dl, MVT::i64));
8906     } else {
8907       // An actual VEXT is needed
8908       SDValue VEXTSrc1 =
8909           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8910                       DAG.getConstant(0, dl, MVT::i64));
8911       SDValue VEXTSrc2 =
8912           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
8913                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
8914       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
8915 
8916       if (!SrcVT.is64BitVector()) {
8917         LLVM_DEBUG(
8918           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
8919                     "for SVE vectors.");
8920         return SDValue();
8921       }
8922 
8923       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
8924                                    VEXTSrc2,
8925                                    DAG.getConstant(Imm, dl, MVT::i32));
8926       Src.WindowBase = -Src.MinElt;
8927     }
8928   }
8929 
8930   // Another possible incompatibility occurs from the vector element types. We
8931   // can fix this by bitcasting the source vectors to the same type we intend
8932   // for the shuffle.
8933   for (auto &Src : Sources) {
8934     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
8935     if (SrcEltTy == SmallestEltTy)
8936       continue;
8937     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
8938     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
8939     Src.WindowScale =
8940         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
8941     Src.WindowBase *= Src.WindowScale;
8942   }
8943 
8944   // Final sanity check before we try to actually produce a shuffle.
8945   LLVM_DEBUG(for (auto Src
8946                   : Sources)
8947                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
8948 
8949   // The stars all align, our next step is to produce the mask for the shuffle.
8950   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
8951   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
8952   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
8953     SDValue Entry = Op.getOperand(i);
8954     if (Entry.isUndef())
8955       continue;
8956 
8957     auto Src = find(Sources, Entry.getOperand(0));
8958     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
8959 
8960     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
8961     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
8962     // segment.
8963     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
8964     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
8965                                VT.getScalarSizeInBits());
8966     int LanesDefined = BitsDefined / BitsPerShuffleLane;
8967 
8968     // This source is expected to fill ResMultiplier lanes of the final shuffle,
8969     // starting at the appropriate offset.
8970     int *LaneMask = &Mask[i * ResMultiplier];
8971 
8972     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
8973     ExtractBase += NumElts * (Src - Sources.begin());
8974     for (int j = 0; j < LanesDefined; ++j)
8975       LaneMask[j] = ExtractBase + j;
8976   }
8977 
8978   // Final check before we try to produce nonsense...
8979   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
8980     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
8981     return SDValue();
8982   }
8983 
8984   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
8985   for (unsigned i = 0; i < Sources.size(); ++i)
8986     ShuffleOps[i] = Sources[i].ShuffleVec;
8987 
8988   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
8989                                          ShuffleOps[1], Mask);
8990   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
8991 
8992   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
8993              dbgs() << "Reshuffle, creating node: "; V.dump(););
8994 
8995   return V;
8996 }
8997 
8998 // check if an EXT instruction can handle the shuffle mask when the
8999 // vector sources of the shuffle are the same.
9000 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
9001   unsigned NumElts = VT.getVectorNumElements();
9002 
9003   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
9004   if (M[0] < 0)
9005     return false;
9006 
9007   Imm = M[0];
9008 
9009   // If this is a VEXT shuffle, the immediate value is the index of the first
9010   // element.  The other shuffle indices must be the successive elements after
9011   // the first one.
9012   unsigned ExpectedElt = Imm;
9013   for (unsigned i = 1; i < NumElts; ++i) {
9014     // Increment the expected index.  If it wraps around, just follow it
9015     // back to index zero and keep going.
9016     ++ExpectedElt;
9017     if (ExpectedElt == NumElts)
9018       ExpectedElt = 0;
9019 
9020     if (M[i] < 0)
9021       continue; // ignore UNDEF indices
9022     if (ExpectedElt != static_cast<unsigned>(M[i]))
9023       return false;
9024   }
9025 
9026   return true;
9027 }
9028 
9029 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
9030 /// element width than the vector lane type. If that is the case the function
9031 /// returns true and writes the value of the DUP instruction lane operand into
9032 /// DupLaneOp
9033 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
9034                           unsigned &DupLaneOp) {
9035   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
9036          "Only possible block sizes for wide DUP are: 16, 32, 64");
9037 
9038   if (BlockSize <= VT.getScalarSizeInBits())
9039     return false;
9040   if (BlockSize % VT.getScalarSizeInBits() != 0)
9041     return false;
9042   if (VT.getSizeInBits() % BlockSize != 0)
9043     return false;
9044 
9045   size_t SingleVecNumElements = VT.getVectorNumElements();
9046   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
9047   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
9048 
9049   // We are looking for masks like
9050   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
9051   // might be replaced by 'undefined'. BlockIndices will eventually contain
9052   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
9053   // for the above examples)
9054   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
9055   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
9056     for (size_t I = 0; I < NumEltsPerBlock; I++) {
9057       int Elt = M[BlockIndex * NumEltsPerBlock + I];
9058       if (Elt < 0)
9059         continue;
9060       // For now we don't support shuffles that use the second operand
9061       if ((unsigned)Elt >= SingleVecNumElements)
9062         return false;
9063       if (BlockElts[I] < 0)
9064         BlockElts[I] = Elt;
9065       else if (BlockElts[I] != Elt)
9066         return false;
9067     }
9068 
9069   // We found a candidate block (possibly with some undefs). It must be a
9070   // sequence of consecutive integers starting with a value divisible by
9071   // NumEltsPerBlock with some values possibly replaced by undef-s.
9072 
9073   // Find first non-undef element
9074   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
9075   assert(FirstRealEltIter != BlockElts.end() &&
9076          "Shuffle with all-undefs must have been caught by previous cases, "
9077          "e.g. isSplat()");
9078   if (FirstRealEltIter == BlockElts.end()) {
9079     DupLaneOp = 0;
9080     return true;
9081   }
9082 
9083   // Index of FirstRealElt in BlockElts
9084   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
9085 
9086   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
9087     return false;
9088   // BlockElts[0] must have the following value if it isn't undef:
9089   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
9090 
9091   // Check the first element
9092   if (Elt0 % NumEltsPerBlock != 0)
9093     return false;
9094   // Check that the sequence indeed consists of consecutive integers (modulo
9095   // undefs)
9096   for (size_t I = 0; I < NumEltsPerBlock; I++)
9097     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
9098       return false;
9099 
9100   DupLaneOp = Elt0 / NumEltsPerBlock;
9101   return true;
9102 }
9103 
9104 // check if an EXT instruction can handle the shuffle mask when the
9105 // vector sources of the shuffle are different.
9106 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
9107                       unsigned &Imm) {
9108   // Look for the first non-undef element.
9109   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
9110 
9111   // Benefit form APInt to handle overflow when calculating expected element.
9112   unsigned NumElts = VT.getVectorNumElements();
9113   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
9114   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
9115   // The following shuffle indices must be the successive elements after the
9116   // first real element.
9117   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
9118       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
9119   if (FirstWrongElt != M.end())
9120     return false;
9121 
9122   // The index of an EXT is the first element if it is not UNDEF.
9123   // Watch out for the beginning UNDEFs. The EXT index should be the expected
9124   // value of the first element.  E.g.
9125   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
9126   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
9127   // ExpectedElt is the last mask index plus 1.
9128   Imm = ExpectedElt.getZExtValue();
9129 
9130   // There are two difference cases requiring to reverse input vectors.
9131   // For example, for vector <4 x i32> we have the following cases,
9132   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
9133   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
9134   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
9135   // to reverse two input vectors.
9136   if (Imm < NumElts)
9137     ReverseEXT = true;
9138   else
9139     Imm -= NumElts;
9140 
9141   return true;
9142 }
9143 
9144 /// isREVMask - Check if a vector shuffle corresponds to a REV
9145 /// instruction with the specified blocksize.  (The order of the elements
9146 /// within each block of the vector is reversed.)
9147 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
9148   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
9149          "Only possible block sizes for REV are: 16, 32, 64");
9150 
9151   unsigned EltSz = VT.getScalarSizeInBits();
9152   if (EltSz == 64)
9153     return false;
9154 
9155   unsigned NumElts = VT.getVectorNumElements();
9156   unsigned BlockElts = M[0] + 1;
9157   // If the first shuffle index is UNDEF, be optimistic.
9158   if (M[0] < 0)
9159     BlockElts = BlockSize / EltSz;
9160 
9161   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
9162     return false;
9163 
9164   for (unsigned i = 0; i < NumElts; ++i) {
9165     if (M[i] < 0)
9166       continue; // ignore UNDEF indices
9167     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
9168       return false;
9169   }
9170 
9171   return true;
9172 }
9173 
9174 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9175   unsigned NumElts = VT.getVectorNumElements();
9176   if (NumElts % 2 != 0)
9177     return false;
9178   WhichResult = (M[0] == 0 ? 0 : 1);
9179   unsigned Idx = WhichResult * NumElts / 2;
9180   for (unsigned i = 0; i != NumElts; i += 2) {
9181     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9182         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
9183       return false;
9184     Idx += 1;
9185   }
9186 
9187   return true;
9188 }
9189 
9190 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9191   unsigned NumElts = VT.getVectorNumElements();
9192   WhichResult = (M[0] == 0 ? 0 : 1);
9193   for (unsigned i = 0; i != NumElts; ++i) {
9194     if (M[i] < 0)
9195       continue; // ignore UNDEF indices
9196     if ((unsigned)M[i] != 2 * i + WhichResult)
9197       return false;
9198   }
9199 
9200   return true;
9201 }
9202 
9203 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9204   unsigned NumElts = VT.getVectorNumElements();
9205   if (NumElts % 2 != 0)
9206     return false;
9207   WhichResult = (M[0] == 0 ? 0 : 1);
9208   for (unsigned i = 0; i < NumElts; i += 2) {
9209     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9210         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
9211       return false;
9212   }
9213   return true;
9214 }
9215 
9216 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
9217 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9218 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
9219 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9220   unsigned NumElts = VT.getVectorNumElements();
9221   if (NumElts % 2 != 0)
9222     return false;
9223   WhichResult = (M[0] == 0 ? 0 : 1);
9224   unsigned Idx = WhichResult * NumElts / 2;
9225   for (unsigned i = 0; i != NumElts; i += 2) {
9226     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
9227         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
9228       return false;
9229     Idx += 1;
9230   }
9231 
9232   return true;
9233 }
9234 
9235 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
9236 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9237 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
9238 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9239   unsigned Half = VT.getVectorNumElements() / 2;
9240   WhichResult = (M[0] == 0 ? 0 : 1);
9241   for (unsigned j = 0; j != 2; ++j) {
9242     unsigned Idx = WhichResult;
9243     for (unsigned i = 0; i != Half; ++i) {
9244       int MIdx = M[i + j * Half];
9245       if (MIdx >= 0 && (unsigned)MIdx != Idx)
9246         return false;
9247       Idx += 2;
9248     }
9249   }
9250 
9251   return true;
9252 }
9253 
9254 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
9255 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
9256 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
9257 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
9258   unsigned NumElts = VT.getVectorNumElements();
9259   if (NumElts % 2 != 0)
9260     return false;
9261   WhichResult = (M[0] == 0 ? 0 : 1);
9262   for (unsigned i = 0; i < NumElts; i += 2) {
9263     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
9264         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
9265       return false;
9266   }
9267   return true;
9268 }
9269 
9270 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
9271                       bool &DstIsLeft, int &Anomaly) {
9272   if (M.size() != static_cast<size_t>(NumInputElements))
9273     return false;
9274 
9275   int NumLHSMatch = 0, NumRHSMatch = 0;
9276   int LastLHSMismatch = -1, LastRHSMismatch = -1;
9277 
9278   for (int i = 0; i < NumInputElements; ++i) {
9279     if (M[i] == -1) {
9280       ++NumLHSMatch;
9281       ++NumRHSMatch;
9282       continue;
9283     }
9284 
9285     if (M[i] == i)
9286       ++NumLHSMatch;
9287     else
9288       LastLHSMismatch = i;
9289 
9290     if (M[i] == i + NumInputElements)
9291       ++NumRHSMatch;
9292     else
9293       LastRHSMismatch = i;
9294   }
9295 
9296   if (NumLHSMatch == NumInputElements - 1) {
9297     DstIsLeft = true;
9298     Anomaly = LastLHSMismatch;
9299     return true;
9300   } else if (NumRHSMatch == NumInputElements - 1) {
9301     DstIsLeft = false;
9302     Anomaly = LastRHSMismatch;
9303     return true;
9304   }
9305 
9306   return false;
9307 }
9308 
9309 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
9310   if (VT.getSizeInBits() != 128)
9311     return false;
9312 
9313   unsigned NumElts = VT.getVectorNumElements();
9314 
9315   for (int I = 0, E = NumElts / 2; I != E; I++) {
9316     if (Mask[I] != I)
9317       return false;
9318   }
9319 
9320   int Offset = NumElts / 2;
9321   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
9322     if (Mask[I] != I + SplitLHS * Offset)
9323       return false;
9324   }
9325 
9326   return true;
9327 }
9328 
9329 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
9330   SDLoc DL(Op);
9331   EVT VT = Op.getValueType();
9332   SDValue V0 = Op.getOperand(0);
9333   SDValue V1 = Op.getOperand(1);
9334   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
9335 
9336   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
9337       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
9338     return SDValue();
9339 
9340   bool SplitV0 = V0.getValueSizeInBits() == 128;
9341 
9342   if (!isConcatMask(Mask, VT, SplitV0))
9343     return SDValue();
9344 
9345   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9346   if (SplitV0) {
9347     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
9348                      DAG.getConstant(0, DL, MVT::i64));
9349   }
9350   if (V1.getValueSizeInBits() == 128) {
9351     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
9352                      DAG.getConstant(0, DL, MVT::i64));
9353   }
9354   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
9355 }
9356 
9357 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9358 /// the specified operations to build the shuffle.
9359 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9360                                       SDValue RHS, SelectionDAG &DAG,
9361                                       const SDLoc &dl) {
9362   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9363   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
9364   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
9365 
9366   enum {
9367     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9368     OP_VREV,
9369     OP_VDUP0,
9370     OP_VDUP1,
9371     OP_VDUP2,
9372     OP_VDUP3,
9373     OP_VEXT1,
9374     OP_VEXT2,
9375     OP_VEXT3,
9376     OP_VUZPL, // VUZP, left result
9377     OP_VUZPR, // VUZP, right result
9378     OP_VZIPL, // VZIP, left result
9379     OP_VZIPR, // VZIP, right result
9380     OP_VTRNL, // VTRN, left result
9381     OP_VTRNR  // VTRN, right result
9382   };
9383 
9384   if (OpNum == OP_COPY) {
9385     if (LHSID == (1 * 9 + 2) * 9 + 3)
9386       return LHS;
9387     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
9388     return RHS;
9389   }
9390 
9391   SDValue OpLHS, OpRHS;
9392   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9393   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9394   EVT VT = OpLHS.getValueType();
9395 
9396   switch (OpNum) {
9397   default:
9398     llvm_unreachable("Unknown shuffle opcode!");
9399   case OP_VREV:
9400     // VREV divides the vector in half and swaps within the half.
9401     if (VT.getVectorElementType() == MVT::i32 ||
9402         VT.getVectorElementType() == MVT::f32)
9403       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
9404     // vrev <4 x i16> -> REV32
9405     if (VT.getVectorElementType() == MVT::i16 ||
9406         VT.getVectorElementType() == MVT::f16 ||
9407         VT.getVectorElementType() == MVT::bf16)
9408       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
9409     // vrev <4 x i8> -> REV16
9410     assert(VT.getVectorElementType() == MVT::i8);
9411     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
9412   case OP_VDUP0:
9413   case OP_VDUP1:
9414   case OP_VDUP2:
9415   case OP_VDUP3: {
9416     EVT EltTy = VT.getVectorElementType();
9417     unsigned Opcode;
9418     if (EltTy == MVT::i8)
9419       Opcode = AArch64ISD::DUPLANE8;
9420     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
9421       Opcode = AArch64ISD::DUPLANE16;
9422     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
9423       Opcode = AArch64ISD::DUPLANE32;
9424     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
9425       Opcode = AArch64ISD::DUPLANE64;
9426     else
9427       llvm_unreachable("Invalid vector element type?");
9428 
9429     if (VT.getSizeInBits() == 64)
9430       OpLHS = WidenVector(OpLHS, DAG);
9431     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
9432     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
9433   }
9434   case OP_VEXT1:
9435   case OP_VEXT2:
9436   case OP_VEXT3: {
9437     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
9438     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
9439                        DAG.getConstant(Imm, dl, MVT::i32));
9440   }
9441   case OP_VUZPL:
9442     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
9443                        OpRHS);
9444   case OP_VUZPR:
9445     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
9446                        OpRHS);
9447   case OP_VZIPL:
9448     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
9449                        OpRHS);
9450   case OP_VZIPR:
9451     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
9452                        OpRHS);
9453   case OP_VTRNL:
9454     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
9455                        OpRHS);
9456   case OP_VTRNR:
9457     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
9458                        OpRHS);
9459   }
9460 }
9461 
9462 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
9463                            SelectionDAG &DAG) {
9464   // Check to see if we can use the TBL instruction.
9465   SDValue V1 = Op.getOperand(0);
9466   SDValue V2 = Op.getOperand(1);
9467   SDLoc DL(Op);
9468 
9469   EVT EltVT = Op.getValueType().getVectorElementType();
9470   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
9471 
9472   SmallVector<SDValue, 8> TBLMask;
9473   for (int Val : ShuffleMask) {
9474     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
9475       unsigned Offset = Byte + Val * BytesPerElt;
9476       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
9477     }
9478   }
9479 
9480   MVT IndexVT = MVT::v8i8;
9481   unsigned IndexLen = 8;
9482   if (Op.getValueSizeInBits() == 128) {
9483     IndexVT = MVT::v16i8;
9484     IndexLen = 16;
9485   }
9486 
9487   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
9488   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
9489 
9490   SDValue Shuffle;
9491   if (V2.getNode()->isUndef()) {
9492     if (IndexLen == 8)
9493       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
9494     Shuffle = DAG.getNode(
9495         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9496         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9497         DAG.getBuildVector(IndexVT, DL,
9498                            makeArrayRef(TBLMask.data(), IndexLen)));
9499   } else {
9500     if (IndexLen == 8) {
9501       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
9502       Shuffle = DAG.getNode(
9503           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9504           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
9505           DAG.getBuildVector(IndexVT, DL,
9506                              makeArrayRef(TBLMask.data(), IndexLen)));
9507     } else {
9508       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
9509       // cannot currently represent the register constraints on the input
9510       // table registers.
9511       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
9512       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
9513       //                   IndexLen));
9514       Shuffle = DAG.getNode(
9515           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
9516           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
9517           V2Cst, DAG.getBuildVector(IndexVT, DL,
9518                                     makeArrayRef(TBLMask.data(), IndexLen)));
9519     }
9520   }
9521   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
9522 }
9523 
9524 static unsigned getDUPLANEOp(EVT EltType) {
9525   if (EltType == MVT::i8)
9526     return AArch64ISD::DUPLANE8;
9527   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
9528     return AArch64ISD::DUPLANE16;
9529   if (EltType == MVT::i32 || EltType == MVT::f32)
9530     return AArch64ISD::DUPLANE32;
9531   if (EltType == MVT::i64 || EltType == MVT::f64)
9532     return AArch64ISD::DUPLANE64;
9533 
9534   llvm_unreachable("Invalid vector element type?");
9535 }
9536 
9537 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
9538                             unsigned Opcode, SelectionDAG &DAG) {
9539   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
9540   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
9541     // Match: dup (bitcast (extract_subv X, C)), LaneC
9542     if (BitCast.getOpcode() != ISD::BITCAST ||
9543         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
9544       return false;
9545 
9546     // The extract index must align in the destination type. That may not
9547     // happen if the bitcast is from narrow to wide type.
9548     SDValue Extract = BitCast.getOperand(0);
9549     unsigned ExtIdx = Extract.getConstantOperandVal(1);
9550     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
9551     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
9552     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
9553     if (ExtIdxInBits % CastedEltBitWidth != 0)
9554       return false;
9555 
9556     // Update the lane value by offsetting with the scaled extract index.
9557     LaneC += ExtIdxInBits / CastedEltBitWidth;
9558 
9559     // Determine the casted vector type of the wide vector input.
9560     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
9561     // Examples:
9562     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
9563     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
9564     unsigned SrcVecNumElts =
9565         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
9566     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
9567                               SrcVecNumElts);
9568     return true;
9569   };
9570   MVT CastVT;
9571   if (getScaledOffsetDup(V, Lane, CastVT)) {
9572     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
9573   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9574     // The lane is incremented by the index of the extract.
9575     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
9576     auto VecVT = V.getOperand(0).getValueType();
9577     if (VecVT.isFixedLengthVector() && VecVT.getFixedSizeInBits() <= 128) {
9578       Lane += V.getConstantOperandVal(1);
9579       V = V.getOperand(0);
9580     }
9581   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
9582     // The lane is decremented if we are splatting from the 2nd operand.
9583     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
9584     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
9585     Lane -= Idx * VT.getVectorNumElements() / 2;
9586     V = WidenVector(V.getOperand(Idx), DAG);
9587   } else if (VT.getSizeInBits() == 64) {
9588     // Widen the operand to 128-bit register with undef.
9589     V = WidenVector(V, DAG);
9590   }
9591   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
9592 }
9593 
9594 // Return true if we can get a new shuffle mask by checking the parameter mask
9595 // array to test whether every two adjacent mask values are continuous and
9596 // starting from an even number.
9597 static bool isWideTypeMask(ArrayRef<int> M, EVT VT,
9598                            SmallVectorImpl<int> &NewMask) {
9599   unsigned NumElts = VT.getVectorNumElements();
9600   if (NumElts % 2 != 0)
9601     return false;
9602 
9603   NewMask.clear();
9604   for (unsigned i = 0; i < NumElts; i += 2) {
9605     int M0 = M[i];
9606     int M1 = M[i + 1];
9607 
9608     // If both elements are undef, new mask is undef too.
9609     if (M0 == -1 && M1 == -1) {
9610       NewMask.push_back(-1);
9611       continue;
9612     }
9613 
9614     if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
9615       NewMask.push_back(M1 / 2);
9616       continue;
9617     }
9618 
9619     if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
9620       NewMask.push_back(M0 / 2);
9621       continue;
9622     }
9623 
9624     NewMask.clear();
9625     return false;
9626   }
9627 
9628   assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
9629   return true;
9630 }
9631 
9632 // Try to widen element type to get a new mask value for a better permutation
9633 // sequence, so that we can use NEON shuffle instructions, such as zip1/2,
9634 // UZP1/2, TRN1/2, REV, INS, etc.
9635 // For example:
9636 //  shufflevector <4 x i32> %a, <4 x i32> %b,
9637 //                <4 x i32> <i32 6, i32 7, i32 2, i32 3>
9638 // is equivalent to:
9639 //  shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
9640 // Finally, we can get:
9641 //  mov     v0.d[0], v1.d[1]
9642 static SDValue tryWidenMaskForShuffle(SDValue Op, SelectionDAG &DAG) {
9643   SDLoc DL(Op);
9644   EVT VT = Op.getValueType();
9645   EVT ScalarVT = VT.getVectorElementType();
9646   unsigned ElementSize = ScalarVT.getFixedSizeInBits();
9647   SDValue V0 = Op.getOperand(0);
9648   SDValue V1 = Op.getOperand(1);
9649   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
9650 
9651   // If combining adjacent elements, like two i16's -> i32, two i32's -> i64 ...
9652   // We need to make sure the wider element type is legal. Thus, ElementSize
9653   // should be not larger than 32 bits, and i1 type should also be excluded.
9654   if (ElementSize > 32 || ElementSize == 1)
9655     return SDValue();
9656 
9657   SmallVector<int, 8> NewMask;
9658   if (isWideTypeMask(Mask, VT, NewMask)) {
9659     MVT NewEltVT = VT.isFloatingPoint()
9660                        ? MVT::getFloatingPointVT(ElementSize * 2)
9661                        : MVT::getIntegerVT(ElementSize * 2);
9662     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
9663     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
9664       V0 = DAG.getBitcast(NewVT, V0);
9665       V1 = DAG.getBitcast(NewVT, V1);
9666       return DAG.getBitcast(VT,
9667                             DAG.getVectorShuffle(NewVT, DL, V0, V1, NewMask));
9668     }
9669   }
9670 
9671   return SDValue();
9672 }
9673 
9674 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9675                                                    SelectionDAG &DAG) const {
9676   SDLoc dl(Op);
9677   EVT VT = Op.getValueType();
9678 
9679   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
9680 
9681   if (useSVEForFixedLengthVectorVT(VT))
9682     return LowerFixedLengthVECTOR_SHUFFLEToSVE(Op, DAG);
9683 
9684   // Convert shuffles that are directly supported on NEON to target-specific
9685   // DAG nodes, instead of keeping them as shuffles and matching them again
9686   // during code selection.  This is more efficient and avoids the possibility
9687   // of inconsistencies between legalization and selection.
9688   ArrayRef<int> ShuffleMask = SVN->getMask();
9689 
9690   SDValue V1 = Op.getOperand(0);
9691   SDValue V2 = Op.getOperand(1);
9692 
9693   assert(V1.getValueType() == VT && "Unexpected VECTOR_SHUFFLE type!");
9694   assert(ShuffleMask.size() == VT.getVectorNumElements() &&
9695          "Unexpected VECTOR_SHUFFLE mask size!");
9696 
9697   if (SVN->isSplat()) {
9698     int Lane = SVN->getSplatIndex();
9699     // If this is undef splat, generate it via "just" vdup, if possible.
9700     if (Lane == -1)
9701       Lane = 0;
9702 
9703     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
9704       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
9705                          V1.getOperand(0));
9706     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
9707     // constant. If so, we can just reference the lane's definition directly.
9708     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
9709         !isa<ConstantSDNode>(V1.getOperand(Lane)))
9710       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
9711 
9712     // Otherwise, duplicate from the lane of the input vector.
9713     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
9714     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
9715   }
9716 
9717   // Check if the mask matches a DUP for a wider element
9718   for (unsigned LaneSize : {64U, 32U, 16U}) {
9719     unsigned Lane = 0;
9720     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
9721       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
9722                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
9723                                                         : AArch64ISD::DUPLANE16;
9724       // Cast V1 to an integer vector with required lane size
9725       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
9726       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
9727       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
9728       V1 = DAG.getBitcast(NewVecTy, V1);
9729       // Constuct the DUP instruction
9730       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
9731       // Cast back to the original type
9732       return DAG.getBitcast(VT, V1);
9733     }
9734   }
9735 
9736   if (isREVMask(ShuffleMask, VT, 64))
9737     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
9738   if (isREVMask(ShuffleMask, VT, 32))
9739     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
9740   if (isREVMask(ShuffleMask, VT, 16))
9741     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
9742 
9743   if (((VT.getVectorNumElements() == 8 && VT.getScalarSizeInBits() == 16) ||
9744        (VT.getVectorNumElements() == 16 && VT.getScalarSizeInBits() == 8)) &&
9745       ShuffleVectorInst::isReverseMask(ShuffleMask)) {
9746     SDValue Rev = DAG.getNode(AArch64ISD::REV64, dl, VT, V1);
9747     return DAG.getNode(AArch64ISD::EXT, dl, VT, Rev, Rev,
9748                        DAG.getConstant(8, dl, MVT::i32));
9749   }
9750 
9751   bool ReverseEXT = false;
9752   unsigned Imm;
9753   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
9754     if (ReverseEXT)
9755       std::swap(V1, V2);
9756     Imm *= getExtFactor(V1);
9757     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
9758                        DAG.getConstant(Imm, dl, MVT::i32));
9759   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
9760     Imm *= getExtFactor(V1);
9761     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
9762                        DAG.getConstant(Imm, dl, MVT::i32));
9763   }
9764 
9765   unsigned WhichResult;
9766   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
9767     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9768     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9769   }
9770   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
9771     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9772     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9773   }
9774   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
9775     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9776     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
9777   }
9778 
9779   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9780     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
9781     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9782   }
9783   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9784     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
9785     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9786   }
9787   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
9788     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
9789     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
9790   }
9791 
9792   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
9793     return Concat;
9794 
9795   bool DstIsLeft;
9796   int Anomaly;
9797   int NumInputElements = V1.getValueType().getVectorNumElements();
9798   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
9799     SDValue DstVec = DstIsLeft ? V1 : V2;
9800     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
9801 
9802     SDValue SrcVec = V1;
9803     int SrcLane = ShuffleMask[Anomaly];
9804     if (SrcLane >= NumInputElements) {
9805       SrcVec = V2;
9806       SrcLane -= VT.getVectorNumElements();
9807     }
9808     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
9809 
9810     EVT ScalarVT = VT.getVectorElementType();
9811 
9812     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
9813       ScalarVT = MVT::i32;
9814 
9815     return DAG.getNode(
9816         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9817         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
9818         DstLaneV);
9819   }
9820 
9821   if (SDValue NewSD = tryWidenMaskForShuffle(Op, DAG))
9822     return NewSD;
9823 
9824   // If the shuffle is not directly supported and it has 4 elements, use
9825   // the PerfectShuffle-generated table to synthesize it from other shuffles.
9826   unsigned NumElts = VT.getVectorNumElements();
9827   if (NumElts == 4) {
9828     unsigned PFIndexes[4];
9829     for (unsigned i = 0; i != 4; ++i) {
9830       if (ShuffleMask[i] < 0)
9831         PFIndexes[i] = 8;
9832       else
9833         PFIndexes[i] = ShuffleMask[i];
9834     }
9835 
9836     // Compute the index in the perfect shuffle table.
9837     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
9838                             PFIndexes[2] * 9 + PFIndexes[3];
9839     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9840     unsigned Cost = (PFEntry >> 30);
9841 
9842     if (Cost <= 4)
9843       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9844   }
9845 
9846   return GenerateTBL(Op, ShuffleMask, DAG);
9847 }
9848 
9849 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
9850                                                  SelectionDAG &DAG) const {
9851   SDLoc dl(Op);
9852   EVT VT = Op.getValueType();
9853   EVT ElemVT = VT.getScalarType();
9854   SDValue SplatVal = Op.getOperand(0);
9855 
9856   if (useSVEForFixedLengthVectorVT(VT))
9857     return LowerToScalableOp(Op, DAG);
9858 
9859   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
9860   // FPRs don't have this restriction.
9861   switch (ElemVT.getSimpleVT().SimpleTy) {
9862   case MVT::i1: {
9863     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
9864     // lowering code.
9865     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
9866       if (ConstVal->isZero())
9867         return SDValue(DAG.getMachineNode(AArch64::PFALSE, dl, VT), 0);
9868       if (ConstVal->isOne())
9869         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
9870     }
9871     // The general case of i1.  There isn't any natural way to do this,
9872     // so we use some trickery with whilelo.
9873     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
9874     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
9875                            DAG.getValueType(MVT::i1));
9876     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
9877                                        MVT::i64);
9878     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
9879                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
9880   }
9881   case MVT::i8:
9882   case MVT::i16:
9883   case MVT::i32:
9884     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
9885     break;
9886   case MVT::i64:
9887     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
9888     break;
9889   case MVT::f16:
9890   case MVT::bf16:
9891   case MVT::f32:
9892   case MVT::f64:
9893     // Fine as is
9894     break;
9895   default:
9896     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
9897   }
9898 
9899   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
9900 }
9901 
9902 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
9903                                              SelectionDAG &DAG) const {
9904   SDLoc DL(Op);
9905 
9906   EVT VT = Op.getValueType();
9907   if (!isTypeLegal(VT) || !VT.isScalableVector())
9908     return SDValue();
9909 
9910   // Current lowering only supports the SVE-ACLE types.
9911   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
9912     return SDValue();
9913 
9914   // The DUPQ operation is indepedent of element type so normalise to i64s.
9915   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
9916   SDValue Idx128 = Op.getOperand(2);
9917 
9918   // DUPQ can be used when idx is in range.
9919   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
9920   if (CIdx && (CIdx->getZExtValue() <= 3)) {
9921     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
9922     SDNode *DUPQ =
9923         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
9924     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
9925   }
9926 
9927   // The ACLE says this must produce the same result as:
9928   //   svtbl(data, svadd_x(svptrue_b64(),
9929   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
9930   //                       index * 2))
9931   SDValue One = DAG.getConstant(1, DL, MVT::i64);
9932   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
9933 
9934   // create the vector 0,1,0,1,...
9935   SDValue SV = DAG.getStepVector(DL, MVT::nxv2i64);
9936   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
9937 
9938   // create the vector idx64,idx64+1,idx64,idx64+1,...
9939   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
9940   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
9941   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
9942 
9943   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
9944   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
9945   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
9946 }
9947 
9948 
9949 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
9950                                APInt &UndefBits) {
9951   EVT VT = BVN->getValueType(0);
9952   APInt SplatBits, SplatUndef;
9953   unsigned SplatBitSize;
9954   bool HasAnyUndefs;
9955   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9956     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
9957 
9958     for (unsigned i = 0; i < NumSplats; ++i) {
9959       CnstBits <<= SplatBitSize;
9960       UndefBits <<= SplatBitSize;
9961       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
9962       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
9963     }
9964 
9965     return true;
9966   }
9967 
9968   return false;
9969 }
9970 
9971 // Try 64-bit splatted SIMD immediate.
9972 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9973                                  const APInt &Bits) {
9974   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9975     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9976     EVT VT = Op.getValueType();
9977     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
9978 
9979     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
9980       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
9981 
9982       SDLoc dl(Op);
9983       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
9984                                 DAG.getConstant(Value, dl, MVT::i32));
9985       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
9986     }
9987   }
9988 
9989   return SDValue();
9990 }
9991 
9992 // Try 32-bit splatted SIMD immediate.
9993 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
9994                                   const APInt &Bits,
9995                                   const SDValue *LHS = nullptr) {
9996   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
9997     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
9998     EVT VT = Op.getValueType();
9999     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
10000     bool isAdvSIMDModImm = false;
10001     uint64_t Shift;
10002 
10003     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
10004       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
10005       Shift = 0;
10006     }
10007     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
10008       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
10009       Shift = 8;
10010     }
10011     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
10012       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
10013       Shift = 16;
10014     }
10015     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
10016       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
10017       Shift = 24;
10018     }
10019 
10020     if (isAdvSIMDModImm) {
10021       SDLoc dl(Op);
10022       SDValue Mov;
10023 
10024       if (LHS)
10025         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
10026                           DAG.getConstant(Value, dl, MVT::i32),
10027                           DAG.getConstant(Shift, dl, MVT::i32));
10028       else
10029         Mov = DAG.getNode(NewOp, dl, MovTy,
10030                           DAG.getConstant(Value, dl, MVT::i32),
10031                           DAG.getConstant(Shift, dl, MVT::i32));
10032 
10033       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10034     }
10035   }
10036 
10037   return SDValue();
10038 }
10039 
10040 // Try 16-bit splatted SIMD immediate.
10041 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10042                                   const APInt &Bits,
10043                                   const SDValue *LHS = nullptr) {
10044   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10045     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10046     EVT VT = Op.getValueType();
10047     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
10048     bool isAdvSIMDModImm = false;
10049     uint64_t Shift;
10050 
10051     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
10052       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
10053       Shift = 0;
10054     }
10055     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
10056       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
10057       Shift = 8;
10058     }
10059 
10060     if (isAdvSIMDModImm) {
10061       SDLoc dl(Op);
10062       SDValue Mov;
10063 
10064       if (LHS)
10065         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
10066                           DAG.getConstant(Value, dl, MVT::i32),
10067                           DAG.getConstant(Shift, dl, MVT::i32));
10068       else
10069         Mov = DAG.getNode(NewOp, dl, MovTy,
10070                           DAG.getConstant(Value, dl, MVT::i32),
10071                           DAG.getConstant(Shift, dl, MVT::i32));
10072 
10073       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10074     }
10075   }
10076 
10077   return SDValue();
10078 }
10079 
10080 // Try 32-bit splatted SIMD immediate with shifted ones.
10081 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
10082                                     SelectionDAG &DAG, const APInt &Bits) {
10083   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10084     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10085     EVT VT = Op.getValueType();
10086     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
10087     bool isAdvSIMDModImm = false;
10088     uint64_t Shift;
10089 
10090     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
10091       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
10092       Shift = 264;
10093     }
10094     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
10095       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
10096       Shift = 272;
10097     }
10098 
10099     if (isAdvSIMDModImm) {
10100       SDLoc dl(Op);
10101       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10102                                 DAG.getConstant(Value, dl, MVT::i32),
10103                                 DAG.getConstant(Shift, dl, MVT::i32));
10104       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10105     }
10106   }
10107 
10108   return SDValue();
10109 }
10110 
10111 // Try 8-bit splatted SIMD immediate.
10112 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10113                                  const APInt &Bits) {
10114   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10115     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10116     EVT VT = Op.getValueType();
10117     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
10118 
10119     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
10120       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
10121 
10122       SDLoc dl(Op);
10123       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10124                                 DAG.getConstant(Value, dl, MVT::i32));
10125       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10126     }
10127   }
10128 
10129   return SDValue();
10130 }
10131 
10132 // Try FP splatted SIMD immediate.
10133 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
10134                                   const APInt &Bits) {
10135   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
10136     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
10137     EVT VT = Op.getValueType();
10138     bool isWide = (VT.getSizeInBits() == 128);
10139     MVT MovTy;
10140     bool isAdvSIMDModImm = false;
10141 
10142     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
10143       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
10144       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
10145     }
10146     else if (isWide &&
10147              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
10148       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
10149       MovTy = MVT::v2f64;
10150     }
10151 
10152     if (isAdvSIMDModImm) {
10153       SDLoc dl(Op);
10154       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
10155                                 DAG.getConstant(Value, dl, MVT::i32));
10156       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
10157     }
10158   }
10159 
10160   return SDValue();
10161 }
10162 
10163 // Specialized code to quickly find if PotentialBVec is a BuildVector that
10164 // consists of only the same constant int value, returned in reference arg
10165 // ConstVal
10166 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
10167                                      uint64_t &ConstVal) {
10168   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
10169   if (!Bvec)
10170     return false;
10171   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
10172   if (!FirstElt)
10173     return false;
10174   EVT VT = Bvec->getValueType(0);
10175   unsigned NumElts = VT.getVectorNumElements();
10176   for (unsigned i = 1; i < NumElts; ++i)
10177     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
10178       return false;
10179   ConstVal = FirstElt->getZExtValue();
10180   return true;
10181 }
10182 
10183 static unsigned getIntrinsicID(const SDNode *N) {
10184   unsigned Opcode = N->getOpcode();
10185   switch (Opcode) {
10186   default:
10187     return Intrinsic::not_intrinsic;
10188   case ISD::INTRINSIC_WO_CHAIN: {
10189     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10190     if (IID < Intrinsic::num_intrinsics)
10191       return IID;
10192     return Intrinsic::not_intrinsic;
10193   }
10194   }
10195 }
10196 
10197 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
10198 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
10199 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
10200 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
10201 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
10202 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
10203 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
10204   EVT VT = N->getValueType(0);
10205 
10206   if (!VT.isVector())
10207     return SDValue();
10208 
10209   SDLoc DL(N);
10210 
10211   SDValue And;
10212   SDValue Shift;
10213 
10214   SDValue FirstOp = N->getOperand(0);
10215   unsigned FirstOpc = FirstOp.getOpcode();
10216   SDValue SecondOp = N->getOperand(1);
10217   unsigned SecondOpc = SecondOp.getOpcode();
10218 
10219   // Is one of the operands an AND or a BICi? The AND may have been optimised to
10220   // a BICi in order to use an immediate instead of a register.
10221   // Is the other operand an shl or lshr? This will have been turned into:
10222   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
10223   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
10224       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
10225     And = FirstOp;
10226     Shift = SecondOp;
10227 
10228   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
10229              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
10230     And = SecondOp;
10231     Shift = FirstOp;
10232   } else
10233     return SDValue();
10234 
10235   bool IsAnd = And.getOpcode() == ISD::AND;
10236   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
10237 
10238   // Is the shift amount constant?
10239   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10240   if (!C2node)
10241     return SDValue();
10242 
10243   uint64_t C1;
10244   if (IsAnd) {
10245     // Is the and mask vector all constant?
10246     if (!isAllConstantBuildVector(And.getOperand(1), C1))
10247       return SDValue();
10248   } else {
10249     // Reconstruct the corresponding AND immediate from the two BICi immediates.
10250     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
10251     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
10252     assert(C1nodeImm && C1nodeShift);
10253     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
10254   }
10255 
10256   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
10257   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
10258   // how much one can shift elements of a particular size?
10259   uint64_t C2 = C2node->getZExtValue();
10260   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
10261   if (C2 > ElemSizeInBits)
10262     return SDValue();
10263 
10264   APInt C1AsAPInt(ElemSizeInBits, C1);
10265   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
10266                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
10267   if (C1AsAPInt != RequiredC1)
10268     return SDValue();
10269 
10270   SDValue X = And.getOperand(0);
10271   SDValue Y = Shift.getOperand(0);
10272 
10273   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
10274   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
10275 
10276   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
10277   LLVM_DEBUG(N->dump(&DAG));
10278   LLVM_DEBUG(dbgs() << "into: \n");
10279   LLVM_DEBUG(ResultSLI->dump(&DAG));
10280 
10281   ++NumShiftInserts;
10282   return ResultSLI;
10283 }
10284 
10285 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
10286                                              SelectionDAG &DAG) const {
10287   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10288     return LowerToScalableOp(Op, DAG);
10289 
10290   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
10291   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
10292     return Res;
10293 
10294   EVT VT = Op.getValueType();
10295 
10296   SDValue LHS = Op.getOperand(0);
10297   BuildVectorSDNode *BVN =
10298       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
10299   if (!BVN) {
10300     // OR commutes, so try swapping the operands.
10301     LHS = Op.getOperand(1);
10302     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
10303   }
10304   if (!BVN)
10305     return Op;
10306 
10307   APInt DefBits(VT.getSizeInBits(), 0);
10308   APInt UndefBits(VT.getSizeInBits(), 0);
10309   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10310     SDValue NewOp;
10311 
10312     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10313                                     DefBits, &LHS)) ||
10314         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10315                                     DefBits, &LHS)))
10316       return NewOp;
10317 
10318     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
10319                                     UndefBits, &LHS)) ||
10320         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
10321                                     UndefBits, &LHS)))
10322       return NewOp;
10323   }
10324 
10325   // We can always fall back to a non-immediate OR.
10326   return Op;
10327 }
10328 
10329 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
10330 // be truncated to fit element width.
10331 static SDValue NormalizeBuildVector(SDValue Op,
10332                                     SelectionDAG &DAG) {
10333   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
10334   SDLoc dl(Op);
10335   EVT VT = Op.getValueType();
10336   EVT EltTy= VT.getVectorElementType();
10337 
10338   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
10339     return Op;
10340 
10341   SmallVector<SDValue, 16> Ops;
10342   for (SDValue Lane : Op->ops()) {
10343     // For integer vectors, type legalization would have promoted the
10344     // operands already. Otherwise, if Op is a floating-point splat
10345     // (with operands cast to integers), then the only possibilities
10346     // are constants and UNDEFs.
10347     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
10348       APInt LowBits(EltTy.getSizeInBits(),
10349                     CstLane->getZExtValue());
10350       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
10351     } else if (Lane.getNode()->isUndef()) {
10352       Lane = DAG.getUNDEF(MVT::i32);
10353     } else {
10354       assert(Lane.getValueType() == MVT::i32 &&
10355              "Unexpected BUILD_VECTOR operand type");
10356     }
10357     Ops.push_back(Lane);
10358   }
10359   return DAG.getBuildVector(VT, dl, Ops);
10360 }
10361 
10362 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
10363   EVT VT = Op.getValueType();
10364 
10365   APInt DefBits(VT.getSizeInBits(), 0);
10366   APInt UndefBits(VT.getSizeInBits(), 0);
10367   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10368   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10369     SDValue NewOp;
10370     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10371         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10372         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10373         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10374         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10375         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10376       return NewOp;
10377 
10378     DefBits = ~DefBits;
10379     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10380         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10381         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10382       return NewOp;
10383 
10384     DefBits = UndefBits;
10385     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
10386         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10387         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
10388         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
10389         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
10390         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
10391       return NewOp;
10392 
10393     DefBits = ~UndefBits;
10394     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
10395         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
10396         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
10397       return NewOp;
10398   }
10399 
10400   return SDValue();
10401 }
10402 
10403 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
10404                                                  SelectionDAG &DAG) const {
10405   EVT VT = Op.getValueType();
10406 
10407   // Try to build a simple constant vector.
10408   Op = NormalizeBuildVector(Op, DAG);
10409   if (VT.isInteger()) {
10410     // Certain vector constants, used to express things like logical NOT and
10411     // arithmetic NEG, are passed through unmodified.  This allows special
10412     // patterns for these operations to match, which will lower these constants
10413     // to whatever is proven necessary.
10414     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
10415     if (BVN->isConstant())
10416       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
10417         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
10418         APInt Val(BitSize,
10419                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
10420         if (Val.isZero() || Val.isAllOnes())
10421           return Op;
10422       }
10423   }
10424 
10425   if (SDValue V = ConstantBuildVector(Op, DAG))
10426     return V;
10427 
10428   // Scan through the operands to find some interesting properties we can
10429   // exploit:
10430   //   1) If only one value is used, we can use a DUP, or
10431   //   2) if only the low element is not undef, we can just insert that, or
10432   //   3) if only one constant value is used (w/ some non-constant lanes),
10433   //      we can splat the constant value into the whole vector then fill
10434   //      in the non-constant lanes.
10435   //   4) FIXME: If different constant values are used, but we can intelligently
10436   //             select the values we'll be overwriting for the non-constant
10437   //             lanes such that we can directly materialize the vector
10438   //             some other way (MOVI, e.g.), we can be sneaky.
10439   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
10440   SDLoc dl(Op);
10441   unsigned NumElts = VT.getVectorNumElements();
10442   bool isOnlyLowElement = true;
10443   bool usesOnlyOneValue = true;
10444   bool usesOnlyOneConstantValue = true;
10445   bool isConstant = true;
10446   bool AllLanesExtractElt = true;
10447   unsigned NumConstantLanes = 0;
10448   unsigned NumDifferentLanes = 0;
10449   unsigned NumUndefLanes = 0;
10450   SDValue Value;
10451   SDValue ConstantValue;
10452   for (unsigned i = 0; i < NumElts; ++i) {
10453     SDValue V = Op.getOperand(i);
10454     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10455       AllLanesExtractElt = false;
10456     if (V.isUndef()) {
10457       ++NumUndefLanes;
10458       continue;
10459     }
10460     if (i > 0)
10461       isOnlyLowElement = false;
10462     if (!isIntOrFPConstant(V))
10463       isConstant = false;
10464 
10465     if (isIntOrFPConstant(V)) {
10466       ++NumConstantLanes;
10467       if (!ConstantValue.getNode())
10468         ConstantValue = V;
10469       else if (ConstantValue != V)
10470         usesOnlyOneConstantValue = false;
10471     }
10472 
10473     if (!Value.getNode())
10474       Value = V;
10475     else if (V != Value) {
10476       usesOnlyOneValue = false;
10477       ++NumDifferentLanes;
10478     }
10479   }
10480 
10481   if (!Value.getNode()) {
10482     LLVM_DEBUG(
10483         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
10484     return DAG.getUNDEF(VT);
10485   }
10486 
10487   // Convert BUILD_VECTOR where all elements but the lowest are undef into
10488   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
10489   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
10490   if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) {
10491     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
10492                          "SCALAR_TO_VECTOR node\n");
10493     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
10494   }
10495 
10496   if (AllLanesExtractElt) {
10497     SDNode *Vector = nullptr;
10498     bool Even = false;
10499     bool Odd = false;
10500     // Check whether the extract elements match the Even pattern <0,2,4,...> or
10501     // the Odd pattern <1,3,5,...>.
10502     for (unsigned i = 0; i < NumElts; ++i) {
10503       SDValue V = Op.getOperand(i);
10504       const SDNode *N = V.getNode();
10505       if (!isa<ConstantSDNode>(N->getOperand(1)))
10506         break;
10507       SDValue N0 = N->getOperand(0);
10508 
10509       // All elements are extracted from the same vector.
10510       if (!Vector) {
10511         Vector = N0.getNode();
10512         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
10513         // BUILD_VECTOR.
10514         if (VT.getVectorElementType() !=
10515             N0.getValueType().getVectorElementType())
10516           break;
10517       } else if (Vector != N0.getNode()) {
10518         Odd = false;
10519         Even = false;
10520         break;
10521       }
10522 
10523       // Extracted values are either at Even indices <0,2,4,...> or at Odd
10524       // indices <1,3,5,...>.
10525       uint64_t Val = N->getConstantOperandVal(1);
10526       if (Val == 2 * i) {
10527         Even = true;
10528         continue;
10529       }
10530       if (Val - 1 == 2 * i) {
10531         Odd = true;
10532         continue;
10533       }
10534 
10535       // Something does not match: abort.
10536       Odd = false;
10537       Even = false;
10538       break;
10539     }
10540     if (Even || Odd) {
10541       SDValue LHS =
10542           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10543                       DAG.getConstant(0, dl, MVT::i64));
10544       SDValue RHS =
10545           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
10546                       DAG.getConstant(NumElts, dl, MVT::i64));
10547 
10548       if (Even && !Odd)
10549         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
10550                            RHS);
10551       if (Odd && !Even)
10552         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
10553                            RHS);
10554     }
10555   }
10556 
10557   // Use DUP for non-constant splats. For f32 constant splats, reduce to
10558   // i32 and try again.
10559   if (usesOnlyOneValue) {
10560     if (!isConstant) {
10561       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10562           Value.getValueType() != VT) {
10563         LLVM_DEBUG(
10564             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
10565         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
10566       }
10567 
10568       // This is actually a DUPLANExx operation, which keeps everything vectory.
10569 
10570       SDValue Lane = Value.getOperand(1);
10571       Value = Value.getOperand(0);
10572       if (Value.getValueSizeInBits() == 64) {
10573         LLVM_DEBUG(
10574             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
10575                       "widening it\n");
10576         Value = WidenVector(Value, DAG);
10577       }
10578 
10579       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
10580       return DAG.getNode(Opcode, dl, VT, Value, Lane);
10581     }
10582 
10583     if (VT.getVectorElementType().isFloatingPoint()) {
10584       SmallVector<SDValue, 8> Ops;
10585       EVT EltTy = VT.getVectorElementType();
10586       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
10587                EltTy == MVT::f64) && "Unsupported floating-point vector type");
10588       LLVM_DEBUG(
10589           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
10590                     "BITCASTS, and try again\n");
10591       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
10592       for (unsigned i = 0; i < NumElts; ++i)
10593         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
10594       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
10595       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
10596       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
10597                  Val.dump(););
10598       Val = LowerBUILD_VECTOR(Val, DAG);
10599       if (Val.getNode())
10600         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
10601     }
10602   }
10603 
10604   // If we need to insert a small number of different non-constant elements and
10605   // the vector width is sufficiently large, prefer using DUP with the common
10606   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
10607   // skip the constant lane handling below.
10608   bool PreferDUPAndInsert =
10609       !isConstant && NumDifferentLanes >= 1 &&
10610       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
10611       NumDifferentLanes >= NumConstantLanes;
10612 
10613   // If there was only one constant value used and for more than one lane,
10614   // start by splatting that value, then replace the non-constant lanes. This
10615   // is better than the default, which will perform a separate initialization
10616   // for each lane.
10617   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
10618     // Firstly, try to materialize the splat constant.
10619     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
10620             Val = ConstantBuildVector(Vec, DAG);
10621     if (!Val) {
10622       // Otherwise, materialize the constant and splat it.
10623       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
10624       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
10625     }
10626 
10627     // Now insert the non-constant lanes.
10628     for (unsigned i = 0; i < NumElts; ++i) {
10629       SDValue V = Op.getOperand(i);
10630       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10631       if (!isIntOrFPConstant(V))
10632         // Note that type legalization likely mucked about with the VT of the
10633         // source operand, so we may have to convert it here before inserting.
10634         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
10635     }
10636     return Val;
10637   }
10638 
10639   // This will generate a load from the constant pool.
10640   if (isConstant) {
10641     LLVM_DEBUG(
10642         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
10643                   "expansion\n");
10644     return SDValue();
10645   }
10646 
10647   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
10648   if (NumElts >= 4) {
10649     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
10650       return shuffle;
10651   }
10652 
10653   if (PreferDUPAndInsert) {
10654     // First, build a constant vector with the common element.
10655     SmallVector<SDValue, 8> Ops(NumElts, Value);
10656     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
10657     // Next, insert the elements that do not match the common value.
10658     for (unsigned I = 0; I < NumElts; ++I)
10659       if (Op.getOperand(I) != Value)
10660         NewVector =
10661             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
10662                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
10663 
10664     return NewVector;
10665   }
10666 
10667   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
10668   // know the default expansion would otherwise fall back on something even
10669   // worse. For a vector with one or two non-undef values, that's
10670   // scalar_to_vector for the elements followed by a shuffle (provided the
10671   // shuffle is valid for the target) and materialization element by element
10672   // on the stack followed by a load for everything else.
10673   if (!isConstant && !usesOnlyOneValue) {
10674     LLVM_DEBUG(
10675         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
10676                   "of INSERT_VECTOR_ELT\n");
10677 
10678     SDValue Vec = DAG.getUNDEF(VT);
10679     SDValue Op0 = Op.getOperand(0);
10680     unsigned i = 0;
10681 
10682     // Use SCALAR_TO_VECTOR for lane zero to
10683     // a) Avoid a RMW dependency on the full vector register, and
10684     // b) Allow the register coalescer to fold away the copy if the
10685     //    value is already in an S or D register, and we're forced to emit an
10686     //    INSERT_SUBREG that we can't fold anywhere.
10687     //
10688     // We also allow types like i8 and i16 which are illegal scalar but legal
10689     // vector element types. After type-legalization the inserted value is
10690     // extended (i32) and it is safe to cast them to the vector type by ignoring
10691     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
10692     if (!Op0.isUndef()) {
10693       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
10694       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
10695       ++i;
10696     }
10697     LLVM_DEBUG(if (i < NumElts) dbgs()
10698                    << "Creating nodes for the other vector elements:\n";);
10699     for (; i < NumElts; ++i) {
10700       SDValue V = Op.getOperand(i);
10701       if (V.isUndef())
10702         continue;
10703       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
10704       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
10705     }
10706     return Vec;
10707   }
10708 
10709   LLVM_DEBUG(
10710       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
10711                 "better alternative\n");
10712   return SDValue();
10713 }
10714 
10715 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
10716                                                    SelectionDAG &DAG) const {
10717   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10718     return LowerFixedLengthConcatVectorsToSVE(Op, DAG);
10719 
10720   assert(Op.getValueType().isScalableVector() &&
10721          isTypeLegal(Op.getValueType()) &&
10722          "Expected legal scalable vector type!");
10723 
10724   if (isTypeLegal(Op.getOperand(0).getValueType())) {
10725     unsigned NumOperands = Op->getNumOperands();
10726     assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10727            "Unexpected number of operands in CONCAT_VECTORS");
10728 
10729     if (NumOperands == 2)
10730       return Op;
10731 
10732     // Concat each pair of subvectors and pack into the lower half of the array.
10733     SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
10734     while (ConcatOps.size() > 1) {
10735       for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
10736         SDValue V1 = ConcatOps[I];
10737         SDValue V2 = ConcatOps[I + 1];
10738         EVT SubVT = V1.getValueType();
10739         EVT PairVT = SubVT.getDoubleNumVectorElementsVT(*DAG.getContext());
10740         ConcatOps[I / 2] =
10741             DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), PairVT, V1, V2);
10742       }
10743       ConcatOps.resize(ConcatOps.size() / 2);
10744     }
10745     return ConcatOps[0];
10746   }
10747 
10748   return SDValue();
10749 }
10750 
10751 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10752                                                       SelectionDAG &DAG) const {
10753   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
10754 
10755   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
10756     return LowerFixedLengthInsertVectorElt(Op, DAG);
10757 
10758   // Check for non-constant or out of range lane.
10759   EVT VT = Op.getOperand(0).getValueType();
10760 
10761   if (VT.getScalarType() == MVT::i1) {
10762     EVT VectorVT = getPromotedVTForPredicate(VT);
10763     SDLoc DL(Op);
10764     SDValue ExtendedVector =
10765         DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, VectorVT);
10766     SDValue ExtendedValue =
10767         DAG.getAnyExtOrTrunc(Op.getOperand(1), DL,
10768                              VectorVT.getScalarType().getSizeInBits() < 32
10769                                  ? MVT::i32
10770                                  : VectorVT.getScalarType());
10771     ExtendedVector =
10772         DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VectorVT, ExtendedVector,
10773                     ExtendedValue, Op.getOperand(2));
10774     return DAG.getAnyExtOrTrunc(ExtendedVector, DL, VT);
10775   }
10776 
10777   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10778   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
10779     return SDValue();
10780 
10781   // Insertion/extraction are legal for V128 types.
10782   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10783       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
10784       VT == MVT::v8f16 || VT == MVT::v8bf16)
10785     return Op;
10786 
10787   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
10788       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
10789       VT != MVT::v4bf16)
10790     return SDValue();
10791 
10792   // For V64 types, we perform insertion by expanding the value
10793   // to a V128 type and perform the insertion on that.
10794   SDLoc DL(Op);
10795   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
10796   EVT WideTy = WideVec.getValueType();
10797 
10798   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
10799                              Op.getOperand(1), Op.getOperand(2));
10800   // Re-narrow the resultant vector.
10801   return NarrowVector(Node, DAG);
10802 }
10803 
10804 SDValue
10805 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10806                                                SelectionDAG &DAG) const {
10807   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
10808   EVT VT = Op.getOperand(0).getValueType();
10809 
10810   if (VT.getScalarType() == MVT::i1) {
10811     // We can't directly extract from an SVE predicate; extend it first.
10812     // (This isn't the only possible lowering, but it's straightforward.)
10813     EVT VectorVT = getPromotedVTForPredicate(VT);
10814     SDLoc DL(Op);
10815     SDValue Extend =
10816         DAG.getNode(ISD::ANY_EXTEND, DL, VectorVT, Op.getOperand(0));
10817     MVT ExtractTy = VectorVT == MVT::nxv2i64 ? MVT::i64 : MVT::i32;
10818     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractTy,
10819                                   Extend, Op.getOperand(1));
10820     return DAG.getAnyExtOrTrunc(Extract, DL, Op.getValueType());
10821   }
10822 
10823   if (useSVEForFixedLengthVectorVT(VT))
10824     return LowerFixedLengthExtractVectorElt(Op, DAG);
10825 
10826   // Check for non-constant or out of range lane.
10827   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10828   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
10829     return SDValue();
10830 
10831   // Insertion/extraction are legal for V128 types.
10832   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10833       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
10834       VT == MVT::v8f16 || VT == MVT::v8bf16)
10835     return Op;
10836 
10837   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
10838       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
10839       VT != MVT::v4bf16)
10840     return SDValue();
10841 
10842   // For V64 types, we perform extraction by expanding the value
10843   // to a V128 type and perform the extraction on that.
10844   SDLoc DL(Op);
10845   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
10846   EVT WideTy = WideVec.getValueType();
10847 
10848   EVT ExtrTy = WideTy.getVectorElementType();
10849   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
10850     ExtrTy = MVT::i32;
10851 
10852   // For extractions, we just return the result directly.
10853   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
10854                      Op.getOperand(1));
10855 }
10856 
10857 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
10858                                                       SelectionDAG &DAG) const {
10859   assert(Op.getValueType().isFixedLengthVector() &&
10860          "Only cases that extract a fixed length vector are supported!");
10861 
10862   EVT InVT = Op.getOperand(0).getValueType();
10863   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10864   unsigned Size = Op.getValueSizeInBits();
10865 
10866   // If we don't have legal types yet, do nothing
10867   if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
10868     return SDValue();
10869 
10870   if (InVT.isScalableVector()) {
10871     // This will be matched by custom code during ISelDAGToDAG.
10872     if (Idx == 0 && isPackedVectorType(InVT, DAG))
10873       return Op;
10874 
10875     return SDValue();
10876   }
10877 
10878   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
10879   if (Idx == 0 && InVT.getSizeInBits() <= 128)
10880     return Op;
10881 
10882   // If this is extracting the upper 64-bits of a 128-bit vector, we match
10883   // that directly.
10884   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
10885       InVT.getSizeInBits() == 128)
10886     return Op;
10887 
10888   if (useSVEForFixedLengthVectorVT(InVT)) {
10889     SDLoc DL(Op);
10890 
10891     EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
10892     SDValue NewInVec =
10893         convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
10894 
10895     SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ContainerVT, NewInVec,
10896                                  NewInVec, DAG.getConstant(Idx, DL, MVT::i64));
10897     return convertFromScalableVector(DAG, Op.getValueType(), Splice);
10898   }
10899 
10900   return SDValue();
10901 }
10902 
10903 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
10904                                                      SelectionDAG &DAG) const {
10905   assert(Op.getValueType().isScalableVector() &&
10906          "Only expect to lower inserts into scalable vectors!");
10907 
10908   EVT InVT = Op.getOperand(1).getValueType();
10909   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10910 
10911   if (InVT.isScalableVector()) {
10912     SDLoc DL(Op);
10913     EVT VT = Op.getValueType();
10914 
10915     if (!isTypeLegal(VT) || !VT.isInteger())
10916       return SDValue();
10917 
10918     SDValue Vec0 = Op.getOperand(0);
10919     SDValue Vec1 = Op.getOperand(1);
10920 
10921     // Ensure the subvector is half the size of the main vector.
10922     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
10923       return SDValue();
10924 
10925     // Extend elements of smaller vector...
10926     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
10927     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
10928 
10929     if (Idx == 0) {
10930       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
10931       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
10932     } else if (Idx == InVT.getVectorMinNumElements()) {
10933       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
10934       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
10935     }
10936 
10937     return SDValue();
10938   }
10939 
10940   // This will be matched by custom code during ISelDAGToDAG.
10941   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
10942     return Op;
10943 
10944   return SDValue();
10945 }
10946 
10947 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
10948   EVT VT = Op.getValueType();
10949 
10950   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
10951     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
10952 
10953   assert(VT.isScalableVector() && "Expected a scalable vector.");
10954 
10955   bool Signed = Op.getOpcode() == ISD::SDIV;
10956   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
10957 
10958   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
10959     return LowerToPredicatedOp(Op, DAG, PredOpcode);
10960 
10961   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
10962   // operations, and truncate the result.
10963   EVT WidenedVT;
10964   if (VT == MVT::nxv16i8)
10965     WidenedVT = MVT::nxv8i16;
10966   else if (VT == MVT::nxv8i16)
10967     WidenedVT = MVT::nxv4i32;
10968   else
10969     llvm_unreachable("Unexpected Custom DIV operation");
10970 
10971   SDLoc dl(Op);
10972   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
10973   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
10974   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
10975   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
10976   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
10977   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
10978   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
10979   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
10980   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
10981 }
10982 
10983 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
10984   // Currently no fixed length shuffles that require SVE are legal.
10985   if (useSVEForFixedLengthVectorVT(VT))
10986     return false;
10987 
10988   if (VT.getVectorNumElements() == 4 &&
10989       (VT.is128BitVector() || VT.is64BitVector())) {
10990     unsigned PFIndexes[4];
10991     for (unsigned i = 0; i != 4; ++i) {
10992       if (M[i] < 0)
10993         PFIndexes[i] = 8;
10994       else
10995         PFIndexes[i] = M[i];
10996     }
10997 
10998     // Compute the index in the perfect shuffle table.
10999     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
11000                             PFIndexes[2] * 9 + PFIndexes[3];
11001     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
11002     unsigned Cost = (PFEntry >> 30);
11003 
11004     if (Cost <= 4)
11005       return true;
11006   }
11007 
11008   bool DummyBool;
11009   int DummyInt;
11010   unsigned DummyUnsigned;
11011 
11012   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
11013           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
11014           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
11015           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
11016           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
11017           isZIPMask(M, VT, DummyUnsigned) ||
11018           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
11019           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
11020           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
11021           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
11022           isConcatMask(M, VT, VT.getSizeInBits() == 128));
11023 }
11024 
11025 /// getVShiftImm - Check if this is a valid build_vector for the immediate
11026 /// operand of a vector shift operation, where all the elements of the
11027 /// build_vector must have the same constant integer value.
11028 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11029   // Ignore bit_converts.
11030   while (Op.getOpcode() == ISD::BITCAST)
11031     Op = Op.getOperand(0);
11032   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11033   APInt SplatBits, SplatUndef;
11034   unsigned SplatBitSize;
11035   bool HasAnyUndefs;
11036   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11037                                     HasAnyUndefs, ElementBits) ||
11038       SplatBitSize > ElementBits)
11039     return false;
11040   Cnt = SplatBits.getSExtValue();
11041   return true;
11042 }
11043 
11044 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11045 /// operand of a vector shift left operation.  That value must be in the range:
11046 ///   0 <= Value < ElementBits for a left shift; or
11047 ///   0 <= Value <= ElementBits for a long left shift.
11048 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11049   assert(VT.isVector() && "vector shift count is not a vector type");
11050   int64_t ElementBits = VT.getScalarSizeInBits();
11051   if (!getVShiftImm(Op, ElementBits, Cnt))
11052     return false;
11053   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
11054 }
11055 
11056 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11057 /// operand of a vector shift right operation. The value must be in the range:
11058 ///   1 <= Value <= ElementBits for a right shift; or
11059 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
11060   assert(VT.isVector() && "vector shift count is not a vector type");
11061   int64_t ElementBits = VT.getScalarSizeInBits();
11062   if (!getVShiftImm(Op, ElementBits, Cnt))
11063     return false;
11064   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
11065 }
11066 
11067 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
11068                                              SelectionDAG &DAG) const {
11069   EVT VT = Op.getValueType();
11070 
11071   if (VT.getScalarType() == MVT::i1) {
11072     // Lower i1 truncate to `(x & 1) != 0`.
11073     SDLoc dl(Op);
11074     EVT OpVT = Op.getOperand(0).getValueType();
11075     SDValue Zero = DAG.getConstant(0, dl, OpVT);
11076     SDValue One = DAG.getConstant(1, dl, OpVT);
11077     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
11078     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
11079   }
11080 
11081   if (!VT.isVector() || VT.isScalableVector())
11082     return SDValue();
11083 
11084   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
11085     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
11086 
11087   return SDValue();
11088 }
11089 
11090 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
11091                                                       SelectionDAG &DAG) const {
11092   EVT VT = Op.getValueType();
11093   SDLoc DL(Op);
11094   int64_t Cnt;
11095 
11096   if (!Op.getOperand(1).getValueType().isVector())
11097     return Op;
11098   unsigned EltSize = VT.getScalarSizeInBits();
11099 
11100   switch (Op.getOpcode()) {
11101   default:
11102     llvm_unreachable("unexpected shift opcode");
11103 
11104   case ISD::SHL:
11105     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
11106       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
11107 
11108     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
11109       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
11110                          DAG.getConstant(Cnt, DL, MVT::i32));
11111     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11112                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
11113                                        MVT::i32),
11114                        Op.getOperand(0), Op.getOperand(1));
11115   case ISD::SRA:
11116   case ISD::SRL:
11117     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
11118       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
11119                                                 : AArch64ISD::SRL_PRED;
11120       return LowerToPredicatedOp(Op, DAG, Opc);
11121     }
11122 
11123     // Right shift immediate
11124     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
11125       unsigned Opc =
11126           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
11127       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
11128                          DAG.getConstant(Cnt, DL, MVT::i32));
11129     }
11130 
11131     // Right shift register.  Note, there is not a shift right register
11132     // instruction, but the shift left register instruction takes a signed
11133     // value, where negative numbers specify a right shift.
11134     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
11135                                                 : Intrinsic::aarch64_neon_ushl;
11136     // negate the shift amount
11137     SDValue NegShift = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
11138                                    Op.getOperand(1));
11139     SDValue NegShiftLeft =
11140         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11141                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
11142                     NegShift);
11143     return NegShiftLeft;
11144   }
11145 
11146   return SDValue();
11147 }
11148 
11149 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
11150                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
11151                                     const SDLoc &dl, SelectionDAG &DAG) {
11152   EVT SrcVT = LHS.getValueType();
11153   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
11154          "function only supposed to emit natural comparisons");
11155 
11156   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
11157   APInt CnstBits(VT.getSizeInBits(), 0);
11158   APInt UndefBits(VT.getSizeInBits(), 0);
11159   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
11160   bool IsZero = IsCnst && (CnstBits == 0);
11161 
11162   if (SrcVT.getVectorElementType().isFloatingPoint()) {
11163     switch (CC) {
11164     default:
11165       return SDValue();
11166     case AArch64CC::NE: {
11167       SDValue Fcmeq;
11168       if (IsZero)
11169         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11170       else
11171         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11172       return DAG.getNOT(dl, Fcmeq, VT);
11173     }
11174     case AArch64CC::EQ:
11175       if (IsZero)
11176         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
11177       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
11178     case AArch64CC::GE:
11179       if (IsZero)
11180         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
11181       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
11182     case AArch64CC::GT:
11183       if (IsZero)
11184         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
11185       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
11186     case AArch64CC::LS:
11187       if (IsZero)
11188         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
11189       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
11190     case AArch64CC::LT:
11191       if (!NoNans)
11192         return SDValue();
11193       // If we ignore NaNs then we can use to the MI implementation.
11194       LLVM_FALLTHROUGH;
11195     case AArch64CC::MI:
11196       if (IsZero)
11197         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
11198       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
11199     }
11200   }
11201 
11202   switch (CC) {
11203   default:
11204     return SDValue();
11205   case AArch64CC::NE: {
11206     SDValue Cmeq;
11207     if (IsZero)
11208       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11209     else
11210       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11211     return DAG.getNOT(dl, Cmeq, VT);
11212   }
11213   case AArch64CC::EQ:
11214     if (IsZero)
11215       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
11216     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
11217   case AArch64CC::GE:
11218     if (IsZero)
11219       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
11220     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
11221   case AArch64CC::GT:
11222     if (IsZero)
11223       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
11224     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
11225   case AArch64CC::LE:
11226     if (IsZero)
11227       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
11228     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
11229   case AArch64CC::LS:
11230     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
11231   case AArch64CC::LO:
11232     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
11233   case AArch64CC::LT:
11234     if (IsZero)
11235       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
11236     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
11237   case AArch64CC::HI:
11238     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
11239   case AArch64CC::HS:
11240     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
11241   }
11242 }
11243 
11244 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
11245                                            SelectionDAG &DAG) const {
11246   if (Op.getValueType().isScalableVector())
11247     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
11248 
11249   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
11250     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
11251 
11252   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11253   SDValue LHS = Op.getOperand(0);
11254   SDValue RHS = Op.getOperand(1);
11255   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
11256   SDLoc dl(Op);
11257 
11258   if (LHS.getValueType().getVectorElementType().isInteger()) {
11259     assert(LHS.getValueType() == RHS.getValueType());
11260     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
11261     SDValue Cmp =
11262         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
11263     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11264   }
11265 
11266   const bool FullFP16 =
11267     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
11268 
11269   // Make v4f16 (only) fcmp operations utilise vector instructions
11270   // v8f16 support will be a litle more complicated
11271   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
11272     if (LHS.getValueType().getVectorNumElements() == 4) {
11273       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
11274       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
11275       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
11276       DAG.ReplaceAllUsesWith(Op, NewSetcc);
11277       CmpVT = MVT::v4i32;
11278     } else
11279       return SDValue();
11280   }
11281 
11282   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
11283           LHS.getValueType().getVectorElementType() != MVT::f128);
11284 
11285   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
11286   // clean.  Some of them require two branches to implement.
11287   AArch64CC::CondCode CC1, CC2;
11288   bool ShouldInvert;
11289   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
11290 
11291   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
11292   SDValue Cmp =
11293       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
11294   if (!Cmp.getNode())
11295     return SDValue();
11296 
11297   if (CC2 != AArch64CC::AL) {
11298     SDValue Cmp2 =
11299         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
11300     if (!Cmp2.getNode())
11301       return SDValue();
11302 
11303     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
11304   }
11305 
11306   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
11307 
11308   if (ShouldInvert)
11309     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
11310 
11311   return Cmp;
11312 }
11313 
11314 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
11315                                   SelectionDAG &DAG) {
11316   SDValue VecOp = ScalarOp.getOperand(0);
11317   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
11318   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
11319                      DAG.getConstant(0, DL, MVT::i64));
11320 }
11321 
11322 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
11323                                               SelectionDAG &DAG) const {
11324   SDValue Src = Op.getOperand(0);
11325 
11326   // Try to lower fixed length reductions to SVE.
11327   EVT SrcVT = Src.getValueType();
11328   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
11329                       Op.getOpcode() == ISD::VECREDUCE_OR ||
11330                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
11331                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
11332                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
11333                        SrcVT.getVectorElementType() == MVT::i64);
11334   if (SrcVT.isScalableVector() ||
11335       useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
11336 
11337     if (SrcVT.getVectorElementType() == MVT::i1)
11338       return LowerPredReductionToSVE(Op, DAG);
11339 
11340     switch (Op.getOpcode()) {
11341     case ISD::VECREDUCE_ADD:
11342       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
11343     case ISD::VECREDUCE_AND:
11344       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
11345     case ISD::VECREDUCE_OR:
11346       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
11347     case ISD::VECREDUCE_SMAX:
11348       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
11349     case ISD::VECREDUCE_SMIN:
11350       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
11351     case ISD::VECREDUCE_UMAX:
11352       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
11353     case ISD::VECREDUCE_UMIN:
11354       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
11355     case ISD::VECREDUCE_XOR:
11356       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
11357     case ISD::VECREDUCE_FADD:
11358       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
11359     case ISD::VECREDUCE_FMAX:
11360       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
11361     case ISD::VECREDUCE_FMIN:
11362       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
11363     default:
11364       llvm_unreachable("Unhandled fixed length reduction");
11365     }
11366   }
11367 
11368   // Lower NEON reductions.
11369   SDLoc dl(Op);
11370   switch (Op.getOpcode()) {
11371   case ISD::VECREDUCE_ADD:
11372     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
11373   case ISD::VECREDUCE_SMAX:
11374     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
11375   case ISD::VECREDUCE_SMIN:
11376     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
11377   case ISD::VECREDUCE_UMAX:
11378     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
11379   case ISD::VECREDUCE_UMIN:
11380     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
11381   case ISD::VECREDUCE_FMAX: {
11382     return DAG.getNode(
11383         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11384         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
11385         Src);
11386   }
11387   case ISD::VECREDUCE_FMIN: {
11388     return DAG.getNode(
11389         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
11390         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
11391         Src);
11392   }
11393   default:
11394     llvm_unreachable("Unhandled reduction");
11395   }
11396 }
11397 
11398 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
11399                                                     SelectionDAG &DAG) const {
11400   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11401   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11402     return SDValue();
11403 
11404   // LSE has an atomic load-add instruction, but not a load-sub.
11405   SDLoc dl(Op);
11406   MVT VT = Op.getSimpleValueType();
11407   SDValue RHS = Op.getOperand(2);
11408   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11409   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
11410   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
11411                        Op.getOperand(0), Op.getOperand(1), RHS,
11412                        AN->getMemOperand());
11413 }
11414 
11415 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
11416                                                     SelectionDAG &DAG) const {
11417   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
11418   if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
11419     return SDValue();
11420 
11421   // LSE has an atomic load-clear instruction, but not a load-and.
11422   SDLoc dl(Op);
11423   MVT VT = Op.getSimpleValueType();
11424   SDValue RHS = Op.getOperand(2);
11425   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
11426   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
11427   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
11428                        Op.getOperand(0), Op.getOperand(1), RHS,
11429                        AN->getMemOperand());
11430 }
11431 
11432 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
11433     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
11434   SDLoc dl(Op);
11435   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11436   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
11437 
11438   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
11439   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
11440   if (Subtarget->hasCustomCallingConv())
11441     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
11442 
11443   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
11444                      DAG.getConstant(4, dl, MVT::i64));
11445   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
11446   Chain =
11447       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
11448                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
11449                   DAG.getRegisterMask(Mask), Chain.getValue(1));
11450   // To match the actual intent better, we should read the output from X15 here
11451   // again (instead of potentially spilling it to the stack), but rereading Size
11452   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
11453   // here.
11454 
11455   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
11456                      DAG.getConstant(4, dl, MVT::i64));
11457   return Chain;
11458 }
11459 
11460 SDValue
11461 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11462                                                SelectionDAG &DAG) const {
11463   assert(Subtarget->isTargetWindows() &&
11464          "Only Windows alloca probing supported");
11465   SDLoc dl(Op);
11466   // Get the inputs.
11467   SDNode *Node = Op.getNode();
11468   SDValue Chain = Op.getOperand(0);
11469   SDValue Size = Op.getOperand(1);
11470   MaybeAlign Align =
11471       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
11472   EVT VT = Node->getValueType(0);
11473 
11474   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
11475           "no-stack-arg-probe")) {
11476     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11477     Chain = SP.getValue(1);
11478     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11479     if (Align)
11480       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11481                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11482     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11483     SDValue Ops[2] = {SP, Chain};
11484     return DAG.getMergeValues(Ops, dl);
11485   }
11486 
11487   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
11488 
11489   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
11490 
11491   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
11492   Chain = SP.getValue(1);
11493   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
11494   if (Align)
11495     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11496                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
11497   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
11498 
11499   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
11500                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
11501 
11502   SDValue Ops[2] = {SP, Chain};
11503   return DAG.getMergeValues(Ops, dl);
11504 }
11505 
11506 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
11507                                            SelectionDAG &DAG) const {
11508   EVT VT = Op.getValueType();
11509   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
11510 
11511   SDLoc DL(Op);
11512   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
11513   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
11514                             DL, VT);
11515 }
11516 
11517 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
11518 template <unsigned NumVecs>
11519 static bool
11520 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
11521               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
11522   Info.opc = ISD::INTRINSIC_VOID;
11523   // Retrieve EC from first vector argument.
11524   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
11525   ElementCount EC = VT.getVectorElementCount();
11526 #ifndef NDEBUG
11527   // Check the assumption that all input vectors are the same type.
11528   for (unsigned I = 0; I < NumVecs; ++I)
11529     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
11530            "Invalid type.");
11531 #endif
11532   // memVT is `NumVecs * VT`.
11533   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
11534                                 EC * NumVecs);
11535   Info.ptrVal = CI.getArgOperand(CI.arg_size() - 1);
11536   Info.offset = 0;
11537   Info.align.reset();
11538   Info.flags = MachineMemOperand::MOStore;
11539   return true;
11540 }
11541 
11542 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11543 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11544 /// specified in the intrinsic calls.
11545 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11546                                                const CallInst &I,
11547                                                MachineFunction &MF,
11548                                                unsigned Intrinsic) const {
11549   auto &DL = I.getModule()->getDataLayout();
11550   switch (Intrinsic) {
11551   case Intrinsic::aarch64_sve_st2:
11552     return setInfoSVEStN<2>(*this, DL, Info, I);
11553   case Intrinsic::aarch64_sve_st3:
11554     return setInfoSVEStN<3>(*this, DL, Info, I);
11555   case Intrinsic::aarch64_sve_st4:
11556     return setInfoSVEStN<4>(*this, DL, Info, I);
11557   case Intrinsic::aarch64_neon_ld2:
11558   case Intrinsic::aarch64_neon_ld3:
11559   case Intrinsic::aarch64_neon_ld4:
11560   case Intrinsic::aarch64_neon_ld1x2:
11561   case Intrinsic::aarch64_neon_ld1x3:
11562   case Intrinsic::aarch64_neon_ld1x4:
11563   case Intrinsic::aarch64_neon_ld2lane:
11564   case Intrinsic::aarch64_neon_ld3lane:
11565   case Intrinsic::aarch64_neon_ld4lane:
11566   case Intrinsic::aarch64_neon_ld2r:
11567   case Intrinsic::aarch64_neon_ld3r:
11568   case Intrinsic::aarch64_neon_ld4r: {
11569     Info.opc = ISD::INTRINSIC_W_CHAIN;
11570     // Conservatively set memVT to the entire set of vectors loaded.
11571     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
11572     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11573     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11574     Info.offset = 0;
11575     Info.align.reset();
11576     // volatile loads with NEON intrinsics not supported
11577     Info.flags = MachineMemOperand::MOLoad;
11578     return true;
11579   }
11580   case Intrinsic::aarch64_neon_st2:
11581   case Intrinsic::aarch64_neon_st3:
11582   case Intrinsic::aarch64_neon_st4:
11583   case Intrinsic::aarch64_neon_st1x2:
11584   case Intrinsic::aarch64_neon_st1x3:
11585   case Intrinsic::aarch64_neon_st1x4:
11586   case Intrinsic::aarch64_neon_st2lane:
11587   case Intrinsic::aarch64_neon_st3lane:
11588   case Intrinsic::aarch64_neon_st4lane: {
11589     Info.opc = ISD::INTRINSIC_VOID;
11590     // Conservatively set memVT to the entire set of vectors stored.
11591     unsigned NumElts = 0;
11592     for (const Value *Arg : I.args()) {
11593       Type *ArgTy = Arg->getType();
11594       if (!ArgTy->isVectorTy())
11595         break;
11596       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
11597     }
11598     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11599     Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
11600     Info.offset = 0;
11601     Info.align.reset();
11602     // volatile stores with NEON intrinsics not supported
11603     Info.flags = MachineMemOperand::MOStore;
11604     return true;
11605   }
11606   case Intrinsic::aarch64_ldaxr:
11607   case Intrinsic::aarch64_ldxr: {
11608     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11609     Info.opc = ISD::INTRINSIC_W_CHAIN;
11610     Info.memVT = MVT::getVT(PtrTy->getElementType());
11611     Info.ptrVal = I.getArgOperand(0);
11612     Info.offset = 0;
11613     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11614     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11615     return true;
11616   }
11617   case Intrinsic::aarch64_stlxr:
11618   case Intrinsic::aarch64_stxr: {
11619     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11620     Info.opc = ISD::INTRINSIC_W_CHAIN;
11621     Info.memVT = MVT::getVT(PtrTy->getElementType());
11622     Info.ptrVal = I.getArgOperand(1);
11623     Info.offset = 0;
11624     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11625     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11626     return true;
11627   }
11628   case Intrinsic::aarch64_ldaxp:
11629   case Intrinsic::aarch64_ldxp:
11630     Info.opc = ISD::INTRINSIC_W_CHAIN;
11631     Info.memVT = MVT::i128;
11632     Info.ptrVal = I.getArgOperand(0);
11633     Info.offset = 0;
11634     Info.align = Align(16);
11635     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
11636     return true;
11637   case Intrinsic::aarch64_stlxp:
11638   case Intrinsic::aarch64_stxp:
11639     Info.opc = ISD::INTRINSIC_W_CHAIN;
11640     Info.memVT = MVT::i128;
11641     Info.ptrVal = I.getArgOperand(2);
11642     Info.offset = 0;
11643     Info.align = Align(16);
11644     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
11645     return true;
11646   case Intrinsic::aarch64_sve_ldnt1: {
11647     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11648     Info.opc = ISD::INTRINSIC_W_CHAIN;
11649     Info.memVT = MVT::getVT(I.getType());
11650     Info.ptrVal = I.getArgOperand(1);
11651     Info.offset = 0;
11652     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11653     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
11654     return true;
11655   }
11656   case Intrinsic::aarch64_sve_stnt1: {
11657     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
11658     Info.opc = ISD::INTRINSIC_W_CHAIN;
11659     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
11660     Info.ptrVal = I.getArgOperand(2);
11661     Info.offset = 0;
11662     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
11663     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
11664     return true;
11665   }
11666   default:
11667     break;
11668   }
11669 
11670   return false;
11671 }
11672 
11673 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
11674                                                   ISD::LoadExtType ExtTy,
11675                                                   EVT NewVT) const {
11676   // TODO: This may be worth removing. Check regression tests for diffs.
11677   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
11678     return false;
11679 
11680   // If we're reducing the load width in order to avoid having to use an extra
11681   // instruction to do extension then it's probably a good idea.
11682   if (ExtTy != ISD::NON_EXTLOAD)
11683     return true;
11684   // Don't reduce load width if it would prevent us from combining a shift into
11685   // the offset.
11686   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
11687   assert(Mem);
11688   const SDValue &Base = Mem->getBasePtr();
11689   if (Base.getOpcode() == ISD::ADD &&
11690       Base.getOperand(1).getOpcode() == ISD::SHL &&
11691       Base.getOperand(1).hasOneUse() &&
11692       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
11693     // The shift can be combined if it matches the size of the value being
11694     // loaded (and so reducing the width would make it not match).
11695     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
11696     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
11697     if (ShiftAmount == Log2_32(LoadBytes))
11698       return false;
11699   }
11700   // We have no reason to disallow reducing the load width, so allow it.
11701   return true;
11702 }
11703 
11704 // Truncations from 64-bit GPR to 32-bit GPR is free.
11705 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11706   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11707     return false;
11708   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
11709   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
11710   return NumBits1 > NumBits2;
11711 }
11712 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11713   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
11714     return false;
11715   uint64_t NumBits1 = VT1.getFixedSizeInBits();
11716   uint64_t NumBits2 = VT2.getFixedSizeInBits();
11717   return NumBits1 > NumBits2;
11718 }
11719 
11720 /// Check if it is profitable to hoist instruction in then/else to if.
11721 /// Not profitable if I and it's user can form a FMA instruction
11722 /// because we prefer FMSUB/FMADD.
11723 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
11724   if (I->getOpcode() != Instruction::FMul)
11725     return true;
11726 
11727   if (!I->hasOneUse())
11728     return true;
11729 
11730   Instruction *User = I->user_back();
11731 
11732   if (User &&
11733       !(User->getOpcode() == Instruction::FSub ||
11734         User->getOpcode() == Instruction::FAdd))
11735     return true;
11736 
11737   const TargetOptions &Options = getTargetMachine().Options;
11738   const Function *F = I->getFunction();
11739   const DataLayout &DL = F->getParent()->getDataLayout();
11740   Type *Ty = User->getOperand(0)->getType();
11741 
11742   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
11743            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
11744            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
11745             Options.UnsafeFPMath));
11746 }
11747 
11748 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
11749 // 64-bit GPR.
11750 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11751   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11752     return false;
11753   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11754   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11755   return NumBits1 == 32 && NumBits2 == 64;
11756 }
11757 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11758   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
11759     return false;
11760   unsigned NumBits1 = VT1.getSizeInBits();
11761   unsigned NumBits2 = VT2.getSizeInBits();
11762   return NumBits1 == 32 && NumBits2 == 64;
11763 }
11764 
11765 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11766   EVT VT1 = Val.getValueType();
11767   if (isZExtFree(VT1, VT2)) {
11768     return true;
11769   }
11770 
11771   if (Val.getOpcode() != ISD::LOAD)
11772     return false;
11773 
11774   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
11775   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
11776           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
11777           VT1.getSizeInBits() <= 32);
11778 }
11779 
11780 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
11781   if (isa<FPExtInst>(Ext))
11782     return false;
11783 
11784   // Vector types are not free.
11785   if (Ext->getType()->isVectorTy())
11786     return false;
11787 
11788   for (const Use &U : Ext->uses()) {
11789     // The extension is free if we can fold it with a left shift in an
11790     // addressing mode or an arithmetic operation: add, sub, and cmp.
11791 
11792     // Is there a shift?
11793     const Instruction *Instr = cast<Instruction>(U.getUser());
11794 
11795     // Is this a constant shift?
11796     switch (Instr->getOpcode()) {
11797     case Instruction::Shl:
11798       if (!isa<ConstantInt>(Instr->getOperand(1)))
11799         return false;
11800       break;
11801     case Instruction::GetElementPtr: {
11802       gep_type_iterator GTI = gep_type_begin(Instr);
11803       auto &DL = Ext->getModule()->getDataLayout();
11804       std::advance(GTI, U.getOperandNo()-1);
11805       Type *IdxTy = GTI.getIndexedType();
11806       // This extension will end up with a shift because of the scaling factor.
11807       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
11808       // Get the shift amount based on the scaling factor:
11809       // log2(sizeof(IdxTy)) - log2(8).
11810       uint64_t ShiftAmt =
11811         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
11812       // Is the constant foldable in the shift of the addressing mode?
11813       // I.e., shift amount is between 1 and 4 inclusive.
11814       if (ShiftAmt == 0 || ShiftAmt > 4)
11815         return false;
11816       break;
11817     }
11818     case Instruction::Trunc:
11819       // Check if this is a noop.
11820       // trunc(sext ty1 to ty2) to ty1.
11821       if (Instr->getType() == Ext->getOperand(0)->getType())
11822         continue;
11823       LLVM_FALLTHROUGH;
11824     default:
11825       return false;
11826     }
11827 
11828     // At this point we can use the bfm family, so this extension is free
11829     // for that use.
11830   }
11831   return true;
11832 }
11833 
11834 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
11835 /// or upper half of the vector elements.
11836 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
11837   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
11838     auto *FullTy = FullV->getType();
11839     auto *HalfTy = HalfV->getType();
11840     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
11841            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
11842   };
11843 
11844   auto extractHalf = [](Value *FullV, Value *HalfV) {
11845     auto *FullVT = cast<FixedVectorType>(FullV->getType());
11846     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
11847     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
11848   };
11849 
11850   ArrayRef<int> M1, M2;
11851   Value *S1Op1, *S2Op1;
11852   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
11853       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
11854     return false;
11855 
11856   // Check that the operands are half as wide as the result and we extract
11857   // half of the elements of the input vectors.
11858   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
11859       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
11860     return false;
11861 
11862   // Check the mask extracts either the lower or upper half of vector
11863   // elements.
11864   int M1Start = -1;
11865   int M2Start = -1;
11866   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
11867   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
11868       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
11869       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
11870     return false;
11871 
11872   return true;
11873 }
11874 
11875 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
11876 /// of the vector elements.
11877 static bool areExtractExts(Value *Ext1, Value *Ext2) {
11878   auto areExtDoubled = [](Instruction *Ext) {
11879     return Ext->getType()->getScalarSizeInBits() ==
11880            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
11881   };
11882 
11883   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
11884       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
11885       !areExtDoubled(cast<Instruction>(Ext1)) ||
11886       !areExtDoubled(cast<Instruction>(Ext2)))
11887     return false;
11888 
11889   return true;
11890 }
11891 
11892 /// Check if Op could be used with vmull_high_p64 intrinsic.
11893 static bool isOperandOfVmullHighP64(Value *Op) {
11894   Value *VectorOperand = nullptr;
11895   ConstantInt *ElementIndex = nullptr;
11896   return match(Op, m_ExtractElt(m_Value(VectorOperand),
11897                                 m_ConstantInt(ElementIndex))) &&
11898          ElementIndex->getValue() == 1 &&
11899          isa<FixedVectorType>(VectorOperand->getType()) &&
11900          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
11901 }
11902 
11903 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
11904 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
11905   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
11906 }
11907 
11908 /// Check if sinking \p I's operands to I's basic block is profitable, because
11909 /// the operands can be folded into a target instruction, e.g.
11910 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
11911 bool AArch64TargetLowering::shouldSinkOperands(
11912     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
11913   if (!I->getType()->isVectorTy())
11914     return false;
11915 
11916   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
11917     switch (II->getIntrinsicID()) {
11918     case Intrinsic::aarch64_neon_umull:
11919       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
11920         return false;
11921       Ops.push_back(&II->getOperandUse(0));
11922       Ops.push_back(&II->getOperandUse(1));
11923       return true;
11924 
11925     case Intrinsic::aarch64_neon_pmull64:
11926       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
11927                                      II->getArgOperand(1)))
11928         return false;
11929       Ops.push_back(&II->getArgOperandUse(0));
11930       Ops.push_back(&II->getArgOperandUse(1));
11931       return true;
11932 
11933     default:
11934       return false;
11935     }
11936   }
11937 
11938   switch (I->getOpcode()) {
11939   case Instruction::Sub:
11940   case Instruction::Add: {
11941     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
11942       return false;
11943 
11944     // If the exts' operands extract either the lower or upper elements, we
11945     // can sink them too.
11946     auto Ext1 = cast<Instruction>(I->getOperand(0));
11947     auto Ext2 = cast<Instruction>(I->getOperand(1));
11948     if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
11949       Ops.push_back(&Ext1->getOperandUse(0));
11950       Ops.push_back(&Ext2->getOperandUse(0));
11951     }
11952 
11953     Ops.push_back(&I->getOperandUse(0));
11954     Ops.push_back(&I->getOperandUse(1));
11955 
11956     return true;
11957   }
11958   case Instruction::Mul: {
11959     bool IsProfitable = false;
11960     for (auto &Op : I->operands()) {
11961       // Make sure we are not already sinking this operand
11962       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
11963         continue;
11964 
11965       ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
11966       if (!Shuffle || !Shuffle->isZeroEltSplat())
11967         continue;
11968 
11969       Value *ShuffleOperand = Shuffle->getOperand(0);
11970       InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
11971       if (!Insert)
11972         continue;
11973 
11974       Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
11975       if (!OperandInstr)
11976         continue;
11977 
11978       ConstantInt *ElementConstant =
11979           dyn_cast<ConstantInt>(Insert->getOperand(2));
11980       // Check that the insertelement is inserting into element 0
11981       if (!ElementConstant || ElementConstant->getZExtValue() != 0)
11982         continue;
11983 
11984       unsigned Opcode = OperandInstr->getOpcode();
11985       if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
11986         continue;
11987 
11988       Ops.push_back(&Shuffle->getOperandUse(0));
11989       Ops.push_back(&Op);
11990       IsProfitable = true;
11991     }
11992 
11993     return IsProfitable;
11994   }
11995   default:
11996     return false;
11997   }
11998   return false;
11999 }
12000 
12001 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
12002                                           Align &RequiredAligment) const {
12003   if (!LoadedType.isSimple() ||
12004       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
12005     return false;
12006   // Cyclone supports unaligned accesses.
12007   RequiredAligment = Align(1);
12008   unsigned NumBits = LoadedType.getSizeInBits();
12009   return NumBits == 32 || NumBits == 64;
12010 }
12011 
12012 /// A helper function for determining the number of interleaved accesses we
12013 /// will generate when lowering accesses of the given type.
12014 unsigned
12015 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
12016                                                  const DataLayout &DL) const {
12017   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
12018 }
12019 
12020 MachineMemOperand::Flags
12021 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
12022   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
12023       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
12024     return MOStridedAccess;
12025   return MachineMemOperand::MONone;
12026 }
12027 
12028 bool AArch64TargetLowering::isLegalInterleavedAccessType(
12029     VectorType *VecTy, const DataLayout &DL) const {
12030 
12031   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
12032   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
12033 
12034   // Ensure the number of vector elements is greater than 1.
12035   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
12036     return false;
12037 
12038   // Ensure the element type is legal.
12039   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
12040     return false;
12041 
12042   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
12043   // 128 will be split into multiple interleaved accesses.
12044   return VecSize == 64 || VecSize % 128 == 0;
12045 }
12046 
12047 /// Lower an interleaved load into a ldN intrinsic.
12048 ///
12049 /// E.g. Lower an interleaved load (Factor = 2):
12050 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
12051 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
12052 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
12053 ///
12054 ///      Into:
12055 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
12056 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
12057 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
12058 bool AArch64TargetLowering::lowerInterleavedLoad(
12059     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
12060     ArrayRef<unsigned> Indices, unsigned Factor) const {
12061   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12062          "Invalid interleave factor");
12063   assert(!Shuffles.empty() && "Empty shufflevector input");
12064   assert(Shuffles.size() == Indices.size() &&
12065          "Unmatched number of shufflevectors and indices");
12066 
12067   const DataLayout &DL = LI->getModule()->getDataLayout();
12068 
12069   VectorType *VTy = Shuffles[0]->getType();
12070 
12071   // Skip if we do not have NEON and skip illegal vector types. We can
12072   // "legalize" wide vector types into multiple interleaved accesses as long as
12073   // the vector types are divisible by 128.
12074   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
12075     return false;
12076 
12077   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
12078 
12079   auto *FVTy = cast<FixedVectorType>(VTy);
12080 
12081   // A pointer vector can not be the return type of the ldN intrinsics. Need to
12082   // load integer vectors first and then convert to pointer vectors.
12083   Type *EltTy = FVTy->getElementType();
12084   if (EltTy->isPointerTy())
12085     FVTy =
12086         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
12087 
12088   IRBuilder<> Builder(LI);
12089 
12090   // The base address of the load.
12091   Value *BaseAddr = LI->getPointerOperand();
12092 
12093   if (NumLoads > 1) {
12094     // If we're going to generate more than one load, reset the sub-vector type
12095     // to something legal.
12096     FVTy = FixedVectorType::get(FVTy->getElementType(),
12097                                 FVTy->getNumElements() / NumLoads);
12098 
12099     // We will compute the pointer operand of each load from the original base
12100     // address using GEPs. Cast the base address to a pointer to the scalar
12101     // element type.
12102     BaseAddr = Builder.CreateBitCast(
12103         BaseAddr,
12104         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
12105   }
12106 
12107   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
12108   Type *Tys[2] = {FVTy, PtrTy};
12109   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
12110                                             Intrinsic::aarch64_neon_ld3,
12111                                             Intrinsic::aarch64_neon_ld4};
12112   Function *LdNFunc =
12113       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
12114 
12115   // Holds sub-vectors extracted from the load intrinsic return values. The
12116   // sub-vectors are associated with the shufflevector instructions they will
12117   // replace.
12118   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
12119 
12120   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
12121 
12122     // If we're generating more than one load, compute the base address of
12123     // subsequent loads as an offset from the previous.
12124     if (LoadCount > 0)
12125       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
12126                                             FVTy->getNumElements() * Factor);
12127 
12128     CallInst *LdN = Builder.CreateCall(
12129         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
12130 
12131     // Extract and store the sub-vectors returned by the load intrinsic.
12132     for (unsigned i = 0; i < Shuffles.size(); i++) {
12133       ShuffleVectorInst *SVI = Shuffles[i];
12134       unsigned Index = Indices[i];
12135 
12136       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
12137 
12138       // Convert the integer vector to pointer vector if the element is pointer.
12139       if (EltTy->isPointerTy())
12140         SubVec = Builder.CreateIntToPtr(
12141             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
12142                                          FVTy->getNumElements()));
12143       SubVecs[SVI].push_back(SubVec);
12144     }
12145   }
12146 
12147   // Replace uses of the shufflevector instructions with the sub-vectors
12148   // returned by the load intrinsic. If a shufflevector instruction is
12149   // associated with more than one sub-vector, those sub-vectors will be
12150   // concatenated into a single wide vector.
12151   for (ShuffleVectorInst *SVI : Shuffles) {
12152     auto &SubVec = SubVecs[SVI];
12153     auto *WideVec =
12154         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
12155     SVI->replaceAllUsesWith(WideVec);
12156   }
12157 
12158   return true;
12159 }
12160 
12161 /// Lower an interleaved store into a stN intrinsic.
12162 ///
12163 /// E.g. Lower an interleaved store (Factor = 3):
12164 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
12165 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
12166 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12167 ///
12168 ///      Into:
12169 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
12170 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
12171 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
12172 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
12173 ///
12174 /// Note that the new shufflevectors will be removed and we'll only generate one
12175 /// st3 instruction in CodeGen.
12176 ///
12177 /// Example for a more general valid mask (Factor 3). Lower:
12178 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
12179 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
12180 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
12181 ///
12182 ///      Into:
12183 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
12184 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
12185 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
12186 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
12187 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
12188                                                   ShuffleVectorInst *SVI,
12189                                                   unsigned Factor) const {
12190   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
12191          "Invalid interleave factor");
12192 
12193   auto *VecTy = cast<FixedVectorType>(SVI->getType());
12194   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
12195 
12196   unsigned LaneLen = VecTy->getNumElements() / Factor;
12197   Type *EltTy = VecTy->getElementType();
12198   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
12199 
12200   const DataLayout &DL = SI->getModule()->getDataLayout();
12201 
12202   // Skip if we do not have NEON and skip illegal vector types. We can
12203   // "legalize" wide vector types into multiple interleaved accesses as long as
12204   // the vector types are divisible by 128.
12205   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
12206     return false;
12207 
12208   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
12209 
12210   Value *Op0 = SVI->getOperand(0);
12211   Value *Op1 = SVI->getOperand(1);
12212   IRBuilder<> Builder(SI);
12213 
12214   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
12215   // vectors to integer vectors.
12216   if (EltTy->isPointerTy()) {
12217     Type *IntTy = DL.getIntPtrType(EltTy);
12218     unsigned NumOpElts =
12219         cast<FixedVectorType>(Op0->getType())->getNumElements();
12220 
12221     // Convert to the corresponding integer vector.
12222     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
12223     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
12224     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
12225 
12226     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
12227   }
12228 
12229   // The base address of the store.
12230   Value *BaseAddr = SI->getPointerOperand();
12231 
12232   if (NumStores > 1) {
12233     // If we're going to generate more than one store, reset the lane length
12234     // and sub-vector type to something legal.
12235     LaneLen /= NumStores;
12236     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
12237 
12238     // We will compute the pointer operand of each store from the original base
12239     // address using GEPs. Cast the base address to a pointer to the scalar
12240     // element type.
12241     BaseAddr = Builder.CreateBitCast(
12242         BaseAddr,
12243         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
12244   }
12245 
12246   auto Mask = SVI->getShuffleMask();
12247 
12248   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
12249   Type *Tys[2] = {SubVecTy, PtrTy};
12250   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
12251                                              Intrinsic::aarch64_neon_st3,
12252                                              Intrinsic::aarch64_neon_st4};
12253   Function *StNFunc =
12254       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
12255 
12256   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
12257 
12258     SmallVector<Value *, 5> Ops;
12259 
12260     // Split the shufflevector operands into sub vectors for the new stN call.
12261     for (unsigned i = 0; i < Factor; i++) {
12262       unsigned IdxI = StoreCount * LaneLen * Factor + i;
12263       if (Mask[IdxI] >= 0) {
12264         Ops.push_back(Builder.CreateShuffleVector(
12265             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
12266       } else {
12267         unsigned StartMask = 0;
12268         for (unsigned j = 1; j < LaneLen; j++) {
12269           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
12270           if (Mask[IdxJ * Factor + IdxI] >= 0) {
12271             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
12272             break;
12273           }
12274         }
12275         // Note: Filling undef gaps with random elements is ok, since
12276         // those elements were being written anyway (with undefs).
12277         // In the case of all undefs we're defaulting to using elems from 0
12278         // Note: StartMask cannot be negative, it's checked in
12279         // isReInterleaveMask
12280         Ops.push_back(Builder.CreateShuffleVector(
12281             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
12282       }
12283     }
12284 
12285     // If we generating more than one store, we compute the base address of
12286     // subsequent stores as an offset from the previous.
12287     if (StoreCount > 0)
12288       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
12289                                             BaseAddr, LaneLen * Factor);
12290 
12291     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
12292     Builder.CreateCall(StNFunc, Ops);
12293   }
12294   return true;
12295 }
12296 
12297 // Lower an SVE structured load intrinsic returning a tuple type to target
12298 // specific intrinsic taking the same input but returning a multi-result value
12299 // of the split tuple type.
12300 //
12301 // E.g. Lowering an LD3:
12302 //
12303 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
12304 //                                                    <vscale x 4 x i1> %pred,
12305 //                                                    <vscale x 4 x i32>* %addr)
12306 //
12307 //  Output DAG:
12308 //
12309 //    t0: ch = EntryToken
12310 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
12311 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
12312 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
12313 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
12314 //
12315 // This is called pre-legalization to avoid widening/splitting issues with
12316 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
12317 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
12318                                                   ArrayRef<SDValue> LoadOps,
12319                                                   EVT VT, SelectionDAG &DAG,
12320                                                   const SDLoc &DL) const {
12321   assert(VT.isScalableVector() && "Can only lower scalable vectors");
12322 
12323   unsigned N, Opcode;
12324   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
12325       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
12326       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
12327       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
12328 
12329   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
12330   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
12331          "invalid tuple vector type!");
12332 
12333   EVT SplitVT =
12334       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
12335                        VT.getVectorElementCount().divideCoefficientBy(N));
12336   assert(isTypeLegal(SplitVT));
12337 
12338   SmallVector<EVT, 5> VTs(N, SplitVT);
12339   VTs.push_back(MVT::Other); // Chain
12340   SDVTList NodeTys = DAG.getVTList(VTs);
12341 
12342   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
12343   SmallVector<SDValue, 4> PseudoLoadOps;
12344   for (unsigned I = 0; I < N; ++I)
12345     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
12346   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
12347 }
12348 
12349 EVT AArch64TargetLowering::getOptimalMemOpType(
12350     const MemOp &Op, const AttributeList &FuncAttributes) const {
12351   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12352   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12353   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12354   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12355   // taken one instruction to materialize the v2i64 zero and one store (with
12356   // restrictive addressing mode). Just do i64 stores.
12357   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12358   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12359     if (Op.isAligned(AlignCheck))
12360       return true;
12361     bool Fast;
12362     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12363                                           MachineMemOperand::MONone, &Fast) &&
12364            Fast;
12365   };
12366 
12367   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12368       AlignmentIsAcceptable(MVT::v16i8, Align(16)))
12369     return MVT::v16i8;
12370   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12371     return MVT::f128;
12372   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12373     return MVT::i64;
12374   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12375     return MVT::i32;
12376   return MVT::Other;
12377 }
12378 
12379 LLT AArch64TargetLowering::getOptimalMemOpLLT(
12380     const MemOp &Op, const AttributeList &FuncAttributes) const {
12381   bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
12382   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
12383   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
12384   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
12385   // taken one instruction to materialize the v2i64 zero and one store (with
12386   // restrictive addressing mode). Just do i64 stores.
12387   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
12388   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
12389     if (Op.isAligned(AlignCheck))
12390       return true;
12391     bool Fast;
12392     return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
12393                                           MachineMemOperand::MONone, &Fast) &&
12394            Fast;
12395   };
12396 
12397   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
12398       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
12399     return LLT::fixed_vector(2, 64);
12400   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
12401     return LLT::scalar(128);
12402   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
12403     return LLT::scalar(64);
12404   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
12405     return LLT::scalar(32);
12406   return LLT();
12407 }
12408 
12409 // 12-bit optionally shifted immediates are legal for adds.
12410 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
12411   if (Immed == std::numeric_limits<int64_t>::min()) {
12412     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
12413                       << ": avoid UB for INT64_MIN\n");
12414     return false;
12415   }
12416   // Same encoding for add/sub, just flip the sign.
12417   Immed = std::abs(Immed);
12418   bool IsLegal = ((Immed >> 12) == 0 ||
12419                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
12420   LLVM_DEBUG(dbgs() << "Is " << Immed
12421                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
12422   return IsLegal;
12423 }
12424 
12425 // Return false to prevent folding
12426 // (mul (add x, c1), c2) -> (add (mul x, c2), c2*c1) in DAGCombine,
12427 // if the folding leads to worse code.
12428 bool AArch64TargetLowering::isMulAddWithConstProfitable(
12429     const SDValue &AddNode, const SDValue &ConstNode) const {
12430   // Let the DAGCombiner decide for vector types and large types.
12431   const EVT VT = AddNode.getValueType();
12432   if (VT.isVector() || VT.getScalarSizeInBits() > 64)
12433     return true;
12434 
12435   // It is worse if c1 is legal add immediate, while c1*c2 is not
12436   // and has to be composed by at least two instructions.
12437   const ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12438   const ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12439   const int64_t C1 = C1Node->getSExtValue();
12440   const APInt C1C2 = C1Node->getAPIntValue() * C2Node->getAPIntValue();
12441   if (!isLegalAddImmediate(C1) || isLegalAddImmediate(C1C2.getSExtValue()))
12442     return true;
12443   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
12444   AArch64_IMM::expandMOVImm(C1C2.getZExtValue(), VT.getSizeInBits(), Insn);
12445   if (Insn.size() > 1)
12446     return false;
12447 
12448   // Default to true and let the DAGCombiner decide.
12449   return true;
12450 }
12451 
12452 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
12453 // immediates is the same as for an add or a sub.
12454 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
12455   return isLegalAddImmediate(Immed);
12456 }
12457 
12458 /// isLegalAddressingMode - Return true if the addressing mode represented
12459 /// by AM is legal for this target, for a load/store of the specified type.
12460 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
12461                                                   const AddrMode &AM, Type *Ty,
12462                                                   unsigned AS, Instruction *I) const {
12463   // AArch64 has five basic addressing modes:
12464   //  reg
12465   //  reg + 9-bit signed offset
12466   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
12467   //  reg1 + reg2
12468   //  reg + SIZE_IN_BYTES * reg
12469 
12470   // No global is ever allowed as a base.
12471   if (AM.BaseGV)
12472     return false;
12473 
12474   // No reg+reg+imm addressing.
12475   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
12476     return false;
12477 
12478   // FIXME: Update this method to support scalable addressing modes.
12479   if (isa<ScalableVectorType>(Ty)) {
12480     uint64_t VecElemNumBytes =
12481         DL.getTypeSizeInBits(cast<VectorType>(Ty)->getElementType()) / 8;
12482     return AM.HasBaseReg && !AM.BaseOffs &&
12483            (AM.Scale == 0 || (uint64_t)AM.Scale == VecElemNumBytes);
12484   }
12485 
12486   // check reg + imm case:
12487   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
12488   uint64_t NumBytes = 0;
12489   if (Ty->isSized()) {
12490     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
12491     NumBytes = NumBits / 8;
12492     if (!isPowerOf2_64(NumBits))
12493       NumBytes = 0;
12494   }
12495 
12496   if (!AM.Scale) {
12497     int64_t Offset = AM.BaseOffs;
12498 
12499     // 9-bit signed offset
12500     if (isInt<9>(Offset))
12501       return true;
12502 
12503     // 12-bit unsigned offset
12504     unsigned shift = Log2_64(NumBytes);
12505     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
12506         // Must be a multiple of NumBytes (NumBytes is a power of 2)
12507         (Offset >> shift) << shift == Offset)
12508       return true;
12509     return false;
12510   }
12511 
12512   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
12513 
12514   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
12515 }
12516 
12517 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
12518   // Consider splitting large offset of struct or array.
12519   return true;
12520 }
12521 
12522 InstructionCost AArch64TargetLowering::getScalingFactorCost(
12523     const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const {
12524   // Scaling factors are not free at all.
12525   // Operands                     | Rt Latency
12526   // -------------------------------------------
12527   // Rt, [Xn, Xm]                 | 4
12528   // -------------------------------------------
12529   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
12530   // Rt, [Xn, Wm, <extend> #imm]  |
12531   if (isLegalAddressingMode(DL, AM, Ty, AS))
12532     // Scale represents reg2 * scale, thus account for 1 if
12533     // it is not equal to 0 or 1.
12534     return AM.Scale != 0 && AM.Scale != 1;
12535   return -1;
12536 }
12537 
12538 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
12539     const MachineFunction &MF, EVT VT) const {
12540   VT = VT.getScalarType();
12541 
12542   if (!VT.isSimple())
12543     return false;
12544 
12545   switch (VT.getSimpleVT().SimpleTy) {
12546   case MVT::f16:
12547     return Subtarget->hasFullFP16();
12548   case MVT::f32:
12549   case MVT::f64:
12550     return true;
12551   default:
12552     break;
12553   }
12554 
12555   return false;
12556 }
12557 
12558 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
12559                                                        Type *Ty) const {
12560   switch (Ty->getScalarType()->getTypeID()) {
12561   case Type::FloatTyID:
12562   case Type::DoubleTyID:
12563     return true;
12564   default:
12565     return false;
12566   }
12567 }
12568 
12569 bool AArch64TargetLowering::generateFMAsInMachineCombiner(
12570     EVT VT, CodeGenOpt::Level OptLevel) const {
12571   return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector();
12572 }
12573 
12574 const MCPhysReg *
12575 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
12576   // LR is a callee-save register, but we must treat it as clobbered by any call
12577   // site. Hence we include LR in the scratch registers, which are in turn added
12578   // as implicit-defs for stackmaps and patchpoints.
12579   static const MCPhysReg ScratchRegs[] = {
12580     AArch64::X16, AArch64::X17, AArch64::LR, 0
12581   };
12582   return ScratchRegs;
12583 }
12584 
12585 bool
12586 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12587                                                      CombineLevel Level) const {
12588   N = N->getOperand(0).getNode();
12589   EVT VT = N->getValueType(0);
12590     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
12591     // it with shift to let it be lowered to UBFX.
12592   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
12593       isa<ConstantSDNode>(N->getOperand(1))) {
12594     uint64_t TruncMask = N->getConstantOperandVal(1);
12595     if (isMask_64(TruncMask) &&
12596       N->getOperand(0).getOpcode() == ISD::SRL &&
12597       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
12598       return false;
12599   }
12600   return true;
12601 }
12602 
12603 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12604                                                               Type *Ty) const {
12605   assert(Ty->isIntegerTy());
12606 
12607   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12608   if (BitSize == 0)
12609     return false;
12610 
12611   int64_t Val = Imm.getSExtValue();
12612   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
12613     return true;
12614 
12615   if ((int64_t)Val < 0)
12616     Val = ~Val;
12617   if (BitSize == 32)
12618     Val &= (1LL << 32) - 1;
12619 
12620   unsigned LZ = countLeadingZeros((uint64_t)Val);
12621   unsigned Shift = (63 - LZ) / 16;
12622   // MOVZ is free so return true for one or fewer MOVK.
12623   return Shift < 3;
12624 }
12625 
12626 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
12627                                                     unsigned Index) const {
12628   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
12629     return false;
12630 
12631   return (Index == 0 || Index == ResVT.getVectorNumElements());
12632 }
12633 
12634 /// Turn vector tests of the signbit in the form of:
12635 ///   xor (sra X, elt_size(X)-1), -1
12636 /// into:
12637 ///   cmge X, X, #0
12638 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
12639                                          const AArch64Subtarget *Subtarget) {
12640   EVT VT = N->getValueType(0);
12641   if (!Subtarget->hasNEON() || !VT.isVector())
12642     return SDValue();
12643 
12644   // There must be a shift right algebraic before the xor, and the xor must be a
12645   // 'not' operation.
12646   SDValue Shift = N->getOperand(0);
12647   SDValue Ones = N->getOperand(1);
12648   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
12649       !ISD::isBuildVectorAllOnes(Ones.getNode()))
12650     return SDValue();
12651 
12652   // The shift should be smearing the sign bit across each vector element.
12653   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
12654   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
12655   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
12656     return SDValue();
12657 
12658   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
12659 }
12660 
12661 // Given a vecreduce_add node, detect the below pattern and convert it to the
12662 // node sequence with UABDL, [S|U]ADB and UADDLP.
12663 //
12664 // i32 vecreduce_add(
12665 //  v16i32 abs(
12666 //    v16i32 sub(
12667 //     v16i32 [sign|zero]_extend(v16i8 a), v16i32 [sign|zero]_extend(v16i8 b))))
12668 // =================>
12669 // i32 vecreduce_add(
12670 //   v4i32 UADDLP(
12671 //     v8i16 add(
12672 //       v8i16 zext(
12673 //         v8i8 [S|U]ABD low8:v16i8 a, low8:v16i8 b
12674 //       v8i16 zext(
12675 //         v8i8 [S|U]ABD high8:v16i8 a, high8:v16i8 b
12676 static SDValue performVecReduceAddCombineWithUADDLP(SDNode *N,
12677                                                     SelectionDAG &DAG) {
12678   // Assumed i32 vecreduce_add
12679   if (N->getValueType(0) != MVT::i32)
12680     return SDValue();
12681 
12682   SDValue VecReduceOp0 = N->getOperand(0);
12683   unsigned Opcode = VecReduceOp0.getOpcode();
12684   // Assumed v16i32 abs
12685   if (Opcode != ISD::ABS || VecReduceOp0->getValueType(0) != MVT::v16i32)
12686     return SDValue();
12687 
12688   SDValue ABS = VecReduceOp0;
12689   // Assumed v16i32 sub
12690   if (ABS->getOperand(0)->getOpcode() != ISD::SUB ||
12691       ABS->getOperand(0)->getValueType(0) != MVT::v16i32)
12692     return SDValue();
12693 
12694   SDValue SUB = ABS->getOperand(0);
12695   unsigned Opcode0 = SUB->getOperand(0).getOpcode();
12696   unsigned Opcode1 = SUB->getOperand(1).getOpcode();
12697   // Assumed v16i32 type
12698   if (SUB->getOperand(0)->getValueType(0) != MVT::v16i32 ||
12699       SUB->getOperand(1)->getValueType(0) != MVT::v16i32)
12700     return SDValue();
12701 
12702   // Assumed zext or sext
12703   bool IsZExt = false;
12704   if (Opcode0 == ISD::ZERO_EXTEND && Opcode1 == ISD::ZERO_EXTEND) {
12705     IsZExt = true;
12706   } else if (Opcode0 == ISD::SIGN_EXTEND && Opcode1 == ISD::SIGN_EXTEND) {
12707     IsZExt = false;
12708   } else
12709     return SDValue();
12710 
12711   SDValue EXT0 = SUB->getOperand(0);
12712   SDValue EXT1 = SUB->getOperand(1);
12713   // Assumed zext's operand has v16i8 type
12714   if (EXT0->getOperand(0)->getValueType(0) != MVT::v16i8 ||
12715       EXT1->getOperand(0)->getValueType(0) != MVT::v16i8)
12716     return SDValue();
12717 
12718   // Pattern is dectected. Let's convert it to sequence of nodes.
12719   SDLoc DL(N);
12720 
12721   // First, create the node pattern of UABD/SABD.
12722   SDValue UABDHigh8Op0 =
12723       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
12724                   DAG.getConstant(8, DL, MVT::i64));
12725   SDValue UABDHigh8Op1 =
12726       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
12727                   DAG.getConstant(8, DL, MVT::i64));
12728   SDValue UABDHigh8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
12729                                   UABDHigh8Op0, UABDHigh8Op1);
12730   SDValue UABDL = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDHigh8);
12731 
12732   // Second, create the node pattern of UABAL.
12733   SDValue UABDLo8Op0 =
12734       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
12735                   DAG.getConstant(0, DL, MVT::i64));
12736   SDValue UABDLo8Op1 =
12737       DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
12738                   DAG.getConstant(0, DL, MVT::i64));
12739   SDValue UABDLo8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
12740                                 UABDLo8Op0, UABDLo8Op1);
12741   SDValue ZExtUABD = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDLo8);
12742   SDValue UABAL = DAG.getNode(ISD::ADD, DL, MVT::v8i16, UABDL, ZExtUABD);
12743 
12744   // Third, create the node of UADDLP.
12745   SDValue UADDLP = DAG.getNode(AArch64ISD::UADDLP, DL, MVT::v4i32, UABAL);
12746 
12747   // Fourth, create the node of VECREDUCE_ADD.
12748   return DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, UADDLP);
12749 }
12750 
12751 // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce
12752 //   vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one))
12753 //   vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B))
12754 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
12755                                           const AArch64Subtarget *ST) {
12756   if (!ST->hasDotProd())
12757     return performVecReduceAddCombineWithUADDLP(N, DAG);
12758 
12759   SDValue Op0 = N->getOperand(0);
12760   if (N->getValueType(0) != MVT::i32 ||
12761       Op0.getValueType().getVectorElementType() != MVT::i32)
12762     return SDValue();
12763 
12764   unsigned ExtOpcode = Op0.getOpcode();
12765   SDValue A = Op0;
12766   SDValue B;
12767   if (ExtOpcode == ISD::MUL) {
12768     A = Op0.getOperand(0);
12769     B = Op0.getOperand(1);
12770     if (A.getOpcode() != B.getOpcode() ||
12771         A.getOperand(0).getValueType() != B.getOperand(0).getValueType())
12772       return SDValue();
12773     ExtOpcode = A.getOpcode();
12774   }
12775   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
12776     return SDValue();
12777 
12778   EVT Op0VT = A.getOperand(0).getValueType();
12779   if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8)
12780     return SDValue();
12781 
12782   SDLoc DL(Op0);
12783   // For non-mla reductions B can be set to 1. For MLA we take the operand of
12784   // the extend B.
12785   if (!B)
12786     B = DAG.getConstant(1, DL, Op0VT);
12787   else
12788     B = B.getOperand(0);
12789 
12790   SDValue Zeros =
12791       DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32);
12792   auto DotOpcode =
12793       (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT;
12794   SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros,
12795                             A.getOperand(0), B);
12796   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
12797 }
12798 
12799 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
12800                                  TargetLowering::DAGCombinerInfo &DCI,
12801                                  const AArch64Subtarget *Subtarget) {
12802   if (DCI.isBeforeLegalizeOps())
12803     return SDValue();
12804 
12805   return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
12806 }
12807 
12808 SDValue
12809 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12810                                      SelectionDAG &DAG,
12811                                      SmallVectorImpl<SDNode *> &Created) const {
12812   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12813   if (isIntDivCheap(N->getValueType(0), Attr))
12814     return SDValue(N,0); // Lower SDIV as SDIV
12815 
12816   // fold (sdiv X, pow2)
12817   EVT VT = N->getValueType(0);
12818   if ((VT != MVT::i32 && VT != MVT::i64) ||
12819       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
12820     return SDValue();
12821 
12822   SDLoc DL(N);
12823   SDValue N0 = N->getOperand(0);
12824   unsigned Lg2 = Divisor.countTrailingZeros();
12825   SDValue Zero = DAG.getConstant(0, DL, VT);
12826   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12827 
12828   // Add (N0 < 0) ? Pow2 - 1 : 0;
12829   SDValue CCVal;
12830   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
12831   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12832   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
12833 
12834   Created.push_back(Cmp.getNode());
12835   Created.push_back(Add.getNode());
12836   Created.push_back(CSel.getNode());
12837 
12838   // Divide by pow2.
12839   SDValue SRA =
12840       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
12841 
12842   // If we're dividing by a positive value, we're done.  Otherwise, we must
12843   // negate the result.
12844   if (Divisor.isNonNegative())
12845     return SRA;
12846 
12847   Created.push_back(SRA.getNode());
12848   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12849 }
12850 
12851 static bool IsSVECntIntrinsic(SDValue S) {
12852   switch(getIntrinsicID(S.getNode())) {
12853   default:
12854     break;
12855   case Intrinsic::aarch64_sve_cntb:
12856   case Intrinsic::aarch64_sve_cnth:
12857   case Intrinsic::aarch64_sve_cntw:
12858   case Intrinsic::aarch64_sve_cntd:
12859     return true;
12860   }
12861   return false;
12862 }
12863 
12864 /// Calculates what the pre-extend type is, based on the extension
12865 /// operation node provided by \p Extend.
12866 ///
12867 /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
12868 /// pre-extend type is pulled directly from the operand, while other extend
12869 /// operations need a bit more inspection to get this information.
12870 ///
12871 /// \param Extend The SDNode from the DAG that represents the extend operation
12872 /// \param DAG The SelectionDAG hosting the \p Extend node
12873 ///
12874 /// \returns The type representing the \p Extend source type, or \p MVT::Other
12875 /// if no valid type can be determined
12876 static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
12877   switch (Extend.getOpcode()) {
12878   case ISD::SIGN_EXTEND:
12879   case ISD::ZERO_EXTEND:
12880     return Extend.getOperand(0).getValueType();
12881   case ISD::AssertSext:
12882   case ISD::AssertZext:
12883   case ISD::SIGN_EXTEND_INREG: {
12884     VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
12885     if (!TypeNode)
12886       return MVT::Other;
12887     return TypeNode->getVT();
12888   }
12889   case ISD::AND: {
12890     ConstantSDNode *Constant =
12891         dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
12892     if (!Constant)
12893       return MVT::Other;
12894 
12895     uint32_t Mask = Constant->getZExtValue();
12896 
12897     if (Mask == UCHAR_MAX)
12898       return MVT::i8;
12899     else if (Mask == USHRT_MAX)
12900       return MVT::i16;
12901     else if (Mask == UINT_MAX)
12902       return MVT::i32;
12903 
12904     return MVT::Other;
12905   }
12906   default:
12907     return MVT::Other;
12908   }
12909 
12910   llvm_unreachable("Code path unhandled in calculatePreExtendType!");
12911 }
12912 
12913 /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
12914 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
12915 static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
12916                                                 SelectionDAG &DAG) {
12917 
12918   ShuffleVectorSDNode *ShuffleNode =
12919       dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
12920   if (!ShuffleNode)
12921     return SDValue();
12922 
12923   // Ensuring the mask is zero before continuing
12924   if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
12925     return SDValue();
12926 
12927   SDValue InsertVectorElt = VectorShuffle.getOperand(0);
12928 
12929   if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
12930     return SDValue();
12931 
12932   SDValue InsertLane = InsertVectorElt.getOperand(2);
12933   ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
12934   // Ensures the insert is inserting into lane 0
12935   if (!Constant || Constant->getZExtValue() != 0)
12936     return SDValue();
12937 
12938   SDValue Extend = InsertVectorElt.getOperand(1);
12939   unsigned ExtendOpcode = Extend.getOpcode();
12940 
12941   bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
12942                 ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
12943                 ExtendOpcode == ISD::AssertSext;
12944   if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
12945       ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
12946     return SDValue();
12947 
12948   EVT TargetType = VectorShuffle.getValueType();
12949   EVT PreExtendType = calculatePreExtendType(Extend, DAG);
12950 
12951   if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
12952        TargetType != MVT::v2i64) ||
12953       (PreExtendType == MVT::Other))
12954     return SDValue();
12955 
12956   // Restrict valid pre-extend data type
12957   if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
12958       PreExtendType != MVT::i32)
12959     return SDValue();
12960 
12961   EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
12962 
12963   if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
12964     return SDValue();
12965 
12966   if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
12967     return SDValue();
12968 
12969   SDLoc DL(VectorShuffle);
12970 
12971   SDValue InsertVectorNode = DAG.getNode(
12972       InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
12973       DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
12974       DAG.getConstant(0, DL, MVT::i64));
12975 
12976   std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue());
12977 
12978   SDValue VectorShuffleNode =
12979       DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
12980                            DAG.getUNDEF(PreExtendVT), ShuffleMask);
12981 
12982   SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12983                                    DL, TargetType, VectorShuffleNode);
12984 
12985   return ExtendNode;
12986 }
12987 
12988 /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
12989 /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
12990 static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
12991   // If the value type isn't a vector, none of the operands are going to be dups
12992   if (!Mul->getValueType(0).isVector())
12993     return SDValue();
12994 
12995   SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
12996   SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
12997 
12998   // Neither operands have been changed, don't make any further changes
12999   if (!Op0 && !Op1)
13000     return SDValue();
13001 
13002   SDLoc DL(Mul);
13003   return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
13004                      Op0 ? Op0 : Mul->getOperand(0),
13005                      Op1 ? Op1 : Mul->getOperand(1));
13006 }
13007 
13008 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
13009                                  TargetLowering::DAGCombinerInfo &DCI,
13010                                  const AArch64Subtarget *Subtarget) {
13011 
13012   if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
13013     return Ext;
13014 
13015   if (DCI.isBeforeLegalizeOps())
13016     return SDValue();
13017 
13018   // The below optimizations require a constant RHS.
13019   if (!isa<ConstantSDNode>(N->getOperand(1)))
13020     return SDValue();
13021 
13022   SDValue N0 = N->getOperand(0);
13023   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
13024   const APInt &ConstValue = C->getAPIntValue();
13025 
13026   // Allow the scaling to be folded into the `cnt` instruction by preventing
13027   // the scaling to be obscured here. This makes it easier to pattern match.
13028   if (IsSVECntIntrinsic(N0) ||
13029      (N0->getOpcode() == ISD::TRUNCATE &&
13030       (IsSVECntIntrinsic(N0->getOperand(0)))))
13031        if (ConstValue.sge(1) && ConstValue.sle(16))
13032          return SDValue();
13033 
13034   // Multiplication of a power of two plus/minus one can be done more
13035   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
13036   // future CPUs have a cheaper MADD instruction, this may need to be
13037   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
13038   // 64-bit is 5 cycles, so this is always a win.
13039   // More aggressively, some multiplications N0 * C can be lowered to
13040   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
13041   // e.g. 6=3*2=(2+1)*2.
13042   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
13043   // which equals to (1+2)*16-(1+2).
13044 
13045   // TrailingZeroes is used to test if the mul can be lowered to
13046   // shift+add+shift.
13047   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
13048   if (TrailingZeroes) {
13049     // Conservatively do not lower to shift+add+shift if the mul might be
13050     // folded into smul or umul.
13051     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
13052                             isZeroExtended(N0.getNode(), DAG)))
13053       return SDValue();
13054     // Conservatively do not lower to shift+add+shift if the mul might be
13055     // folded into madd or msub.
13056     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
13057                            N->use_begin()->getOpcode() == ISD::SUB))
13058       return SDValue();
13059   }
13060   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
13061   // and shift+add+shift.
13062   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
13063 
13064   unsigned ShiftAmt, AddSubOpc;
13065   // Is the shifted value the LHS operand of the add/sub?
13066   bool ShiftValUseIsN0 = true;
13067   // Do we need to negate the result?
13068   bool NegateResult = false;
13069 
13070   if (ConstValue.isNonNegative()) {
13071     // (mul x, 2^N + 1) => (add (shl x, N), x)
13072     // (mul x, 2^N - 1) => (sub (shl x, N), x)
13073     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
13074     APInt SCVMinus1 = ShiftedConstValue - 1;
13075     APInt CVPlus1 = ConstValue + 1;
13076     if (SCVMinus1.isPowerOf2()) {
13077       ShiftAmt = SCVMinus1.logBase2();
13078       AddSubOpc = ISD::ADD;
13079     } else if (CVPlus1.isPowerOf2()) {
13080       ShiftAmt = CVPlus1.logBase2();
13081       AddSubOpc = ISD::SUB;
13082     } else
13083       return SDValue();
13084   } else {
13085     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
13086     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
13087     APInt CVNegPlus1 = -ConstValue + 1;
13088     APInt CVNegMinus1 = -ConstValue - 1;
13089     if (CVNegPlus1.isPowerOf2()) {
13090       ShiftAmt = CVNegPlus1.logBase2();
13091       AddSubOpc = ISD::SUB;
13092       ShiftValUseIsN0 = false;
13093     } else if (CVNegMinus1.isPowerOf2()) {
13094       ShiftAmt = CVNegMinus1.logBase2();
13095       AddSubOpc = ISD::ADD;
13096       NegateResult = true;
13097     } else
13098       return SDValue();
13099   }
13100 
13101   SDLoc DL(N);
13102   EVT VT = N->getValueType(0);
13103   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
13104                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
13105 
13106   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
13107   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
13108   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
13109   assert(!(NegateResult && TrailingZeroes) &&
13110          "NegateResult and TrailingZeroes cannot both be true for now.");
13111   // Negate the result.
13112   if (NegateResult)
13113     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
13114   // Shift the result.
13115   if (TrailingZeroes)
13116     return DAG.getNode(ISD::SHL, DL, VT, Res,
13117                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
13118   return Res;
13119 }
13120 
13121 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
13122                                                          SelectionDAG &DAG) {
13123   // Take advantage of vector comparisons producing 0 or -1 in each lane to
13124   // optimize away operation when it's from a constant.
13125   //
13126   // The general transformation is:
13127   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
13128   //       AND(VECTOR_CMP(x,y), constant2)
13129   //    constant2 = UNARYOP(constant)
13130 
13131   // Early exit if this isn't a vector operation, the operand of the
13132   // unary operation isn't a bitwise AND, or if the sizes of the operations
13133   // aren't the same.
13134   EVT VT = N->getValueType(0);
13135   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
13136       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
13137       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
13138     return SDValue();
13139 
13140   // Now check that the other operand of the AND is a constant. We could
13141   // make the transformation for non-constant splats as well, but it's unclear
13142   // that would be a benefit as it would not eliminate any operations, just
13143   // perform one more step in scalar code before moving to the vector unit.
13144   if (BuildVectorSDNode *BV =
13145           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
13146     // Bail out if the vector isn't a constant.
13147     if (!BV->isConstant())
13148       return SDValue();
13149 
13150     // Everything checks out. Build up the new and improved node.
13151     SDLoc DL(N);
13152     EVT IntVT = BV->getValueType(0);
13153     // Create a new constant of the appropriate type for the transformed
13154     // DAG.
13155     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
13156     // The AND node needs bitcasts to/from an integer vector type around it.
13157     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
13158     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
13159                                  N->getOperand(0)->getOperand(0), MaskConst);
13160     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
13161     return Res;
13162   }
13163 
13164   return SDValue();
13165 }
13166 
13167 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
13168                                      const AArch64Subtarget *Subtarget) {
13169   // First try to optimize away the conversion when it's conditionally from
13170   // a constant. Vectors only.
13171   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
13172     return Res;
13173 
13174   EVT VT = N->getValueType(0);
13175   if (VT != MVT::f32 && VT != MVT::f64)
13176     return SDValue();
13177 
13178   // Only optimize when the source and destination types have the same width.
13179   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
13180     return SDValue();
13181 
13182   // If the result of an integer load is only used by an integer-to-float
13183   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
13184   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
13185   SDValue N0 = N->getOperand(0);
13186   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
13187       // Do not change the width of a volatile load.
13188       !cast<LoadSDNode>(N0)->isVolatile()) {
13189     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13190     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
13191                                LN0->getPointerInfo(), LN0->getAlignment(),
13192                                LN0->getMemOperand()->getFlags());
13193 
13194     // Make sure successors of the original load stay after it by updating them
13195     // to use the new Chain.
13196     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
13197 
13198     unsigned Opcode =
13199         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
13200     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
13201   }
13202 
13203   return SDValue();
13204 }
13205 
13206 /// Fold a floating-point multiply by power of two into floating-point to
13207 /// fixed-point conversion.
13208 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
13209                                      TargetLowering::DAGCombinerInfo &DCI,
13210                                      const AArch64Subtarget *Subtarget) {
13211   if (!Subtarget->hasNEON())
13212     return SDValue();
13213 
13214   if (!N->getValueType(0).isSimple())
13215     return SDValue();
13216 
13217   SDValue Op = N->getOperand(0);
13218   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13219       Op.getOpcode() != ISD::FMUL)
13220     return SDValue();
13221 
13222   SDValue ConstVec = Op->getOperand(1);
13223   if (!isa<BuildVectorSDNode>(ConstVec))
13224     return SDValue();
13225 
13226   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13227   uint32_t FloatBits = FloatTy.getSizeInBits();
13228   if (FloatBits != 32 && FloatBits != 64)
13229     return SDValue();
13230 
13231   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13232   uint32_t IntBits = IntTy.getSizeInBits();
13233   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13234     return SDValue();
13235 
13236   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
13237   if (IntBits > FloatBits)
13238     return SDValue();
13239 
13240   BitVector UndefElements;
13241   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13242   int32_t Bits = IntBits == 64 ? 64 : 32;
13243   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
13244   if (C == -1 || C == 0 || C > Bits)
13245     return SDValue();
13246 
13247   MVT ResTy;
13248   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13249   switch (NumLanes) {
13250   default:
13251     return SDValue();
13252   case 2:
13253     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
13254     break;
13255   case 4:
13256     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
13257     break;
13258   }
13259 
13260   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
13261     return SDValue();
13262 
13263   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
13264          "Illegal vector type after legalization");
13265 
13266   SDLoc DL(N);
13267   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13268   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
13269                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
13270   SDValue FixConv =
13271       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
13272                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
13273                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
13274   // We can handle smaller integers by generating an extra trunc.
13275   if (IntBits < FloatBits)
13276     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
13277 
13278   return FixConv;
13279 }
13280 
13281 /// Fold a floating-point divide by power of two into fixed-point to
13282 /// floating-point conversion.
13283 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
13284                                   TargetLowering::DAGCombinerInfo &DCI,
13285                                   const AArch64Subtarget *Subtarget) {
13286   if (!Subtarget->hasNEON())
13287     return SDValue();
13288 
13289   SDValue Op = N->getOperand(0);
13290   unsigned Opc = Op->getOpcode();
13291   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13292       !Op.getOperand(0).getValueType().isSimple() ||
13293       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
13294     return SDValue();
13295 
13296   SDValue ConstVec = N->getOperand(1);
13297   if (!isa<BuildVectorSDNode>(ConstVec))
13298     return SDValue();
13299 
13300   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13301   int32_t IntBits = IntTy.getSizeInBits();
13302   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
13303     return SDValue();
13304 
13305   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13306   int32_t FloatBits = FloatTy.getSizeInBits();
13307   if (FloatBits != 32 && FloatBits != 64)
13308     return SDValue();
13309 
13310   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
13311   if (IntBits > FloatBits)
13312     return SDValue();
13313 
13314   BitVector UndefElements;
13315   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13316   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
13317   if (C == -1 || C == 0 || C > FloatBits)
13318     return SDValue();
13319 
13320   MVT ResTy;
13321   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13322   switch (NumLanes) {
13323   default:
13324     return SDValue();
13325   case 2:
13326     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
13327     break;
13328   case 4:
13329     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
13330     break;
13331   }
13332 
13333   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
13334     return SDValue();
13335 
13336   SDLoc DL(N);
13337   SDValue ConvInput = Op.getOperand(0);
13338   bool IsSigned = Opc == ISD::SINT_TO_FP;
13339   if (IntBits < FloatBits)
13340     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
13341                             ResTy, ConvInput);
13342 
13343   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
13344                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
13345   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
13346                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
13347                      DAG.getConstant(C, DL, MVT::i32));
13348 }
13349 
13350 /// An EXTR instruction is made up of two shifts, ORed together. This helper
13351 /// searches for and classifies those shifts.
13352 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
13353                          bool &FromHi) {
13354   if (N.getOpcode() == ISD::SHL)
13355     FromHi = false;
13356   else if (N.getOpcode() == ISD::SRL)
13357     FromHi = true;
13358   else
13359     return false;
13360 
13361   if (!isa<ConstantSDNode>(N.getOperand(1)))
13362     return false;
13363 
13364   ShiftAmount = N->getConstantOperandVal(1);
13365   Src = N->getOperand(0);
13366   return true;
13367 }
13368 
13369 /// EXTR instruction extracts a contiguous chunk of bits from two existing
13370 /// registers viewed as a high/low pair. This function looks for the pattern:
13371 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
13372 /// with an EXTR. Can't quite be done in TableGen because the two immediates
13373 /// aren't independent.
13374 static SDValue tryCombineToEXTR(SDNode *N,
13375                                 TargetLowering::DAGCombinerInfo &DCI) {
13376   SelectionDAG &DAG = DCI.DAG;
13377   SDLoc DL(N);
13378   EVT VT = N->getValueType(0);
13379 
13380   assert(N->getOpcode() == ISD::OR && "Unexpected root");
13381 
13382   if (VT != MVT::i32 && VT != MVT::i64)
13383     return SDValue();
13384 
13385   SDValue LHS;
13386   uint32_t ShiftLHS = 0;
13387   bool LHSFromHi = false;
13388   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
13389     return SDValue();
13390 
13391   SDValue RHS;
13392   uint32_t ShiftRHS = 0;
13393   bool RHSFromHi = false;
13394   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
13395     return SDValue();
13396 
13397   // If they're both trying to come from the high part of the register, they're
13398   // not really an EXTR.
13399   if (LHSFromHi == RHSFromHi)
13400     return SDValue();
13401 
13402   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
13403     return SDValue();
13404 
13405   if (LHSFromHi) {
13406     std::swap(LHS, RHS);
13407     std::swap(ShiftLHS, ShiftRHS);
13408   }
13409 
13410   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
13411                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
13412 }
13413 
13414 static SDValue tryCombineToBSL(SDNode *N,
13415                                 TargetLowering::DAGCombinerInfo &DCI) {
13416   EVT VT = N->getValueType(0);
13417   SelectionDAG &DAG = DCI.DAG;
13418   SDLoc DL(N);
13419 
13420   if (!VT.isVector())
13421     return SDValue();
13422 
13423   // The combining code currently only works for NEON vectors. In particular,
13424   // it does not work for SVE when dealing with vectors wider than 128 bits.
13425   if (!VT.is64BitVector() && !VT.is128BitVector())
13426     return SDValue();
13427 
13428   SDValue N0 = N->getOperand(0);
13429   if (N0.getOpcode() != ISD::AND)
13430     return SDValue();
13431 
13432   SDValue N1 = N->getOperand(1);
13433   if (N1.getOpcode() != ISD::AND)
13434     return SDValue();
13435 
13436   // InstCombine does (not (neg a)) => (add a -1).
13437   // Try: (or (and (neg a) b) (and (add a -1) c)) => (bsl (neg a) b c)
13438   // Loop over all combinations of AND operands.
13439   for (int i = 1; i >= 0; --i) {
13440     for (int j = 1; j >= 0; --j) {
13441       SDValue O0 = N0->getOperand(i);
13442       SDValue O1 = N1->getOperand(j);
13443       SDValue Sub, Add, SubSibling, AddSibling;
13444 
13445       // Find a SUB and an ADD operand, one from each AND.
13446       if (O0.getOpcode() == ISD::SUB && O1.getOpcode() == ISD::ADD) {
13447         Sub = O0;
13448         Add = O1;
13449         SubSibling = N0->getOperand(1 - i);
13450         AddSibling = N1->getOperand(1 - j);
13451       } else if (O0.getOpcode() == ISD::ADD && O1.getOpcode() == ISD::SUB) {
13452         Add = O0;
13453         Sub = O1;
13454         AddSibling = N0->getOperand(1 - i);
13455         SubSibling = N1->getOperand(1 - j);
13456       } else
13457         continue;
13458 
13459       if (!ISD::isBuildVectorAllZeros(Sub.getOperand(0).getNode()))
13460         continue;
13461 
13462       // Constant ones is always righthand operand of the Add.
13463       if (!ISD::isBuildVectorAllOnes(Add.getOperand(1).getNode()))
13464         continue;
13465 
13466       if (Sub.getOperand(1) != Add.getOperand(0))
13467         continue;
13468 
13469       return DAG.getNode(AArch64ISD::BSP, DL, VT, Sub, SubSibling, AddSibling);
13470     }
13471   }
13472 
13473   // (or (and a b) (and (not a) c)) => (bsl a b c)
13474   // We only have to look for constant vectors here since the general, variable
13475   // case can be handled in TableGen.
13476   unsigned Bits = VT.getScalarSizeInBits();
13477   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
13478   for (int i = 1; i >= 0; --i)
13479     for (int j = 1; j >= 0; --j) {
13480       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
13481       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
13482       if (!BVN0 || !BVN1)
13483         continue;
13484 
13485       bool FoundMatch = true;
13486       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
13487         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
13488         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
13489         if (!CN0 || !CN1 ||
13490             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
13491           FoundMatch = false;
13492           break;
13493         }
13494       }
13495 
13496       if (FoundMatch)
13497         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
13498                            N0->getOperand(1 - i), N1->getOperand(1 - j));
13499     }
13500 
13501   return SDValue();
13502 }
13503 
13504 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13505                                 const AArch64Subtarget *Subtarget) {
13506   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
13507   SelectionDAG &DAG = DCI.DAG;
13508   EVT VT = N->getValueType(0);
13509 
13510   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13511     return SDValue();
13512 
13513   if (SDValue Res = tryCombineToEXTR(N, DCI))
13514     return Res;
13515 
13516   if (SDValue Res = tryCombineToBSL(N, DCI))
13517     return Res;
13518 
13519   return SDValue();
13520 }
13521 
13522 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
13523   if (!MemVT.getVectorElementType().isSimple())
13524     return false;
13525 
13526   uint64_t MaskForTy = 0ull;
13527   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
13528   case MVT::i8:
13529     MaskForTy = 0xffull;
13530     break;
13531   case MVT::i16:
13532     MaskForTy = 0xffffull;
13533     break;
13534   case MVT::i32:
13535     MaskForTy = 0xffffffffull;
13536     break;
13537   default:
13538     return false;
13539     break;
13540   }
13541 
13542   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
13543     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
13544       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
13545 
13546   return false;
13547 }
13548 
13549 static SDValue performSVEAndCombine(SDNode *N,
13550                                     TargetLowering::DAGCombinerInfo &DCI) {
13551   if (DCI.isBeforeLegalizeOps())
13552     return SDValue();
13553 
13554   SelectionDAG &DAG = DCI.DAG;
13555   SDValue Src = N->getOperand(0);
13556   unsigned Opc = Src->getOpcode();
13557 
13558   // Zero/any extend of an unsigned unpack
13559   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13560     SDValue UnpkOp = Src->getOperand(0);
13561     SDValue Dup = N->getOperand(1);
13562 
13563     if (Dup.getOpcode() != AArch64ISD::DUP)
13564       return SDValue();
13565 
13566     SDLoc DL(N);
13567     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
13568     if (!C)
13569       return SDValue();
13570 
13571     uint64_t ExtVal = C->getZExtValue();
13572 
13573     // If the mask is fully covered by the unpack, we don't need to push
13574     // a new AND onto the operand
13575     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
13576     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
13577         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
13578         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
13579       return Src;
13580 
13581     // Truncate to prevent a DUP with an over wide constant
13582     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
13583 
13584     // Otherwise, make sure we propagate the AND to the operand
13585     // of the unpack
13586     Dup = DAG.getNode(AArch64ISD::DUP, DL,
13587                       UnpkOp->getValueType(0),
13588                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
13589 
13590     SDValue And = DAG.getNode(ISD::AND, DL,
13591                               UnpkOp->getValueType(0), UnpkOp, Dup);
13592 
13593     return DAG.getNode(Opc, DL, N->getValueType(0), And);
13594   }
13595 
13596   if (!EnableCombineMGatherIntrinsics)
13597     return SDValue();
13598 
13599   SDValue Mask = N->getOperand(1);
13600 
13601   if (!Src.hasOneUse())
13602     return SDValue();
13603 
13604   EVT MemVT;
13605 
13606   // SVE load instructions perform an implicit zero-extend, which makes them
13607   // perfect candidates for combining.
13608   switch (Opc) {
13609   case AArch64ISD::LD1_MERGE_ZERO:
13610   case AArch64ISD::LDNF1_MERGE_ZERO:
13611   case AArch64ISD::LDFF1_MERGE_ZERO:
13612     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
13613     break;
13614   case AArch64ISD::GLD1_MERGE_ZERO:
13615   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
13616   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
13617   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
13618   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
13619   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
13620   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
13621   case AArch64ISD::GLDFF1_MERGE_ZERO:
13622   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
13623   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
13624   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
13625   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
13626   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
13627   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
13628   case AArch64ISD::GLDNT1_MERGE_ZERO:
13629     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
13630     break;
13631   default:
13632     return SDValue();
13633   }
13634 
13635   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
13636     return Src;
13637 
13638   return SDValue();
13639 }
13640 
13641 static SDValue performANDCombine(SDNode *N,
13642                                  TargetLowering::DAGCombinerInfo &DCI) {
13643   SelectionDAG &DAG = DCI.DAG;
13644   SDValue LHS = N->getOperand(0);
13645   EVT VT = N->getValueType(0);
13646   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
13647     return SDValue();
13648 
13649   if (VT.isScalableVector())
13650     return performSVEAndCombine(N, DCI);
13651 
13652   // The combining code below works only for NEON vectors. In particular, it
13653   // does not work for SVE when dealing with vectors wider than 128 bits.
13654   if (!(VT.is64BitVector() || VT.is128BitVector()))
13655     return SDValue();
13656 
13657   BuildVectorSDNode *BVN =
13658       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
13659   if (!BVN)
13660     return SDValue();
13661 
13662   // AND does not accept an immediate, so check if we can use a BIC immediate
13663   // instruction instead. We do this here instead of using a (and x, (mvni imm))
13664   // pattern in isel, because some immediates may be lowered to the preferred
13665   // (and x, (movi imm)) form, even though an mvni representation also exists.
13666   APInt DefBits(VT.getSizeInBits(), 0);
13667   APInt UndefBits(VT.getSizeInBits(), 0);
13668   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
13669     SDValue NewOp;
13670 
13671     DefBits = ~DefBits;
13672     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
13673                                     DefBits, &LHS)) ||
13674         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
13675                                     DefBits, &LHS)))
13676       return NewOp;
13677 
13678     UndefBits = ~UndefBits;
13679     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
13680                                     UndefBits, &LHS)) ||
13681         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
13682                                     UndefBits, &LHS)))
13683       return NewOp;
13684   }
13685 
13686   return SDValue();
13687 }
13688 
13689 static SDValue performSRLCombine(SDNode *N,
13690                                  TargetLowering::DAGCombinerInfo &DCI) {
13691   SelectionDAG &DAG = DCI.DAG;
13692   EVT VT = N->getValueType(0);
13693   if (VT != MVT::i32 && VT != MVT::i64)
13694     return SDValue();
13695 
13696   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
13697   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
13698   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
13699   SDValue N0 = N->getOperand(0);
13700   if (N0.getOpcode() == ISD::BSWAP) {
13701     SDLoc DL(N);
13702     SDValue N1 = N->getOperand(1);
13703     SDValue N00 = N0.getOperand(0);
13704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13705       uint64_t ShiftAmt = C->getZExtValue();
13706       if (VT == MVT::i32 && ShiftAmt == 16 &&
13707           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
13708         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
13709       if (VT == MVT::i64 && ShiftAmt == 32 &&
13710           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
13711         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
13712     }
13713   }
13714   return SDValue();
13715 }
13716 
13717 // Attempt to form urhadd(OpA, OpB) from
13718 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
13719 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
13720 // The original form of the first expression is
13721 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
13722 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
13723 // Before this function is called the srl will have been lowered to
13724 // AArch64ISD::VLSHR.
13725 // This pass can also recognize signed variants of the patterns that use sign
13726 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
13727 // shadd(OpA, OpB) from them.
13728 static SDValue
13729 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13730                              SelectionDAG &DAG) {
13731   EVT VT = N->getValueType(0);
13732 
13733   // Since we are looking for a right shift by a constant value of 1 and we are
13734   // operating on types at least 16 bits in length (sign/zero extended OpA and
13735   // OpB, which are at least 8 bits), it follows that the truncate will always
13736   // discard the shifted-in bit and therefore the right shift will be logical
13737   // regardless of the signedness of OpA and OpB.
13738   SDValue Shift = N->getOperand(0);
13739   if (Shift.getOpcode() != AArch64ISD::VLSHR)
13740     return SDValue();
13741 
13742   // Is the right shift using an immediate value of 1?
13743   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
13744   if (ShiftAmount != 1)
13745     return SDValue();
13746 
13747   SDValue ExtendOpA, ExtendOpB;
13748   SDValue ShiftOp0 = Shift.getOperand(0);
13749   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
13750   if (ShiftOp0Opc == ISD::SUB) {
13751 
13752     SDValue Xor = ShiftOp0.getOperand(1);
13753     if (Xor.getOpcode() != ISD::XOR)
13754       return SDValue();
13755 
13756     // Is the XOR using a constant amount of all ones in the right hand side?
13757     uint64_t C;
13758     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
13759       return SDValue();
13760 
13761     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
13762     APInt CAsAPInt(ElemSizeInBits, C);
13763     if (CAsAPInt != APInt::getAllOnes(ElemSizeInBits))
13764       return SDValue();
13765 
13766     ExtendOpA = Xor.getOperand(0);
13767     ExtendOpB = ShiftOp0.getOperand(0);
13768   } else if (ShiftOp0Opc == ISD::ADD) {
13769     ExtendOpA = ShiftOp0.getOperand(0);
13770     ExtendOpB = ShiftOp0.getOperand(1);
13771   } else
13772     return SDValue();
13773 
13774   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
13775   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
13776   if (!(ExtendOpAOpc == ExtendOpBOpc &&
13777         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
13778     return SDValue();
13779 
13780   // Is the result of the right shift being truncated to the same value type as
13781   // the original operands, OpA and OpB?
13782   SDValue OpA = ExtendOpA.getOperand(0);
13783   SDValue OpB = ExtendOpB.getOperand(0);
13784   EVT OpAVT = OpA.getValueType();
13785   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
13786   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
13787     return SDValue();
13788 
13789   SDLoc DL(N);
13790   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
13791   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
13792   unsigned HADDOpc = IsSignExtend
13793                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
13794                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
13795   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
13796 
13797   return ResultHADD;
13798 }
13799 
13800 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
13801   switch (Opcode) {
13802   case ISD::FADD:
13803     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
13804   case ISD::ADD:
13805     return VT == MVT::i64;
13806   default:
13807     return false;
13808   }
13809 }
13810 
13811 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
13812   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
13813   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
13814 
13815   EVT VT = N->getValueType(0);
13816   const bool FullFP16 =
13817       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
13818 
13819   // Rewrite for pairwise fadd pattern
13820   //   (f32 (extract_vector_elt
13821   //           (fadd (vXf32 Other)
13822   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
13823   // ->
13824   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
13825   //              (extract_vector_elt (vXf32 Other) 1))
13826   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
13827       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
13828     SDLoc DL(N0);
13829     SDValue N00 = N0->getOperand(0);
13830     SDValue N01 = N0->getOperand(1);
13831 
13832     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
13833     SDValue Other = N00;
13834 
13835     // And handle the commutative case.
13836     if (!Shuffle) {
13837       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
13838       Other = N01;
13839     }
13840 
13841     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
13842         Other == Shuffle->getOperand(0)) {
13843       return DAG.getNode(N0->getOpcode(), DL, VT,
13844                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
13845                                      DAG.getConstant(0, DL, MVT::i64)),
13846                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
13847                                      DAG.getConstant(1, DL, MVT::i64)));
13848     }
13849   }
13850 
13851   return SDValue();
13852 }
13853 
13854 static SDValue performConcatVectorsCombine(SDNode *N,
13855                                            TargetLowering::DAGCombinerInfo &DCI,
13856                                            SelectionDAG &DAG) {
13857   SDLoc dl(N);
13858   EVT VT = N->getValueType(0);
13859   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
13860   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
13861 
13862   // Optimize concat_vectors of truncated vectors, where the intermediate
13863   // type is illegal, to avoid said illegality,  e.g.,
13864   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
13865   //                          (v2i16 (truncate (v2i64)))))
13866   // ->
13867   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
13868   //                                    (v4i32 (bitcast (v2i64))),
13869   //                                    <0, 2, 4, 6>)))
13870   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
13871   // on both input and result type, so we might generate worse code.
13872   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
13873   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
13874       N1Opc == ISD::TRUNCATE) {
13875     SDValue N00 = N0->getOperand(0);
13876     SDValue N10 = N1->getOperand(0);
13877     EVT N00VT = N00.getValueType();
13878 
13879     if (N00VT == N10.getValueType() &&
13880         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
13881         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
13882       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
13883       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
13884       for (size_t i = 0; i < Mask.size(); ++i)
13885         Mask[i] = i * 2;
13886       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13887                          DAG.getVectorShuffle(
13888                              MidVT, dl,
13889                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
13890                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
13891     }
13892   }
13893 
13894   // Wait 'til after everything is legalized to try this. That way we have
13895   // legal vector types and such.
13896   if (DCI.isBeforeLegalizeOps())
13897     return SDValue();
13898 
13899   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
13900   // subvectors from the same original vectors. Combine these into a single
13901   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
13902   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
13903   //                                        extract_subvector (v16i8 OpB,
13904   //                                        <0>))),
13905   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
13906   //                                        extract_subvector (v16i8 OpB,
13907   //                                        <8>)))))
13908   // ->
13909   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
13910   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
13911       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
13912        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
13913     SDValue N00 = N0->getOperand(0);
13914     SDValue N01 = N0->getOperand(1);
13915     SDValue N10 = N1->getOperand(0);
13916     SDValue N11 = N1->getOperand(1);
13917 
13918     EVT N00VT = N00.getValueType();
13919     EVT N10VT = N10.getValueType();
13920 
13921     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13922         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13923         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13924         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
13925       SDValue N00Source = N00->getOperand(0);
13926       SDValue N01Source = N01->getOperand(0);
13927       SDValue N10Source = N10->getOperand(0);
13928       SDValue N11Source = N11->getOperand(0);
13929 
13930       if (N00Source == N10Source && N01Source == N11Source &&
13931           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
13932         assert(N0.getValueType() == N1.getValueType());
13933 
13934         uint64_t N00Index = N00.getConstantOperandVal(1);
13935         uint64_t N01Index = N01.getConstantOperandVal(1);
13936         uint64_t N10Index = N10.getConstantOperandVal(1);
13937         uint64_t N11Index = N11.getConstantOperandVal(1);
13938 
13939         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
13940             N10Index == N00VT.getVectorNumElements())
13941           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
13942       }
13943     }
13944   }
13945 
13946   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
13947   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
13948   // canonicalise to that.
13949   if (N->getNumOperands() == 2 && N0 == N1 && VT.getVectorNumElements() == 2) {
13950     assert(VT.getScalarSizeInBits() == 64);
13951     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
13952                        DAG.getConstant(0, dl, MVT::i64));
13953   }
13954 
13955   // Canonicalise concat_vectors so that the right-hand vector has as few
13956   // bit-casts as possible before its real operation. The primary matching
13957   // destination for these operations will be the narrowing "2" instructions,
13958   // which depend on the operation being performed on this right-hand vector.
13959   // For example,
13960   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
13961   // becomes
13962   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
13963 
13964   if (N->getNumOperands() != 2 || N1Opc != ISD::BITCAST)
13965     return SDValue();
13966   SDValue RHS = N1->getOperand(0);
13967   MVT RHSTy = RHS.getValueType().getSimpleVT();
13968   // If the RHS is not a vector, this is not the pattern we're looking for.
13969   if (!RHSTy.isVector())
13970     return SDValue();
13971 
13972   LLVM_DEBUG(
13973       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
13974 
13975   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
13976                                   RHSTy.getVectorNumElements() * 2);
13977   return DAG.getNode(ISD::BITCAST, dl, VT,
13978                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
13979                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
13980                                  RHS));
13981 }
13982 
13983 static SDValue
13984 performInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13985                               SelectionDAG &DAG) {
13986   SDValue Vec = N->getOperand(0);
13987   SDValue SubVec = N->getOperand(1);
13988   uint64_t IdxVal = N->getConstantOperandVal(2);
13989   EVT VecVT = Vec.getValueType();
13990   EVT SubVT = SubVec.getValueType();
13991 
13992   // Only do this for legal fixed vector types.
13993   if (!VecVT.isFixedLengthVector() ||
13994       !DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
13995       !DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
13996     return SDValue();
13997 
13998   // Ignore widening patterns.
13999   if (IdxVal == 0 && Vec.isUndef())
14000     return SDValue();
14001 
14002   // Subvector must be half the width and an "aligned" insertion.
14003   unsigned NumSubElts = SubVT.getVectorNumElements();
14004   if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
14005       (IdxVal != 0 && IdxVal != NumSubElts))
14006     return SDValue();
14007 
14008   // Fold insert_subvector -> concat_vectors
14009   // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
14010   // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
14011   SDLoc DL(N);
14012   SDValue Lo, Hi;
14013   if (IdxVal == 0) {
14014     Lo = SubVec;
14015     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
14016                      DAG.getVectorIdxConstant(NumSubElts, DL));
14017   } else {
14018     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
14019                      DAG.getVectorIdxConstant(0, DL));
14020     Hi = SubVec;
14021   }
14022   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
14023 }
14024 
14025 static SDValue tryCombineFixedPointConvert(SDNode *N,
14026                                            TargetLowering::DAGCombinerInfo &DCI,
14027                                            SelectionDAG &DAG) {
14028   // Wait until after everything is legalized to try this. That way we have
14029   // legal vector types and such.
14030   if (DCI.isBeforeLegalizeOps())
14031     return SDValue();
14032   // Transform a scalar conversion of a value from a lane extract into a
14033   // lane extract of a vector conversion. E.g., from foo1 to foo2:
14034   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
14035   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
14036   //
14037   // The second form interacts better with instruction selection and the
14038   // register allocator to avoid cross-class register copies that aren't
14039   // coalescable due to a lane reference.
14040 
14041   // Check the operand and see if it originates from a lane extract.
14042   SDValue Op1 = N->getOperand(1);
14043   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14044     // Yep, no additional predication needed. Perform the transform.
14045     SDValue IID = N->getOperand(0);
14046     SDValue Shift = N->getOperand(2);
14047     SDValue Vec = Op1.getOperand(0);
14048     SDValue Lane = Op1.getOperand(1);
14049     EVT ResTy = N->getValueType(0);
14050     EVT VecResTy;
14051     SDLoc DL(N);
14052 
14053     // The vector width should be 128 bits by the time we get here, even
14054     // if it started as 64 bits (the extract_vector handling will have
14055     // done so).
14056     assert(Vec.getValueSizeInBits() == 128 &&
14057            "unexpected vector size on extract_vector_elt!");
14058     if (Vec.getValueType() == MVT::v4i32)
14059       VecResTy = MVT::v4f32;
14060     else if (Vec.getValueType() == MVT::v2i64)
14061       VecResTy = MVT::v2f64;
14062     else
14063       llvm_unreachable("unexpected vector type!");
14064 
14065     SDValue Convert =
14066         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
14067     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
14068   }
14069   return SDValue();
14070 }
14071 
14072 // AArch64 high-vector "long" operations are formed by performing the non-high
14073 // version on an extract_subvector of each operand which gets the high half:
14074 //
14075 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
14076 //
14077 // However, there are cases which don't have an extract_high explicitly, but
14078 // have another operation that can be made compatible with one for free. For
14079 // example:
14080 //
14081 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
14082 //
14083 // This routine does the actual conversion of such DUPs, once outer routines
14084 // have determined that everything else is in order.
14085 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
14086 // similarly here.
14087 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
14088   switch (N.getOpcode()) {
14089   case AArch64ISD::DUP:
14090   case AArch64ISD::DUPLANE8:
14091   case AArch64ISD::DUPLANE16:
14092   case AArch64ISD::DUPLANE32:
14093   case AArch64ISD::DUPLANE64:
14094   case AArch64ISD::MOVI:
14095   case AArch64ISD::MOVIshift:
14096   case AArch64ISD::MOVIedit:
14097   case AArch64ISD::MOVImsl:
14098   case AArch64ISD::MVNIshift:
14099   case AArch64ISD::MVNImsl:
14100     break;
14101   default:
14102     // FMOV could be supported, but isn't very useful, as it would only occur
14103     // if you passed a bitcast' floating point immediate to an eligible long
14104     // integer op (addl, smull, ...).
14105     return SDValue();
14106   }
14107 
14108   MVT NarrowTy = N.getSimpleValueType();
14109   if (!NarrowTy.is64BitVector())
14110     return SDValue();
14111 
14112   MVT ElementTy = NarrowTy.getVectorElementType();
14113   unsigned NumElems = NarrowTy.getVectorNumElements();
14114   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
14115 
14116   SDLoc dl(N);
14117   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
14118                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
14119                      DAG.getConstant(NumElems, dl, MVT::i64));
14120 }
14121 
14122 static bool isEssentiallyExtractHighSubvector(SDValue N) {
14123   if (N.getOpcode() == ISD::BITCAST)
14124     N = N.getOperand(0);
14125   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
14126     return false;
14127   if (N.getOperand(0).getValueType().isScalableVector())
14128     return false;
14129   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
14130          N.getOperand(0).getValueType().getVectorNumElements() / 2;
14131 }
14132 
14133 /// Helper structure to keep track of ISD::SET_CC operands.
14134 struct GenericSetCCInfo {
14135   const SDValue *Opnd0;
14136   const SDValue *Opnd1;
14137   ISD::CondCode CC;
14138 };
14139 
14140 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
14141 struct AArch64SetCCInfo {
14142   const SDValue *Cmp;
14143   AArch64CC::CondCode CC;
14144 };
14145 
14146 /// Helper structure to keep track of SetCC information.
14147 union SetCCInfo {
14148   GenericSetCCInfo Generic;
14149   AArch64SetCCInfo AArch64;
14150 };
14151 
14152 /// Helper structure to be able to read SetCC information.  If set to
14153 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
14154 /// GenericSetCCInfo.
14155 struct SetCCInfoAndKind {
14156   SetCCInfo Info;
14157   bool IsAArch64;
14158 };
14159 
14160 /// Check whether or not \p Op is a SET_CC operation, either a generic or
14161 /// an
14162 /// AArch64 lowered one.
14163 /// \p SetCCInfo is filled accordingly.
14164 /// \post SetCCInfo is meanginfull only when this function returns true.
14165 /// \return True when Op is a kind of SET_CC operation.
14166 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
14167   // If this is a setcc, this is straight forward.
14168   if (Op.getOpcode() == ISD::SETCC) {
14169     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
14170     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
14171     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14172     SetCCInfo.IsAArch64 = false;
14173     return true;
14174   }
14175   // Otherwise, check if this is a matching csel instruction.
14176   // In other words:
14177   // - csel 1, 0, cc
14178   // - csel 0, 1, !cc
14179   if (Op.getOpcode() != AArch64ISD::CSEL)
14180     return false;
14181   // Set the information about the operands.
14182   // TODO: we want the operands of the Cmp not the csel
14183   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
14184   SetCCInfo.IsAArch64 = true;
14185   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
14186       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14187 
14188   // Check that the operands matches the constraints:
14189   // (1) Both operands must be constants.
14190   // (2) One must be 1 and the other must be 0.
14191   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
14192   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14193 
14194   // Check (1).
14195   if (!TValue || !FValue)
14196     return false;
14197 
14198   // Check (2).
14199   if (!TValue->isOne()) {
14200     // Update the comparison when we are interested in !cc.
14201     std::swap(TValue, FValue);
14202     SetCCInfo.Info.AArch64.CC =
14203         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
14204   }
14205   return TValue->isOne() && FValue->isZero();
14206 }
14207 
14208 // Returns true if Op is setcc or zext of setcc.
14209 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
14210   if (isSetCC(Op, Info))
14211     return true;
14212   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
14213     isSetCC(Op->getOperand(0), Info));
14214 }
14215 
14216 // The folding we want to perform is:
14217 // (add x, [zext] (setcc cc ...) )
14218 //   -->
14219 // (csel x, (add x, 1), !cc ...)
14220 //
14221 // The latter will get matched to a CSINC instruction.
14222 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
14223   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
14224   SDValue LHS = Op->getOperand(0);
14225   SDValue RHS = Op->getOperand(1);
14226   SetCCInfoAndKind InfoAndKind;
14227 
14228   // If both operands are a SET_CC, then we don't want to perform this
14229   // folding and create another csel as this results in more instructions
14230   // (and higher register usage).
14231   if (isSetCCOrZExtSetCC(LHS, InfoAndKind) &&
14232       isSetCCOrZExtSetCC(RHS, InfoAndKind))
14233     return SDValue();
14234 
14235   // If neither operand is a SET_CC, give up.
14236   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
14237     std::swap(LHS, RHS);
14238     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
14239       return SDValue();
14240   }
14241 
14242   // FIXME: This could be generatized to work for FP comparisons.
14243   EVT CmpVT = InfoAndKind.IsAArch64
14244                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
14245                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
14246   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
14247     return SDValue();
14248 
14249   SDValue CCVal;
14250   SDValue Cmp;
14251   SDLoc dl(Op);
14252   if (InfoAndKind.IsAArch64) {
14253     CCVal = DAG.getConstant(
14254         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
14255         MVT::i32);
14256     Cmp = *InfoAndKind.Info.AArch64.Cmp;
14257   } else
14258     Cmp = getAArch64Cmp(
14259         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
14260         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
14261         dl);
14262 
14263   EVT VT = Op->getValueType(0);
14264   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
14265   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
14266 }
14267 
14268 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
14269 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
14270   EVT VT = N->getValueType(0);
14271   // Only scalar integer and vector types.
14272   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
14273     return SDValue();
14274 
14275   SDValue LHS = N->getOperand(0);
14276   SDValue RHS = N->getOperand(1);
14277   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14278       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
14279     return SDValue();
14280 
14281   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14282   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
14283   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isZero())
14284     return SDValue();
14285 
14286   SDValue Op1 = LHS->getOperand(0);
14287   SDValue Op2 = RHS->getOperand(0);
14288   EVT OpVT1 = Op1.getValueType();
14289   EVT OpVT2 = Op2.getValueType();
14290   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
14291       Op2.getOpcode() != AArch64ISD::UADDV ||
14292       OpVT1.getVectorElementType() != VT)
14293     return SDValue();
14294 
14295   SDValue Val1 = Op1.getOperand(0);
14296   SDValue Val2 = Op2.getOperand(0);
14297   EVT ValVT = Val1->getValueType(0);
14298   SDLoc DL(N);
14299   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
14300   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14301                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
14302                      DAG.getConstant(0, DL, MVT::i64));
14303 }
14304 
14305 // ADD(UDOT(zero, x, y), A) -->  UDOT(A, x, y)
14306 static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) {
14307   EVT VT = N->getValueType(0);
14308   if (N->getOpcode() != ISD::ADD)
14309     return SDValue();
14310 
14311   SDValue Dot = N->getOperand(0);
14312   SDValue A = N->getOperand(1);
14313   // Handle commutivity
14314   auto isZeroDot = [](SDValue Dot) {
14315     return (Dot.getOpcode() == AArch64ISD::UDOT ||
14316             Dot.getOpcode() == AArch64ISD::SDOT) &&
14317            isZerosVector(Dot.getOperand(0).getNode());
14318   };
14319   if (!isZeroDot(Dot))
14320     std::swap(Dot, A);
14321   if (!isZeroDot(Dot))
14322     return SDValue();
14323 
14324   return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1),
14325                      Dot.getOperand(2));
14326 }
14327 
14328 // The basic add/sub long vector instructions have variants with "2" on the end
14329 // which act on the high-half of their inputs. They are normally matched by
14330 // patterns like:
14331 //
14332 // (add (zeroext (extract_high LHS)),
14333 //      (zeroext (extract_high RHS)))
14334 // -> uaddl2 vD, vN, vM
14335 //
14336 // However, if one of the extracts is something like a duplicate, this
14337 // instruction can still be used profitably. This function puts the DAG into a
14338 // more appropriate form for those patterns to trigger.
14339 static SDValue performAddSubLongCombine(SDNode *N,
14340                                         TargetLowering::DAGCombinerInfo &DCI,
14341                                         SelectionDAG &DAG) {
14342   if (DCI.isBeforeLegalizeOps())
14343     return SDValue();
14344 
14345   MVT VT = N->getSimpleValueType(0);
14346   if (!VT.is128BitVector()) {
14347     if (N->getOpcode() == ISD::ADD)
14348       return performSetccAddFolding(N, DAG);
14349     return SDValue();
14350   }
14351 
14352   // Make sure both branches are extended in the same way.
14353   SDValue LHS = N->getOperand(0);
14354   SDValue RHS = N->getOperand(1);
14355   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
14356        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
14357       LHS.getOpcode() != RHS.getOpcode())
14358     return SDValue();
14359 
14360   unsigned ExtType = LHS.getOpcode();
14361 
14362   // It's not worth doing if at least one of the inputs isn't already an
14363   // extract, but we don't know which it'll be so we have to try both.
14364   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
14365     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
14366     if (!RHS.getNode())
14367       return SDValue();
14368 
14369     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
14370   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
14371     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
14372     if (!LHS.getNode())
14373       return SDValue();
14374 
14375     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
14376   }
14377 
14378   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
14379 }
14380 
14381 static SDValue performAddSubCombine(SDNode *N,
14382                                     TargetLowering::DAGCombinerInfo &DCI,
14383                                     SelectionDAG &DAG) {
14384   // Try to change sum of two reductions.
14385   if (SDValue Val = performUADDVCombine(N, DAG))
14386     return Val;
14387   if (SDValue Val = performAddDotCombine(N, DAG))
14388     return Val;
14389 
14390   return performAddSubLongCombine(N, DCI, DAG);
14391 }
14392 
14393 // Massage DAGs which we can use the high-half "long" operations on into
14394 // something isel will recognize better. E.g.
14395 //
14396 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
14397 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
14398 //                     (extract_high (v2i64 (dup128 scalar)))))
14399 //
14400 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
14401                                        TargetLowering::DAGCombinerInfo &DCI,
14402                                        SelectionDAG &DAG) {
14403   if (DCI.isBeforeLegalizeOps())
14404     return SDValue();
14405 
14406   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
14407   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
14408   assert(LHS.getValueType().is64BitVector() &&
14409          RHS.getValueType().is64BitVector() &&
14410          "unexpected shape for long operation");
14411 
14412   // Either node could be a DUP, but it's not worth doing both of them (you'd
14413   // just as well use the non-high version) so look for a corresponding extract
14414   // operation on the other "wing".
14415   if (isEssentiallyExtractHighSubvector(LHS)) {
14416     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
14417     if (!RHS.getNode())
14418       return SDValue();
14419   } else if (isEssentiallyExtractHighSubvector(RHS)) {
14420     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
14421     if (!LHS.getNode())
14422       return SDValue();
14423   }
14424 
14425   if (IID == Intrinsic::not_intrinsic)
14426     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
14427 
14428   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
14429                      N->getOperand(0), LHS, RHS);
14430 }
14431 
14432 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
14433   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
14434   unsigned ElemBits = ElemTy.getSizeInBits();
14435 
14436   int64_t ShiftAmount;
14437   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
14438     APInt SplatValue, SplatUndef;
14439     unsigned SplatBitSize;
14440     bool HasAnyUndefs;
14441     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
14442                               HasAnyUndefs, ElemBits) ||
14443         SplatBitSize != ElemBits)
14444       return SDValue();
14445 
14446     ShiftAmount = SplatValue.getSExtValue();
14447   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14448     ShiftAmount = CVN->getSExtValue();
14449   } else
14450     return SDValue();
14451 
14452   unsigned Opcode;
14453   bool IsRightShift;
14454   switch (IID) {
14455   default:
14456     llvm_unreachable("Unknown shift intrinsic");
14457   case Intrinsic::aarch64_neon_sqshl:
14458     Opcode = AArch64ISD::SQSHL_I;
14459     IsRightShift = false;
14460     break;
14461   case Intrinsic::aarch64_neon_uqshl:
14462     Opcode = AArch64ISD::UQSHL_I;
14463     IsRightShift = false;
14464     break;
14465   case Intrinsic::aarch64_neon_srshl:
14466     Opcode = AArch64ISD::SRSHR_I;
14467     IsRightShift = true;
14468     break;
14469   case Intrinsic::aarch64_neon_urshl:
14470     Opcode = AArch64ISD::URSHR_I;
14471     IsRightShift = true;
14472     break;
14473   case Intrinsic::aarch64_neon_sqshlu:
14474     Opcode = AArch64ISD::SQSHLU_I;
14475     IsRightShift = false;
14476     break;
14477   case Intrinsic::aarch64_neon_sshl:
14478   case Intrinsic::aarch64_neon_ushl:
14479     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
14480     // left shift for positive shift amounts. Below, we only replace the current
14481     // node with VSHL, if this condition is met.
14482     Opcode = AArch64ISD::VSHL;
14483     IsRightShift = false;
14484     break;
14485   }
14486 
14487   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
14488     SDLoc dl(N);
14489     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14490                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
14491   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
14492     SDLoc dl(N);
14493     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
14494                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
14495   }
14496 
14497   return SDValue();
14498 }
14499 
14500 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
14501 // the intrinsics must be legal and take an i32, this means there's almost
14502 // certainly going to be a zext in the DAG which we can eliminate.
14503 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
14504   SDValue AndN = N->getOperand(2);
14505   if (AndN.getOpcode() != ISD::AND)
14506     return SDValue();
14507 
14508   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
14509   if (!CMask || CMask->getZExtValue() != Mask)
14510     return SDValue();
14511 
14512   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
14513                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
14514 }
14515 
14516 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
14517                                            SelectionDAG &DAG) {
14518   SDLoc dl(N);
14519   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
14520                      DAG.getNode(Opc, dl,
14521                                  N->getOperand(1).getSimpleValueType(),
14522                                  N->getOperand(1)),
14523                      DAG.getConstant(0, dl, MVT::i64));
14524 }
14525 
14526 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
14527   SDLoc DL(N);
14528   SDValue Op1 = N->getOperand(1);
14529   SDValue Op2 = N->getOperand(2);
14530   EVT ScalarTy = Op2.getValueType();
14531   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14532     ScalarTy = MVT::i32;
14533 
14534   // Lower index_vector(base, step) to mul(step step_vector(1)) + splat(base).
14535   SDValue StepVector = DAG.getStepVector(DL, N->getValueType(0));
14536   SDValue Step = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op2);
14537   SDValue Mul = DAG.getNode(ISD::MUL, DL, N->getValueType(0), StepVector, Step);
14538   SDValue Base = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op1);
14539   return DAG.getNode(ISD::ADD, DL, N->getValueType(0), Mul, Base);
14540 }
14541 
14542 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
14543   SDLoc dl(N);
14544   SDValue Scalar = N->getOperand(3);
14545   EVT ScalarTy = Scalar.getValueType();
14546 
14547   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
14548     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
14549 
14550   SDValue Passthru = N->getOperand(1);
14551   SDValue Pred = N->getOperand(2);
14552   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
14553                      Pred, Scalar, Passthru);
14554 }
14555 
14556 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
14557   SDLoc dl(N);
14558   LLVMContext &Ctx = *DAG.getContext();
14559   EVT VT = N->getValueType(0);
14560 
14561   assert(VT.isScalableVector() && "Expected a scalable vector.");
14562 
14563   // Current lowering only supports the SVE-ACLE types.
14564   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
14565     return SDValue();
14566 
14567   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
14568   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
14569   EVT ByteVT =
14570       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
14571 
14572   // Convert everything to the domain of EXT (i.e bytes).
14573   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
14574   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
14575   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
14576                             DAG.getConstant(ElemSize, dl, MVT::i32));
14577 
14578   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
14579   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
14580 }
14581 
14582 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
14583                                         TargetLowering::DAGCombinerInfo &DCI,
14584                                         SelectionDAG &DAG) {
14585   if (DCI.isBeforeLegalize())
14586     return SDValue();
14587 
14588   SDValue Comparator = N->getOperand(3);
14589   if (Comparator.getOpcode() == AArch64ISD::DUP ||
14590       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
14591     unsigned IID = getIntrinsicID(N);
14592     EVT VT = N->getValueType(0);
14593     EVT CmpVT = N->getOperand(2).getValueType();
14594     SDValue Pred = N->getOperand(1);
14595     SDValue Imm;
14596     SDLoc DL(N);
14597 
14598     switch (IID) {
14599     default:
14600       llvm_unreachable("Called with wrong intrinsic!");
14601       break;
14602 
14603     // Signed comparisons
14604     case Intrinsic::aarch64_sve_cmpeq_wide:
14605     case Intrinsic::aarch64_sve_cmpne_wide:
14606     case Intrinsic::aarch64_sve_cmpge_wide:
14607     case Intrinsic::aarch64_sve_cmpgt_wide:
14608     case Intrinsic::aarch64_sve_cmplt_wide:
14609     case Intrinsic::aarch64_sve_cmple_wide: {
14610       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
14611         int64_t ImmVal = CN->getSExtValue();
14612         if (ImmVal >= -16 && ImmVal <= 15)
14613           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
14614         else
14615           return SDValue();
14616       }
14617       break;
14618     }
14619     // Unsigned comparisons
14620     case Intrinsic::aarch64_sve_cmphs_wide:
14621     case Intrinsic::aarch64_sve_cmphi_wide:
14622     case Intrinsic::aarch64_sve_cmplo_wide:
14623     case Intrinsic::aarch64_sve_cmpls_wide:  {
14624       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
14625         uint64_t ImmVal = CN->getZExtValue();
14626         if (ImmVal <= 127)
14627           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
14628         else
14629           return SDValue();
14630       }
14631       break;
14632     }
14633     }
14634 
14635     if (!Imm)
14636       return SDValue();
14637 
14638     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
14639     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
14640                        N->getOperand(2), Splat, DAG.getCondCode(CC));
14641   }
14642 
14643   return SDValue();
14644 }
14645 
14646 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
14647                         AArch64CC::CondCode Cond) {
14648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14649 
14650   SDLoc DL(Op);
14651   assert(Op.getValueType().isScalableVector() &&
14652          TLI.isTypeLegal(Op.getValueType()) &&
14653          "Expected legal scalable vector type!");
14654 
14655   // Ensure target specific opcodes are using legal type.
14656   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
14657   SDValue TVal = DAG.getConstant(1, DL, OutVT);
14658   SDValue FVal = DAG.getConstant(0, DL, OutVT);
14659 
14660   // Set condition code (CC) flags.
14661   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
14662 
14663   // Convert CC to integer based on requested condition.
14664   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
14665   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
14666   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
14667   return DAG.getZExtOrTrunc(Res, DL, VT);
14668 }
14669 
14670 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
14671                                       SelectionDAG &DAG) {
14672   SDLoc DL(N);
14673 
14674   SDValue Pred = N->getOperand(1);
14675   SDValue VecToReduce = N->getOperand(2);
14676 
14677   // NOTE: The integer reduction's result type is not always linked to the
14678   // operand's element type so we construct it from the intrinsic's result type.
14679   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
14680   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
14681 
14682   // SVE reductions set the whole vector register with the first element
14683   // containing the reduction result, which we'll now extract.
14684   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14685   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14686                      Zero);
14687 }
14688 
14689 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
14690                                      SelectionDAG &DAG) {
14691   SDLoc DL(N);
14692 
14693   SDValue Pred = N->getOperand(1);
14694   SDValue VecToReduce = N->getOperand(2);
14695 
14696   EVT ReduceVT = VecToReduce.getValueType();
14697   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
14698 
14699   // SVE reductions set the whole vector register with the first element
14700   // containing the reduction result, which we'll now extract.
14701   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14702   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14703                      Zero);
14704 }
14705 
14706 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
14707                                             SelectionDAG &DAG) {
14708   SDLoc DL(N);
14709 
14710   SDValue Pred = N->getOperand(1);
14711   SDValue InitVal = N->getOperand(2);
14712   SDValue VecToReduce = N->getOperand(3);
14713   EVT ReduceVT = VecToReduce.getValueType();
14714 
14715   // Ordered reductions use the first lane of the result vector as the
14716   // reduction's initial value.
14717   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
14718   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
14719                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
14720 
14721   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
14722 
14723   // SVE reductions set the whole vector register with the first element
14724   // containing the reduction result, which we'll now extract.
14725   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
14726                      Zero);
14727 }
14728 
14729 static bool isAllActivePredicate(SDValue N) {
14730   unsigned NumElts = N.getValueType().getVectorMinNumElements();
14731 
14732   // Look through cast.
14733   while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST) {
14734     N = N.getOperand(0);
14735     // When reinterpreting from a type with fewer elements the "new" elements
14736     // are not active, so bail if they're likely to be used.
14737     if (N.getValueType().getVectorMinNumElements() < NumElts)
14738       return false;
14739   }
14740 
14741   // "ptrue p.<ty>, all" can be considered all active when <ty> is the same size
14742   // or smaller than the implicit element type represented by N.
14743   // NOTE: A larger element count implies a smaller element type.
14744   if (N.getOpcode() == AArch64ISD::PTRUE &&
14745       N.getConstantOperandVal(0) == AArch64SVEPredPattern::all)
14746     return N.getValueType().getVectorMinNumElements() >= NumElts;
14747 
14748   return false;
14749 }
14750 
14751 // If a merged operation has no inactive lanes we can relax it to a predicated
14752 // or unpredicated operation, which potentially allows better isel (perhaps
14753 // using immediate forms) or relaxing register reuse requirements.
14754 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned Opc,
14755                                        SelectionDAG &DAG, bool UnpredOp = false,
14756                                        bool SwapOperands = false) {
14757   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
14758   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
14759   SDValue Pg = N->getOperand(1);
14760   SDValue Op1 = N->getOperand(SwapOperands ? 3 : 2);
14761   SDValue Op2 = N->getOperand(SwapOperands ? 2 : 3);
14762 
14763   // ISD way to specify an all active predicate.
14764   if (isAllActivePredicate(Pg)) {
14765     if (UnpredOp)
14766       return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Op1, Op2);
14767 
14768     return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Pg, Op1, Op2);
14769   }
14770 
14771   // FUTURE: SplatVector(true)
14772   return SDValue();
14773 }
14774 
14775 static SDValue performIntrinsicCombine(SDNode *N,
14776                                        TargetLowering::DAGCombinerInfo &DCI,
14777                                        const AArch64Subtarget *Subtarget) {
14778   SelectionDAG &DAG = DCI.DAG;
14779   unsigned IID = getIntrinsicID(N);
14780   switch (IID) {
14781   default:
14782     break;
14783   case Intrinsic::aarch64_neon_vcvtfxs2fp:
14784   case Intrinsic::aarch64_neon_vcvtfxu2fp:
14785     return tryCombineFixedPointConvert(N, DCI, DAG);
14786   case Intrinsic::aarch64_neon_saddv:
14787     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
14788   case Intrinsic::aarch64_neon_uaddv:
14789     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
14790   case Intrinsic::aarch64_neon_sminv:
14791     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
14792   case Intrinsic::aarch64_neon_uminv:
14793     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
14794   case Intrinsic::aarch64_neon_smaxv:
14795     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
14796   case Intrinsic::aarch64_neon_umaxv:
14797     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
14798   case Intrinsic::aarch64_neon_fmax:
14799     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
14800                        N->getOperand(1), N->getOperand(2));
14801   case Intrinsic::aarch64_neon_fmin:
14802     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
14803                        N->getOperand(1), N->getOperand(2));
14804   case Intrinsic::aarch64_neon_fmaxnm:
14805     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
14806                        N->getOperand(1), N->getOperand(2));
14807   case Intrinsic::aarch64_neon_fminnm:
14808     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
14809                        N->getOperand(1), N->getOperand(2));
14810   case Intrinsic::aarch64_neon_smull:
14811   case Intrinsic::aarch64_neon_umull:
14812   case Intrinsic::aarch64_neon_pmull:
14813   case Intrinsic::aarch64_neon_sqdmull:
14814     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
14815   case Intrinsic::aarch64_neon_sqshl:
14816   case Intrinsic::aarch64_neon_uqshl:
14817   case Intrinsic::aarch64_neon_sqshlu:
14818   case Intrinsic::aarch64_neon_srshl:
14819   case Intrinsic::aarch64_neon_urshl:
14820   case Intrinsic::aarch64_neon_sshl:
14821   case Intrinsic::aarch64_neon_ushl:
14822     return tryCombineShiftImm(IID, N, DAG);
14823   case Intrinsic::aarch64_crc32b:
14824   case Intrinsic::aarch64_crc32cb:
14825     return tryCombineCRC32(0xff, N, DAG);
14826   case Intrinsic::aarch64_crc32h:
14827   case Intrinsic::aarch64_crc32ch:
14828     return tryCombineCRC32(0xffff, N, DAG);
14829   case Intrinsic::aarch64_sve_saddv:
14830     // There is no i64 version of SADDV because the sign is irrelevant.
14831     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
14832       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
14833     else
14834       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
14835   case Intrinsic::aarch64_sve_uaddv:
14836     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
14837   case Intrinsic::aarch64_sve_smaxv:
14838     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
14839   case Intrinsic::aarch64_sve_umaxv:
14840     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
14841   case Intrinsic::aarch64_sve_sminv:
14842     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
14843   case Intrinsic::aarch64_sve_uminv:
14844     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
14845   case Intrinsic::aarch64_sve_orv:
14846     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
14847   case Intrinsic::aarch64_sve_eorv:
14848     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
14849   case Intrinsic::aarch64_sve_andv:
14850     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
14851   case Intrinsic::aarch64_sve_index:
14852     return LowerSVEIntrinsicIndex(N, DAG);
14853   case Intrinsic::aarch64_sve_dup:
14854     return LowerSVEIntrinsicDUP(N, DAG);
14855   case Intrinsic::aarch64_sve_dup_x:
14856     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
14857                        N->getOperand(1));
14858   case Intrinsic::aarch64_sve_ext:
14859     return LowerSVEIntrinsicEXT(N, DAG);
14860   case Intrinsic::aarch64_sve_mul:
14861     return convertMergedOpToPredOp(N, AArch64ISD::MUL_PRED, DAG);
14862   case Intrinsic::aarch64_sve_smulh:
14863     return convertMergedOpToPredOp(N, AArch64ISD::MULHS_PRED, DAG);
14864   case Intrinsic::aarch64_sve_umulh:
14865     return convertMergedOpToPredOp(N, AArch64ISD::MULHU_PRED, DAG);
14866   case Intrinsic::aarch64_sve_smin:
14867     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
14868   case Intrinsic::aarch64_sve_umin:
14869     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
14870   case Intrinsic::aarch64_sve_smax:
14871     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
14872   case Intrinsic::aarch64_sve_umax:
14873     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
14874   case Intrinsic::aarch64_sve_lsl:
14875     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
14876   case Intrinsic::aarch64_sve_lsr:
14877     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
14878   case Intrinsic::aarch64_sve_asr:
14879     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
14880   case Intrinsic::aarch64_sve_fadd:
14881     return convertMergedOpToPredOp(N, AArch64ISD::FADD_PRED, DAG);
14882   case Intrinsic::aarch64_sve_fsub:
14883     return convertMergedOpToPredOp(N, AArch64ISD::FSUB_PRED, DAG);
14884   case Intrinsic::aarch64_sve_fmul:
14885     return convertMergedOpToPredOp(N, AArch64ISD::FMUL_PRED, DAG);
14886   case Intrinsic::aarch64_sve_add:
14887     return convertMergedOpToPredOp(N, ISD::ADD, DAG, true);
14888   case Intrinsic::aarch64_sve_sub:
14889     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true);
14890   case Intrinsic::aarch64_sve_subr:
14891     return convertMergedOpToPredOp(N, ISD::SUB, DAG, true, true);
14892   case Intrinsic::aarch64_sve_and:
14893     return convertMergedOpToPredOp(N, ISD::AND, DAG, true);
14894   case Intrinsic::aarch64_sve_bic:
14895     return convertMergedOpToPredOp(N, AArch64ISD::BIC, DAG, true);
14896   case Intrinsic::aarch64_sve_eor:
14897     return convertMergedOpToPredOp(N, ISD::XOR, DAG, true);
14898   case Intrinsic::aarch64_sve_orr:
14899     return convertMergedOpToPredOp(N, ISD::OR, DAG, true);
14900   case Intrinsic::aarch64_sve_sqadd:
14901     return convertMergedOpToPredOp(N, ISD::SADDSAT, DAG, true);
14902   case Intrinsic::aarch64_sve_sqsub:
14903     return convertMergedOpToPredOp(N, ISD::SSUBSAT, DAG, true);
14904   case Intrinsic::aarch64_sve_uqadd:
14905     return convertMergedOpToPredOp(N, ISD::UADDSAT, DAG, true);
14906   case Intrinsic::aarch64_sve_uqsub:
14907     return convertMergedOpToPredOp(N, ISD::USUBSAT, DAG, true);
14908   case Intrinsic::aarch64_sve_sqadd_x:
14909     return DAG.getNode(ISD::SADDSAT, SDLoc(N), N->getValueType(0),
14910                        N->getOperand(1), N->getOperand(2));
14911   case Intrinsic::aarch64_sve_sqsub_x:
14912     return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
14913                        N->getOperand(1), N->getOperand(2));
14914   case Intrinsic::aarch64_sve_uqadd_x:
14915     return DAG.getNode(ISD::UADDSAT, SDLoc(N), N->getValueType(0),
14916                        N->getOperand(1), N->getOperand(2));
14917   case Intrinsic::aarch64_sve_uqsub_x:
14918     return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
14919                        N->getOperand(1), N->getOperand(2));
14920   case Intrinsic::aarch64_sve_cmphs:
14921     if (!N->getOperand(2).getValueType().isFloatingPoint())
14922       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14923                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
14924                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
14925     break;
14926   case Intrinsic::aarch64_sve_cmphi:
14927     if (!N->getOperand(2).getValueType().isFloatingPoint())
14928       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14929                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
14930                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
14931     break;
14932   case Intrinsic::aarch64_sve_fcmpge:
14933   case Intrinsic::aarch64_sve_cmpge:
14934     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14935                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14936                        N->getOperand(3), DAG.getCondCode(ISD::SETGE));
14937     break;
14938   case Intrinsic::aarch64_sve_fcmpgt:
14939   case Intrinsic::aarch64_sve_cmpgt:
14940     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14941                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14942                        N->getOperand(3), DAG.getCondCode(ISD::SETGT));
14943     break;
14944   case Intrinsic::aarch64_sve_fcmpeq:
14945   case Intrinsic::aarch64_sve_cmpeq:
14946     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14947                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14948                        N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
14949     break;
14950   case Intrinsic::aarch64_sve_fcmpne:
14951   case Intrinsic::aarch64_sve_cmpne:
14952     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14953                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14954                        N->getOperand(3), DAG.getCondCode(ISD::SETNE));
14955     break;
14956   case Intrinsic::aarch64_sve_fcmpuo:
14957     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
14958                        N->getValueType(0), N->getOperand(1), N->getOperand(2),
14959                        N->getOperand(3), DAG.getCondCode(ISD::SETUO));
14960     break;
14961   case Intrinsic::aarch64_sve_fadda:
14962     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
14963   case Intrinsic::aarch64_sve_faddv:
14964     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
14965   case Intrinsic::aarch64_sve_fmaxnmv:
14966     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
14967   case Intrinsic::aarch64_sve_fmaxv:
14968     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
14969   case Intrinsic::aarch64_sve_fminnmv:
14970     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
14971   case Intrinsic::aarch64_sve_fminv:
14972     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
14973   case Intrinsic::aarch64_sve_sel:
14974     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
14975                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
14976   case Intrinsic::aarch64_sve_cmpeq_wide:
14977     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
14978   case Intrinsic::aarch64_sve_cmpne_wide:
14979     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
14980   case Intrinsic::aarch64_sve_cmpge_wide:
14981     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
14982   case Intrinsic::aarch64_sve_cmpgt_wide:
14983     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
14984   case Intrinsic::aarch64_sve_cmplt_wide:
14985     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
14986   case Intrinsic::aarch64_sve_cmple_wide:
14987     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
14988   case Intrinsic::aarch64_sve_cmphs_wide:
14989     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
14990   case Intrinsic::aarch64_sve_cmphi_wide:
14991     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
14992   case Intrinsic::aarch64_sve_cmplo_wide:
14993     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
14994   case Intrinsic::aarch64_sve_cmpls_wide:
14995     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
14996   case Intrinsic::aarch64_sve_ptest_any:
14997     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
14998                     AArch64CC::ANY_ACTIVE);
14999   case Intrinsic::aarch64_sve_ptest_first:
15000     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
15001                     AArch64CC::FIRST_ACTIVE);
15002   case Intrinsic::aarch64_sve_ptest_last:
15003     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
15004                     AArch64CC::LAST_ACTIVE);
15005   }
15006   return SDValue();
15007 }
15008 
15009 static SDValue performExtendCombine(SDNode *N,
15010                                     TargetLowering::DAGCombinerInfo &DCI,
15011                                     SelectionDAG &DAG) {
15012   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
15013   // we can convert that DUP into another extract_high (of a bigger DUP), which
15014   // helps the backend to decide that an sabdl2 would be useful, saving a real
15015   // extract_high operation.
15016   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
15017       (N->getOperand(0).getOpcode() == ISD::ABDU ||
15018        N->getOperand(0).getOpcode() == ISD::ABDS)) {
15019     SDNode *ABDNode = N->getOperand(0).getNode();
15020     SDValue NewABD =
15021         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
15022     if (!NewABD.getNode())
15023       return SDValue();
15024 
15025     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
15026   }
15027   return SDValue();
15028 }
15029 
15030 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
15031                                SDValue SplatVal, unsigned NumVecElts) {
15032   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
15033   unsigned OrigAlignment = St.getAlignment();
15034   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
15035 
15036   // Create scalar stores. This is at least as good as the code sequence for a
15037   // split unaligned store which is a dup.s, ext.b, and two stores.
15038   // Most of the time the three stores should be replaced by store pair
15039   // instructions (stp).
15040   SDLoc DL(&St);
15041   SDValue BasePtr = St.getBasePtr();
15042   uint64_t BaseOffset = 0;
15043 
15044   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
15045   SDValue NewST1 =
15046       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
15047                    OrigAlignment, St.getMemOperand()->getFlags());
15048 
15049   // As this in ISel, we will not merge this add which may degrade results.
15050   if (BasePtr->getOpcode() == ISD::ADD &&
15051       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
15052     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
15053     BasePtr = BasePtr->getOperand(0);
15054   }
15055 
15056   unsigned Offset = EltOffset;
15057   while (--NumVecElts) {
15058     unsigned Alignment = MinAlign(OrigAlignment, Offset);
15059     SDValue OffsetPtr =
15060         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
15061                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
15062     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
15063                           PtrInfo.getWithOffset(Offset), Alignment,
15064                           St.getMemOperand()->getFlags());
15065     Offset += EltOffset;
15066   }
15067   return NewST1;
15068 }
15069 
15070 // Returns an SVE type that ContentTy can be trivially sign or zero extended
15071 // into.
15072 static MVT getSVEContainerType(EVT ContentTy) {
15073   assert(ContentTy.isSimple() && "No SVE containers for extended types");
15074 
15075   switch (ContentTy.getSimpleVT().SimpleTy) {
15076   default:
15077     llvm_unreachable("No known SVE container for this MVT type");
15078   case MVT::nxv2i8:
15079   case MVT::nxv2i16:
15080   case MVT::nxv2i32:
15081   case MVT::nxv2i64:
15082   case MVT::nxv2f32:
15083   case MVT::nxv2f64:
15084     return MVT::nxv2i64;
15085   case MVT::nxv4i8:
15086   case MVT::nxv4i16:
15087   case MVT::nxv4i32:
15088   case MVT::nxv4f32:
15089     return MVT::nxv4i32;
15090   case MVT::nxv8i8:
15091   case MVT::nxv8i16:
15092   case MVT::nxv8f16:
15093   case MVT::nxv8bf16:
15094     return MVT::nxv8i16;
15095   case MVT::nxv16i8:
15096     return MVT::nxv16i8;
15097   }
15098 }
15099 
15100 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
15101   SDLoc DL(N);
15102   EVT VT = N->getValueType(0);
15103 
15104   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
15105     return SDValue();
15106 
15107   EVT ContainerVT = VT;
15108   if (ContainerVT.isInteger())
15109     ContainerVT = getSVEContainerType(ContainerVT);
15110 
15111   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
15112   SDValue Ops[] = { N->getOperand(0), // Chain
15113                     N->getOperand(2), // Pg
15114                     N->getOperand(3), // Base
15115                     DAG.getValueType(VT) };
15116 
15117   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
15118   SDValue LoadChain = SDValue(Load.getNode(), 1);
15119 
15120   if (ContainerVT.isInteger() && (VT != ContainerVT))
15121     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
15122 
15123   return DAG.getMergeValues({ Load, LoadChain }, DL);
15124 }
15125 
15126 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
15127   SDLoc DL(N);
15128   EVT VT = N->getValueType(0);
15129   EVT PtrTy = N->getOperand(3).getValueType();
15130 
15131   if (VT == MVT::nxv8bf16 &&
15132       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15133     return SDValue();
15134 
15135   EVT LoadVT = VT;
15136   if (VT.isFloatingPoint())
15137     LoadVT = VT.changeTypeToInteger();
15138 
15139   auto *MINode = cast<MemIntrinsicSDNode>(N);
15140   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
15141   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
15142                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
15143                                 MINode->getOperand(2), PassThru,
15144                                 MINode->getMemoryVT(), MINode->getMemOperand(),
15145                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
15146 
15147    if (VT.isFloatingPoint()) {
15148      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
15149      return DAG.getMergeValues(Ops, DL);
15150    }
15151 
15152   return L;
15153 }
15154 
15155 template <unsigned Opcode>
15156 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
15157   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
15158                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
15159                 "Unsupported opcode.");
15160   SDLoc DL(N);
15161   EVT VT = N->getValueType(0);
15162   if (VT == MVT::nxv8bf16 &&
15163       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15164     return SDValue();
15165 
15166   EVT LoadVT = VT;
15167   if (VT.isFloatingPoint())
15168     LoadVT = VT.changeTypeToInteger();
15169 
15170   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
15171   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
15172   SDValue LoadChain = SDValue(Load.getNode(), 1);
15173 
15174   if (VT.isFloatingPoint())
15175     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
15176 
15177   return DAG.getMergeValues({Load, LoadChain}, DL);
15178 }
15179 
15180 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
15181   SDLoc DL(N);
15182   SDValue Data = N->getOperand(2);
15183   EVT DataVT = Data.getValueType();
15184   EVT HwSrcVt = getSVEContainerType(DataVT);
15185   SDValue InputVT = DAG.getValueType(DataVT);
15186 
15187   if (DataVT == MVT::nxv8bf16 &&
15188       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15189     return SDValue();
15190 
15191   if (DataVT.isFloatingPoint())
15192     InputVT = DAG.getValueType(HwSrcVt);
15193 
15194   SDValue SrcNew;
15195   if (Data.getValueType().isFloatingPoint())
15196     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
15197   else
15198     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
15199 
15200   SDValue Ops[] = { N->getOperand(0), // Chain
15201                     SrcNew,
15202                     N->getOperand(4), // Base
15203                     N->getOperand(3), // Pg
15204                     InputVT
15205                   };
15206 
15207   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
15208 }
15209 
15210 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
15211   SDLoc DL(N);
15212 
15213   SDValue Data = N->getOperand(2);
15214   EVT DataVT = Data.getValueType();
15215   EVT PtrTy = N->getOperand(4).getValueType();
15216 
15217   if (DataVT == MVT::nxv8bf16 &&
15218       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
15219     return SDValue();
15220 
15221   if (DataVT.isFloatingPoint())
15222     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
15223 
15224   auto *MINode = cast<MemIntrinsicSDNode>(N);
15225   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
15226                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
15227                             MINode->getMemoryVT(), MINode->getMemOperand(),
15228                             ISD::UNINDEXED, false, false);
15229 }
15230 
15231 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
15232 /// load store optimizer pass will merge them to store pair stores.  This should
15233 /// be better than a movi to create the vector zero followed by a vector store
15234 /// if the zero constant is not re-used, since one instructions and one register
15235 /// live range will be removed.
15236 ///
15237 /// For example, the final generated code should be:
15238 ///
15239 ///   stp xzr, xzr, [x0]
15240 ///
15241 /// instead of:
15242 ///
15243 ///   movi v0.2d, #0
15244 ///   str q0, [x0]
15245 ///
15246 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15247   SDValue StVal = St.getValue();
15248   EVT VT = StVal.getValueType();
15249 
15250   // Avoid scalarizing zero splat stores for scalable vectors.
15251   if (VT.isScalableVector())
15252     return SDValue();
15253 
15254   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
15255   // 2, 3 or 4 i32 elements.
15256   int NumVecElts = VT.getVectorNumElements();
15257   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
15258          VT.getVectorElementType().getSizeInBits() == 64) ||
15259         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
15260          VT.getVectorElementType().getSizeInBits() == 32)))
15261     return SDValue();
15262 
15263   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
15264     return SDValue();
15265 
15266   // If the zero constant has more than one use then the vector store could be
15267   // better since the constant mov will be amortized and stp q instructions
15268   // should be able to be formed.
15269   if (!StVal.hasOneUse())
15270     return SDValue();
15271 
15272   // If the store is truncating then it's going down to i16 or smaller, which
15273   // means it can be implemented in a single store anyway.
15274   if (St.isTruncatingStore())
15275     return SDValue();
15276 
15277   // If the immediate offset of the address operand is too large for the stp
15278   // instruction, then bail out.
15279   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
15280     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
15281     if (Offset < -512 || Offset > 504)
15282       return SDValue();
15283   }
15284 
15285   for (int I = 0; I < NumVecElts; ++I) {
15286     SDValue EltVal = StVal.getOperand(I);
15287     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
15288       return SDValue();
15289   }
15290 
15291   // Use a CopyFromReg WZR/XZR here to prevent
15292   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
15293   SDLoc DL(&St);
15294   unsigned ZeroReg;
15295   EVT ZeroVT;
15296   if (VT.getVectorElementType().getSizeInBits() == 32) {
15297     ZeroReg = AArch64::WZR;
15298     ZeroVT = MVT::i32;
15299   } else {
15300     ZeroReg = AArch64::XZR;
15301     ZeroVT = MVT::i64;
15302   }
15303   SDValue SplatVal =
15304       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
15305   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15306 }
15307 
15308 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
15309 /// value. The load store optimizer pass will merge them to store pair stores.
15310 /// This has better performance than a splat of the scalar followed by a split
15311 /// vector store. Even if the stores are not merged it is four stores vs a dup,
15312 /// followed by an ext.b and two stores.
15313 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
15314   SDValue StVal = St.getValue();
15315   EVT VT = StVal.getValueType();
15316 
15317   // Don't replace floating point stores, they possibly won't be transformed to
15318   // stp because of the store pair suppress pass.
15319   if (VT.isFloatingPoint())
15320     return SDValue();
15321 
15322   // We can express a splat as store pair(s) for 2 or 4 elements.
15323   unsigned NumVecElts = VT.getVectorNumElements();
15324   if (NumVecElts != 4 && NumVecElts != 2)
15325     return SDValue();
15326 
15327   // If the store is truncating then it's going down to i16 or smaller, which
15328   // means it can be implemented in a single store anyway.
15329   if (St.isTruncatingStore())
15330     return SDValue();
15331 
15332   // Check that this is a splat.
15333   // Make sure that each of the relevant vector element locations are inserted
15334   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
15335   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
15336   SDValue SplatVal;
15337   for (unsigned I = 0; I < NumVecElts; ++I) {
15338     // Check for insert vector elements.
15339     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
15340       return SDValue();
15341 
15342     // Check that same value is inserted at each vector element.
15343     if (I == 0)
15344       SplatVal = StVal.getOperand(1);
15345     else if (StVal.getOperand(1) != SplatVal)
15346       return SDValue();
15347 
15348     // Check insert element index.
15349     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
15350     if (!CIndex)
15351       return SDValue();
15352     uint64_t IndexVal = CIndex->getZExtValue();
15353     if (IndexVal >= NumVecElts)
15354       return SDValue();
15355     IndexNotInserted.reset(IndexVal);
15356 
15357     StVal = StVal.getOperand(0);
15358   }
15359   // Check that all vector element locations were inserted to.
15360   if (IndexNotInserted.any())
15361       return SDValue();
15362 
15363   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
15364 }
15365 
15366 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
15367                            SelectionDAG &DAG,
15368                            const AArch64Subtarget *Subtarget) {
15369 
15370   StoreSDNode *S = cast<StoreSDNode>(N);
15371   if (S->isVolatile() || S->isIndexed())
15372     return SDValue();
15373 
15374   SDValue StVal = S->getValue();
15375   EVT VT = StVal.getValueType();
15376 
15377   if (!VT.isFixedLengthVector())
15378     return SDValue();
15379 
15380   // If we get a splat of zeros, convert this vector store to a store of
15381   // scalars. They will be merged into store pairs of xzr thereby removing one
15382   // instruction and one register.
15383   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
15384     return ReplacedZeroSplat;
15385 
15386   // FIXME: The logic for deciding if an unaligned store should be split should
15387   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
15388   // a call to that function here.
15389 
15390   if (!Subtarget->isMisaligned128StoreSlow())
15391     return SDValue();
15392 
15393   // Don't split at -Oz.
15394   if (DAG.getMachineFunction().getFunction().hasMinSize())
15395     return SDValue();
15396 
15397   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
15398   // those up regresses performance on micro-benchmarks and olden/bh.
15399   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
15400     return SDValue();
15401 
15402   // Split unaligned 16B stores. They are terrible for performance.
15403   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
15404   // extensions can use this to mark that it does not want splitting to happen
15405   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
15406   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
15407   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
15408       S->getAlignment() <= 2)
15409     return SDValue();
15410 
15411   // If we get a splat of a scalar convert this vector store to a store of
15412   // scalars. They will be merged into store pairs thereby removing two
15413   // instructions.
15414   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
15415     return ReplacedSplat;
15416 
15417   SDLoc DL(S);
15418 
15419   // Split VT into two.
15420   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
15421   unsigned NumElts = HalfVT.getVectorNumElements();
15422   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15423                                    DAG.getConstant(0, DL, MVT::i64));
15424   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
15425                                    DAG.getConstant(NumElts, DL, MVT::i64));
15426   SDValue BasePtr = S->getBasePtr();
15427   SDValue NewST1 =
15428       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
15429                    S->getAlignment(), S->getMemOperand()->getFlags());
15430   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
15431                                   DAG.getConstant(8, DL, MVT::i64));
15432   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
15433                       S->getPointerInfo(), S->getAlignment(),
15434                       S->getMemOperand()->getFlags());
15435 }
15436 
15437 static SDValue performSpliceCombine(SDNode *N, SelectionDAG &DAG) {
15438   assert(N->getOpcode() == AArch64ISD::SPLICE && "Unexepected Opcode!");
15439 
15440   // splice(pg, op1, undef) -> op1
15441   if (N->getOperand(2).isUndef())
15442     return N->getOperand(1);
15443 
15444   return SDValue();
15445 }
15446 
15447 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
15448   SDLoc DL(N);
15449   SDValue Op0 = N->getOperand(0);
15450   SDValue Op1 = N->getOperand(1);
15451   EVT ResVT = N->getValueType(0);
15452 
15453   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
15454   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
15455     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
15456       SDValue X = Op0.getOperand(0).getOperand(0);
15457       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
15458     }
15459   }
15460 
15461   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
15462   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
15463     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
15464       SDValue Z = Op1.getOperand(0).getOperand(1);
15465       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
15466     }
15467   }
15468 
15469   return SDValue();
15470 }
15471 
15472 static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) {
15473   unsigned Opc = N->getOpcode();
15474 
15475   assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads
15476            Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) ||
15477           (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads
15478            Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) &&
15479          "Invalid opcode.");
15480 
15481   const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO ||
15482                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
15483   const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO ||
15484                       Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
15485   const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO ||
15486                         Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO ||
15487                         Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO ||
15488                         Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO;
15489 
15490   SDLoc DL(N);
15491   SDValue Chain = N->getOperand(0);
15492   SDValue Pg = N->getOperand(1);
15493   SDValue Base = N->getOperand(2);
15494   SDValue Offset = N->getOperand(3);
15495   SDValue Ty = N->getOperand(4);
15496 
15497   EVT ResVT = N->getValueType(0);
15498 
15499   const auto OffsetOpc = Offset.getOpcode();
15500   const bool OffsetIsZExt =
15501       OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU;
15502   const bool OffsetIsSExt =
15503       OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU;
15504 
15505   // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible.
15506   if (!Extended && (OffsetIsSExt || OffsetIsZExt)) {
15507     SDValue ExtPg = Offset.getOperand(0);
15508     VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode());
15509     EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType();
15510 
15511     // If the predicate for the sign- or zero-extended offset is the
15512     // same as the predicate used for this load and the sign-/zero-extension
15513     // was from a 32-bits...
15514     if (ExtPg == Pg && ExtFromEVT == MVT::i32) {
15515       SDValue UnextendedOffset = Offset.getOperand(1);
15516 
15517       unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true);
15518       if (Signed)
15519         NewOpc = getSignExtendedGatherOpcode(NewOpc);
15520 
15521       return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other},
15522                          {Chain, Pg, Base, UnextendedOffset, Ty});
15523     }
15524   }
15525 
15526   return SDValue();
15527 }
15528 
15529 /// Optimize a vector shift instruction and its operand if shifted out
15530 /// bits are not used.
15531 static SDValue performVectorShiftCombine(SDNode *N,
15532                                          const AArch64TargetLowering &TLI,
15533                                          TargetLowering::DAGCombinerInfo &DCI) {
15534   assert(N->getOpcode() == AArch64ISD::VASHR ||
15535          N->getOpcode() == AArch64ISD::VLSHR);
15536 
15537   SDValue Op = N->getOperand(0);
15538   unsigned OpScalarSize = Op.getScalarValueSizeInBits();
15539 
15540   unsigned ShiftImm = N->getConstantOperandVal(1);
15541   assert(OpScalarSize > ShiftImm && "Invalid shift imm");
15542 
15543   APInt ShiftedOutBits = APInt::getLowBitsSet(OpScalarSize, ShiftImm);
15544   APInt DemandedMask = ~ShiftedOutBits;
15545 
15546   if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
15547     return SDValue(N, 0);
15548 
15549   return SDValue();
15550 }
15551 
15552 /// Target-specific DAG combine function for post-increment LD1 (lane) and
15553 /// post-increment LD1R.
15554 static SDValue performPostLD1Combine(SDNode *N,
15555                                      TargetLowering::DAGCombinerInfo &DCI,
15556                                      bool IsLaneOp) {
15557   if (DCI.isBeforeLegalizeOps())
15558     return SDValue();
15559 
15560   SelectionDAG &DAG = DCI.DAG;
15561   EVT VT = N->getValueType(0);
15562 
15563   if (VT.isScalableVector())
15564     return SDValue();
15565 
15566   unsigned LoadIdx = IsLaneOp ? 1 : 0;
15567   SDNode *LD = N->getOperand(LoadIdx).getNode();
15568   // If it is not LOAD, can not do such combine.
15569   if (LD->getOpcode() != ISD::LOAD)
15570     return SDValue();
15571 
15572   // The vector lane must be a constant in the LD1LANE opcode.
15573   SDValue Lane;
15574   if (IsLaneOp) {
15575     Lane = N->getOperand(2);
15576     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
15577     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
15578       return SDValue();
15579   }
15580 
15581   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
15582   EVT MemVT = LoadSDN->getMemoryVT();
15583   // Check if memory operand is the same type as the vector element.
15584   if (MemVT != VT.getVectorElementType())
15585     return SDValue();
15586 
15587   // Check if there are other uses. If so, do not combine as it will introduce
15588   // an extra load.
15589   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
15590        ++UI) {
15591     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
15592       continue;
15593     if (*UI != N)
15594       return SDValue();
15595   }
15596 
15597   SDValue Addr = LD->getOperand(1);
15598   SDValue Vector = N->getOperand(0);
15599   // Search for a use of the address operand that is an increment.
15600   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
15601        Addr.getNode()->use_end(); UI != UE; ++UI) {
15602     SDNode *User = *UI;
15603     if (User->getOpcode() != ISD::ADD
15604         || UI.getUse().getResNo() != Addr.getResNo())
15605       continue;
15606 
15607     // If the increment is a constant, it must match the memory ref size.
15608     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15609     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
15610       uint32_t IncVal = CInc->getZExtValue();
15611       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
15612       if (IncVal != NumBytes)
15613         continue;
15614       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
15615     }
15616 
15617     // To avoid cycle construction make sure that neither the load nor the add
15618     // are predecessors to each other or the Vector.
15619     SmallPtrSet<const SDNode *, 32> Visited;
15620     SmallVector<const SDNode *, 16> Worklist;
15621     Visited.insert(Addr.getNode());
15622     Worklist.push_back(User);
15623     Worklist.push_back(LD);
15624     Worklist.push_back(Vector.getNode());
15625     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
15626         SDNode::hasPredecessorHelper(User, Visited, Worklist))
15627       continue;
15628 
15629     SmallVector<SDValue, 8> Ops;
15630     Ops.push_back(LD->getOperand(0));  // Chain
15631     if (IsLaneOp) {
15632       Ops.push_back(Vector);           // The vector to be inserted
15633       Ops.push_back(Lane);             // The lane to be inserted in the vector
15634     }
15635     Ops.push_back(Addr);
15636     Ops.push_back(Inc);
15637 
15638     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
15639     SDVTList SDTys = DAG.getVTList(Tys);
15640     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
15641     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
15642                                            MemVT,
15643                                            LoadSDN->getMemOperand());
15644 
15645     // Update the uses.
15646     SDValue NewResults[] = {
15647         SDValue(LD, 0),            // The result of load
15648         SDValue(UpdN.getNode(), 2) // Chain
15649     };
15650     DCI.CombineTo(LD, NewResults);
15651     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
15652     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
15653 
15654     break;
15655   }
15656   return SDValue();
15657 }
15658 
15659 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
15660 /// address translation.
15661 static bool performTBISimplification(SDValue Addr,
15662                                      TargetLowering::DAGCombinerInfo &DCI,
15663                                      SelectionDAG &DAG) {
15664   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
15665   KnownBits Known;
15666   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15667                                         !DCI.isBeforeLegalizeOps());
15668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15669   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
15670     DCI.CommitTargetLoweringOpt(TLO);
15671     return true;
15672   }
15673   return false;
15674 }
15675 
15676 static SDValue foldTruncStoreOfExt(SelectionDAG &DAG, SDNode *N) {
15677   assert((N->getOpcode() == ISD::STORE || N->getOpcode() == ISD::MSTORE) &&
15678          "Expected STORE dag node in input!");
15679 
15680   if (auto Store = dyn_cast<StoreSDNode>(N)) {
15681     if (!Store->isTruncatingStore() || Store->isIndexed())
15682       return SDValue();
15683     SDValue Ext = Store->getValue();
15684     auto ExtOpCode = Ext.getOpcode();
15685     if (ExtOpCode != ISD::ZERO_EXTEND && ExtOpCode != ISD::SIGN_EXTEND &&
15686         ExtOpCode != ISD::ANY_EXTEND)
15687       return SDValue();
15688     SDValue Orig = Ext->getOperand(0);
15689     if (Store->getMemoryVT() != Orig.getValueType())
15690       return SDValue();
15691     return DAG.getStore(Store->getChain(), SDLoc(Store), Orig,
15692                         Store->getBasePtr(), Store->getMemOperand());
15693   }
15694 
15695   return SDValue();
15696 }
15697 
15698 static SDValue performSTORECombine(SDNode *N,
15699                                    TargetLowering::DAGCombinerInfo &DCI,
15700                                    SelectionDAG &DAG,
15701                                    const AArch64Subtarget *Subtarget) {
15702   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
15703     return Split;
15704 
15705   if (Subtarget->supportsAddressTopByteIgnored() &&
15706       performTBISimplification(N->getOperand(2), DCI, DAG))
15707     return SDValue(N, 0);
15708 
15709   if (SDValue Store = foldTruncStoreOfExt(DAG, N))
15710     return Store;
15711 
15712   return SDValue();
15713 }
15714 
15715 /// Target-specific DAG combine function for NEON load/store intrinsics
15716 /// to merge base address updates.
15717 static SDValue performNEONPostLDSTCombine(SDNode *N,
15718                                           TargetLowering::DAGCombinerInfo &DCI,
15719                                           SelectionDAG &DAG) {
15720   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15721     return SDValue();
15722 
15723   unsigned AddrOpIdx = N->getNumOperands() - 1;
15724   SDValue Addr = N->getOperand(AddrOpIdx);
15725 
15726   // Search for a use of the address operand that is an increment.
15727   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
15728        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
15729     SDNode *User = *UI;
15730     if (User->getOpcode() != ISD::ADD ||
15731         UI.getUse().getResNo() != Addr.getResNo())
15732       continue;
15733 
15734     // Check that the add is independent of the load/store.  Otherwise, folding
15735     // it would create a cycle.
15736     SmallPtrSet<const SDNode *, 32> Visited;
15737     SmallVector<const SDNode *, 16> Worklist;
15738     Visited.insert(Addr.getNode());
15739     Worklist.push_back(N);
15740     Worklist.push_back(User);
15741     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
15742         SDNode::hasPredecessorHelper(User, Visited, Worklist))
15743       continue;
15744 
15745     // Find the new opcode for the updating load/store.
15746     bool IsStore = false;
15747     bool IsLaneOp = false;
15748     bool IsDupOp = false;
15749     unsigned NewOpc = 0;
15750     unsigned NumVecs = 0;
15751     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15752     switch (IntNo) {
15753     default: llvm_unreachable("unexpected intrinsic for Neon base update");
15754     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
15755       NumVecs = 2; break;
15756     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
15757       NumVecs = 3; break;
15758     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
15759       NumVecs = 4; break;
15760     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
15761       NumVecs = 2; IsStore = true; break;
15762     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
15763       NumVecs = 3; IsStore = true; break;
15764     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
15765       NumVecs = 4; IsStore = true; break;
15766     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
15767       NumVecs = 2; break;
15768     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
15769       NumVecs = 3; break;
15770     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
15771       NumVecs = 4; break;
15772     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
15773       NumVecs = 2; IsStore = true; break;
15774     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
15775       NumVecs = 3; IsStore = true; break;
15776     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
15777       NumVecs = 4; IsStore = true; break;
15778     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
15779       NumVecs = 2; IsDupOp = true; break;
15780     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
15781       NumVecs = 3; IsDupOp = true; break;
15782     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
15783       NumVecs = 4; IsDupOp = true; break;
15784     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
15785       NumVecs = 2; IsLaneOp = true; break;
15786     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
15787       NumVecs = 3; IsLaneOp = true; break;
15788     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
15789       NumVecs = 4; IsLaneOp = true; break;
15790     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
15791       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
15792     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
15793       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
15794     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
15795       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
15796     }
15797 
15798     EVT VecTy;
15799     if (IsStore)
15800       VecTy = N->getOperand(2).getValueType();
15801     else
15802       VecTy = N->getValueType(0);
15803 
15804     // If the increment is a constant, it must match the memory ref size.
15805     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
15806     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
15807       uint32_t IncVal = CInc->getZExtValue();
15808       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
15809       if (IsLaneOp || IsDupOp)
15810         NumBytes /= VecTy.getVectorNumElements();
15811       if (IncVal != NumBytes)
15812         continue;
15813       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
15814     }
15815     SmallVector<SDValue, 8> Ops;
15816     Ops.push_back(N->getOperand(0)); // Incoming chain
15817     // Load lane and store have vector list as input.
15818     if (IsLaneOp || IsStore)
15819       for (unsigned i = 2; i < AddrOpIdx; ++i)
15820         Ops.push_back(N->getOperand(i));
15821     Ops.push_back(Addr); // Base register
15822     Ops.push_back(Inc);
15823 
15824     // Return Types.
15825     EVT Tys[6];
15826     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
15827     unsigned n;
15828     for (n = 0; n < NumResultVecs; ++n)
15829       Tys[n] = VecTy;
15830     Tys[n++] = MVT::i64;  // Type of write back register
15831     Tys[n] = MVT::Other;  // Type of the chain
15832     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
15833 
15834     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
15835     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
15836                                            MemInt->getMemoryVT(),
15837                                            MemInt->getMemOperand());
15838 
15839     // Update the uses.
15840     std::vector<SDValue> NewResults;
15841     for (unsigned i = 0; i < NumResultVecs; ++i) {
15842       NewResults.push_back(SDValue(UpdN.getNode(), i));
15843     }
15844     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
15845     DCI.CombineTo(N, NewResults);
15846     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
15847 
15848     break;
15849   }
15850   return SDValue();
15851 }
15852 
15853 // Checks to see if the value is the prescribed width and returns information
15854 // about its extension mode.
15855 static
15856 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
15857   ExtType = ISD::NON_EXTLOAD;
15858   switch(V.getNode()->getOpcode()) {
15859   default:
15860     return false;
15861   case ISD::LOAD: {
15862     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
15863     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
15864        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
15865       ExtType = LoadNode->getExtensionType();
15866       return true;
15867     }
15868     return false;
15869   }
15870   case ISD::AssertSext: {
15871     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
15872     if ((TypeNode->getVT() == MVT::i8 && width == 8)
15873        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
15874       ExtType = ISD::SEXTLOAD;
15875       return true;
15876     }
15877     return false;
15878   }
15879   case ISD::AssertZext: {
15880     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
15881     if ((TypeNode->getVT() == MVT::i8 && width == 8)
15882        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
15883       ExtType = ISD::ZEXTLOAD;
15884       return true;
15885     }
15886     return false;
15887   }
15888   case ISD::Constant:
15889   case ISD::TargetConstant: {
15890     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
15891            1LL << (width - 1);
15892   }
15893   }
15894 
15895   return true;
15896 }
15897 
15898 // This function does a whole lot of voodoo to determine if the tests are
15899 // equivalent without and with a mask. Essentially what happens is that given a
15900 // DAG resembling:
15901 //
15902 //  +-------------+ +-------------+ +-------------+ +-------------+
15903 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
15904 //  +-------------+ +-------------+ +-------------+ +-------------+
15905 //           |           |           |               |
15906 //           V           V           |    +----------+
15907 //          +-------------+  +----+  |    |
15908 //          |     ADD     |  |0xff|  |    |
15909 //          +-------------+  +----+  |    |
15910 //                  |           |    |    |
15911 //                  V           V    |    |
15912 //                 +-------------+   |    |
15913 //                 |     AND     |   |    |
15914 //                 +-------------+   |    |
15915 //                      |            |    |
15916 //                      +-----+      |    |
15917 //                            |      |    |
15918 //                            V      V    V
15919 //                           +-------------+
15920 //                           |     CMP     |
15921 //                           +-------------+
15922 //
15923 // The AND node may be safely removed for some combinations of inputs. In
15924 // particular we need to take into account the extension type of the Input,
15925 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
15926 // width of the input (this can work for any width inputs, the above graph is
15927 // specific to 8 bits.
15928 //
15929 // The specific equations were worked out by generating output tables for each
15930 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
15931 // problem was simplified by working with 4 bit inputs, which means we only
15932 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
15933 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
15934 // patterns present in both extensions (0,7). For every distinct set of
15935 // AddConstant and CompConstants bit patterns we can consider the masked and
15936 // unmasked versions to be equivalent if the result of this function is true for
15937 // all 16 distinct bit patterns of for the current extension type of Input (w0).
15938 //
15939 //   sub      w8, w0, w1
15940 //   and      w10, w8, #0x0f
15941 //   cmp      w8, w2
15942 //   cset     w9, AArch64CC
15943 //   cmp      w10, w2
15944 //   cset     w11, AArch64CC
15945 //   cmp      w9, w11
15946 //   cset     w0, eq
15947 //   ret
15948 //
15949 // Since the above function shows when the outputs are equivalent it defines
15950 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
15951 // would be expensive to run during compiles. The equations below were written
15952 // in a test harness that confirmed they gave equivalent outputs to the above
15953 // for all inputs function, so they can be used determine if the removal is
15954 // legal instead.
15955 //
15956 // isEquivalentMaskless() is the code for testing if the AND can be removed
15957 // factored out of the DAG recognition as the DAG can take several forms.
15958 
15959 static bool isEquivalentMaskless(unsigned CC, unsigned width,
15960                                  ISD::LoadExtType ExtType, int AddConstant,
15961                                  int CompConstant) {
15962   // By being careful about our equations and only writing the in term
15963   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
15964   // make them generally applicable to all bit widths.
15965   int MaxUInt = (1 << width);
15966 
15967   // For the purposes of these comparisons sign extending the type is
15968   // equivalent to zero extending the add and displacing it by half the integer
15969   // width. Provided we are careful and make sure our equations are valid over
15970   // the whole range we can just adjust the input and avoid writing equations
15971   // for sign extended inputs.
15972   if (ExtType == ISD::SEXTLOAD)
15973     AddConstant -= (1 << (width-1));
15974 
15975   switch(CC) {
15976   case AArch64CC::LE:
15977   case AArch64CC::GT:
15978     if ((AddConstant == 0) ||
15979         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
15980         (AddConstant >= 0 && CompConstant < 0) ||
15981         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
15982       return true;
15983     break;
15984   case AArch64CC::LT:
15985   case AArch64CC::GE:
15986     if ((AddConstant == 0) ||
15987         (AddConstant >= 0 && CompConstant <= 0) ||
15988         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
15989       return true;
15990     break;
15991   case AArch64CC::HI:
15992   case AArch64CC::LS:
15993     if ((AddConstant >= 0 && CompConstant < 0) ||
15994        (AddConstant <= 0 && CompConstant >= -1 &&
15995         CompConstant < AddConstant + MaxUInt))
15996       return true;
15997    break;
15998   case AArch64CC::PL:
15999   case AArch64CC::MI:
16000     if ((AddConstant == 0) ||
16001         (AddConstant > 0 && CompConstant <= 0) ||
16002         (AddConstant < 0 && CompConstant <= AddConstant))
16003       return true;
16004     break;
16005   case AArch64CC::LO:
16006   case AArch64CC::HS:
16007     if ((AddConstant >= 0 && CompConstant <= 0) ||
16008         (AddConstant <= 0 && CompConstant >= 0 &&
16009          CompConstant <= AddConstant + MaxUInt))
16010       return true;
16011     break;
16012   case AArch64CC::EQ:
16013   case AArch64CC::NE:
16014     if ((AddConstant > 0 && CompConstant < 0) ||
16015         (AddConstant < 0 && CompConstant >= 0 &&
16016          CompConstant < AddConstant + MaxUInt) ||
16017         (AddConstant >= 0 && CompConstant >= 0 &&
16018          CompConstant >= AddConstant) ||
16019         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
16020       return true;
16021     break;
16022   case AArch64CC::VS:
16023   case AArch64CC::VC:
16024   case AArch64CC::AL:
16025   case AArch64CC::NV:
16026     return true;
16027   case AArch64CC::Invalid:
16028     break;
16029   }
16030 
16031   return false;
16032 }
16033 
16034 static
16035 SDValue performCONDCombine(SDNode *N,
16036                            TargetLowering::DAGCombinerInfo &DCI,
16037                            SelectionDAG &DAG, unsigned CCIndex,
16038                            unsigned CmpIndex) {
16039   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
16040   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
16041   unsigned CondOpcode = SubsNode->getOpcode();
16042 
16043   if (CondOpcode != AArch64ISD::SUBS)
16044     return SDValue();
16045 
16046   // There is a SUBS feeding this condition. Is it fed by a mask we can
16047   // use?
16048 
16049   SDNode *AndNode = SubsNode->getOperand(0).getNode();
16050   unsigned MaskBits = 0;
16051 
16052   if (AndNode->getOpcode() != ISD::AND)
16053     return SDValue();
16054 
16055   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
16056     uint32_t CNV = CN->getZExtValue();
16057     if (CNV == 255)
16058       MaskBits = 8;
16059     else if (CNV == 65535)
16060       MaskBits = 16;
16061   }
16062 
16063   if (!MaskBits)
16064     return SDValue();
16065 
16066   SDValue AddValue = AndNode->getOperand(0);
16067 
16068   if (AddValue.getOpcode() != ISD::ADD)
16069     return SDValue();
16070 
16071   // The basic dag structure is correct, grab the inputs and validate them.
16072 
16073   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
16074   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
16075   SDValue SubsInputValue = SubsNode->getOperand(1);
16076 
16077   // The mask is present and the provenance of all the values is a smaller type,
16078   // lets see if the mask is superfluous.
16079 
16080   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
16081       !isa<ConstantSDNode>(SubsInputValue.getNode()))
16082     return SDValue();
16083 
16084   ISD::LoadExtType ExtType;
16085 
16086   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
16087       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
16088       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
16089     return SDValue();
16090 
16091   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
16092                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
16093                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
16094     return SDValue();
16095 
16096   // The AND is not necessary, remove it.
16097 
16098   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
16099                                SubsNode->getValueType(1));
16100   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
16101 
16102   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
16103   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
16104 
16105   return SDValue(N, 0);
16106 }
16107 
16108 // Optimize compare with zero and branch.
16109 static SDValue performBRCONDCombine(SDNode *N,
16110                                     TargetLowering::DAGCombinerInfo &DCI,
16111                                     SelectionDAG &DAG) {
16112   MachineFunction &MF = DAG.getMachineFunction();
16113   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
16114   // will not be produced, as they are conditional branch instructions that do
16115   // not set flags.
16116   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
16117     return SDValue();
16118 
16119   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
16120     N = NV.getNode();
16121   SDValue Chain = N->getOperand(0);
16122   SDValue Dest = N->getOperand(1);
16123   SDValue CCVal = N->getOperand(2);
16124   SDValue Cmp = N->getOperand(3);
16125 
16126   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
16127   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
16128   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
16129     return SDValue();
16130 
16131   unsigned CmpOpc = Cmp.getOpcode();
16132   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
16133     return SDValue();
16134 
16135   // Only attempt folding if there is only one use of the flag and no use of the
16136   // value.
16137   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
16138     return SDValue();
16139 
16140   SDValue LHS = Cmp.getOperand(0);
16141   SDValue RHS = Cmp.getOperand(1);
16142 
16143   assert(LHS.getValueType() == RHS.getValueType() &&
16144          "Expected the value type to be the same for both operands!");
16145   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
16146     return SDValue();
16147 
16148   if (isNullConstant(LHS))
16149     std::swap(LHS, RHS);
16150 
16151   if (!isNullConstant(RHS))
16152     return SDValue();
16153 
16154   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
16155       LHS.getOpcode() == ISD::SRL)
16156     return SDValue();
16157 
16158   // Fold the compare into the branch instruction.
16159   SDValue BR;
16160   if (CC == AArch64CC::EQ)
16161     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16162   else
16163     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
16164 
16165   // Do not add new nodes to DAG combiner worklist.
16166   DCI.CombineTo(N, BR, false);
16167 
16168   return SDValue();
16169 }
16170 
16171 // Optimize CSEL instructions
16172 static SDValue performCSELCombine(SDNode *N,
16173                                   TargetLowering::DAGCombinerInfo &DCI,
16174                                   SelectionDAG &DAG) {
16175   // CSEL x, x, cc -> x
16176   if (N->getOperand(0) == N->getOperand(1))
16177     return N->getOperand(0);
16178 
16179   return performCONDCombine(N, DCI, DAG, 2, 3);
16180 }
16181 
16182 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16183   assert(N->getOpcode() == ISD::SETCC && "Unexpected opcode!");
16184   SDValue LHS = N->getOperand(0);
16185   SDValue RHS = N->getOperand(1);
16186   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
16187 
16188   // setcc (csel 0, 1, cond, X), 1, ne ==> csel 0, 1, !cond, X
16189   if (Cond == ISD::SETNE && isOneConstant(RHS) &&
16190       LHS->getOpcode() == AArch64ISD::CSEL &&
16191       isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
16192       LHS->hasOneUse()) {
16193     SDLoc DL(N);
16194 
16195     // Invert CSEL's condition.
16196     auto *OpCC = cast<ConstantSDNode>(LHS.getOperand(2));
16197     auto OldCond = static_cast<AArch64CC::CondCode>(OpCC->getZExtValue());
16198     auto NewCond = getInvertedCondCode(OldCond);
16199 
16200     // csel 0, 1, !cond, X
16201     SDValue CSEL =
16202         DAG.getNode(AArch64ISD::CSEL, DL, LHS.getValueType(), LHS.getOperand(0),
16203                     LHS.getOperand(1), DAG.getConstant(NewCond, DL, MVT::i32),
16204                     LHS.getOperand(3));
16205     return DAG.getZExtOrTrunc(CSEL, DL, N->getValueType(0));
16206   }
16207 
16208   return SDValue();
16209 }
16210 
16211 static SDValue performSetccMergeZeroCombine(SDNode *N, SelectionDAG &DAG) {
16212   assert(N->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16213          "Unexpected opcode!");
16214 
16215   SDValue Pred = N->getOperand(0);
16216   SDValue LHS = N->getOperand(1);
16217   SDValue RHS = N->getOperand(2);
16218   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
16219 
16220   // setcc_merge_zero pred (sign_extend (setcc_merge_zero ... pred ...)), 0, ne
16221   //    => inner setcc_merge_zero
16222   if (Cond == ISD::SETNE && isZerosVector(RHS.getNode()) &&
16223       LHS->getOpcode() == ISD::SIGN_EXTEND &&
16224       LHS->getOperand(0)->getValueType(0) == N->getValueType(0) &&
16225       LHS->getOperand(0)->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
16226       LHS->getOperand(0)->getOperand(0) == Pred)
16227     return LHS->getOperand(0);
16228 
16229   return SDValue();
16230 }
16231 
16232 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
16233 // as well as whether the test should be inverted.  This code is required to
16234 // catch these cases (as opposed to standard dag combines) because
16235 // AArch64ISD::TBZ is matched during legalization.
16236 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
16237                                  SelectionDAG &DAG) {
16238 
16239   if (!Op->hasOneUse())
16240     return Op;
16241 
16242   // We don't handle undef/constant-fold cases below, as they should have
16243   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
16244   // etc.)
16245 
16246   // (tbz (trunc x), b) -> (tbz x, b)
16247   // This case is just here to enable more of the below cases to be caught.
16248   if (Op->getOpcode() == ISD::TRUNCATE &&
16249       Bit < Op->getValueType(0).getSizeInBits()) {
16250     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16251   }
16252 
16253   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
16254   if (Op->getOpcode() == ISD::ANY_EXTEND &&
16255       Bit < Op->getOperand(0).getValueSizeInBits()) {
16256     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16257   }
16258 
16259   if (Op->getNumOperands() != 2)
16260     return Op;
16261 
16262   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16263   if (!C)
16264     return Op;
16265 
16266   switch (Op->getOpcode()) {
16267   default:
16268     return Op;
16269 
16270   // (tbz (and x, m), b) -> (tbz x, b)
16271   case ISD::AND:
16272     if ((C->getZExtValue() >> Bit) & 1)
16273       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16274     return Op;
16275 
16276   // (tbz (shl x, c), b) -> (tbz x, b-c)
16277   case ISD::SHL:
16278     if (C->getZExtValue() <= Bit &&
16279         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16280       Bit = Bit - C->getZExtValue();
16281       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16282     }
16283     return Op;
16284 
16285   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
16286   case ISD::SRA:
16287     Bit = Bit + C->getZExtValue();
16288     if (Bit >= Op->getValueType(0).getSizeInBits())
16289       Bit = Op->getValueType(0).getSizeInBits() - 1;
16290     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16291 
16292   // (tbz (srl x, c), b) -> (tbz x, b+c)
16293   case ISD::SRL:
16294     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
16295       Bit = Bit + C->getZExtValue();
16296       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16297     }
16298     return Op;
16299 
16300   // (tbz (xor x, -1), b) -> (tbnz x, b)
16301   case ISD::XOR:
16302     if ((C->getZExtValue() >> Bit) & 1)
16303       Invert = !Invert;
16304     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
16305   }
16306 }
16307 
16308 // Optimize test single bit zero/non-zero and branch.
16309 static SDValue performTBZCombine(SDNode *N,
16310                                  TargetLowering::DAGCombinerInfo &DCI,
16311                                  SelectionDAG &DAG) {
16312   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
16313   bool Invert = false;
16314   SDValue TestSrc = N->getOperand(1);
16315   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
16316 
16317   if (TestSrc == NewTestSrc)
16318     return SDValue();
16319 
16320   unsigned NewOpc = N->getOpcode();
16321   if (Invert) {
16322     if (NewOpc == AArch64ISD::TBZ)
16323       NewOpc = AArch64ISD::TBNZ;
16324     else {
16325       assert(NewOpc == AArch64ISD::TBNZ);
16326       NewOpc = AArch64ISD::TBZ;
16327     }
16328   }
16329 
16330   SDLoc DL(N);
16331   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
16332                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
16333 }
16334 
16335 // vselect (v1i1 setcc) ->
16336 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
16337 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
16338 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
16339 // such VSELECT.
16340 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
16341   SDValue N0 = N->getOperand(0);
16342   EVT CCVT = N0.getValueType();
16343 
16344   // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
16345   // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
16346   // supported types.
16347   SDValue SetCC = N->getOperand(0);
16348   if (SetCC.getOpcode() == ISD::SETCC &&
16349       SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
16350     SDValue CmpLHS = SetCC.getOperand(0);
16351     EVT VT = CmpLHS.getValueType();
16352     SDNode *CmpRHS = SetCC.getOperand(1).getNode();
16353     SDNode *SplatLHS = N->getOperand(1).getNode();
16354     SDNode *SplatRHS = N->getOperand(2).getNode();
16355     APInt SplatLHSVal;
16356     if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
16357         VT.isSimple() &&
16358         is_contained(
16359             makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
16360                           MVT::v2i32, MVT::v4i32, MVT::v2i64}),
16361             VT.getSimpleVT().SimpleTy) &&
16362         ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
16363         SplatLHSVal.isOne() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
16364         ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
16365       unsigned NumElts = VT.getVectorNumElements();
16366       SmallVector<SDValue, 8> Ops(
16367           NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
16368                                    VT.getScalarType()));
16369       SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
16370 
16371       auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
16372       auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
16373       return Or;
16374     }
16375   }
16376 
16377   if (N0.getOpcode() != ISD::SETCC ||
16378       CCVT.getVectorElementCount() != ElementCount::getFixed(1) ||
16379       CCVT.getVectorElementType() != MVT::i1)
16380     return SDValue();
16381 
16382   EVT ResVT = N->getValueType(0);
16383   EVT CmpVT = N0.getOperand(0).getValueType();
16384   // Only combine when the result type is of the same size as the compared
16385   // operands.
16386   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
16387     return SDValue();
16388 
16389   SDValue IfTrue = N->getOperand(1);
16390   SDValue IfFalse = N->getOperand(2);
16391   SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
16392                        N0.getOperand(0), N0.getOperand(1),
16393                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
16394   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
16395                      IfTrue, IfFalse);
16396 }
16397 
16398 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
16399 /// the compare-mask instructions rather than going via NZCV, even if LHS and
16400 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
16401 /// with a vector one followed by a DUP shuffle on the result.
16402 static SDValue performSelectCombine(SDNode *N,
16403                                     TargetLowering::DAGCombinerInfo &DCI) {
16404   SelectionDAG &DAG = DCI.DAG;
16405   SDValue N0 = N->getOperand(0);
16406   EVT ResVT = N->getValueType(0);
16407 
16408   if (N0.getOpcode() != ISD::SETCC)
16409     return SDValue();
16410 
16411   if (ResVT.isScalableVector())
16412     return SDValue();
16413 
16414   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
16415   // scalar SetCCResultType. We also don't expect vectors, because we assume
16416   // that selects fed by vector SETCCs are canonicalized to VSELECT.
16417   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
16418          "Scalar-SETCC feeding SELECT has unexpected result type!");
16419 
16420   // If NumMaskElts == 0, the comparison is larger than select result. The
16421   // largest real NEON comparison is 64-bits per lane, which means the result is
16422   // at most 32-bits and an illegal vector. Just bail out for now.
16423   EVT SrcVT = N0.getOperand(0).getValueType();
16424 
16425   // Don't try to do this optimization when the setcc itself has i1 operands.
16426   // There are no legal vectors of i1, so this would be pointless.
16427   if (SrcVT == MVT::i1)
16428     return SDValue();
16429 
16430   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
16431   if (!ResVT.isVector() || NumMaskElts == 0)
16432     return SDValue();
16433 
16434   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
16435   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
16436 
16437   // Also bail out if the vector CCVT isn't the same size as ResVT.
16438   // This can happen if the SETCC operand size doesn't divide the ResVT size
16439   // (e.g., f64 vs v3f32).
16440   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
16441     return SDValue();
16442 
16443   // Make sure we didn't create illegal types, if we're not supposed to.
16444   assert(DCI.isBeforeLegalize() ||
16445          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
16446 
16447   // First perform a vector comparison, where lane 0 is the one we're interested
16448   // in.
16449   SDLoc DL(N0);
16450   SDValue LHS =
16451       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
16452   SDValue RHS =
16453       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
16454   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
16455 
16456   // Now duplicate the comparison mask we want across all other lanes.
16457   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
16458   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
16459   Mask = DAG.getNode(ISD::BITCAST, DL,
16460                      ResVT.changeVectorElementTypeToInteger(), Mask);
16461 
16462   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
16463 }
16464 
16465 /// Get rid of unnecessary NVCASTs (that don't change the type).
16466 static SDValue performNVCASTCombine(SDNode *N) {
16467   if (N->getValueType(0) == N->getOperand(0).getValueType())
16468     return N->getOperand(0);
16469 
16470   return SDValue();
16471 }
16472 
16473 // If all users of the globaladdr are of the form (globaladdr + constant), find
16474 // the smallest constant, fold it into the globaladdr's offset and rewrite the
16475 // globaladdr as (globaladdr + constant) - constant.
16476 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
16477                                            const AArch64Subtarget *Subtarget,
16478                                            const TargetMachine &TM) {
16479   auto *GN = cast<GlobalAddressSDNode>(N);
16480   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
16481       AArch64II::MO_NO_FLAG)
16482     return SDValue();
16483 
16484   uint64_t MinOffset = -1ull;
16485   for (SDNode *N : GN->uses()) {
16486     if (N->getOpcode() != ISD::ADD)
16487       return SDValue();
16488     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
16489     if (!C)
16490       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16491     if (!C)
16492       return SDValue();
16493     MinOffset = std::min(MinOffset, C->getZExtValue());
16494   }
16495   uint64_t Offset = MinOffset + GN->getOffset();
16496 
16497   // Require that the new offset is larger than the existing one. Otherwise, we
16498   // can end up oscillating between two possible DAGs, for example,
16499   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
16500   if (Offset <= uint64_t(GN->getOffset()))
16501     return SDValue();
16502 
16503   // Check whether folding this offset is legal. It must not go out of bounds of
16504   // the referenced object to avoid violating the code model, and must be
16505   // smaller than 2^21 because this is the largest offset expressible in all
16506   // object formats.
16507   //
16508   // This check also prevents us from folding negative offsets, which will end
16509   // up being treated in the same way as large positive ones. They could also
16510   // cause code model violations, and aren't really common enough to matter.
16511   if (Offset >= (1 << 21))
16512     return SDValue();
16513 
16514   const GlobalValue *GV = GN->getGlobal();
16515   Type *T = GV->getValueType();
16516   if (!T->isSized() ||
16517       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
16518     return SDValue();
16519 
16520   SDLoc DL(GN);
16521   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
16522   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
16523                      DAG.getConstant(MinOffset, DL, MVT::i64));
16524 }
16525 
16526 // Turns the vector of indices into a vector of byte offstes by scaling Offset
16527 // by (BitWidth / 8).
16528 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
16529                                           SDLoc DL, unsigned BitWidth) {
16530   assert(Offset.getValueType().isScalableVector() &&
16531          "This method is only for scalable vectors of offsets");
16532 
16533   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
16534   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
16535 
16536   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
16537 }
16538 
16539 /// Check if the value of \p OffsetInBytes can be used as an immediate for
16540 /// the gather load/prefetch and scatter store instructions with vector base and
16541 /// immediate offset addressing mode:
16542 ///
16543 ///      [<Zn>.[S|D]{, #<imm>}]
16544 ///
16545 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
16546 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
16547                                                   unsigned ScalarSizeInBytes) {
16548   // The immediate is not a multiple of the scalar size.
16549   if (OffsetInBytes % ScalarSizeInBytes)
16550     return false;
16551 
16552   // The immediate is out of range.
16553   if (OffsetInBytes / ScalarSizeInBytes > 31)
16554     return false;
16555 
16556   return true;
16557 }
16558 
16559 /// Check if the value of \p Offset represents a valid immediate for the SVE
16560 /// gather load/prefetch and scatter store instructiona with vector base and
16561 /// immediate offset addressing mode:
16562 ///
16563 ///      [<Zn>.[S|D]{, #<imm>}]
16564 ///
16565 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
16566 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
16567                                            unsigned ScalarSizeInBytes) {
16568   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
16569   return OffsetConst && isValidImmForSVEVecImmAddrMode(
16570                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
16571 }
16572 
16573 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
16574                                           unsigned Opcode,
16575                                           bool OnlyPackedOffsets = true) {
16576   const SDValue Src = N->getOperand(2);
16577   const EVT SrcVT = Src->getValueType(0);
16578   assert(SrcVT.isScalableVector() &&
16579          "Scatter stores are only possible for SVE vectors");
16580 
16581   SDLoc DL(N);
16582   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
16583 
16584   // Make sure that source data will fit into an SVE register
16585   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
16586     return SDValue();
16587 
16588   // For FPs, ACLE only supports _packed_ single and double precision types.
16589   if (SrcElVT.isFloatingPoint())
16590     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
16591       return SDValue();
16592 
16593   // Depending on the addressing mode, this is either a pointer or a vector of
16594   // pointers (that fits into one register)
16595   SDValue Base = N->getOperand(4);
16596   // Depending on the addressing mode, this is either a single offset or a
16597   // vector of offsets  (that fits into one register)
16598   SDValue Offset = N->getOperand(5);
16599 
16600   // For "scalar + vector of indices", just scale the indices. This only
16601   // applies to non-temporal scatters because there's no instruction that takes
16602   // indicies.
16603   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
16604     Offset =
16605         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
16606     Opcode = AArch64ISD::SSTNT1_PRED;
16607   }
16608 
16609   // In the case of non-temporal gather loads there's only one SVE instruction
16610   // per data-size: "scalar + vector", i.e.
16611   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
16612   // Since we do have intrinsics that allow the arguments to be in a different
16613   // order, we may need to swap them to match the spec.
16614   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
16615     std::swap(Base, Offset);
16616 
16617   // SST1_IMM requires that the offset is an immediate that is:
16618   //    * a multiple of #SizeInBytes,
16619   //    * in the range [0, 31 x #SizeInBytes],
16620   // where #SizeInBytes is the size in bytes of the stored items. For
16621   // immediates outside that range and non-immediate scalar offsets use SST1 or
16622   // SST1_UXTW instead.
16623   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
16624     if (!isValidImmForSVEVecImmAddrMode(Offset,
16625                                         SrcVT.getScalarSizeInBits() / 8)) {
16626       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
16627         Opcode = AArch64ISD::SST1_UXTW_PRED;
16628       else
16629         Opcode = AArch64ISD::SST1_PRED;
16630 
16631       std::swap(Base, Offset);
16632     }
16633   }
16634 
16635   auto &TLI = DAG.getTargetLoweringInfo();
16636   if (!TLI.isTypeLegal(Base.getValueType()))
16637     return SDValue();
16638 
16639   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
16640   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
16641   // nxv2i64. Legalize accordingly.
16642   if (!OnlyPackedOffsets &&
16643       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
16644     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
16645 
16646   if (!TLI.isTypeLegal(Offset.getValueType()))
16647     return SDValue();
16648 
16649   // Source value type that is representable in hardware
16650   EVT HwSrcVt = getSVEContainerType(SrcVT);
16651 
16652   // Keep the original type of the input data to store - this is needed to be
16653   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
16654   // FP values we want the integer equivalent, so just use HwSrcVt.
16655   SDValue InputVT = DAG.getValueType(SrcVT);
16656   if (SrcVT.isFloatingPoint())
16657     InputVT = DAG.getValueType(HwSrcVt);
16658 
16659   SDVTList VTs = DAG.getVTList(MVT::Other);
16660   SDValue SrcNew;
16661 
16662   if (Src.getValueType().isFloatingPoint())
16663     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
16664   else
16665     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
16666 
16667   SDValue Ops[] = {N->getOperand(0), // Chain
16668                    SrcNew,
16669                    N->getOperand(3), // Pg
16670                    Base,
16671                    Offset,
16672                    InputVT};
16673 
16674   return DAG.getNode(Opcode, DL, VTs, Ops);
16675 }
16676 
16677 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
16678                                         unsigned Opcode,
16679                                         bool OnlyPackedOffsets = true) {
16680   const EVT RetVT = N->getValueType(0);
16681   assert(RetVT.isScalableVector() &&
16682          "Gather loads are only possible for SVE vectors");
16683 
16684   SDLoc DL(N);
16685 
16686   // Make sure that the loaded data will fit into an SVE register
16687   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
16688     return SDValue();
16689 
16690   // Depending on the addressing mode, this is either a pointer or a vector of
16691   // pointers (that fits into one register)
16692   SDValue Base = N->getOperand(3);
16693   // Depending on the addressing mode, this is either a single offset or a
16694   // vector of offsets  (that fits into one register)
16695   SDValue Offset = N->getOperand(4);
16696 
16697   // For "scalar + vector of indices", just scale the indices. This only
16698   // applies to non-temporal gathers because there's no instruction that takes
16699   // indicies.
16700   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
16701     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
16702                                         RetVT.getScalarSizeInBits());
16703     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
16704   }
16705 
16706   // In the case of non-temporal gather loads there's only one SVE instruction
16707   // per data-size: "scalar + vector", i.e.
16708   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
16709   // Since we do have intrinsics that allow the arguments to be in a different
16710   // order, we may need to swap them to match the spec.
16711   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
16712       Offset.getValueType().isVector())
16713     std::swap(Base, Offset);
16714 
16715   // GLD{FF}1_IMM requires that the offset is an immediate that is:
16716   //    * a multiple of #SizeInBytes,
16717   //    * in the range [0, 31 x #SizeInBytes],
16718   // where #SizeInBytes is the size in bytes of the loaded items. For
16719   // immediates outside that range and non-immediate scalar offsets use
16720   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
16721   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
16722       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
16723     if (!isValidImmForSVEVecImmAddrMode(Offset,
16724                                         RetVT.getScalarSizeInBits() / 8)) {
16725       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
16726         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
16727                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
16728                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
16729       else
16730         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
16731                      ? AArch64ISD::GLD1_MERGE_ZERO
16732                      : AArch64ISD::GLDFF1_MERGE_ZERO;
16733 
16734       std::swap(Base, Offset);
16735     }
16736   }
16737 
16738   auto &TLI = DAG.getTargetLoweringInfo();
16739   if (!TLI.isTypeLegal(Base.getValueType()))
16740     return SDValue();
16741 
16742   // Some gather load variants allow unpacked offsets, but only as nxv2i32
16743   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
16744   // nxv2i64. Legalize accordingly.
16745   if (!OnlyPackedOffsets &&
16746       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
16747     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
16748 
16749   // Return value type that is representable in hardware
16750   EVT HwRetVt = getSVEContainerType(RetVT);
16751 
16752   // Keep the original output value type around - this is needed to be able to
16753   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
16754   // values we want the integer equivalent, so just use HwRetVT.
16755   SDValue OutVT = DAG.getValueType(RetVT);
16756   if (RetVT.isFloatingPoint())
16757     OutVT = DAG.getValueType(HwRetVt);
16758 
16759   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
16760   SDValue Ops[] = {N->getOperand(0), // Chain
16761                    N->getOperand(2), // Pg
16762                    Base, Offset, OutVT};
16763 
16764   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
16765   SDValue LoadChain = SDValue(Load.getNode(), 1);
16766 
16767   if (RetVT.isInteger() && (RetVT != HwRetVt))
16768     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
16769 
16770   // If the original return value was FP, bitcast accordingly. Doing it here
16771   // means that we can avoid adding TableGen patterns for FPs.
16772   if (RetVT.isFloatingPoint())
16773     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
16774 
16775   return DAG.getMergeValues({Load, LoadChain}, DL);
16776 }
16777 
16778 static SDValue
16779 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
16780                               SelectionDAG &DAG) {
16781   SDLoc DL(N);
16782   SDValue Src = N->getOperand(0);
16783   unsigned Opc = Src->getOpcode();
16784 
16785   // Sign extend of an unsigned unpack -> signed unpack
16786   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
16787 
16788     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
16789                                                : AArch64ISD::SUNPKLO;
16790 
16791     // Push the sign extend to the operand of the unpack
16792     // This is necessary where, for example, the operand of the unpack
16793     // is another unpack:
16794     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
16795     // ->
16796     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
16797     // ->
16798     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
16799     SDValue ExtOp = Src->getOperand(0);
16800     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
16801     EVT EltTy = VT.getVectorElementType();
16802     (void)EltTy;
16803 
16804     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
16805            "Sign extending from an invalid type");
16806 
16807     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
16808 
16809     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
16810                               ExtOp, DAG.getValueType(ExtVT));
16811 
16812     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
16813   }
16814 
16815   if (DCI.isBeforeLegalizeOps())
16816     return SDValue();
16817 
16818   if (!EnableCombineMGatherIntrinsics)
16819     return SDValue();
16820 
16821   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
16822   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
16823   unsigned NewOpc;
16824   unsigned MemVTOpNum = 4;
16825   switch (Opc) {
16826   case AArch64ISD::LD1_MERGE_ZERO:
16827     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
16828     MemVTOpNum = 3;
16829     break;
16830   case AArch64ISD::LDNF1_MERGE_ZERO:
16831     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
16832     MemVTOpNum = 3;
16833     break;
16834   case AArch64ISD::LDFF1_MERGE_ZERO:
16835     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
16836     MemVTOpNum = 3;
16837     break;
16838   case AArch64ISD::GLD1_MERGE_ZERO:
16839     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
16840     break;
16841   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
16842     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
16843     break;
16844   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
16845     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
16846     break;
16847   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
16848     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
16849     break;
16850   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
16851     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
16852     break;
16853   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
16854     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
16855     break;
16856   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
16857     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
16858     break;
16859   case AArch64ISD::GLDFF1_MERGE_ZERO:
16860     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
16861     break;
16862   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
16863     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
16864     break;
16865   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
16866     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
16867     break;
16868   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
16869     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
16870     break;
16871   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
16872     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
16873     break;
16874   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
16875     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
16876     break;
16877   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
16878     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
16879     break;
16880   case AArch64ISD::GLDNT1_MERGE_ZERO:
16881     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
16882     break;
16883   default:
16884     return SDValue();
16885   }
16886 
16887   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
16888   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
16889 
16890   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
16891     return SDValue();
16892 
16893   EVT DstVT = N->getValueType(0);
16894   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
16895 
16896   SmallVector<SDValue, 5> Ops;
16897   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
16898     Ops.push_back(Src->getOperand(I));
16899 
16900   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
16901   DCI.CombineTo(N, ExtLoad);
16902   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
16903 
16904   // Return N so it doesn't get rechecked
16905   return SDValue(N, 0);
16906 }
16907 
16908 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
16909 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
16910 /// != nxv2i32) do not need legalization.
16911 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
16912   const unsigned OffsetPos = 4;
16913   SDValue Offset = N->getOperand(OffsetPos);
16914 
16915   // Not an unpacked vector, bail out.
16916   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
16917     return SDValue();
16918 
16919   // Extend the unpacked offset vector to 64-bit lanes.
16920   SDLoc DL(N);
16921   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
16922   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
16923   // Replace the offset operand with the 64-bit one.
16924   Ops[OffsetPos] = Offset;
16925 
16926   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
16927 }
16928 
16929 /// Combines a node carrying the intrinsic
16930 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
16931 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
16932 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
16933 /// sve gather prefetch instruction with vector plus immediate addressing mode.
16934 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
16935                                                unsigned ScalarSizeInBytes) {
16936   const unsigned ImmPos = 4, OffsetPos = 3;
16937   // No need to combine the node if the immediate is valid...
16938   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
16939     return SDValue();
16940 
16941   // ...otherwise swap the offset base with the offset...
16942   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
16943   std::swap(Ops[ImmPos], Ops[OffsetPos]);
16944   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
16945   // `aarch64_sve_prfb_gather_uxtw_index`.
16946   SDLoc DL(N);
16947   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
16948                            MVT::i64);
16949 
16950   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
16951 }
16952 
16953 // Return true if the vector operation can guarantee only the first lane of its
16954 // result contains data, with all bits in other lanes set to zero.
16955 static bool isLanes1toNKnownZero(SDValue Op) {
16956   switch (Op.getOpcode()) {
16957   default:
16958     return false;
16959   case AArch64ISD::ANDV_PRED:
16960   case AArch64ISD::EORV_PRED:
16961   case AArch64ISD::FADDA_PRED:
16962   case AArch64ISD::FADDV_PRED:
16963   case AArch64ISD::FMAXNMV_PRED:
16964   case AArch64ISD::FMAXV_PRED:
16965   case AArch64ISD::FMINNMV_PRED:
16966   case AArch64ISD::FMINV_PRED:
16967   case AArch64ISD::ORV_PRED:
16968   case AArch64ISD::SADDV_PRED:
16969   case AArch64ISD::SMAXV_PRED:
16970   case AArch64ISD::SMINV_PRED:
16971   case AArch64ISD::UADDV_PRED:
16972   case AArch64ISD::UMAXV_PRED:
16973   case AArch64ISD::UMINV_PRED:
16974     return true;
16975   }
16976 }
16977 
16978 static SDValue removeRedundantInsertVectorElt(SDNode *N) {
16979   assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Unexpected node!");
16980   SDValue InsertVec = N->getOperand(0);
16981   SDValue InsertElt = N->getOperand(1);
16982   SDValue InsertIdx = N->getOperand(2);
16983 
16984   // We only care about inserts into the first element...
16985   if (!isNullConstant(InsertIdx))
16986     return SDValue();
16987   // ...of a zero'd vector...
16988   if (!ISD::isConstantSplatVectorAllZeros(InsertVec.getNode()))
16989     return SDValue();
16990   // ...where the inserted data was previously extracted...
16991   if (InsertElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16992     return SDValue();
16993 
16994   SDValue ExtractVec = InsertElt.getOperand(0);
16995   SDValue ExtractIdx = InsertElt.getOperand(1);
16996 
16997   // ...from the first element of a vector.
16998   if (!isNullConstant(ExtractIdx))
16999     return SDValue();
17000 
17001   // If we get here we are effectively trying to zero lanes 1-N of a vector.
17002 
17003   // Ensure there's no type conversion going on.
17004   if (N->getValueType(0) != ExtractVec.getValueType())
17005     return SDValue();
17006 
17007   if (!isLanes1toNKnownZero(ExtractVec))
17008     return SDValue();
17009 
17010   // The explicit zeroing is redundant.
17011   return ExtractVec;
17012 }
17013 
17014 static SDValue
17015 performInsertVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
17016   if (SDValue Res = removeRedundantInsertVectorElt(N))
17017     return Res;
17018 
17019   return performPostLD1Combine(N, DCI, true);
17020 }
17021 
17022 SDValue performSVESpliceCombine(SDNode *N, SelectionDAG &DAG) {
17023   EVT Ty = N->getValueType(0);
17024   if (Ty.isInteger())
17025     return SDValue();
17026 
17027   EVT IntTy = Ty.changeVectorElementTypeToInteger();
17028   EVT ExtIntTy = getPackedSVEVectorVT(IntTy.getVectorElementCount());
17029   if (ExtIntTy.getVectorElementType().getScalarSizeInBits() <
17030       IntTy.getVectorElementType().getScalarSizeInBits())
17031     return SDValue();
17032 
17033   SDLoc DL(N);
17034   SDValue LHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(0)),
17035                                      DL, ExtIntTy);
17036   SDValue RHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(1)),
17037                                      DL, ExtIntTy);
17038   SDValue Idx = N->getOperand(2);
17039   SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ExtIntTy, LHS, RHS, Idx);
17040   SDValue Trunc = DAG.getAnyExtOrTrunc(Splice, DL, IntTy);
17041   return DAG.getBitcast(Ty, Trunc);
17042 }
17043 
17044 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
17045                                                  DAGCombinerInfo &DCI) const {
17046   SelectionDAG &DAG = DCI.DAG;
17047   switch (N->getOpcode()) {
17048   default:
17049     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
17050     break;
17051   case ISD::ADD:
17052   case ISD::SUB:
17053     return performAddSubCombine(N, DCI, DAG);
17054   case ISD::XOR:
17055     return performXorCombine(N, DAG, DCI, Subtarget);
17056   case ISD::MUL:
17057     return performMulCombine(N, DAG, DCI, Subtarget);
17058   case ISD::SINT_TO_FP:
17059   case ISD::UINT_TO_FP:
17060     return performIntToFpCombine(N, DAG, Subtarget);
17061   case ISD::FP_TO_SINT:
17062   case ISD::FP_TO_UINT:
17063     return performFpToIntCombine(N, DAG, DCI, Subtarget);
17064   case ISD::FDIV:
17065     return performFDivCombine(N, DAG, DCI, Subtarget);
17066   case ISD::OR:
17067     return performORCombine(N, DCI, Subtarget);
17068   case ISD::AND:
17069     return performANDCombine(N, DCI);
17070   case ISD::SRL:
17071     return performSRLCombine(N, DCI);
17072   case ISD::INTRINSIC_WO_CHAIN:
17073     return performIntrinsicCombine(N, DCI, Subtarget);
17074   case ISD::ANY_EXTEND:
17075   case ISD::ZERO_EXTEND:
17076   case ISD::SIGN_EXTEND:
17077     return performExtendCombine(N, DCI, DAG);
17078   case ISD::SIGN_EXTEND_INREG:
17079     return performSignExtendInRegCombine(N, DCI, DAG);
17080   case ISD::TRUNCATE:
17081     return performVectorTruncateCombine(N, DCI, DAG);
17082   case ISD::CONCAT_VECTORS:
17083     return performConcatVectorsCombine(N, DCI, DAG);
17084   case ISD::INSERT_SUBVECTOR:
17085     return performInsertSubvectorCombine(N, DCI, DAG);
17086   case ISD::SELECT:
17087     return performSelectCombine(N, DCI);
17088   case ISD::VSELECT:
17089     return performVSelectCombine(N, DCI.DAG);
17090   case ISD::SETCC:
17091     return performSETCCCombine(N, DAG);
17092   case ISD::LOAD:
17093     if (performTBISimplification(N->getOperand(1), DCI, DAG))
17094       return SDValue(N, 0);
17095     break;
17096   case ISD::STORE:
17097     return performSTORECombine(N, DCI, DAG, Subtarget);
17098   case ISD::VECTOR_SPLICE:
17099     return performSVESpliceCombine(N, DAG);
17100   case AArch64ISD::BRCOND:
17101     return performBRCONDCombine(N, DCI, DAG);
17102   case AArch64ISD::TBNZ:
17103   case AArch64ISD::TBZ:
17104     return performTBZCombine(N, DCI, DAG);
17105   case AArch64ISD::CSEL:
17106     return performCSELCombine(N, DCI, DAG);
17107   case AArch64ISD::DUP:
17108     return performPostLD1Combine(N, DCI, false);
17109   case AArch64ISD::NVCAST:
17110     return performNVCASTCombine(N);
17111   case AArch64ISD::SPLICE:
17112     return performSpliceCombine(N, DAG);
17113   case AArch64ISD::UZP1:
17114     return performUzpCombine(N, DAG);
17115   case AArch64ISD::SETCC_MERGE_ZERO:
17116     return performSetccMergeZeroCombine(N, DAG);
17117   case AArch64ISD::GLD1_MERGE_ZERO:
17118   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
17119   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
17120   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
17121   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
17122   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
17123   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
17124   case AArch64ISD::GLD1S_MERGE_ZERO:
17125   case AArch64ISD::GLD1S_SCALED_MERGE_ZERO:
17126   case AArch64ISD::GLD1S_UXTW_MERGE_ZERO:
17127   case AArch64ISD::GLD1S_SXTW_MERGE_ZERO:
17128   case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO:
17129   case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO:
17130   case AArch64ISD::GLD1S_IMM_MERGE_ZERO:
17131     return performGLD1Combine(N, DAG);
17132   case AArch64ISD::VASHR:
17133   case AArch64ISD::VLSHR:
17134     return performVectorShiftCombine(N, *this, DCI);
17135   case ISD::INSERT_VECTOR_ELT:
17136     return performInsertVectorEltCombine(N, DCI);
17137   case ISD::EXTRACT_VECTOR_ELT:
17138     return performExtractVectorEltCombine(N, DAG);
17139   case ISD::VECREDUCE_ADD:
17140     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
17141   case ISD::INTRINSIC_VOID:
17142   case ISD::INTRINSIC_W_CHAIN:
17143     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
17144     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
17145       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
17146     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
17147       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
17148     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
17149       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
17150     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
17151       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
17152     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
17153     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
17154     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
17155     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
17156     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
17157     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
17158     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
17159     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
17160       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
17161     case Intrinsic::aarch64_neon_ld2:
17162     case Intrinsic::aarch64_neon_ld3:
17163     case Intrinsic::aarch64_neon_ld4:
17164     case Intrinsic::aarch64_neon_ld1x2:
17165     case Intrinsic::aarch64_neon_ld1x3:
17166     case Intrinsic::aarch64_neon_ld1x4:
17167     case Intrinsic::aarch64_neon_ld2lane:
17168     case Intrinsic::aarch64_neon_ld3lane:
17169     case Intrinsic::aarch64_neon_ld4lane:
17170     case Intrinsic::aarch64_neon_ld2r:
17171     case Intrinsic::aarch64_neon_ld3r:
17172     case Intrinsic::aarch64_neon_ld4r:
17173     case Intrinsic::aarch64_neon_st2:
17174     case Intrinsic::aarch64_neon_st3:
17175     case Intrinsic::aarch64_neon_st4:
17176     case Intrinsic::aarch64_neon_st1x2:
17177     case Intrinsic::aarch64_neon_st1x3:
17178     case Intrinsic::aarch64_neon_st1x4:
17179     case Intrinsic::aarch64_neon_st2lane:
17180     case Intrinsic::aarch64_neon_st3lane:
17181     case Intrinsic::aarch64_neon_st4lane:
17182       return performNEONPostLDSTCombine(N, DCI, DAG);
17183     case Intrinsic::aarch64_sve_ldnt1:
17184       return performLDNT1Combine(N, DAG);
17185     case Intrinsic::aarch64_sve_ld1rq:
17186       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
17187     case Intrinsic::aarch64_sve_ld1ro:
17188       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
17189     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
17190       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17191     case Intrinsic::aarch64_sve_ldnt1_gather:
17192       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17193     case Intrinsic::aarch64_sve_ldnt1_gather_index:
17194       return performGatherLoadCombine(N, DAG,
17195                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
17196     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
17197       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
17198     case Intrinsic::aarch64_sve_ld1:
17199       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
17200     case Intrinsic::aarch64_sve_ldnf1:
17201       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
17202     case Intrinsic::aarch64_sve_ldff1:
17203       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
17204     case Intrinsic::aarch64_sve_st1:
17205       return performST1Combine(N, DAG);
17206     case Intrinsic::aarch64_sve_stnt1:
17207       return performSTNT1Combine(N, DAG);
17208     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
17209       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17210     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
17211       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17212     case Intrinsic::aarch64_sve_stnt1_scatter:
17213       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
17214     case Intrinsic::aarch64_sve_stnt1_scatter_index:
17215       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
17216     case Intrinsic::aarch64_sve_ld1_gather:
17217       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
17218     case Intrinsic::aarch64_sve_ld1_gather_index:
17219       return performGatherLoadCombine(N, DAG,
17220                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
17221     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
17222       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
17223                                       /*OnlyPackedOffsets=*/false);
17224     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
17225       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
17226                                       /*OnlyPackedOffsets=*/false);
17227     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
17228       return performGatherLoadCombine(N, DAG,
17229                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
17230                                       /*OnlyPackedOffsets=*/false);
17231     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
17232       return performGatherLoadCombine(N, DAG,
17233                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
17234                                       /*OnlyPackedOffsets=*/false);
17235     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
17236       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
17237     case Intrinsic::aarch64_sve_ldff1_gather:
17238       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
17239     case Intrinsic::aarch64_sve_ldff1_gather_index:
17240       return performGatherLoadCombine(N, DAG,
17241                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
17242     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
17243       return performGatherLoadCombine(N, DAG,
17244                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
17245                                       /*OnlyPackedOffsets=*/false);
17246     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
17247       return performGatherLoadCombine(N, DAG,
17248                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
17249                                       /*OnlyPackedOffsets=*/false);
17250     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
17251       return performGatherLoadCombine(N, DAG,
17252                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
17253                                       /*OnlyPackedOffsets=*/false);
17254     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
17255       return performGatherLoadCombine(N, DAG,
17256                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
17257                                       /*OnlyPackedOffsets=*/false);
17258     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
17259       return performGatherLoadCombine(N, DAG,
17260                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
17261     case Intrinsic::aarch64_sve_st1_scatter:
17262       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
17263     case Intrinsic::aarch64_sve_st1_scatter_index:
17264       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
17265     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
17266       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
17267                                         /*OnlyPackedOffsets=*/false);
17268     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
17269       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
17270                                         /*OnlyPackedOffsets=*/false);
17271     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
17272       return performScatterStoreCombine(N, DAG,
17273                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
17274                                         /*OnlyPackedOffsets=*/false);
17275     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
17276       return performScatterStoreCombine(N, DAG,
17277                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
17278                                         /*OnlyPackedOffsets=*/false);
17279     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
17280       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
17281     case Intrinsic::aarch64_sve_tuple_get: {
17282       SDLoc DL(N);
17283       SDValue Chain = N->getOperand(0);
17284       SDValue Src1 = N->getOperand(2);
17285       SDValue Idx = N->getOperand(3);
17286 
17287       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17288       EVT ResVT = N->getValueType(0);
17289       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
17290       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
17291       SDValue Val =
17292           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
17293       return DAG.getMergeValues({Val, Chain}, DL);
17294     }
17295     case Intrinsic::aarch64_sve_tuple_set: {
17296       SDLoc DL(N);
17297       SDValue Chain = N->getOperand(0);
17298       SDValue Tuple = N->getOperand(2);
17299       SDValue Idx = N->getOperand(3);
17300       SDValue Vec = N->getOperand(4);
17301 
17302       EVT TupleVT = Tuple.getValueType();
17303       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
17304 
17305       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
17306       uint64_t NumLanes =
17307           Vec.getValueType().getVectorElementCount().getKnownMinValue();
17308 
17309       if ((TupleLanes % NumLanes) != 0)
17310         report_fatal_error("invalid tuple vector!");
17311 
17312       uint64_t NumVecs = TupleLanes / NumLanes;
17313 
17314       SmallVector<SDValue, 4> Opnds;
17315       for (unsigned I = 0; I < NumVecs; ++I) {
17316         if (I == IdxConst)
17317           Opnds.push_back(Vec);
17318         else {
17319           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
17320           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
17321                                       Vec.getValueType(), Tuple, ExtIdx));
17322         }
17323       }
17324       SDValue Concat =
17325           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
17326       return DAG.getMergeValues({Concat, Chain}, DL);
17327     }
17328     case Intrinsic::aarch64_sve_tuple_create2:
17329     case Intrinsic::aarch64_sve_tuple_create3:
17330     case Intrinsic::aarch64_sve_tuple_create4: {
17331       SDLoc DL(N);
17332       SDValue Chain = N->getOperand(0);
17333 
17334       SmallVector<SDValue, 4> Opnds;
17335       for (unsigned I = 2; I < N->getNumOperands(); ++I)
17336         Opnds.push_back(N->getOperand(I));
17337 
17338       EVT VT = Opnds[0].getValueType();
17339       EVT EltVT = VT.getVectorElementType();
17340       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
17341                                     VT.getVectorElementCount() *
17342                                         (N->getNumOperands() - 2));
17343       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
17344       return DAG.getMergeValues({Concat, Chain}, DL);
17345     }
17346     case Intrinsic::aarch64_sve_ld2:
17347     case Intrinsic::aarch64_sve_ld3:
17348     case Intrinsic::aarch64_sve_ld4: {
17349       SDLoc DL(N);
17350       SDValue Chain = N->getOperand(0);
17351       SDValue Mask = N->getOperand(2);
17352       SDValue BasePtr = N->getOperand(3);
17353       SDValue LoadOps[] = {Chain, Mask, BasePtr};
17354       unsigned IntrinsicID =
17355           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17356       SDValue Result =
17357           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
17358       return DAG.getMergeValues({Result, Chain}, DL);
17359     }
17360     case Intrinsic::aarch64_rndr:
17361     case Intrinsic::aarch64_rndrrs: {
17362       unsigned IntrinsicID =
17363           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17364       auto Register =
17365           (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR
17366                                                   : AArch64SysReg::RNDRRS);
17367       SDLoc DL(N);
17368       SDValue A = DAG.getNode(
17369           AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other),
17370           N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64));
17371       SDValue B = DAG.getNode(
17372           AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
17373           DAG.getConstant(0, DL, MVT::i32),
17374           DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1));
17375       return DAG.getMergeValues(
17376           {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL);
17377     }
17378     default:
17379       break;
17380     }
17381     break;
17382   case ISD::GlobalAddress:
17383     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
17384   }
17385   return SDValue();
17386 }
17387 
17388 // Check if the return value is used as only a return value, as otherwise
17389 // we can't perform a tail-call. In particular, we need to check for
17390 // target ISD nodes that are returns and any other "odd" constructs
17391 // that the generic analysis code won't necessarily catch.
17392 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
17393                                                SDValue &Chain) const {
17394   if (N->getNumValues() != 1)
17395     return false;
17396   if (!N->hasNUsesOfValue(1, 0))
17397     return false;
17398 
17399   SDValue TCChain = Chain;
17400   SDNode *Copy = *N->use_begin();
17401   if (Copy->getOpcode() == ISD::CopyToReg) {
17402     // If the copy has a glue operand, we conservatively assume it isn't safe to
17403     // perform a tail call.
17404     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
17405         MVT::Glue)
17406       return false;
17407     TCChain = Copy->getOperand(0);
17408   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
17409     return false;
17410 
17411   bool HasRet = false;
17412   for (SDNode *Node : Copy->uses()) {
17413     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
17414       return false;
17415     HasRet = true;
17416   }
17417 
17418   if (!HasRet)
17419     return false;
17420 
17421   Chain = TCChain;
17422   return true;
17423 }
17424 
17425 // Return whether the an instruction can potentially be optimized to a tail
17426 // call. This will cause the optimizers to attempt to move, or duplicate,
17427 // return instructions to help enable tail call optimizations for this
17428 // instruction.
17429 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17430   return CI->isTailCall();
17431 }
17432 
17433 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
17434                                                    SDValue &Offset,
17435                                                    ISD::MemIndexedMode &AM,
17436                                                    bool &IsInc,
17437                                                    SelectionDAG &DAG) const {
17438   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
17439     return false;
17440 
17441   Base = Op->getOperand(0);
17442   // All of the indexed addressing mode instructions take a signed
17443   // 9 bit immediate offset.
17444   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
17445     int64_t RHSC = RHS->getSExtValue();
17446     if (Op->getOpcode() == ISD::SUB)
17447       RHSC = -(uint64_t)RHSC;
17448     if (!isInt<9>(RHSC))
17449       return false;
17450     IsInc = (Op->getOpcode() == ISD::ADD);
17451     Offset = Op->getOperand(1);
17452     return true;
17453   }
17454   return false;
17455 }
17456 
17457 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17458                                                       SDValue &Offset,
17459                                                       ISD::MemIndexedMode &AM,
17460                                                       SelectionDAG &DAG) const {
17461   EVT VT;
17462   SDValue Ptr;
17463   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17464     VT = LD->getMemoryVT();
17465     Ptr = LD->getBasePtr();
17466   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17467     VT = ST->getMemoryVT();
17468     Ptr = ST->getBasePtr();
17469   } else
17470     return false;
17471 
17472   bool IsInc;
17473   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
17474     return false;
17475   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
17476   return true;
17477 }
17478 
17479 bool AArch64TargetLowering::getPostIndexedAddressParts(
17480     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
17481     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
17482   EVT VT;
17483   SDValue Ptr;
17484   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17485     VT = LD->getMemoryVT();
17486     Ptr = LD->getBasePtr();
17487   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17488     VT = ST->getMemoryVT();
17489     Ptr = ST->getBasePtr();
17490   } else
17491     return false;
17492 
17493   bool IsInc;
17494   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
17495     return false;
17496   // Post-indexing updates the base, so it's not a valid transform
17497   // if that's not the same as the load's pointer.
17498   if (Ptr != Base)
17499     return false;
17500   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
17501   return true;
17502 }
17503 
17504 void AArch64TargetLowering::ReplaceBITCASTResults(
17505     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17506   SDLoc DL(N);
17507   SDValue Op = N->getOperand(0);
17508   EVT VT = N->getValueType(0);
17509   EVT SrcVT = Op.getValueType();
17510 
17511   if (VT.isScalableVector() && !isTypeLegal(VT) && isTypeLegal(SrcVT)) {
17512     assert(!VT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
17513            "Expected fp->int bitcast!");
17514     SDValue CastResult = getSVESafeBitCast(getSVEContainerType(VT), Op, DAG);
17515     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, CastResult));
17516     return;
17517   }
17518 
17519   if (VT != MVT::i16 || (SrcVT != MVT::f16 && SrcVT != MVT::bf16))
17520     return;
17521 
17522   Op = SDValue(
17523       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
17524                          DAG.getUNDEF(MVT::i32), Op,
17525                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
17526       0);
17527   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
17528   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
17529 }
17530 
17531 static void ReplaceReductionResults(SDNode *N,
17532                                     SmallVectorImpl<SDValue> &Results,
17533                                     SelectionDAG &DAG, unsigned InterOp,
17534                                     unsigned AcrossOp) {
17535   EVT LoVT, HiVT;
17536   SDValue Lo, Hi;
17537   SDLoc dl(N);
17538   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
17539   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
17540   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
17541   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
17542   Results.push_back(SplitVal);
17543 }
17544 
17545 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
17546   SDLoc DL(N);
17547   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
17548   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
17549                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
17550                                        DAG.getConstant(64, DL, MVT::i64)));
17551   return std::make_pair(Lo, Hi);
17552 }
17553 
17554 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
17555     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17556   SDValue In = N->getOperand(0);
17557   EVT InVT = In.getValueType();
17558 
17559   // Common code will handle these just fine.
17560   if (!InVT.isScalableVector() || !InVT.isInteger())
17561     return;
17562 
17563   SDLoc DL(N);
17564   EVT VT = N->getValueType(0);
17565 
17566   // The following checks bail if this is not a halving operation.
17567 
17568   ElementCount ResEC = VT.getVectorElementCount();
17569 
17570   if (InVT.getVectorElementCount() != (ResEC * 2))
17571     return;
17572 
17573   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
17574   if (!CIndex)
17575     return;
17576 
17577   unsigned Index = CIndex->getZExtValue();
17578   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
17579     return;
17580 
17581   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
17582   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
17583 
17584   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
17585   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
17586 }
17587 
17588 // Create an even/odd pair of X registers holding integer value V.
17589 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
17590   SDLoc dl(V.getNode());
17591   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
17592   SDValue VHi = DAG.getAnyExtOrTrunc(
17593       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
17594       dl, MVT::i64);
17595   if (DAG.getDataLayout().isBigEndian())
17596     std::swap (VLo, VHi);
17597   SDValue RegClass =
17598       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
17599   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
17600   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
17601   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
17602   return SDValue(
17603       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
17604 }
17605 
17606 static void ReplaceCMP_SWAP_128Results(SDNode *N,
17607                                        SmallVectorImpl<SDValue> &Results,
17608                                        SelectionDAG &DAG,
17609                                        const AArch64Subtarget *Subtarget) {
17610   assert(N->getValueType(0) == MVT::i128 &&
17611          "AtomicCmpSwap on types less than 128 should be legal");
17612 
17613   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
17614   if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
17615     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
17616     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
17617     SDValue Ops[] = {
17618         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
17619         createGPRPairNode(DAG, N->getOperand(3)), // Store value
17620         N->getOperand(1), // Ptr
17621         N->getOperand(0), // Chain in
17622     };
17623 
17624     unsigned Opcode;
17625     switch (MemOp->getMergedOrdering()) {
17626     case AtomicOrdering::Monotonic:
17627       Opcode = AArch64::CASPX;
17628       break;
17629     case AtomicOrdering::Acquire:
17630       Opcode = AArch64::CASPAX;
17631       break;
17632     case AtomicOrdering::Release:
17633       Opcode = AArch64::CASPLX;
17634       break;
17635     case AtomicOrdering::AcquireRelease:
17636     case AtomicOrdering::SequentiallyConsistent:
17637       Opcode = AArch64::CASPALX;
17638       break;
17639     default:
17640       llvm_unreachable("Unexpected ordering!");
17641     }
17642 
17643     MachineSDNode *CmpSwap = DAG.getMachineNode(
17644         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
17645     DAG.setNodeMemRefs(CmpSwap, {MemOp});
17646 
17647     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
17648     if (DAG.getDataLayout().isBigEndian())
17649       std::swap(SubReg1, SubReg2);
17650     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
17651                                             SDValue(CmpSwap, 0));
17652     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
17653                                             SDValue(CmpSwap, 0));
17654     Results.push_back(
17655         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
17656     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
17657     return;
17658   }
17659 
17660   unsigned Opcode;
17661   switch (MemOp->getMergedOrdering()) {
17662   case AtomicOrdering::Monotonic:
17663     Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
17664     break;
17665   case AtomicOrdering::Acquire:
17666     Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
17667     break;
17668   case AtomicOrdering::Release:
17669     Opcode = AArch64::CMP_SWAP_128_RELEASE;
17670     break;
17671   case AtomicOrdering::AcquireRelease:
17672   case AtomicOrdering::SequentiallyConsistent:
17673     Opcode = AArch64::CMP_SWAP_128;
17674     break;
17675   default:
17676     llvm_unreachable("Unexpected ordering!");
17677   }
17678 
17679   auto Desired = splitInt128(N->getOperand(2), DAG);
17680   auto New = splitInt128(N->getOperand(3), DAG);
17681   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
17682                    New.first,        New.second,    N->getOperand(0)};
17683   SDNode *CmpSwap = DAG.getMachineNode(
17684       Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other),
17685       Ops);
17686   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
17687 
17688   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
17689                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
17690   Results.push_back(SDValue(CmpSwap, 3));
17691 }
17692 
17693 void AArch64TargetLowering::ReplaceNodeResults(
17694     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
17695   switch (N->getOpcode()) {
17696   default:
17697     llvm_unreachable("Don't know how to custom expand this");
17698   case ISD::BITCAST:
17699     ReplaceBITCASTResults(N, Results, DAG);
17700     return;
17701   case ISD::VECREDUCE_ADD:
17702   case ISD::VECREDUCE_SMAX:
17703   case ISD::VECREDUCE_SMIN:
17704   case ISD::VECREDUCE_UMAX:
17705   case ISD::VECREDUCE_UMIN:
17706     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
17707     return;
17708 
17709   case ISD::CTPOP:
17710     if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
17711       Results.push_back(Result);
17712     return;
17713   case AArch64ISD::SADDV:
17714     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
17715     return;
17716   case AArch64ISD::UADDV:
17717     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
17718     return;
17719   case AArch64ISD::SMINV:
17720     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
17721     return;
17722   case AArch64ISD::UMINV:
17723     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
17724     return;
17725   case AArch64ISD::SMAXV:
17726     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
17727     return;
17728   case AArch64ISD::UMAXV:
17729     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
17730     return;
17731   case ISD::FP_TO_UINT:
17732   case ISD::FP_TO_SINT:
17733   case ISD::STRICT_FP_TO_SINT:
17734   case ISD::STRICT_FP_TO_UINT:
17735     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
17736     // Let normal code take care of it by not adding anything to Results.
17737     return;
17738   case ISD::ATOMIC_CMP_SWAP:
17739     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
17740     return;
17741   case ISD::ATOMIC_LOAD:
17742   case ISD::LOAD: {
17743     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
17744            "unexpected load's value type");
17745     MemSDNode *LoadNode = cast<MemSDNode>(N);
17746     if ((!LoadNode->isVolatile() && !LoadNode->isAtomic()) ||
17747         LoadNode->getMemoryVT() != MVT::i128) {
17748       // Non-volatile or atomic loads are optimized later in AArch64's load/store
17749       // optimizer.
17750       return;
17751     }
17752 
17753     SDValue Result = DAG.getMemIntrinsicNode(
17754         AArch64ISD::LDP, SDLoc(N),
17755         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
17756         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
17757         LoadNode->getMemOperand());
17758 
17759     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
17760                                Result.getValue(0), Result.getValue(1));
17761     Results.append({Pair, Result.getValue(2) /* Chain */});
17762     return;
17763   }
17764   case ISD::EXTRACT_SUBVECTOR:
17765     ReplaceExtractSubVectorResults(N, Results, DAG);
17766     return;
17767   case ISD::INSERT_SUBVECTOR:
17768     // Custom lowering has been requested for INSERT_SUBVECTOR -- but delegate
17769     // to common code for result type legalisation
17770     return;
17771   case ISD::INTRINSIC_WO_CHAIN: {
17772     EVT VT = N->getValueType(0);
17773     assert((VT == MVT::i8 || VT == MVT::i16) &&
17774            "custom lowering for unexpected type");
17775 
17776     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
17777     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17778     switch (IntID) {
17779     default:
17780       return;
17781     case Intrinsic::aarch64_sve_clasta_n: {
17782       SDLoc DL(N);
17783       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
17784       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
17785                            N->getOperand(1), Op2, N->getOperand(3));
17786       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17787       return;
17788     }
17789     case Intrinsic::aarch64_sve_clastb_n: {
17790       SDLoc DL(N);
17791       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
17792       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
17793                            N->getOperand(1), Op2, N->getOperand(3));
17794       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17795       return;
17796     }
17797     case Intrinsic::aarch64_sve_lasta: {
17798       SDLoc DL(N);
17799       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
17800                            N->getOperand(1), N->getOperand(2));
17801       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17802       return;
17803     }
17804     case Intrinsic::aarch64_sve_lastb: {
17805       SDLoc DL(N);
17806       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
17807                            N->getOperand(1), N->getOperand(2));
17808       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
17809       return;
17810     }
17811     }
17812   }
17813   }
17814 }
17815 
17816 bool AArch64TargetLowering::useLoadStackGuardNode() const {
17817   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
17818     return TargetLowering::useLoadStackGuardNode();
17819   return true;
17820 }
17821 
17822 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
17823   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
17824   // reciprocal if there are three or more FDIVs.
17825   return 3;
17826 }
17827 
17828 TargetLoweringBase::LegalizeTypeAction
17829 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
17830   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
17831   // v4i16, v2i32 instead of to promote.
17832   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
17833       VT == MVT::v1f32)
17834     return TypeWidenVector;
17835 
17836   return TargetLoweringBase::getPreferredVectorAction(VT);
17837 }
17838 
17839 // In v8.4a, ldp and stp instructions are guaranteed to be single-copy atomic
17840 // provided the address is 16-byte aligned.
17841 bool AArch64TargetLowering::isOpSuitableForLDPSTP(const Instruction *I) const {
17842   if (!Subtarget->hasLSE2())
17843     return false;
17844 
17845   if (auto LI = dyn_cast<LoadInst>(I))
17846     return LI->getType()->getPrimitiveSizeInBits() == 128 &&
17847            LI->getAlignment() >= 16;
17848 
17849   if (auto SI = dyn_cast<StoreInst>(I))
17850     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
17851            SI->getAlignment() >= 16;
17852 
17853   return false;
17854 }
17855 
17856 bool AArch64TargetLowering::shouldInsertFencesForAtomic(
17857     const Instruction *I) const {
17858   return isOpSuitableForLDPSTP(I);
17859 }
17860 
17861 // Loads and stores less than 128-bits are already atomic; ones above that
17862 // are doomed anyway, so defer to the default libcall and blame the OS when
17863 // things go wrong.
17864 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17865   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
17866   if (Size != 128)
17867     return false;
17868 
17869   return !isOpSuitableForLDPSTP(SI);
17870 }
17871 
17872 // Loads and stores less than 128-bits are already atomic; ones above that
17873 // are doomed anyway, so defer to the default libcall and blame the OS when
17874 // things go wrong.
17875 TargetLowering::AtomicExpansionKind
17876 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17877   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
17878 
17879   if (Size != 128 || isOpSuitableForLDPSTP(LI))
17880     return AtomicExpansionKind::None;
17881 
17882   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17883   // implement atomicrmw without spilling. If the target address is also on the
17884   // stack and close enough to the spill slot, this can lead to a situation
17885   // where the monitor always gets cleared and the atomic operation can never
17886   // succeed. So at -O0 lower this operation to a CAS loop.
17887   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17888     return AtomicExpansionKind::CmpXChg;
17889 
17890   return AtomicExpansionKind::LLSC;
17891 }
17892 
17893 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
17894 TargetLowering::AtomicExpansionKind
17895 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17896   if (AI->isFloatingPointOperation())
17897     return AtomicExpansionKind::CmpXChg;
17898 
17899   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17900   if (Size > 128) return AtomicExpansionKind::None;
17901 
17902   // Nand is not supported in LSE.
17903   // Leave 128 bits to LLSC or CmpXChg.
17904   if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
17905     if (Subtarget->hasLSE())
17906       return AtomicExpansionKind::None;
17907     if (Subtarget->outlineAtomics()) {
17908       // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
17909       // Don't outline them unless
17910       // (1) high level <atomic> support approved:
17911       //   http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
17912       // (2) low level libgcc and compiler-rt support implemented by:
17913       //   min/max outline atomics helpers
17914       if (AI->getOperation() != AtomicRMWInst::Min &&
17915           AI->getOperation() != AtomicRMWInst::Max &&
17916           AI->getOperation() != AtomicRMWInst::UMin &&
17917           AI->getOperation() != AtomicRMWInst::UMax) {
17918         return AtomicExpansionKind::None;
17919       }
17920     }
17921   }
17922 
17923   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17924   // implement atomicrmw without spilling. If the target address is also on the
17925   // stack and close enough to the spill slot, this can lead to a situation
17926   // where the monitor always gets cleared and the atomic operation can never
17927   // succeed. So at -O0 lower this operation to a CAS loop.
17928   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17929     return AtomicExpansionKind::CmpXChg;
17930 
17931   return AtomicExpansionKind::LLSC;
17932 }
17933 
17934 TargetLowering::AtomicExpansionKind
17935 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
17936     AtomicCmpXchgInst *AI) const {
17937   // If subtarget has LSE, leave cmpxchg intact for codegen.
17938   if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
17939     return AtomicExpansionKind::None;
17940   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17941   // implement cmpxchg without spilling. If the address being exchanged is also
17942   // on the stack and close enough to the spill slot, this can lead to a
17943   // situation where the monitor always gets cleared and the atomic operation
17944   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
17945   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
17946     return AtomicExpansionKind::None;
17947 
17948   // 128-bit atomic cmpxchg is weird; AtomicExpand doesn't know how to expand
17949   // it.
17950   unsigned Size = AI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
17951   if (Size > 64)
17952     return AtomicExpansionKind::None;
17953 
17954   return AtomicExpansionKind::LLSC;
17955 }
17956 
17957 Value *AArch64TargetLowering::emitLoadLinked(IRBuilderBase &Builder,
17958                                              Type *ValueTy, Value *Addr,
17959                                              AtomicOrdering Ord) const {
17960   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17961   bool IsAcquire = isAcquireOrStronger(Ord);
17962 
17963   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
17964   // intrinsic must return {i64, i64} and we have to recombine them into a
17965   // single i128 here.
17966   if (ValueTy->getPrimitiveSizeInBits() == 128) {
17967     Intrinsic::ID Int =
17968         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
17969     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
17970 
17971     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17972     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
17973 
17974     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17975     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17976     Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
17977     Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
17978     return Builder.CreateOr(
17979         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 64)), "val64");
17980   }
17981 
17982   Type *Tys[] = { Addr->getType() };
17983   Intrinsic::ID Int =
17984       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
17985   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
17986 
17987   const DataLayout &DL = M->getDataLayout();
17988   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(ValueTy));
17989   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
17990 
17991   return Builder.CreateBitCast(Trunc, ValueTy);
17992 }
17993 
17994 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
17995     IRBuilderBase &Builder) const {
17996   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17997   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
17998 }
17999 
18000 Value *AArch64TargetLowering::emitStoreConditional(IRBuilderBase &Builder,
18001                                                    Value *Val, Value *Addr,
18002                                                    AtomicOrdering Ord) const {
18003   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18004   bool IsRelease = isReleaseOrStronger(Ord);
18005 
18006   // Since the intrinsics must have legal type, the i128 intrinsics take two
18007   // parameters: "i64, i64". We must marshal Val into the appropriate form
18008   // before the call.
18009   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
18010     Intrinsic::ID Int =
18011         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
18012     Function *Stxr = Intrinsic::getDeclaration(M, Int);
18013     Type *Int64Ty = Type::getInt64Ty(M->getContext());
18014 
18015     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
18016     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
18017     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18018     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
18019   }
18020 
18021   Intrinsic::ID Int =
18022       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
18023   Type *Tys[] = { Addr->getType() };
18024   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
18025 
18026   const DataLayout &DL = M->getDataLayout();
18027   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
18028   Val = Builder.CreateBitCast(Val, IntValTy);
18029 
18030   return Builder.CreateCall(Stxr,
18031                             {Builder.CreateZExtOrBitCast(
18032                                  Val, Stxr->getFunctionType()->getParamType(0)),
18033                              Addr});
18034 }
18035 
18036 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
18037     Type *Ty, CallingConv::ID CallConv, bool isVarArg,
18038     const DataLayout &DL) const {
18039   if (!Ty->isArrayTy()) {
18040     const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
18041     return TySize.isScalable() && TySize.getKnownMinSize() > 128;
18042   }
18043 
18044   // All non aggregate members of the type must have the same type
18045   SmallVector<EVT> ValueVTs;
18046   ComputeValueVTs(*this, DL, Ty, ValueVTs);
18047   return is_splat(ValueVTs);
18048 }
18049 
18050 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
18051                                                             EVT) const {
18052   return false;
18053 }
18054 
18055 static Value *UseTlsOffset(IRBuilderBase &IRB, unsigned Offset) {
18056   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
18057   Function *ThreadPointerFunc =
18058       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
18059   return IRB.CreatePointerCast(
18060       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
18061                              Offset),
18062       IRB.getInt8PtrTy()->getPointerTo(0));
18063 }
18064 
18065 Value *AArch64TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
18066   // Android provides a fixed TLS slot for the stack cookie. See the definition
18067   // of TLS_SLOT_STACK_GUARD in
18068   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
18069   if (Subtarget->isTargetAndroid())
18070     return UseTlsOffset(IRB, 0x28);
18071 
18072   // Fuchsia is similar.
18073   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
18074   if (Subtarget->isTargetFuchsia())
18075     return UseTlsOffset(IRB, -0x10);
18076 
18077   return TargetLowering::getIRStackGuard(IRB);
18078 }
18079 
18080 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
18081   // MSVC CRT provides functionalities for stack protection.
18082   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
18083     // MSVC CRT has a global variable holding security cookie.
18084     M.getOrInsertGlobal("__security_cookie",
18085                         Type::getInt8PtrTy(M.getContext()));
18086 
18087     // MSVC CRT has a function to validate security cookie.
18088     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18089         "__security_check_cookie", Type::getVoidTy(M.getContext()),
18090         Type::getInt8PtrTy(M.getContext()));
18091     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
18092       F->setCallingConv(CallingConv::Win64);
18093       F->addParamAttr(0, Attribute::AttrKind::InReg);
18094     }
18095     return;
18096   }
18097   TargetLowering::insertSSPDeclarations(M);
18098 }
18099 
18100 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
18101   // MSVC CRT has a global variable holding security cookie.
18102   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18103     return M.getGlobalVariable("__security_cookie");
18104   return TargetLowering::getSDagStackGuard(M);
18105 }
18106 
18107 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
18108   // MSVC CRT has a function to validate security cookie.
18109   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18110     return M.getFunction("__security_check_cookie");
18111   return TargetLowering::getSSPStackGuardCheck(M);
18112 }
18113 
18114 Value *
18115 AArch64TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
18116   // Android provides a fixed TLS slot for the SafeStack pointer. See the
18117   // definition of TLS_SLOT_SAFESTACK in
18118   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
18119   if (Subtarget->isTargetAndroid())
18120     return UseTlsOffset(IRB, 0x48);
18121 
18122   // Fuchsia is similar.
18123   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
18124   if (Subtarget->isTargetFuchsia())
18125     return UseTlsOffset(IRB, -0x8);
18126 
18127   return TargetLowering::getSafeStackPointerLocation(IRB);
18128 }
18129 
18130 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
18131     const Instruction &AndI) const {
18132   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
18133   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
18134   // may be beneficial to sink in other cases, but we would have to check that
18135   // the cmp would not get folded into the br to form a cbz for these to be
18136   // beneficial.
18137   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
18138   if (!Mask)
18139     return false;
18140   return Mask->getValue().isPowerOf2();
18141 }
18142 
18143 bool AArch64TargetLowering::
18144     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18145         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
18146         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
18147         SelectionDAG &DAG) const {
18148   // Does baseline recommend not to perform the fold by default?
18149   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
18150           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
18151     return false;
18152   // Else, if this is a vector shift, prefer 'shl'.
18153   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
18154 }
18155 
18156 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
18157                                               SDNode *N) const {
18158   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
18159       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
18160     return false;
18161   return true;
18162 }
18163 
18164 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18165   // Update IsSplitCSR in AArch64unctionInfo.
18166   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
18167   AFI->setIsSplitCSR(true);
18168 }
18169 
18170 void AArch64TargetLowering::insertCopiesSplitCSR(
18171     MachineBasicBlock *Entry,
18172     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18173   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
18174   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18175   if (!IStart)
18176     return;
18177 
18178   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18179   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18180   MachineBasicBlock::iterator MBBI = Entry->begin();
18181   for (const MCPhysReg *I = IStart; *I; ++I) {
18182     const TargetRegisterClass *RC = nullptr;
18183     if (AArch64::GPR64RegClass.contains(*I))
18184       RC = &AArch64::GPR64RegClass;
18185     else if (AArch64::FPR64RegClass.contains(*I))
18186       RC = &AArch64::FPR64RegClass;
18187     else
18188       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18189 
18190     Register NewVR = MRI->createVirtualRegister(RC);
18191     // Create copy from CSR to a virtual register.
18192     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18193     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18194     // nounwind. If we want to generalize this later, we may need to emit
18195     // CFI pseudo-instructions.
18196     assert(Entry->getParent()->getFunction().hasFnAttribute(
18197                Attribute::NoUnwind) &&
18198            "Function should be nounwind in insertCopiesSplitCSR!");
18199     Entry->addLiveIn(*I);
18200     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18201         .addReg(*I);
18202 
18203     // Insert the copy-back instructions right before the terminator.
18204     for (auto *Exit : Exits)
18205       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18206               TII->get(TargetOpcode::COPY), *I)
18207           .addReg(NewVR);
18208   }
18209 }
18210 
18211 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
18212   // Integer division on AArch64 is expensive. However, when aggressively
18213   // optimizing for code size, we prefer to use a div instruction, as it is
18214   // usually smaller than the alternative sequence.
18215   // The exception to this is vector division. Since AArch64 doesn't have vector
18216   // integer division, leaving the division as-is is a loss even in terms of
18217   // size, because it will have to be scalarized, while the alternative code
18218   // sequence can be performed in vector form.
18219   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
18220   return OptSize && !VT.isVector();
18221 }
18222 
18223 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
18224   // We want inc-of-add for scalars and sub-of-not for vectors.
18225   return VT.isScalarInteger();
18226 }
18227 
18228 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
18229   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
18230 }
18231 
18232 unsigned
18233 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
18234   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
18235     return getPointerTy(DL).getSizeInBits();
18236 
18237   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
18238 }
18239 
18240 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
18241   MF.getFrameInfo().computeMaxCallFrameSize(MF);
18242   TargetLoweringBase::finalizeLowering(MF);
18243 }
18244 
18245 // Unlike X86, we let frame lowering assign offsets to all catch objects.
18246 bool AArch64TargetLowering::needsFixedCatchObjects() const {
18247   return false;
18248 }
18249 
18250 bool AArch64TargetLowering::shouldLocalize(
18251     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
18252   switch (MI.getOpcode()) {
18253   case TargetOpcode::G_GLOBAL_VALUE: {
18254     // On Darwin, TLS global vars get selected into function calls, which
18255     // we don't want localized, as they can get moved into the middle of a
18256     // another call sequence.
18257     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
18258     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
18259       return false;
18260     break;
18261   }
18262   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
18263   // localizable.
18264   case AArch64::ADRP:
18265   case AArch64::G_ADD_LOW:
18266     return true;
18267   default:
18268     break;
18269   }
18270   return TargetLoweringBase::shouldLocalize(MI, TTI);
18271 }
18272 
18273 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
18274   if (isa<ScalableVectorType>(Inst.getType()))
18275     return true;
18276 
18277   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
18278     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
18279       return true;
18280 
18281   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
18282     if (isa<ScalableVectorType>(AI->getAllocatedType()))
18283       return true;
18284   }
18285 
18286   return false;
18287 }
18288 
18289 // Return the largest legal scalable vector type that matches VT's element type.
18290 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
18291   assert(VT.isFixedLengthVector() &&
18292          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18293          "Expected legal fixed length vector!");
18294   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
18295   default:
18296     llvm_unreachable("unexpected element type for SVE container");
18297   case MVT::i8:
18298     return EVT(MVT::nxv16i8);
18299   case MVT::i16:
18300     return EVT(MVT::nxv8i16);
18301   case MVT::i32:
18302     return EVT(MVT::nxv4i32);
18303   case MVT::i64:
18304     return EVT(MVT::nxv2i64);
18305   case MVT::f16:
18306     return EVT(MVT::nxv8f16);
18307   case MVT::f32:
18308     return EVT(MVT::nxv4f32);
18309   case MVT::f64:
18310     return EVT(MVT::nxv2f64);
18311   }
18312 }
18313 
18314 // Return a PTRUE with active lanes corresponding to the extent of VT.
18315 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
18316                                                 EVT VT) {
18317   assert(VT.isFixedLengthVector() &&
18318          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18319          "Expected legal fixed length vector!");
18320 
18321   unsigned PgPattern =
18322       getSVEPredPatternFromNumElements(VT.getVectorNumElements());
18323   assert(PgPattern && "Unexpected element count for SVE predicate");
18324 
18325   // For vectors that are exactly getMaxSVEVectorSizeInBits big, we can use
18326   // AArch64SVEPredPattern::all, which can enable the use of unpredicated
18327   // variants of instructions when available.
18328   const auto &Subtarget =
18329       static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
18330   unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
18331   unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
18332   if (MaxSVESize && MinSVESize == MaxSVESize &&
18333       MaxSVESize == VT.getSizeInBits())
18334     PgPattern = AArch64SVEPredPattern::all;
18335 
18336   MVT MaskVT;
18337   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
18338   default:
18339     llvm_unreachable("unexpected element type for SVE predicate");
18340   case MVT::i8:
18341     MaskVT = MVT::nxv16i1;
18342     break;
18343   case MVT::i16:
18344   case MVT::f16:
18345     MaskVT = MVT::nxv8i1;
18346     break;
18347   case MVT::i32:
18348   case MVT::f32:
18349     MaskVT = MVT::nxv4i1;
18350     break;
18351   case MVT::i64:
18352   case MVT::f64:
18353     MaskVT = MVT::nxv2i1;
18354     break;
18355   }
18356 
18357   return getPTrue(DAG, DL, MaskVT, PgPattern);
18358 }
18359 
18360 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
18361                                              EVT VT) {
18362   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
18363          "Expected legal scalable vector!");
18364   auto PredTy = VT.changeVectorElementType(MVT::i1);
18365   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
18366 }
18367 
18368 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
18369   if (VT.isFixedLengthVector())
18370     return getPredicateForFixedLengthVector(DAG, DL, VT);
18371 
18372   return getPredicateForScalableVector(DAG, DL, VT);
18373 }
18374 
18375 // Grow V to consume an entire SVE register.
18376 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
18377   assert(VT.isScalableVector() &&
18378          "Expected to convert into a scalable vector!");
18379   assert(V.getValueType().isFixedLengthVector() &&
18380          "Expected a fixed length vector operand!");
18381   SDLoc DL(V);
18382   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18383   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
18384 }
18385 
18386 // Shrink V so it's just big enough to maintain a VT's worth of data.
18387 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
18388   assert(VT.isFixedLengthVector() &&
18389          "Expected to convert into a fixed length vector!");
18390   assert(V.getValueType().isScalableVector() &&
18391          "Expected a scalable vector operand!");
18392   SDLoc DL(V);
18393   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18394   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
18395 }
18396 
18397 // Convert all fixed length vector loads larger than NEON to masked_loads.
18398 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
18399     SDValue Op, SelectionDAG &DAG) const {
18400   auto Load = cast<LoadSDNode>(Op);
18401 
18402   SDLoc DL(Op);
18403   EVT VT = Op.getValueType();
18404   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18405 
18406   auto NewLoad = DAG.getMaskedLoad(
18407       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
18408       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
18409       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
18410       Load->getExtensionType());
18411 
18412   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
18413   SDValue MergedValues[2] = {Result, Load->getChain()};
18414   return DAG.getMergeValues(MergedValues, DL);
18415 }
18416 
18417 static SDValue convertFixedMaskToScalableVector(SDValue Mask,
18418                                                 SelectionDAG &DAG) {
18419   SDLoc DL(Mask);
18420   EVT InVT = Mask.getValueType();
18421   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18422 
18423   auto Op1 = convertToScalableVector(DAG, ContainerVT, Mask);
18424   auto Op2 = DAG.getConstant(0, DL, ContainerVT);
18425   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
18426 
18427   EVT CmpVT = Pg.getValueType();
18428   return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
18429                      {Pg, Op1, Op2, DAG.getCondCode(ISD::SETNE)});
18430 }
18431 
18432 // Convert all fixed length vector loads larger than NEON to masked_loads.
18433 SDValue AArch64TargetLowering::LowerFixedLengthVectorMLoadToSVE(
18434     SDValue Op, SelectionDAG &DAG) const {
18435   auto Load = cast<MaskedLoadSDNode>(Op);
18436 
18437   SDLoc DL(Op);
18438   EVT VT = Op.getValueType();
18439   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18440 
18441   SDValue Mask = convertFixedMaskToScalableVector(Load->getMask(), DAG);
18442 
18443   SDValue PassThru;
18444   bool IsPassThruZeroOrUndef = false;
18445 
18446   if (Load->getPassThru()->isUndef()) {
18447     PassThru = DAG.getUNDEF(ContainerVT);
18448     IsPassThruZeroOrUndef = true;
18449   } else {
18450     if (ContainerVT.isInteger())
18451       PassThru = DAG.getConstant(0, DL, ContainerVT);
18452     else
18453       PassThru = DAG.getConstantFP(0, DL, ContainerVT);
18454     if (isZerosVector(Load->getPassThru().getNode()))
18455       IsPassThruZeroOrUndef = true;
18456   }
18457 
18458   auto NewLoad = DAG.getMaskedLoad(
18459       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
18460       Mask, PassThru, Load->getMemoryVT(), Load->getMemOperand(),
18461       Load->getAddressingMode(), Load->getExtensionType());
18462 
18463   if (!IsPassThruZeroOrUndef) {
18464     SDValue OldPassThru =
18465         convertToScalableVector(DAG, ContainerVT, Load->getPassThru());
18466     NewLoad = DAG.getSelect(DL, ContainerVT, Mask, NewLoad, OldPassThru);
18467   }
18468 
18469   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
18470   SDValue MergedValues[2] = {Result, Load->getChain()};
18471   return DAG.getMergeValues(MergedValues, DL);
18472 }
18473 
18474 // Convert all fixed length vector stores larger than NEON to masked_stores.
18475 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
18476     SDValue Op, SelectionDAG &DAG) const {
18477   auto Store = cast<StoreSDNode>(Op);
18478 
18479   SDLoc DL(Op);
18480   EVT VT = Store->getValue().getValueType();
18481   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18482 
18483   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
18484   return DAG.getMaskedStore(
18485       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
18486       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
18487       Store->getMemOperand(), Store->getAddressingMode(),
18488       Store->isTruncatingStore());
18489 }
18490 
18491 SDValue AArch64TargetLowering::LowerFixedLengthVectorMStoreToSVE(
18492     SDValue Op, SelectionDAG &DAG) const {
18493   auto Store = cast<MaskedStoreSDNode>(Op);
18494 
18495   if (Store->isTruncatingStore())
18496     return SDValue();
18497 
18498   SDLoc DL(Op);
18499   EVT VT = Store->getValue().getValueType();
18500   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18501 
18502   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
18503   SDValue Mask = convertFixedMaskToScalableVector(Store->getMask(), DAG);
18504 
18505   return DAG.getMaskedStore(
18506       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
18507       Mask, Store->getMemoryVT(), Store->getMemOperand(),
18508       Store->getAddressingMode(), Store->isTruncatingStore());
18509 }
18510 
18511 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
18512     SDValue Op, SelectionDAG &DAG) const {
18513   SDLoc dl(Op);
18514   EVT VT = Op.getValueType();
18515   EVT EltVT = VT.getVectorElementType();
18516 
18517   bool Signed = Op.getOpcode() == ISD::SDIV;
18518   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
18519 
18520   // Scalable vector i32/i64 DIV is supported.
18521   if (EltVT == MVT::i32 || EltVT == MVT::i64)
18522     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
18523 
18524   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
18525   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18526   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
18527   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
18528   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
18529 
18530   // If this is not a full vector, extend, div, and truncate it.
18531   EVT WidenedVT = VT.widenIntegerVectorElementType(*DAG.getContext());
18532   if (DAG.getTargetLoweringInfo().isTypeLegal(WidenedVT)) {
18533     unsigned ExtendOpcode = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18534     SDValue Op0 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(0));
18535     SDValue Op1 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(1));
18536     SDValue Div = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0, Op1);
18537     return DAG.getNode(ISD::TRUNCATE, dl, VT, Div);
18538   }
18539 
18540   // Convert the operands to scalable vectors.
18541   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
18542   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
18543 
18544   // Extend the scalable operands.
18545   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
18546   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
18547   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
18548   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
18549   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
18550   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
18551 
18552   // Convert back to fixed vectors so the DIV can be further lowered.
18553   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
18554   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
18555   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
18556   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
18557   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
18558                                  Op0Lo, Op1Lo);
18559   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
18560                                  Op0Hi, Op1Hi);
18561 
18562   // Convert again to scalable vectors to truncate.
18563   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
18564   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
18565   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
18566                                        ResultLo, ResultHi);
18567 
18568   return convertFromScalableVector(DAG, VT, ScalableResult);
18569 }
18570 
18571 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
18572     SDValue Op, SelectionDAG &DAG) const {
18573   EVT VT = Op.getValueType();
18574   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18575 
18576   SDLoc DL(Op);
18577   SDValue Val = Op.getOperand(0);
18578   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
18579   Val = convertToScalableVector(DAG, ContainerVT, Val);
18580 
18581   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
18582   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
18583 
18584   // Repeatedly unpack Val until the result is of the desired element type.
18585   switch (ContainerVT.getSimpleVT().SimpleTy) {
18586   default:
18587     llvm_unreachable("unimplemented container type");
18588   case MVT::nxv16i8:
18589     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
18590     if (VT.getVectorElementType() == MVT::i16)
18591       break;
18592     LLVM_FALLTHROUGH;
18593   case MVT::nxv8i16:
18594     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
18595     if (VT.getVectorElementType() == MVT::i32)
18596       break;
18597     LLVM_FALLTHROUGH;
18598   case MVT::nxv4i32:
18599     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
18600     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
18601     break;
18602   }
18603 
18604   return convertFromScalableVector(DAG, VT, Val);
18605 }
18606 
18607 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
18608     SDValue Op, SelectionDAG &DAG) const {
18609   EVT VT = Op.getValueType();
18610   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18611 
18612   SDLoc DL(Op);
18613   SDValue Val = Op.getOperand(0);
18614   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
18615   Val = convertToScalableVector(DAG, ContainerVT, Val);
18616 
18617   // Repeatedly truncate Val until the result is of the desired element type.
18618   switch (ContainerVT.getSimpleVT().SimpleTy) {
18619   default:
18620     llvm_unreachable("unimplemented container type");
18621   case MVT::nxv2i64:
18622     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
18623     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
18624     if (VT.getVectorElementType() == MVT::i32)
18625       break;
18626     LLVM_FALLTHROUGH;
18627   case MVT::nxv4i32:
18628     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
18629     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
18630     if (VT.getVectorElementType() == MVT::i16)
18631       break;
18632     LLVM_FALLTHROUGH;
18633   case MVT::nxv8i16:
18634     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
18635     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
18636     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
18637     break;
18638   }
18639 
18640   return convertFromScalableVector(DAG, VT, Val);
18641 }
18642 
18643 SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt(
18644     SDValue Op, SelectionDAG &DAG) const {
18645   EVT VT = Op.getValueType();
18646   EVT InVT = Op.getOperand(0).getValueType();
18647   assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!");
18648 
18649   SDLoc DL(Op);
18650   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18651   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
18652 
18653   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1));
18654 }
18655 
18656 SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt(
18657     SDValue Op, SelectionDAG &DAG) const {
18658   EVT VT = Op.getValueType();
18659   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18660 
18661   SDLoc DL(Op);
18662   EVT InVT = Op.getOperand(0).getValueType();
18663   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18664   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
18665 
18666   auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0,
18667                                  Op.getOperand(1), Op.getOperand(2));
18668 
18669   return convertFromScalableVector(DAG, VT, ScalableRes);
18670 }
18671 
18672 // Convert vector operation 'Op' to an equivalent predicated operation whereby
18673 // the original operation's type is used to construct a suitable predicate.
18674 // NOTE: The results for inactive lanes are undefined.
18675 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
18676                                                    SelectionDAG &DAG,
18677                                                    unsigned NewOp,
18678                                                    bool OverrideNEON) const {
18679   EVT VT = Op.getValueType();
18680   SDLoc DL(Op);
18681   auto Pg = getPredicateForVector(DAG, DL, VT);
18682 
18683   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
18684     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18685 
18686     // Create list of operands by converting existing ones to scalable types.
18687     SmallVector<SDValue, 4> Operands = {Pg};
18688     for (const SDValue &V : Op->op_values()) {
18689       if (isa<CondCodeSDNode>(V)) {
18690         Operands.push_back(V);
18691         continue;
18692       }
18693 
18694       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
18695         EVT VTArg = VTNode->getVT().getVectorElementType();
18696         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
18697         Operands.push_back(DAG.getValueType(NewVTArg));
18698         continue;
18699       }
18700 
18701       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
18702              "Only fixed length vectors are supported!");
18703       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
18704     }
18705 
18706     if (isMergePassthruOpcode(NewOp))
18707       Operands.push_back(DAG.getUNDEF(ContainerVT));
18708 
18709     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
18710     return convertFromScalableVector(DAG, VT, ScalableRes);
18711   }
18712 
18713   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
18714 
18715   SmallVector<SDValue, 4> Operands = {Pg};
18716   for (const SDValue &V : Op->op_values()) {
18717     assert((!V.getValueType().isVector() ||
18718             V.getValueType().isScalableVector()) &&
18719            "Only scalable vectors are supported!");
18720     Operands.push_back(V);
18721   }
18722 
18723   if (isMergePassthruOpcode(NewOp))
18724     Operands.push_back(DAG.getUNDEF(VT));
18725 
18726   return DAG.getNode(NewOp, DL, VT, Operands);
18727 }
18728 
18729 // If a fixed length vector operation has no side effects when applied to
18730 // undefined elements, we can safely use scalable vectors to perform the same
18731 // operation without needing to worry about predication.
18732 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
18733                                                  SelectionDAG &DAG) const {
18734   EVT VT = Op.getValueType();
18735   assert(useSVEForFixedLengthVectorVT(VT) &&
18736          "Only expected to lower fixed length vector operation!");
18737   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18738 
18739   // Create list of operands by converting existing ones to scalable types.
18740   SmallVector<SDValue, 4> Ops;
18741   for (const SDValue &V : Op->op_values()) {
18742     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
18743 
18744     // Pass through non-vector operands.
18745     if (!V.getValueType().isVector()) {
18746       Ops.push_back(V);
18747       continue;
18748     }
18749 
18750     // "cast" fixed length vector to a scalable vector.
18751     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
18752            "Only fixed length vectors are supported!");
18753     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
18754   }
18755 
18756   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
18757   return convertFromScalableVector(DAG, VT, ScalableRes);
18758 }
18759 
18760 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
18761     SelectionDAG &DAG) const {
18762   SDLoc DL(ScalarOp);
18763   SDValue AccOp = ScalarOp.getOperand(0);
18764   SDValue VecOp = ScalarOp.getOperand(1);
18765   EVT SrcVT = VecOp.getValueType();
18766   EVT ResVT = SrcVT.getVectorElementType();
18767 
18768   EVT ContainerVT = SrcVT;
18769   if (SrcVT.isFixedLengthVector()) {
18770     ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
18771     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
18772   }
18773 
18774   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
18775   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
18776 
18777   // Convert operands to Scalable.
18778   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
18779                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
18780 
18781   // Perform reduction.
18782   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
18783                             Pg, AccOp, VecOp);
18784 
18785   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
18786 }
18787 
18788 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
18789                                                        SelectionDAG &DAG) const {
18790   SDLoc DL(ReduceOp);
18791   SDValue Op = ReduceOp.getOperand(0);
18792   EVT OpVT = Op.getValueType();
18793   EVT VT = ReduceOp.getValueType();
18794 
18795   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
18796     return SDValue();
18797 
18798   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
18799 
18800   switch (ReduceOp.getOpcode()) {
18801   default:
18802     return SDValue();
18803   case ISD::VECREDUCE_OR:
18804     return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
18805   case ISD::VECREDUCE_AND: {
18806     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
18807     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
18808   }
18809   case ISD::VECREDUCE_XOR: {
18810     SDValue ID =
18811         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
18812     SDValue Cntp =
18813         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
18814     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
18815   }
18816   }
18817 
18818   return SDValue();
18819 }
18820 
18821 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
18822                                                    SDValue ScalarOp,
18823                                                    SelectionDAG &DAG) const {
18824   SDLoc DL(ScalarOp);
18825   SDValue VecOp = ScalarOp.getOperand(0);
18826   EVT SrcVT = VecOp.getValueType();
18827 
18828   if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
18829     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
18830     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
18831   }
18832 
18833   // UADDV always returns an i64 result.
18834   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
18835                                                    SrcVT.getVectorElementType();
18836   EVT RdxVT = SrcVT;
18837   if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
18838     RdxVT = getPackedSVEVectorVT(ResVT);
18839 
18840   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
18841   SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
18842   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
18843                             Rdx, DAG.getConstant(0, DL, MVT::i64));
18844 
18845   // The VEC_REDUCE nodes expect an element size result.
18846   if (ResVT != ScalarOp.getValueType())
18847     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
18848 
18849   return Res;
18850 }
18851 
18852 SDValue
18853 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
18854     SelectionDAG &DAG) const {
18855   EVT VT = Op.getValueType();
18856   SDLoc DL(Op);
18857 
18858   EVT InVT = Op.getOperand(1).getValueType();
18859   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18860   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
18861   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
18862 
18863   // Convert the mask to a predicated (NOTE: We don't need to worry about
18864   // inactive lanes since VSELECT is safe when given undefined elements).
18865   EVT MaskVT = Op.getOperand(0).getValueType();
18866   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
18867   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
18868   Mask = DAG.getNode(ISD::TRUNCATE, DL,
18869                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
18870 
18871   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
18872                                 Mask, Op1, Op2);
18873 
18874   return convertFromScalableVector(DAG, VT, ScalableRes);
18875 }
18876 
18877 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
18878     SDValue Op, SelectionDAG &DAG) const {
18879   SDLoc DL(Op);
18880   EVT InVT = Op.getOperand(0).getValueType();
18881   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
18882 
18883   assert(useSVEForFixedLengthVectorVT(InVT) &&
18884          "Only expected to lower fixed length vector operation!");
18885   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
18886          "Expected integer result of the same bit length as the inputs!");
18887 
18888   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
18889   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
18890   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
18891 
18892   EVT CmpVT = Pg.getValueType();
18893   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
18894                          {Pg, Op1, Op2, Op.getOperand(2)});
18895 
18896   EVT PromoteVT = ContainerVT.changeTypeToInteger();
18897   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
18898   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
18899 }
18900 
18901 SDValue
18902 AArch64TargetLowering::LowerFixedLengthBitcastToSVE(SDValue Op,
18903                                                     SelectionDAG &DAG) const {
18904   SDLoc DL(Op);
18905   auto SrcOp = Op.getOperand(0);
18906   EVT VT = Op.getValueType();
18907   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
18908   EVT ContainerSrcVT =
18909       getContainerForFixedLengthVector(DAG, SrcOp.getValueType());
18910 
18911   SrcOp = convertToScalableVector(DAG, ContainerSrcVT, SrcOp);
18912   Op = DAG.getNode(ISD::BITCAST, DL, ContainerDstVT, SrcOp);
18913   return convertFromScalableVector(DAG, VT, Op);
18914 }
18915 
18916 SDValue AArch64TargetLowering::LowerFixedLengthConcatVectorsToSVE(
18917     SDValue Op, SelectionDAG &DAG) const {
18918   SDLoc DL(Op);
18919   unsigned NumOperands = Op->getNumOperands();
18920 
18921   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
18922          "Unexpected number of operands in CONCAT_VECTORS");
18923 
18924   auto SrcOp1 = Op.getOperand(0);
18925   auto SrcOp2 = Op.getOperand(1);
18926   EVT VT = Op.getValueType();
18927   EVT SrcVT = SrcOp1.getValueType();
18928 
18929   if (NumOperands > 2) {
18930     SmallVector<SDValue, 4> Ops;
18931     EVT PairVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
18932     for (unsigned I = 0; I < NumOperands; I += 2)
18933       Ops.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, PairVT,
18934                                 Op->getOperand(I), Op->getOperand(I + 1)));
18935 
18936     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
18937   }
18938 
18939   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18940 
18941   SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
18942   SrcOp1 = convertToScalableVector(DAG, ContainerVT, SrcOp1);
18943   SrcOp2 = convertToScalableVector(DAG, ContainerVT, SrcOp2);
18944 
18945   Op = DAG.getNode(AArch64ISD::SPLICE, DL, ContainerVT, Pg, SrcOp1, SrcOp2);
18946 
18947   return convertFromScalableVector(DAG, VT, Op);
18948 }
18949 
18950 SDValue
18951 AArch64TargetLowering::LowerFixedLengthFPExtendToSVE(SDValue Op,
18952                                                      SelectionDAG &DAG) const {
18953   EVT VT = Op.getValueType();
18954   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18955 
18956   SDLoc DL(Op);
18957   SDValue Val = Op.getOperand(0);
18958   SDValue Pg = getPredicateForVector(DAG, DL, VT);
18959   EVT SrcVT = Val.getValueType();
18960   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
18961   EVT ExtendVT = ContainerVT.changeVectorElementType(
18962       SrcVT.getVectorElementType());
18963 
18964   Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
18965   Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT.changeTypeToInteger(), Val);
18966 
18967   Val = convertToScalableVector(DAG, ContainerVT.changeTypeToInteger(), Val);
18968   Val = getSVESafeBitCast(ExtendVT, Val, DAG);
18969   Val = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
18970                     Pg, Val, DAG.getUNDEF(ContainerVT));
18971 
18972   return convertFromScalableVector(DAG, VT, Val);
18973 }
18974 
18975 SDValue
18976 AArch64TargetLowering::LowerFixedLengthFPRoundToSVE(SDValue Op,
18977                                                     SelectionDAG &DAG) const {
18978   EVT VT = Op.getValueType();
18979   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
18980 
18981   SDLoc DL(Op);
18982   SDValue Val = Op.getOperand(0);
18983   EVT SrcVT = Val.getValueType();
18984   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
18985   EVT RoundVT = ContainerSrcVT.changeVectorElementType(
18986       VT.getVectorElementType());
18987   SDValue Pg = getPredicateForVector(DAG, DL, RoundVT);
18988 
18989   Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
18990   Val = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, RoundVT, Pg, Val,
18991                     Op.getOperand(1), DAG.getUNDEF(RoundVT));
18992   Val = getSVESafeBitCast(ContainerSrcVT.changeTypeToInteger(), Val, DAG);
18993   Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
18994 
18995   Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
18996   return DAG.getNode(ISD::BITCAST, DL, VT, Val);
18997 }
18998 
18999 SDValue
19000 AArch64TargetLowering::LowerFixedLengthIntToFPToSVE(SDValue Op,
19001                                                     SelectionDAG &DAG) const {
19002   EVT VT = Op.getValueType();
19003   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19004 
19005   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
19006   unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
19007                              : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
19008 
19009   SDLoc DL(Op);
19010   SDValue Val = Op.getOperand(0);
19011   EVT SrcVT = Val.getValueType();
19012   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
19013   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
19014 
19015   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
19016       ContainerDstVT.getVectorElementType().getSizeInBits()) {
19017     SDValue Pg = getPredicateForVector(DAG, DL, VT);
19018 
19019     Val = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
19020                       VT.changeTypeToInteger(), Val);
19021 
19022     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19023     Val = getSVESafeBitCast(ContainerDstVT.changeTypeToInteger(), Val, DAG);
19024     // Safe to use a larger than specified operand since we just unpacked the
19025     // data, hence the upper bits are zero.
19026     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
19027                       DAG.getUNDEF(ContainerDstVT));
19028     return convertFromScalableVector(DAG, VT, Val);
19029   } else {
19030     EVT CvtVT = ContainerSrcVT.changeVectorElementType(
19031         ContainerDstVT.getVectorElementType());
19032     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
19033 
19034     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19035     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
19036     Val = getSVESafeBitCast(ContainerSrcVT, Val, DAG);
19037     Val = convertFromScalableVector(DAG, SrcVT, Val);
19038 
19039     Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
19040     return DAG.getNode(ISD::BITCAST, DL, VT, Val);
19041   }
19042 }
19043 
19044 SDValue
19045 AArch64TargetLowering::LowerFixedLengthFPToIntToSVE(SDValue Op,
19046                                                     SelectionDAG &DAG) const {
19047   EVT VT = Op.getValueType();
19048   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19049 
19050   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
19051   unsigned Opcode = IsSigned ? AArch64ISD::FCVTZS_MERGE_PASSTHRU
19052                              : AArch64ISD::FCVTZU_MERGE_PASSTHRU;
19053 
19054   SDLoc DL(Op);
19055   SDValue Val = Op.getOperand(0);
19056   EVT SrcVT = Val.getValueType();
19057   EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
19058   EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
19059 
19060   if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
19061       ContainerDstVT.getVectorElementType().getSizeInBits()) {
19062     EVT CvtVT = ContainerDstVT.changeVectorElementType(
19063       ContainerSrcVT.getVectorElementType());
19064     SDValue Pg = getPredicateForVector(DAG, DL, VT);
19065 
19066     Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
19067     Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Val);
19068 
19069     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19070     Val = getSVESafeBitCast(CvtVT, Val, DAG);
19071     Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
19072                       DAG.getUNDEF(ContainerDstVT));
19073     return convertFromScalableVector(DAG, VT, Val);
19074   } else {
19075     EVT CvtVT = ContainerSrcVT.changeTypeToInteger();
19076     SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
19077 
19078     // Safe to use a larger than specified result since an fp_to_int where the
19079     // result doesn't fit into the destination is undefined.
19080     Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
19081     Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
19082     Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
19083 
19084     return DAG.getNode(ISD::TRUNCATE, DL, VT, Val);
19085   }
19086 }
19087 
19088 SDValue AArch64TargetLowering::LowerFixedLengthVECTOR_SHUFFLEToSVE(
19089     SDValue Op, SelectionDAG &DAG) const {
19090   EVT VT = Op.getValueType();
19091   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
19092 
19093   auto *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
19094   auto ShuffleMask = SVN->getMask();
19095 
19096   SDLoc DL(Op);
19097   SDValue Op1 = Op.getOperand(0);
19098   SDValue Op2 = Op.getOperand(1);
19099 
19100   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
19101   Op1 = convertToScalableVector(DAG, ContainerVT, Op1);
19102   Op2 = convertToScalableVector(DAG, ContainerVT, Op2);
19103 
19104   bool ReverseEXT = false;
19105   unsigned Imm;
19106   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm) &&
19107       Imm == VT.getVectorNumElements() - 1) {
19108     if (ReverseEXT)
19109       std::swap(Op1, Op2);
19110 
19111     EVT ScalarTy = VT.getVectorElementType();
19112     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
19113       ScalarTy = MVT::i32;
19114     SDValue Scalar = DAG.getNode(
19115         ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
19116         DAG.getConstant(VT.getVectorNumElements() - 1, DL, MVT::i64));
19117     Op = DAG.getNode(AArch64ISD::INSR, DL, ContainerVT, Op2, Scalar);
19118     return convertFromScalableVector(DAG, VT, Op);
19119   }
19120 
19121   return SDValue();
19122 }
19123 
19124 SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
19125                                                  SelectionDAG &DAG) const {
19126   SDLoc DL(Op);
19127   EVT InVT = Op.getValueType();
19128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19129   (void)TLI;
19130 
19131   assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
19132          InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
19133          "Only expect to cast between legal scalable vector types!");
19134   assert((VT.getVectorElementType() == MVT::i1) ==
19135              (InVT.getVectorElementType() == MVT::i1) &&
19136          "Cannot cast between data and predicate scalable vector types!");
19137 
19138   if (InVT == VT)
19139     return Op;
19140 
19141   if (VT.getVectorElementType() == MVT::i1)
19142     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
19143 
19144   EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
19145   EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
19146 
19147   // Pack input if required.
19148   if (InVT != PackedInVT)
19149     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
19150 
19151   Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
19152 
19153   // Unpack result if required.
19154   if (VT != PackedVT)
19155     Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
19156 
19157   return Op;
19158 }
19159 
19160 bool AArch64TargetLowering::isAllActivePredicate(SDValue N) const {
19161   return ::isAllActivePredicate(N);
19162 }
19163 
19164 EVT AArch64TargetLowering::getPromotedVTForPredicate(EVT VT) const {
19165   return ::getPromotedVTForPredicate(VT);
19166 }
19167 
19168 bool AArch64TargetLowering::SimplifyDemandedBitsForTargetNode(
19169     SDValue Op, const APInt &OriginalDemandedBits,
19170     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
19171     unsigned Depth) const {
19172 
19173   unsigned Opc = Op.getOpcode();
19174   switch (Opc) {
19175   case AArch64ISD::VSHL: {
19176     // Match (VSHL (VLSHR Val X) X)
19177     SDValue ShiftL = Op;
19178     SDValue ShiftR = Op->getOperand(0);
19179     if (ShiftR->getOpcode() != AArch64ISD::VLSHR)
19180       return false;
19181 
19182     if (!ShiftL.hasOneUse() || !ShiftR.hasOneUse())
19183       return false;
19184 
19185     unsigned ShiftLBits = ShiftL->getConstantOperandVal(1);
19186     unsigned ShiftRBits = ShiftR->getConstantOperandVal(1);
19187 
19188     // Other cases can be handled as well, but this is not
19189     // implemented.
19190     if (ShiftRBits != ShiftLBits)
19191       return false;
19192 
19193     unsigned ScalarSize = Op.getScalarValueSizeInBits();
19194     assert(ScalarSize > ShiftLBits && "Invalid shift imm");
19195 
19196     APInt ZeroBits = APInt::getLowBitsSet(ScalarSize, ShiftLBits);
19197     APInt UnusedBits = ~OriginalDemandedBits;
19198 
19199     if ((ZeroBits & UnusedBits) != ZeroBits)
19200       return false;
19201 
19202     // All bits that are zeroed by (VSHL (VLSHR Val X) X) are not
19203     // used - simplify to just Val.
19204     return TLO.CombineTo(Op, ShiftR->getOperand(0));
19205   }
19206   }
19207 
19208   return TargetLowering::SimplifyDemandedBitsForTargetNode(
19209       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
19210 }
19211 
19212 bool AArch64TargetLowering::isConstantUnsignedBitfieldExtactLegal(
19213     unsigned Opc, LLT Ty1, LLT Ty2) const {
19214   return Ty1 == Ty2 && (Ty1 == LLT::scalar(32) || Ty1 == LLT::scalar(64));
19215 }
19216