1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64ExpandImm.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/IntrinsicsAArch64.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/OperandTraits.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/MC/MCRegisterInfo.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CodeGen.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Target/TargetMachine.h"
80 #include "llvm/Target/TargetOptions.h"
81 #include <algorithm>
82 #include <bitset>
83 #include <cassert>
84 #include <cctype>
85 #include <cstdint>
86 #include <cstdlib>
87 #include <iterator>
88 #include <limits>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
92 
93 using namespace llvm;
94 using namespace llvm::PatternMatch;
95 
96 #define DEBUG_TYPE "aarch64-lower"
97 
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
119 static inline EVT getPackedSVEVectorVT(EVT VT) {
120   switch (VT.getSimpleVT().SimpleTy) {
121   default:
122     llvm_unreachable("unexpected element type for vector");
123   case MVT::i8:
124     return MVT::nxv16i8;
125   case MVT::i16:
126     return MVT::nxv8i16;
127   case MVT::i32:
128     return MVT::nxv4i32;
129   case MVT::i64:
130     return MVT::nxv2i64;
131   case MVT::f16:
132     return MVT::nxv8f16;
133   case MVT::f32:
134     return MVT::nxv4f32;
135   case MVT::f64:
136     return MVT::nxv2f64;
137   }
138 }
139 
140 static inline MVT getPromotedVTForPredicate(MVT VT) {
141   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
142          "Expected scalable predicate vector type!");
143   switch (VT.getVectorMinNumElements()) {
144   default:
145     llvm_unreachable("unexpected element count for vector");
146   case 2:
147     return MVT::nxv2i64;
148   case 4:
149     return MVT::nxv4i32;
150   case 8:
151     return MVT::nxv8i16;
152   case 16:
153     return MVT::nxv16i8;
154   }
155 }
156 
157 /// Returns true if VT's elements occupy the lowest bit positions of its
158 /// associated register class without any intervening space.
159 ///
160 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
161 /// same register class, but only nxv8f16 can be treated as a packed vector.
162 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
163   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
164          "Expected legal vector type!");
165   return VT.isFixedLengthVector() ||
166          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
167 }
168 
169 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
170 // predicate and end with a passthru value matching the result type.
171 static bool isMergePassthruOpcode(unsigned Opc) {
172   switch (Opc) {
173   default:
174     return false;
175   case AArch64ISD::DUP_MERGE_PASSTHRU:
176   case AArch64ISD::FNEG_MERGE_PASSTHRU:
177   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
178   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
179   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
180   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
181   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
182   case AArch64ISD::FRINT_MERGE_PASSTHRU:
183   case AArch64ISD::FROUND_MERGE_PASSTHRU:
184   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
185   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
186   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
187   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
188   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
189   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
190   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
191   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
192   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
193   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
194   case AArch64ISD::FABS_MERGE_PASSTHRU:
195     return true;
196   }
197 }
198 
199 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
200                                              const AArch64Subtarget &STI)
201     : TargetLowering(TM), Subtarget(&STI) {
202   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
203   // we have to make something up. Arbitrarily, choose ZeroOrOne.
204   setBooleanContents(ZeroOrOneBooleanContent);
205   // When comparing vectors the result sets the different elements in the
206   // vector to all-one or all-zero.
207   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
208 
209   // Set up the register classes.
210   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
211   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
212 
213   if (Subtarget->hasFPARMv8()) {
214     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
215     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
216     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
217     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
218     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
219   }
220 
221   if (Subtarget->hasNEON()) {
222     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
223     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
224     // Someone set us up the NEON.
225     addDRTypeForNEON(MVT::v2f32);
226     addDRTypeForNEON(MVT::v8i8);
227     addDRTypeForNEON(MVT::v4i16);
228     addDRTypeForNEON(MVT::v2i32);
229     addDRTypeForNEON(MVT::v1i64);
230     addDRTypeForNEON(MVT::v1f64);
231     addDRTypeForNEON(MVT::v4f16);
232     if (Subtarget->hasBF16())
233       addDRTypeForNEON(MVT::v4bf16);
234 
235     addQRTypeForNEON(MVT::v4f32);
236     addQRTypeForNEON(MVT::v2f64);
237     addQRTypeForNEON(MVT::v16i8);
238     addQRTypeForNEON(MVT::v8i16);
239     addQRTypeForNEON(MVT::v4i32);
240     addQRTypeForNEON(MVT::v2i64);
241     addQRTypeForNEON(MVT::v8f16);
242     if (Subtarget->hasBF16())
243       addQRTypeForNEON(MVT::v8bf16);
244   }
245 
246   if (Subtarget->hasSVE()) {
247     // Add legal sve predicate types
248     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
249     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
250     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
251     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
252 
253     // Add legal sve data types
254     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
255     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
256     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
257     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
258 
259     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
260     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
261     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
262     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
263     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
264     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
265 
266     if (Subtarget->hasBF16()) {
267       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
268       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
269       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
270     }
271 
272     if (useSVEForFixedLengthVectors()) {
273       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
274         if (useSVEForFixedLengthVectorVT(VT))
275           addRegisterClass(VT, &AArch64::ZPRRegClass);
276 
277       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
278         if (useSVEForFixedLengthVectorVT(VT))
279           addRegisterClass(VT, &AArch64::ZPRRegClass);
280     }
281 
282     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
283       setOperationAction(ISD::SADDSAT, VT, Legal);
284       setOperationAction(ISD::UADDSAT, VT, Legal);
285       setOperationAction(ISD::SSUBSAT, VT, Legal);
286       setOperationAction(ISD::USUBSAT, VT, Legal);
287       setOperationAction(ISD::UREM, VT, Expand);
288       setOperationAction(ISD::SREM, VT, Expand);
289       setOperationAction(ISD::SDIVREM, VT, Expand);
290       setOperationAction(ISD::UDIVREM, VT, Expand);
291     }
292 
293     for (auto VT :
294          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
295            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
296       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
297 
298     for (auto VT :
299          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
300            MVT::nxv2f64 }) {
301       setCondCodeAction(ISD::SETO, VT, Expand);
302       setCondCodeAction(ISD::SETOLT, VT, Expand);
303       setCondCodeAction(ISD::SETLT, VT, Expand);
304       setCondCodeAction(ISD::SETOLE, VT, Expand);
305       setCondCodeAction(ISD::SETLE, VT, Expand);
306       setCondCodeAction(ISD::SETULT, VT, Expand);
307       setCondCodeAction(ISD::SETULE, VT, Expand);
308       setCondCodeAction(ISD::SETUGE, VT, Expand);
309       setCondCodeAction(ISD::SETUGT, VT, Expand);
310       setCondCodeAction(ISD::SETUEQ, VT, Expand);
311       setCondCodeAction(ISD::SETUNE, VT, Expand);
312     }
313   }
314 
315   // Compute derived properties from the register classes
316   computeRegisterProperties(Subtarget->getRegisterInfo());
317 
318   // Provide all sorts of operation actions
319   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
320   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
321   setOperationAction(ISD::SETCC, MVT::i32, Custom);
322   setOperationAction(ISD::SETCC, MVT::i64, Custom);
323   setOperationAction(ISD::SETCC, MVT::f16, Custom);
324   setOperationAction(ISD::SETCC, MVT::f32, Custom);
325   setOperationAction(ISD::SETCC, MVT::f64, Custom);
326   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
327   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
328   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
329   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
330   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
331   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
332   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
333   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
334   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
335   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
336   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
337   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
338   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
339   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
340   setOperationAction(ISD::SELECT, MVT::i32, Custom);
341   setOperationAction(ISD::SELECT, MVT::i64, Custom);
342   setOperationAction(ISD::SELECT, MVT::f16, Custom);
343   setOperationAction(ISD::SELECT, MVT::f32, Custom);
344   setOperationAction(ISD::SELECT, MVT::f64, Custom);
345   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
346   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
347   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
348   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
349   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
350   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
351   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
352 
353   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
354   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
355   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
356 
357   setOperationAction(ISD::FREM, MVT::f32, Expand);
358   setOperationAction(ISD::FREM, MVT::f64, Expand);
359   setOperationAction(ISD::FREM, MVT::f80, Expand);
360 
361   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
362 
363   // Custom lowering hooks are needed for XOR
364   // to fold it into CSINC/CSINV.
365   setOperationAction(ISD::XOR, MVT::i32, Custom);
366   setOperationAction(ISD::XOR, MVT::i64, Custom);
367 
368   // Virtually no operation on f128 is legal, but LLVM can't expand them when
369   // there's a valid register class, so we need custom operations in most cases.
370   setOperationAction(ISD::FABS, MVT::f128, Expand);
371   setOperationAction(ISD::FADD, MVT::f128, Custom);
372   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
373   setOperationAction(ISD::FCOS, MVT::f128, Expand);
374   setOperationAction(ISD::FDIV, MVT::f128, Custom);
375   setOperationAction(ISD::FMA, MVT::f128, Expand);
376   setOperationAction(ISD::FMUL, MVT::f128, Custom);
377   setOperationAction(ISD::FNEG, MVT::f128, Expand);
378   setOperationAction(ISD::FPOW, MVT::f128, Expand);
379   setOperationAction(ISD::FREM, MVT::f128, Expand);
380   setOperationAction(ISD::FRINT, MVT::f128, Expand);
381   setOperationAction(ISD::FSIN, MVT::f128, Expand);
382   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
383   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
384   setOperationAction(ISD::FSUB, MVT::f128, Custom);
385   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
386   setOperationAction(ISD::SETCC, MVT::f128, Custom);
387   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
388   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
389   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
390   setOperationAction(ISD::SELECT, MVT::f128, Custom);
391   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
392   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
393 
394   // Lowering for many of the conversions is actually specified by the non-f128
395   // type. The LowerXXX function will be trivial when f128 isn't involved.
396   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
397   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
398   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
399   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
400   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
401   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
402   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
403   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
404   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
405   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
406   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
407   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
408   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
409   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
410   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
411   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
412   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
413   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
414   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
415   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
416   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
417   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
418   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
419   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
420   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
421   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
422   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
423   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
424 
425   // Variable arguments.
426   setOperationAction(ISD::VASTART, MVT::Other, Custom);
427   setOperationAction(ISD::VAARG, MVT::Other, Custom);
428   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
429   setOperationAction(ISD::VAEND, MVT::Other, Expand);
430 
431   // Variable-sized objects.
432   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
433   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
434 
435   if (Subtarget->isTargetWindows())
436     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
437   else
438     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
439 
440   // Constant pool entries
441   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
442 
443   // BlockAddress
444   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
445 
446   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
447   setOperationAction(ISD::ADDC, MVT::i32, Custom);
448   setOperationAction(ISD::ADDE, MVT::i32, Custom);
449   setOperationAction(ISD::SUBC, MVT::i32, Custom);
450   setOperationAction(ISD::SUBE, MVT::i32, Custom);
451   setOperationAction(ISD::ADDC, MVT::i64, Custom);
452   setOperationAction(ISD::ADDE, MVT::i64, Custom);
453   setOperationAction(ISD::SUBC, MVT::i64, Custom);
454   setOperationAction(ISD::SUBE, MVT::i64, Custom);
455 
456   // AArch64 lacks both left-rotate and popcount instructions.
457   setOperationAction(ISD::ROTL, MVT::i32, Expand);
458   setOperationAction(ISD::ROTL, MVT::i64, Expand);
459   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
460     setOperationAction(ISD::ROTL, VT, Expand);
461     setOperationAction(ISD::ROTR, VT, Expand);
462   }
463 
464   // AArch64 doesn't have i32 MULH{S|U}.
465   setOperationAction(ISD::MULHU, MVT::i32, Expand);
466   setOperationAction(ISD::MULHS, MVT::i32, Expand);
467 
468   // AArch64 doesn't have {U|S}MUL_LOHI.
469   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
470   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
471 
472   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
473   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
474   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
475 
476   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
477   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
478   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
479     setOperationAction(ISD::SDIVREM, VT, Expand);
480     setOperationAction(ISD::UDIVREM, VT, Expand);
481   }
482   setOperationAction(ISD::SREM, MVT::i32, Expand);
483   setOperationAction(ISD::SREM, MVT::i64, Expand);
484   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
485   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
486   setOperationAction(ISD::UREM, MVT::i32, Expand);
487   setOperationAction(ISD::UREM, MVT::i64, Expand);
488 
489   // Custom lower Add/Sub/Mul with overflow.
490   setOperationAction(ISD::SADDO, MVT::i32, Custom);
491   setOperationAction(ISD::SADDO, MVT::i64, Custom);
492   setOperationAction(ISD::UADDO, MVT::i32, Custom);
493   setOperationAction(ISD::UADDO, MVT::i64, Custom);
494   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
495   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
496   setOperationAction(ISD::USUBO, MVT::i32, Custom);
497   setOperationAction(ISD::USUBO, MVT::i64, Custom);
498   setOperationAction(ISD::SMULO, MVT::i32, Custom);
499   setOperationAction(ISD::SMULO, MVT::i64, Custom);
500   setOperationAction(ISD::UMULO, MVT::i32, Custom);
501   setOperationAction(ISD::UMULO, MVT::i64, Custom);
502 
503   setOperationAction(ISD::FSIN, MVT::f32, Expand);
504   setOperationAction(ISD::FSIN, MVT::f64, Expand);
505   setOperationAction(ISD::FCOS, MVT::f32, Expand);
506   setOperationAction(ISD::FCOS, MVT::f64, Expand);
507   setOperationAction(ISD::FPOW, MVT::f32, Expand);
508   setOperationAction(ISD::FPOW, MVT::f64, Expand);
509   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
510   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
511   if (Subtarget->hasFullFP16())
512     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
513   else
514     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
515 
516   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
517   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
518   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
519   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
520   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
521   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
522   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
523   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
524   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
525   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
526   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
527   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
528   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
529   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
530   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
531   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
532   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
533   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
534   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
535   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
536   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
537   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
538   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
539   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
540   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
541   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
542   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
543   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
544   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
545   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
546   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
547   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
548   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
549 
550   if (!Subtarget->hasFullFP16()) {
551     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
552     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
553     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
554     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
555     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
556     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
557     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
558     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
559     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
560     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
561     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
562     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
563     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
564     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
565     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
566     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
567     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
568     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
569     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
570     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
571     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
572     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
573 
574     // promote v4f16 to v4f32 when that is known to be safe.
575     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
576     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
577     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
578     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
579     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
580     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
581     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
582     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
583 
584     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
585     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
586     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
587     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
588     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
589     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
590     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
591     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
592     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
593     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
594     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
595     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
596     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
597     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
598     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
599 
600     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
601     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
602     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
603     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
604     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
605     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
606     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
607     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
608     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
609     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
610     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
611     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
612     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
613     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
614     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
615     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
616     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
617     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
618     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
619     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
620   }
621 
622   // AArch64 has implementations of a lot of rounding-like FP operations.
623   for (MVT Ty : {MVT::f32, MVT::f64}) {
624     setOperationAction(ISD::FFLOOR, Ty, Legal);
625     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
626     setOperationAction(ISD::FCEIL, Ty, Legal);
627     setOperationAction(ISD::FRINT, Ty, Legal);
628     setOperationAction(ISD::FTRUNC, Ty, Legal);
629     setOperationAction(ISD::FROUND, Ty, Legal);
630     setOperationAction(ISD::FMINNUM, Ty, Legal);
631     setOperationAction(ISD::FMAXNUM, Ty, Legal);
632     setOperationAction(ISD::FMINIMUM, Ty, Legal);
633     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
634     setOperationAction(ISD::LROUND, Ty, Legal);
635     setOperationAction(ISD::LLROUND, Ty, Legal);
636     setOperationAction(ISD::LRINT, Ty, Legal);
637     setOperationAction(ISD::LLRINT, Ty, Legal);
638   }
639 
640   if (Subtarget->hasFullFP16()) {
641     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
642     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
643     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
644     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
645     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
646     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
647     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
648     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
649     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
650     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
651   }
652 
653   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
654 
655   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
656 
657   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
658   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
659   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
660   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
661   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
662 
663   // 128-bit loads and stores can be done without expanding
664   setOperationAction(ISD::LOAD, MVT::i128, Custom);
665   setOperationAction(ISD::STORE, MVT::i128, Custom);
666 
667   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
668   // custom lowering, as there are no un-paired non-temporal stores and
669   // legalization will break up 256 bit inputs.
670   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
671   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
672   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
673   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
674   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
675   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
676   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
677 
678   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
679   // This requires the Performance Monitors extension.
680   if (Subtarget->hasPerfMon())
681     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
682 
683   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
684       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
685     // Issue __sincos_stret if available.
686     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
687     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
688   } else {
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
691   }
692 
693   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
694     // MSVCRT doesn't have powi; fall back to pow
695     setLibcallName(RTLIB::POWI_F32, nullptr);
696     setLibcallName(RTLIB::POWI_F64, nullptr);
697   }
698 
699   // Make floating-point constants legal for the large code model, so they don't
700   // become loads from the constant pool.
701   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
702     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
703     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
704   }
705 
706   // AArch64 does not have floating-point extending loads, i1 sign-extending
707   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
708   for (MVT VT : MVT::fp_valuetypes()) {
709     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
710     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
711     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
712     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
713   }
714   for (MVT VT : MVT::integer_valuetypes())
715     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
716 
717   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
718   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
719   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
720   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
721   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
722   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
723   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
724 
725   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
726   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
727   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
728 
729   // Indexed loads and stores are supported.
730   for (unsigned im = (unsigned)ISD::PRE_INC;
731        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
732     setIndexedLoadAction(im, MVT::i8, Legal);
733     setIndexedLoadAction(im, MVT::i16, Legal);
734     setIndexedLoadAction(im, MVT::i32, Legal);
735     setIndexedLoadAction(im, MVT::i64, Legal);
736     setIndexedLoadAction(im, MVT::f64, Legal);
737     setIndexedLoadAction(im, MVT::f32, Legal);
738     setIndexedLoadAction(im, MVT::f16, Legal);
739     setIndexedLoadAction(im, MVT::bf16, Legal);
740     setIndexedStoreAction(im, MVT::i8, Legal);
741     setIndexedStoreAction(im, MVT::i16, Legal);
742     setIndexedStoreAction(im, MVT::i32, Legal);
743     setIndexedStoreAction(im, MVT::i64, Legal);
744     setIndexedStoreAction(im, MVT::f64, Legal);
745     setIndexedStoreAction(im, MVT::f32, Legal);
746     setIndexedStoreAction(im, MVT::f16, Legal);
747     setIndexedStoreAction(im, MVT::bf16, Legal);
748   }
749 
750   // Trap.
751   setOperationAction(ISD::TRAP, MVT::Other, Legal);
752   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
753 
754   // We combine OR nodes for bitfield operations.
755   setTargetDAGCombine(ISD::OR);
756   // Try to create BICs for vector ANDs.
757   setTargetDAGCombine(ISD::AND);
758 
759   // Vector add and sub nodes may conceal a high-half opportunity.
760   // Also, try to fold ADD into CSINC/CSINV..
761   setTargetDAGCombine(ISD::ADD);
762   setTargetDAGCombine(ISD::ABS);
763   setTargetDAGCombine(ISD::SUB);
764   setTargetDAGCombine(ISD::SRL);
765   setTargetDAGCombine(ISD::XOR);
766   setTargetDAGCombine(ISD::SINT_TO_FP);
767   setTargetDAGCombine(ISD::UINT_TO_FP);
768 
769   setTargetDAGCombine(ISD::FP_TO_SINT);
770   setTargetDAGCombine(ISD::FP_TO_UINT);
771   setTargetDAGCombine(ISD::FDIV);
772 
773   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
774 
775   setTargetDAGCombine(ISD::ANY_EXTEND);
776   setTargetDAGCombine(ISD::ZERO_EXTEND);
777   setTargetDAGCombine(ISD::SIGN_EXTEND);
778   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
779   setTargetDAGCombine(ISD::TRUNCATE);
780   setTargetDAGCombine(ISD::CONCAT_VECTORS);
781   setTargetDAGCombine(ISD::STORE);
782   if (Subtarget->supportsAddressTopByteIgnored())
783     setTargetDAGCombine(ISD::LOAD);
784 
785   setTargetDAGCombine(ISD::MUL);
786 
787   setTargetDAGCombine(ISD::SELECT);
788   setTargetDAGCombine(ISD::VSELECT);
789 
790   setTargetDAGCombine(ISD::INTRINSIC_VOID);
791   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
792   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
793   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
794   setTargetDAGCombine(ISD::VECREDUCE_ADD);
795 
796   setTargetDAGCombine(ISD::GlobalAddress);
797 
798   // In case of strict alignment, avoid an excessive number of byte wide stores.
799   MaxStoresPerMemsetOptSize = 8;
800   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
801                        ? MaxStoresPerMemsetOptSize : 32;
802 
803   MaxGluedStoresPerMemcpy = 4;
804   MaxStoresPerMemcpyOptSize = 4;
805   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
806                        ? MaxStoresPerMemcpyOptSize : 16;
807 
808   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
809 
810   MaxLoadsPerMemcmpOptSize = 4;
811   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
812                       ? MaxLoadsPerMemcmpOptSize : 8;
813 
814   setStackPointerRegisterToSaveRestore(AArch64::SP);
815 
816   setSchedulingPreference(Sched::Hybrid);
817 
818   EnableExtLdPromotion = true;
819 
820   // Set required alignment.
821   setMinFunctionAlignment(Align(4));
822   // Set preferred alignments.
823   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
824   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
825 
826   // Only change the limit for entries in a jump table if specified by
827   // the sub target, but not at the command line.
828   unsigned MaxJT = STI.getMaximumJumpTableSize();
829   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
830     setMaximumJumpTableSize(MaxJT);
831 
832   setHasExtractBitsInsn(true);
833 
834   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
835 
836   if (Subtarget->hasNEON()) {
837     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
838     // silliness like this:
839     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
840     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
841     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
842     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
843     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
844     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
845     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
846     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
847     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
848     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
849     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
850     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
851     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
852     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
853     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
854     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
855     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
856     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
857     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
858     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
859     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
860     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
861     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
862     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
863     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
864 
865     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
866     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
867     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
868     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
869     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
870 
871     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
872 
873     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
874     // elements smaller than i32, so promote the input to i32 first.
875     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
876     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
877     // i8 vector elements also need promotion to i32 for v8i8
878     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
879     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
880     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
881     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
882     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
883     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
884     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
885     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
886     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
887     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
888     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
889 
890     if (Subtarget->hasFullFP16()) {
891       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
892       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
893       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
894       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
895     } else {
896       // when AArch64 doesn't have fullfp16 support, promote the input
897       // to i32 first.
898       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
899       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
900       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
901       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
902     }
903 
904     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
905     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
906 
907     // AArch64 doesn't have MUL.2d:
908     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
909     // Custom handling for some quad-vector types to detect MULL.
910     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
911     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
912     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
913 
914     // Saturates
915     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
916                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
917       setOperationAction(ISD::SADDSAT, VT, Legal);
918       setOperationAction(ISD::UADDSAT, VT, Legal);
919       setOperationAction(ISD::SSUBSAT, VT, Legal);
920       setOperationAction(ISD::USUBSAT, VT, Legal);
921     }
922 
923     // Vector reductions
924     for (MVT VT : { MVT::v4f16, MVT::v2f32,
925                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
926       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
927       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
928     }
929     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
930                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
931       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
932       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
933       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
934       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
935       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
936     }
937     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
938 
939     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
940     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
941     // Likewise, narrowing and extending vector loads/stores aren't handled
942     // directly.
943     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
944       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
945 
946       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
947         setOperationAction(ISD::MULHS, VT, Legal);
948         setOperationAction(ISD::MULHU, VT, Legal);
949       } else {
950         setOperationAction(ISD::MULHS, VT, Expand);
951         setOperationAction(ISD::MULHU, VT, Expand);
952       }
953       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
954       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
955 
956       setOperationAction(ISD::BSWAP, VT, Expand);
957       setOperationAction(ISD::CTTZ, VT, Expand);
958 
959       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
960         setTruncStoreAction(VT, InnerVT, Expand);
961         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
962         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
963         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
964       }
965     }
966 
967     // AArch64 has implementations of a lot of rounding-like FP operations.
968     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
969       setOperationAction(ISD::FFLOOR, Ty, Legal);
970       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
971       setOperationAction(ISD::FCEIL, Ty, Legal);
972       setOperationAction(ISD::FRINT, Ty, Legal);
973       setOperationAction(ISD::FTRUNC, Ty, Legal);
974       setOperationAction(ISD::FROUND, Ty, Legal);
975     }
976 
977     if (Subtarget->hasFullFP16()) {
978       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
979         setOperationAction(ISD::FFLOOR, Ty, Legal);
980         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
981         setOperationAction(ISD::FCEIL, Ty, Legal);
982         setOperationAction(ISD::FRINT, Ty, Legal);
983         setOperationAction(ISD::FTRUNC, Ty, Legal);
984         setOperationAction(ISD::FROUND, Ty, Legal);
985       }
986     }
987 
988     if (Subtarget->hasSVE())
989       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
990 
991     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
992   }
993 
994   if (Subtarget->hasSVE()) {
995     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
996     // splat of 0 or undef) once vector selects supported in SVE codegen. See
997     // D68877 for more details.
998     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
999       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1000       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1001       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1002       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1003       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1004       setOperationAction(ISD::MUL, VT, Custom);
1005       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1006       setOperationAction(ISD::SELECT, VT, Custom);
1007       setOperationAction(ISD::SDIV, VT, Custom);
1008       setOperationAction(ISD::UDIV, VT, Custom);
1009       setOperationAction(ISD::SMIN, VT, Custom);
1010       setOperationAction(ISD::UMIN, VT, Custom);
1011       setOperationAction(ISD::SMAX, VT, Custom);
1012       setOperationAction(ISD::UMAX, VT, Custom);
1013       setOperationAction(ISD::SHL, VT, Custom);
1014       setOperationAction(ISD::SRL, VT, Custom);
1015       setOperationAction(ISD::SRA, VT, Custom);
1016     }
1017 
1018     // Illegal unpacked integer vector types.
1019     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1020       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1021       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1022     }
1023 
1024     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1025       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1026       setOperationAction(ISD::SELECT, VT, Custom);
1027       setOperationAction(ISD::SETCC, VT, Custom);
1028       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1029       setOperationAction(ISD::TRUNCATE, VT, Custom);
1030 
1031       // There are no legal MVT::nxv16f## based types.
1032       if (VT != MVT::nxv16i1) {
1033         setOperationAction(ISD::SINT_TO_FP, VT, Promote);
1034         AddPromotedToType(ISD::SINT_TO_FP, VT, getPromotedVTForPredicate(VT));
1035         setOperationAction(ISD::UINT_TO_FP, VT, Promote);
1036         AddPromotedToType(ISD::UINT_TO_FP, VT, getPromotedVTForPredicate(VT));
1037       }
1038     }
1039 
1040     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1041                     MVT::nxv4f32, MVT::nxv2f64}) {
1042       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1043       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1044       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1045       setOperationAction(ISD::SELECT, VT, Custom);
1046       setOperationAction(ISD::FADD, VT, Custom);
1047       setOperationAction(ISD::FDIV, VT, Custom);
1048       setOperationAction(ISD::FMA, VT, Custom);
1049       setOperationAction(ISD::FMUL, VT, Custom);
1050       setOperationAction(ISD::FNEG, VT, Custom);
1051       setOperationAction(ISD::FSUB, VT, Custom);
1052       setOperationAction(ISD::FCEIL, VT, Custom);
1053       setOperationAction(ISD::FFLOOR, VT, Custom);
1054       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1055       setOperationAction(ISD::FRINT, VT, Custom);
1056       setOperationAction(ISD::FROUND, VT, Custom);
1057       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1058       setOperationAction(ISD::FTRUNC, VT, Custom);
1059       setOperationAction(ISD::FSQRT, VT, Custom);
1060       setOperationAction(ISD::FABS, VT, Custom);
1061       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1062       setOperationAction(ISD::FP_ROUND, VT, Custom);
1063     }
1064 
1065     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1066 
1067     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1068     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1069 
1070     // NOTE: Currently this has to happen after computeRegisterProperties rather
1071     // than the preferred option of combining it with the addRegisterClass call.
1072     if (useSVEForFixedLengthVectors()) {
1073       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1074         if (useSVEForFixedLengthVectorVT(VT))
1075           addTypeForFixedLengthSVE(VT);
1076       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1077         if (useSVEForFixedLengthVectorVT(VT))
1078           addTypeForFixedLengthSVE(VT);
1079 
1080       // 64bit results can mean a bigger than NEON input.
1081       for (auto VT : {MVT::v8i8, MVT::v4i16})
1082         setOperationAction(ISD::TRUNCATE, VT, Custom);
1083       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1084 
1085       // 128bit results imply a bigger than NEON input.
1086       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1087         setOperationAction(ISD::TRUNCATE, VT, Custom);
1088       for (auto VT : {MVT::v8f16, MVT::v4f32})
1089         setOperationAction(ISD::FP_ROUND, VT, Expand);
1090 
1091       // These operations are not supported on NEON but SVE can do them.
1092       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1093       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1094       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1095       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1096       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1097       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1098       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1099       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1100       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1101       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1102       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1103       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1104       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1105       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1106       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1107       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1108       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1109       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1110       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1111       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1112       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1113       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1114       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1115       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1116       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1117       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1118       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1119       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1120       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1121       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1122       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1123                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1124         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1125         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1126         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1127       }
1128 
1129       // Use SVE for vectors with more than 2 elements.
1130       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1131         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1132     }
1133   }
1134 
1135   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1136 }
1137 
1138 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
1139   assert(VT.isVector() && "VT should be a vector type");
1140 
1141   if (VT.isFloatingPoint()) {
1142     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1143     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1144     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1145   }
1146 
1147   // Mark vector float intrinsics as expand.
1148   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1149     setOperationAction(ISD::FSIN, VT, Expand);
1150     setOperationAction(ISD::FCOS, VT, Expand);
1151     setOperationAction(ISD::FPOW, VT, Expand);
1152     setOperationAction(ISD::FLOG, VT, Expand);
1153     setOperationAction(ISD::FLOG2, VT, Expand);
1154     setOperationAction(ISD::FLOG10, VT, Expand);
1155     setOperationAction(ISD::FEXP, VT, Expand);
1156     setOperationAction(ISD::FEXP2, VT, Expand);
1157 
1158     // But we do support custom-lowering for FCOPYSIGN.
1159     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1160   }
1161 
1162   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1163   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1164   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1165   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1166   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1167   setOperationAction(ISD::SRA, VT, Custom);
1168   setOperationAction(ISD::SRL, VT, Custom);
1169   setOperationAction(ISD::SHL, VT, Custom);
1170   setOperationAction(ISD::OR, VT, Custom);
1171   setOperationAction(ISD::SETCC, VT, Custom);
1172   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1173 
1174   setOperationAction(ISD::SELECT, VT, Expand);
1175   setOperationAction(ISD::SELECT_CC, VT, Expand);
1176   setOperationAction(ISD::VSELECT, VT, Expand);
1177   for (MVT InnerVT : MVT::all_valuetypes())
1178     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1179 
1180   // CNT supports only B element sizes, then use UADDLP to widen.
1181   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1182     setOperationAction(ISD::CTPOP, VT, Custom);
1183 
1184   setOperationAction(ISD::UDIV, VT, Expand);
1185   setOperationAction(ISD::SDIV, VT, Expand);
1186   setOperationAction(ISD::UREM, VT, Expand);
1187   setOperationAction(ISD::SREM, VT, Expand);
1188   setOperationAction(ISD::FREM, VT, Expand);
1189 
1190   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1191   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1192 
1193   if (!VT.isFloatingPoint())
1194     setOperationAction(ISD::ABS, VT, Legal);
1195 
1196   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1197   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1198     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1199       setOperationAction(Opcode, VT, Legal);
1200 
1201   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1202   if (VT.isFloatingPoint() &&
1203       VT.getVectorElementType() != MVT::bf16 &&
1204       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1205     for (unsigned Opcode :
1206          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1207       setOperationAction(Opcode, VT, Legal);
1208 
1209   if (Subtarget->isLittleEndian()) {
1210     for (unsigned im = (unsigned)ISD::PRE_INC;
1211          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1212       setIndexedLoadAction(im, VT, Legal);
1213       setIndexedStoreAction(im, VT, Legal);
1214     }
1215   }
1216 }
1217 
1218 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1219   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1220 
1221   // By default everything must be expanded.
1222   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1223     setOperationAction(Op, VT, Expand);
1224 
1225   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1226   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1227 
1228   // Lower fixed length vector operations to scalable equivalents.
1229   setOperationAction(ISD::ADD, VT, Custom);
1230   setOperationAction(ISD::AND, VT, Custom);
1231   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1232   setOperationAction(ISD::FADD, VT, Custom);
1233   setOperationAction(ISD::FCEIL, VT, Custom);
1234   setOperationAction(ISD::FDIV, VT, Custom);
1235   setOperationAction(ISD::FFLOOR, VT, Custom);
1236   setOperationAction(ISD::FMA, VT, Custom);
1237   setOperationAction(ISD::FMAXNUM, VT, Custom);
1238   setOperationAction(ISD::FMINNUM, VT, Custom);
1239   setOperationAction(ISD::FMUL, VT, Custom);
1240   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1241   setOperationAction(ISD::FNEG, VT, Custom);
1242   setOperationAction(ISD::FRINT, VT, Custom);
1243   setOperationAction(ISD::FROUND, VT, Custom);
1244   setOperationAction(ISD::FSQRT, VT, Custom);
1245   setOperationAction(ISD::FSUB, VT, Custom);
1246   setOperationAction(ISD::FTRUNC, VT, Custom);
1247   setOperationAction(ISD::LOAD, VT, Custom);
1248   setOperationAction(ISD::MUL, VT, Custom);
1249   setOperationAction(ISD::OR, VT, Custom);
1250   setOperationAction(ISD::SDIV, VT, Custom);
1251   setOperationAction(ISD::SETCC, VT, Custom);
1252   setOperationAction(ISD::SHL, VT, Custom);
1253   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1254   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1255   setOperationAction(ISD::SMAX, VT, Custom);
1256   setOperationAction(ISD::SMIN, VT, Custom);
1257   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1258   setOperationAction(ISD::SRA, VT, Custom);
1259   setOperationAction(ISD::SRL, VT, Custom);
1260   setOperationAction(ISD::STORE, VT, Custom);
1261   setOperationAction(ISD::SUB, VT, Custom);
1262   setOperationAction(ISD::TRUNCATE, VT, Custom);
1263   setOperationAction(ISD::UDIV, VT, Custom);
1264   setOperationAction(ISD::UMAX, VT, Custom);
1265   setOperationAction(ISD::UMIN, VT, Custom);
1266   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1267   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1268   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1269   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1270   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1271   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1272   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1273   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1274   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1275   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1276   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1277   setOperationAction(ISD::VSELECT, VT, Custom);
1278   setOperationAction(ISD::XOR, VT, Custom);
1279   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1280 }
1281 
1282 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1283   addRegisterClass(VT, &AArch64::FPR64RegClass);
1284   addTypeForNEON(VT, MVT::v2i32);
1285 }
1286 
1287 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1288   addRegisterClass(VT, &AArch64::FPR128RegClass);
1289   addTypeForNEON(VT, MVT::v4i32);
1290 }
1291 
1292 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1293                                               LLVMContext &C, EVT VT) const {
1294   if (!VT.isVector())
1295     return MVT::i32;
1296   if (VT.isScalableVector())
1297     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1298   return VT.changeVectorElementTypeToInteger();
1299 }
1300 
1301 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1302                                const APInt &Demanded,
1303                                TargetLowering::TargetLoweringOpt &TLO,
1304                                unsigned NewOpc) {
1305   uint64_t OldImm = Imm, NewImm, Enc;
1306   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1307 
1308   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1309   // bimm64.
1310   if (Imm == 0 || Imm == Mask ||
1311       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1312     return false;
1313 
1314   unsigned EltSize = Size;
1315   uint64_t DemandedBits = Demanded.getZExtValue();
1316 
1317   // Clear bits that are not demanded.
1318   Imm &= DemandedBits;
1319 
1320   while (true) {
1321     // The goal here is to set the non-demanded bits in a way that minimizes
1322     // the number of switching between 0 and 1. In order to achieve this goal,
1323     // we set the non-demanded bits to the value of the preceding demanded bits.
1324     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1325     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1326     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1327     // The final result is 0b11000011.
1328     uint64_t NonDemandedBits = ~DemandedBits;
1329     uint64_t InvertedImm = ~Imm & DemandedBits;
1330     uint64_t RotatedImm =
1331         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1332         NonDemandedBits;
1333     uint64_t Sum = RotatedImm + NonDemandedBits;
1334     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1335     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1336     NewImm = (Imm | Ones) & Mask;
1337 
1338     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1339     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1340     // we halve the element size and continue the search.
1341     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1342       break;
1343 
1344     // We cannot shrink the element size any further if it is 2-bits.
1345     if (EltSize == 2)
1346       return false;
1347 
1348     EltSize /= 2;
1349     Mask >>= EltSize;
1350     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1351 
1352     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1353     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1354       return false;
1355 
1356     // Merge the upper and lower halves of Imm and DemandedBits.
1357     Imm |= Hi;
1358     DemandedBits |= DemandedBitsHi;
1359   }
1360 
1361   ++NumOptimizedImms;
1362 
1363   // Replicate the element across the register width.
1364   while (EltSize < Size) {
1365     NewImm |= NewImm << EltSize;
1366     EltSize *= 2;
1367   }
1368 
1369   (void)OldImm;
1370   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1371          "demanded bits should never be altered");
1372   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1373 
1374   // Create the new constant immediate node.
1375   EVT VT = Op.getValueType();
1376   SDLoc DL(Op);
1377   SDValue New;
1378 
1379   // If the new constant immediate is all-zeros or all-ones, let the target
1380   // independent DAG combine optimize this node.
1381   if (NewImm == 0 || NewImm == OrigMask) {
1382     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1383                           TLO.DAG.getConstant(NewImm, DL, VT));
1384   // Otherwise, create a machine node so that target independent DAG combine
1385   // doesn't undo this optimization.
1386   } else {
1387     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1388     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1389     New = SDValue(
1390         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1391   }
1392 
1393   return TLO.CombineTo(Op, New);
1394 }
1395 
1396 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1397     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1398     TargetLoweringOpt &TLO) const {
1399   // Delay this optimization to as late as possible.
1400   if (!TLO.LegalOps)
1401     return false;
1402 
1403   if (!EnableOptimizeLogicalImm)
1404     return false;
1405 
1406   EVT VT = Op.getValueType();
1407   if (VT.isVector())
1408     return false;
1409 
1410   unsigned Size = VT.getSizeInBits();
1411   assert((Size == 32 || Size == 64) &&
1412          "i32 or i64 is expected after legalization.");
1413 
1414   // Exit early if we demand all bits.
1415   if (DemandedBits.countPopulation() == Size)
1416     return false;
1417 
1418   unsigned NewOpc;
1419   switch (Op.getOpcode()) {
1420   default:
1421     return false;
1422   case ISD::AND:
1423     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1424     break;
1425   case ISD::OR:
1426     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1427     break;
1428   case ISD::XOR:
1429     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1430     break;
1431   }
1432   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1433   if (!C)
1434     return false;
1435   uint64_t Imm = C->getZExtValue();
1436   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1437 }
1438 
1439 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1440 /// Mask are known to be either zero or one and return them Known.
1441 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1442     const SDValue Op, KnownBits &Known,
1443     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1444   switch (Op.getOpcode()) {
1445   default:
1446     break;
1447   case AArch64ISD::CSEL: {
1448     KnownBits Known2;
1449     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1450     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1451     Known.Zero &= Known2.Zero;
1452     Known.One &= Known2.One;
1453     break;
1454   }
1455   case AArch64ISD::LOADgot:
1456   case AArch64ISD::ADDlow: {
1457     if (!Subtarget->isTargetILP32())
1458       break;
1459     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1460     Known.Zero = APInt::getHighBitsSet(64, 32);
1461     break;
1462   }
1463   case ISD::INTRINSIC_W_CHAIN: {
1464     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1465     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1466     switch (IntID) {
1467     default: return;
1468     case Intrinsic::aarch64_ldaxr:
1469     case Intrinsic::aarch64_ldxr: {
1470       unsigned BitWidth = Known.getBitWidth();
1471       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1472       unsigned MemBits = VT.getScalarSizeInBits();
1473       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1474       return;
1475     }
1476     }
1477     break;
1478   }
1479   case ISD::INTRINSIC_WO_CHAIN:
1480   case ISD::INTRINSIC_VOID: {
1481     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1482     switch (IntNo) {
1483     default:
1484       break;
1485     case Intrinsic::aarch64_neon_umaxv:
1486     case Intrinsic::aarch64_neon_uminv: {
1487       // Figure out the datatype of the vector operand. The UMINV instruction
1488       // will zero extend the result, so we can mark as known zero all the
1489       // bits larger than the element datatype. 32-bit or larget doesn't need
1490       // this as those are legal types and will be handled by isel directly.
1491       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1492       unsigned BitWidth = Known.getBitWidth();
1493       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1494         assert(BitWidth >= 8 && "Unexpected width!");
1495         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1496         Known.Zero |= Mask;
1497       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1498         assert(BitWidth >= 16 && "Unexpected width!");
1499         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1500         Known.Zero |= Mask;
1501       }
1502       break;
1503     } break;
1504     }
1505   }
1506   }
1507 }
1508 
1509 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1510                                                   EVT) const {
1511   return MVT::i64;
1512 }
1513 
1514 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1515     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1516     bool *Fast) const {
1517   if (Subtarget->requiresStrictAlign())
1518     return false;
1519 
1520   if (Fast) {
1521     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1522     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1523             // See comments in performSTORECombine() for more details about
1524             // these conditions.
1525 
1526             // Code that uses clang vector extensions can mark that it
1527             // wants unaligned accesses to be treated as fast by
1528             // underspecifying alignment to be 1 or 2.
1529             Align <= 2 ||
1530 
1531             // Disregard v2i64. Memcpy lowering produces those and splitting
1532             // them regresses performance on micro-benchmarks and olden/bh.
1533             VT == MVT::v2i64;
1534   }
1535   return true;
1536 }
1537 
1538 // Same as above but handling LLTs instead.
1539 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1540     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1541     bool *Fast) const {
1542   if (Subtarget->requiresStrictAlign())
1543     return false;
1544 
1545   if (Fast) {
1546     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1547     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1548             Ty.getSizeInBytes() != 16 ||
1549             // See comments in performSTORECombine() for more details about
1550             // these conditions.
1551 
1552             // Code that uses clang vector extensions can mark that it
1553             // wants unaligned accesses to be treated as fast by
1554             // underspecifying alignment to be 1 or 2.
1555             Alignment <= 2 ||
1556 
1557             // Disregard v2i64. Memcpy lowering produces those and splitting
1558             // them regresses performance on micro-benchmarks and olden/bh.
1559             Ty == LLT::vector(2, 64);
1560   }
1561   return true;
1562 }
1563 
1564 FastISel *
1565 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1566                                       const TargetLibraryInfo *libInfo) const {
1567   return AArch64::createFastISel(funcInfo, libInfo);
1568 }
1569 
1570 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1571 #define MAKE_CASE(V)                                                           \
1572   case V:                                                                      \
1573     return #V;
1574   switch ((AArch64ISD::NodeType)Opcode) {
1575   case AArch64ISD::FIRST_NUMBER:
1576     break;
1577     MAKE_CASE(AArch64ISD::CALL)
1578     MAKE_CASE(AArch64ISD::ADRP)
1579     MAKE_CASE(AArch64ISD::ADR)
1580     MAKE_CASE(AArch64ISD::ADDlow)
1581     MAKE_CASE(AArch64ISD::LOADgot)
1582     MAKE_CASE(AArch64ISD::RET_FLAG)
1583     MAKE_CASE(AArch64ISD::BRCOND)
1584     MAKE_CASE(AArch64ISD::CSEL)
1585     MAKE_CASE(AArch64ISD::FCSEL)
1586     MAKE_CASE(AArch64ISD::CSINV)
1587     MAKE_CASE(AArch64ISD::CSNEG)
1588     MAKE_CASE(AArch64ISD::CSINC)
1589     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1590     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1591     MAKE_CASE(AArch64ISD::ADD_PRED)
1592     MAKE_CASE(AArch64ISD::MUL_PRED)
1593     MAKE_CASE(AArch64ISD::SDIV_PRED)
1594     MAKE_CASE(AArch64ISD::SHL_PRED)
1595     MAKE_CASE(AArch64ISD::SMAX_PRED)
1596     MAKE_CASE(AArch64ISD::SMIN_PRED)
1597     MAKE_CASE(AArch64ISD::SRA_PRED)
1598     MAKE_CASE(AArch64ISD::SRL_PRED)
1599     MAKE_CASE(AArch64ISD::SUB_PRED)
1600     MAKE_CASE(AArch64ISD::UDIV_PRED)
1601     MAKE_CASE(AArch64ISD::UMAX_PRED)
1602     MAKE_CASE(AArch64ISD::UMIN_PRED)
1603     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
1604     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1605     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1606     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
1607     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
1608     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
1609     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
1610     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
1611     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
1612     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
1613     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
1614     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
1615     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
1616     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
1617     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
1618     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
1619     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
1620     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
1621     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
1622     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1623     MAKE_CASE(AArch64ISD::ADC)
1624     MAKE_CASE(AArch64ISD::SBC)
1625     MAKE_CASE(AArch64ISD::ADDS)
1626     MAKE_CASE(AArch64ISD::SUBS)
1627     MAKE_CASE(AArch64ISD::ADCS)
1628     MAKE_CASE(AArch64ISD::SBCS)
1629     MAKE_CASE(AArch64ISD::ANDS)
1630     MAKE_CASE(AArch64ISD::CCMP)
1631     MAKE_CASE(AArch64ISD::CCMN)
1632     MAKE_CASE(AArch64ISD::FCCMP)
1633     MAKE_CASE(AArch64ISD::FCMP)
1634     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1635     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1636     MAKE_CASE(AArch64ISD::DUP)
1637     MAKE_CASE(AArch64ISD::DUPLANE8)
1638     MAKE_CASE(AArch64ISD::DUPLANE16)
1639     MAKE_CASE(AArch64ISD::DUPLANE32)
1640     MAKE_CASE(AArch64ISD::DUPLANE64)
1641     MAKE_CASE(AArch64ISD::MOVI)
1642     MAKE_CASE(AArch64ISD::MOVIshift)
1643     MAKE_CASE(AArch64ISD::MOVIedit)
1644     MAKE_CASE(AArch64ISD::MOVImsl)
1645     MAKE_CASE(AArch64ISD::FMOV)
1646     MAKE_CASE(AArch64ISD::MVNIshift)
1647     MAKE_CASE(AArch64ISD::MVNImsl)
1648     MAKE_CASE(AArch64ISD::BICi)
1649     MAKE_CASE(AArch64ISD::ORRi)
1650     MAKE_CASE(AArch64ISD::BSP)
1651     MAKE_CASE(AArch64ISD::NEG)
1652     MAKE_CASE(AArch64ISD::EXTR)
1653     MAKE_CASE(AArch64ISD::ZIP1)
1654     MAKE_CASE(AArch64ISD::ZIP2)
1655     MAKE_CASE(AArch64ISD::UZP1)
1656     MAKE_CASE(AArch64ISD::UZP2)
1657     MAKE_CASE(AArch64ISD::TRN1)
1658     MAKE_CASE(AArch64ISD::TRN2)
1659     MAKE_CASE(AArch64ISD::REV16)
1660     MAKE_CASE(AArch64ISD::REV32)
1661     MAKE_CASE(AArch64ISD::REV64)
1662     MAKE_CASE(AArch64ISD::EXT)
1663     MAKE_CASE(AArch64ISD::VSHL)
1664     MAKE_CASE(AArch64ISD::VLSHR)
1665     MAKE_CASE(AArch64ISD::VASHR)
1666     MAKE_CASE(AArch64ISD::VSLI)
1667     MAKE_CASE(AArch64ISD::VSRI)
1668     MAKE_CASE(AArch64ISD::CMEQ)
1669     MAKE_CASE(AArch64ISD::CMGE)
1670     MAKE_CASE(AArch64ISD::CMGT)
1671     MAKE_CASE(AArch64ISD::CMHI)
1672     MAKE_CASE(AArch64ISD::CMHS)
1673     MAKE_CASE(AArch64ISD::FCMEQ)
1674     MAKE_CASE(AArch64ISD::FCMGE)
1675     MAKE_CASE(AArch64ISD::FCMGT)
1676     MAKE_CASE(AArch64ISD::CMEQz)
1677     MAKE_CASE(AArch64ISD::CMGEz)
1678     MAKE_CASE(AArch64ISD::CMGTz)
1679     MAKE_CASE(AArch64ISD::CMLEz)
1680     MAKE_CASE(AArch64ISD::CMLTz)
1681     MAKE_CASE(AArch64ISD::FCMEQz)
1682     MAKE_CASE(AArch64ISD::FCMGEz)
1683     MAKE_CASE(AArch64ISD::FCMGTz)
1684     MAKE_CASE(AArch64ISD::FCMLEz)
1685     MAKE_CASE(AArch64ISD::FCMLTz)
1686     MAKE_CASE(AArch64ISD::SADDV)
1687     MAKE_CASE(AArch64ISD::UADDV)
1688     MAKE_CASE(AArch64ISD::SRHADD)
1689     MAKE_CASE(AArch64ISD::URHADD)
1690     MAKE_CASE(AArch64ISD::SHADD)
1691     MAKE_CASE(AArch64ISD::UHADD)
1692     MAKE_CASE(AArch64ISD::SMINV)
1693     MAKE_CASE(AArch64ISD::UMINV)
1694     MAKE_CASE(AArch64ISD::SMAXV)
1695     MAKE_CASE(AArch64ISD::UMAXV)
1696     MAKE_CASE(AArch64ISD::SADDV_PRED)
1697     MAKE_CASE(AArch64ISD::UADDV_PRED)
1698     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1699     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1700     MAKE_CASE(AArch64ISD::SMINV_PRED)
1701     MAKE_CASE(AArch64ISD::UMINV_PRED)
1702     MAKE_CASE(AArch64ISD::ORV_PRED)
1703     MAKE_CASE(AArch64ISD::EORV_PRED)
1704     MAKE_CASE(AArch64ISD::ANDV_PRED)
1705     MAKE_CASE(AArch64ISD::CLASTA_N)
1706     MAKE_CASE(AArch64ISD::CLASTB_N)
1707     MAKE_CASE(AArch64ISD::LASTA)
1708     MAKE_CASE(AArch64ISD::LASTB)
1709     MAKE_CASE(AArch64ISD::REV)
1710     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1711     MAKE_CASE(AArch64ISD::TBL)
1712     MAKE_CASE(AArch64ISD::FADD_PRED)
1713     MAKE_CASE(AArch64ISD::FADDA_PRED)
1714     MAKE_CASE(AArch64ISD::FADDV_PRED)
1715     MAKE_CASE(AArch64ISD::FDIV_PRED)
1716     MAKE_CASE(AArch64ISD::FMA_PRED)
1717     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1718     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
1719     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1720     MAKE_CASE(AArch64ISD::FMINV_PRED)
1721     MAKE_CASE(AArch64ISD::FMINNM_PRED)
1722     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1723     MAKE_CASE(AArch64ISD::FMUL_PRED)
1724     MAKE_CASE(AArch64ISD::FSUB_PRED)
1725     MAKE_CASE(AArch64ISD::NOT)
1726     MAKE_CASE(AArch64ISD::BIT)
1727     MAKE_CASE(AArch64ISD::CBZ)
1728     MAKE_CASE(AArch64ISD::CBNZ)
1729     MAKE_CASE(AArch64ISD::TBZ)
1730     MAKE_CASE(AArch64ISD::TBNZ)
1731     MAKE_CASE(AArch64ISD::TC_RETURN)
1732     MAKE_CASE(AArch64ISD::PREFETCH)
1733     MAKE_CASE(AArch64ISD::SITOF)
1734     MAKE_CASE(AArch64ISD::UITOF)
1735     MAKE_CASE(AArch64ISD::NVCAST)
1736     MAKE_CASE(AArch64ISD::SQSHL_I)
1737     MAKE_CASE(AArch64ISD::UQSHL_I)
1738     MAKE_CASE(AArch64ISD::SRSHR_I)
1739     MAKE_CASE(AArch64ISD::URSHR_I)
1740     MAKE_CASE(AArch64ISD::SQSHLU_I)
1741     MAKE_CASE(AArch64ISD::WrapperLarge)
1742     MAKE_CASE(AArch64ISD::LD2post)
1743     MAKE_CASE(AArch64ISD::LD3post)
1744     MAKE_CASE(AArch64ISD::LD4post)
1745     MAKE_CASE(AArch64ISD::ST2post)
1746     MAKE_CASE(AArch64ISD::ST3post)
1747     MAKE_CASE(AArch64ISD::ST4post)
1748     MAKE_CASE(AArch64ISD::LD1x2post)
1749     MAKE_CASE(AArch64ISD::LD1x3post)
1750     MAKE_CASE(AArch64ISD::LD1x4post)
1751     MAKE_CASE(AArch64ISD::ST1x2post)
1752     MAKE_CASE(AArch64ISD::ST1x3post)
1753     MAKE_CASE(AArch64ISD::ST1x4post)
1754     MAKE_CASE(AArch64ISD::LD1DUPpost)
1755     MAKE_CASE(AArch64ISD::LD2DUPpost)
1756     MAKE_CASE(AArch64ISD::LD3DUPpost)
1757     MAKE_CASE(AArch64ISD::LD4DUPpost)
1758     MAKE_CASE(AArch64ISD::LD1LANEpost)
1759     MAKE_CASE(AArch64ISD::LD2LANEpost)
1760     MAKE_CASE(AArch64ISD::LD3LANEpost)
1761     MAKE_CASE(AArch64ISD::LD4LANEpost)
1762     MAKE_CASE(AArch64ISD::ST2LANEpost)
1763     MAKE_CASE(AArch64ISD::ST3LANEpost)
1764     MAKE_CASE(AArch64ISD::ST4LANEpost)
1765     MAKE_CASE(AArch64ISD::SMULL)
1766     MAKE_CASE(AArch64ISD::UMULL)
1767     MAKE_CASE(AArch64ISD::FRECPE)
1768     MAKE_CASE(AArch64ISD::FRECPS)
1769     MAKE_CASE(AArch64ISD::FRSQRTE)
1770     MAKE_CASE(AArch64ISD::FRSQRTS)
1771     MAKE_CASE(AArch64ISD::STG)
1772     MAKE_CASE(AArch64ISD::STZG)
1773     MAKE_CASE(AArch64ISD::ST2G)
1774     MAKE_CASE(AArch64ISD::STZ2G)
1775     MAKE_CASE(AArch64ISD::SUNPKHI)
1776     MAKE_CASE(AArch64ISD::SUNPKLO)
1777     MAKE_CASE(AArch64ISD::UUNPKHI)
1778     MAKE_CASE(AArch64ISD::UUNPKLO)
1779     MAKE_CASE(AArch64ISD::INSR)
1780     MAKE_CASE(AArch64ISD::PTEST)
1781     MAKE_CASE(AArch64ISD::PTRUE)
1782     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1783     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1784     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1785     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1786     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1787     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1788     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1789     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1790     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1791     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1792     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1793     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1794     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1795     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1796     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1797     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1798     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1799     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1800     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1801     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1802     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1803     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1804     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1805     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1806     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1807     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1808     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1809     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1810     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1811     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1812     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1813     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1814     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1815     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1816     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1817     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1818     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1819     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1820     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1821     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1822     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1823     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1824     MAKE_CASE(AArch64ISD::ST1_PRED)
1825     MAKE_CASE(AArch64ISD::SST1_PRED)
1826     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1827     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1828     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1829     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1830     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1831     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1832     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1833     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1834     MAKE_CASE(AArch64ISD::LDP)
1835     MAKE_CASE(AArch64ISD::STP)
1836     MAKE_CASE(AArch64ISD::STNP)
1837     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1838     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1839     MAKE_CASE(AArch64ISD::UABD)
1840     MAKE_CASE(AArch64ISD::SABD)
1841   }
1842 #undef MAKE_CASE
1843   return nullptr;
1844 }
1845 
1846 MachineBasicBlock *
1847 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1848                                     MachineBasicBlock *MBB) const {
1849   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1850   // phi node:
1851 
1852   // OrigBB:
1853   //     [... previous instrs leading to comparison ...]
1854   //     b.ne TrueBB
1855   //     b EndBB
1856   // TrueBB:
1857   //     ; Fallthrough
1858   // EndBB:
1859   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1860 
1861   MachineFunction *MF = MBB->getParent();
1862   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1863   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1864   DebugLoc DL = MI.getDebugLoc();
1865   MachineFunction::iterator It = ++MBB->getIterator();
1866 
1867   Register DestReg = MI.getOperand(0).getReg();
1868   Register IfTrueReg = MI.getOperand(1).getReg();
1869   Register IfFalseReg = MI.getOperand(2).getReg();
1870   unsigned CondCode = MI.getOperand(3).getImm();
1871   bool NZCVKilled = MI.getOperand(4).isKill();
1872 
1873   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1874   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1875   MF->insert(It, TrueBB);
1876   MF->insert(It, EndBB);
1877 
1878   // Transfer rest of current basic-block to EndBB
1879   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1880                 MBB->end());
1881   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1882 
1883   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1884   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1885   MBB->addSuccessor(TrueBB);
1886   MBB->addSuccessor(EndBB);
1887 
1888   // TrueBB falls through to the end.
1889   TrueBB->addSuccessor(EndBB);
1890 
1891   if (!NZCVKilled) {
1892     TrueBB->addLiveIn(AArch64::NZCV);
1893     EndBB->addLiveIn(AArch64::NZCV);
1894   }
1895 
1896   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1897       .addReg(IfTrueReg)
1898       .addMBB(TrueBB)
1899       .addReg(IfFalseReg)
1900       .addMBB(MBB);
1901 
1902   MI.eraseFromParent();
1903   return EndBB;
1904 }
1905 
1906 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1907        MachineInstr &MI, MachineBasicBlock *BB) const {
1908   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1909              BB->getParent()->getFunction().getPersonalityFn())) &&
1910          "SEH does not use catchret!");
1911   return BB;
1912 }
1913 
1914 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1915     MachineInstr &MI, MachineBasicBlock *BB) const {
1916   switch (MI.getOpcode()) {
1917   default:
1918 #ifndef NDEBUG
1919     MI.dump();
1920 #endif
1921     llvm_unreachable("Unexpected instruction for custom inserter!");
1922 
1923   case AArch64::F128CSEL:
1924     return EmitF128CSEL(MI, BB);
1925 
1926   case TargetOpcode::STACKMAP:
1927   case TargetOpcode::PATCHPOINT:
1928   case TargetOpcode::STATEPOINT:
1929     return emitPatchPoint(MI, BB);
1930 
1931   case AArch64::CATCHRET:
1932     return EmitLoweredCatchRet(MI, BB);
1933   }
1934 }
1935 
1936 //===----------------------------------------------------------------------===//
1937 // AArch64 Lowering private implementation.
1938 //===----------------------------------------------------------------------===//
1939 
1940 //===----------------------------------------------------------------------===//
1941 // Lowering Code
1942 //===----------------------------------------------------------------------===//
1943 
1944 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1945 /// CC
1946 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1947   switch (CC) {
1948   default:
1949     llvm_unreachable("Unknown condition code!");
1950   case ISD::SETNE:
1951     return AArch64CC::NE;
1952   case ISD::SETEQ:
1953     return AArch64CC::EQ;
1954   case ISD::SETGT:
1955     return AArch64CC::GT;
1956   case ISD::SETGE:
1957     return AArch64CC::GE;
1958   case ISD::SETLT:
1959     return AArch64CC::LT;
1960   case ISD::SETLE:
1961     return AArch64CC::LE;
1962   case ISD::SETUGT:
1963     return AArch64CC::HI;
1964   case ISD::SETUGE:
1965     return AArch64CC::HS;
1966   case ISD::SETULT:
1967     return AArch64CC::LO;
1968   case ISD::SETULE:
1969     return AArch64CC::LS;
1970   }
1971 }
1972 
1973 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1974 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1975                                   AArch64CC::CondCode &CondCode,
1976                                   AArch64CC::CondCode &CondCode2) {
1977   CondCode2 = AArch64CC::AL;
1978   switch (CC) {
1979   default:
1980     llvm_unreachable("Unknown FP condition!");
1981   case ISD::SETEQ:
1982   case ISD::SETOEQ:
1983     CondCode = AArch64CC::EQ;
1984     break;
1985   case ISD::SETGT:
1986   case ISD::SETOGT:
1987     CondCode = AArch64CC::GT;
1988     break;
1989   case ISD::SETGE:
1990   case ISD::SETOGE:
1991     CondCode = AArch64CC::GE;
1992     break;
1993   case ISD::SETOLT:
1994     CondCode = AArch64CC::MI;
1995     break;
1996   case ISD::SETOLE:
1997     CondCode = AArch64CC::LS;
1998     break;
1999   case ISD::SETONE:
2000     CondCode = AArch64CC::MI;
2001     CondCode2 = AArch64CC::GT;
2002     break;
2003   case ISD::SETO:
2004     CondCode = AArch64CC::VC;
2005     break;
2006   case ISD::SETUO:
2007     CondCode = AArch64CC::VS;
2008     break;
2009   case ISD::SETUEQ:
2010     CondCode = AArch64CC::EQ;
2011     CondCode2 = AArch64CC::VS;
2012     break;
2013   case ISD::SETUGT:
2014     CondCode = AArch64CC::HI;
2015     break;
2016   case ISD::SETUGE:
2017     CondCode = AArch64CC::PL;
2018     break;
2019   case ISD::SETLT:
2020   case ISD::SETULT:
2021     CondCode = AArch64CC::LT;
2022     break;
2023   case ISD::SETLE:
2024   case ISD::SETULE:
2025     CondCode = AArch64CC::LE;
2026     break;
2027   case ISD::SETNE:
2028   case ISD::SETUNE:
2029     CondCode = AArch64CC::NE;
2030     break;
2031   }
2032 }
2033 
2034 /// Convert a DAG fp condition code to an AArch64 CC.
2035 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2036 /// should be AND'ed instead of OR'ed.
2037 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2038                                      AArch64CC::CondCode &CondCode,
2039                                      AArch64CC::CondCode &CondCode2) {
2040   CondCode2 = AArch64CC::AL;
2041   switch (CC) {
2042   default:
2043     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2044     assert(CondCode2 == AArch64CC::AL);
2045     break;
2046   case ISD::SETONE:
2047     // (a one b)
2048     // == ((a olt b) || (a ogt b))
2049     // == ((a ord b) && (a une b))
2050     CondCode = AArch64CC::VC;
2051     CondCode2 = AArch64CC::NE;
2052     break;
2053   case ISD::SETUEQ:
2054     // (a ueq b)
2055     // == ((a uno b) || (a oeq b))
2056     // == ((a ule b) && (a uge b))
2057     CondCode = AArch64CC::PL;
2058     CondCode2 = AArch64CC::LE;
2059     break;
2060   }
2061 }
2062 
2063 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2064 /// CC usable with the vector instructions. Fewer operations are available
2065 /// without a real NZCV register, so we have to use less efficient combinations
2066 /// to get the same effect.
2067 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2068                                         AArch64CC::CondCode &CondCode,
2069                                         AArch64CC::CondCode &CondCode2,
2070                                         bool &Invert) {
2071   Invert = false;
2072   switch (CC) {
2073   default:
2074     // Mostly the scalar mappings work fine.
2075     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2076     break;
2077   case ISD::SETUO:
2078     Invert = true;
2079     LLVM_FALLTHROUGH;
2080   case ISD::SETO:
2081     CondCode = AArch64CC::MI;
2082     CondCode2 = AArch64CC::GE;
2083     break;
2084   case ISD::SETUEQ:
2085   case ISD::SETULT:
2086   case ISD::SETULE:
2087   case ISD::SETUGT:
2088   case ISD::SETUGE:
2089     // All of the compare-mask comparisons are ordered, but we can switch
2090     // between the two by a double inversion. E.g. ULE == !OGT.
2091     Invert = true;
2092     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2093                           CondCode, CondCode2);
2094     break;
2095   }
2096 }
2097 
2098 static bool isLegalArithImmed(uint64_t C) {
2099   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2100   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2101   LLVM_DEBUG(dbgs() << "Is imm " << C
2102                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2103   return IsLegal;
2104 }
2105 
2106 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2107 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2108 // can be set differently by this operation. It comes down to whether
2109 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2110 // everything is fine. If not then the optimization is wrong. Thus general
2111 // comparisons are only valid if op2 != 0.
2112 //
2113 // So, finally, the only LLVM-native comparisons that don't mention C and V
2114 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2115 // the absence of information about op2.
2116 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2117   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2118          (CC == ISD::SETEQ || CC == ISD::SETNE);
2119 }
2120 
2121 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2122                                       SelectionDAG &DAG, SDValue Chain,
2123                                       bool IsSignaling) {
2124   EVT VT = LHS.getValueType();
2125   assert(VT != MVT::f128);
2126   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2127   unsigned Opcode =
2128       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2129   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2130 }
2131 
2132 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2133                               const SDLoc &dl, SelectionDAG &DAG) {
2134   EVT VT = LHS.getValueType();
2135   const bool FullFP16 =
2136     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2137 
2138   if (VT.isFloatingPoint()) {
2139     assert(VT != MVT::f128);
2140     if (VT == MVT::f16 && !FullFP16) {
2141       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2142       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2143       VT = MVT::f32;
2144     }
2145     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2146   }
2147 
2148   // The CMP instruction is just an alias for SUBS, and representing it as
2149   // SUBS means that it's possible to get CSE with subtract operations.
2150   // A later phase can perform the optimization of setting the destination
2151   // register to WZR/XZR if it ends up being unused.
2152   unsigned Opcode = AArch64ISD::SUBS;
2153 
2154   if (isCMN(RHS, CC)) {
2155     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2156     Opcode = AArch64ISD::ADDS;
2157     RHS = RHS.getOperand(1);
2158   } else if (isCMN(LHS, CC)) {
2159     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2160     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2161     Opcode = AArch64ISD::ADDS;
2162     LHS = LHS.getOperand(1);
2163   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2164     if (LHS.getOpcode() == ISD::AND) {
2165       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2166       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2167       // of the signed comparisons.
2168       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2169                                            DAG.getVTList(VT, MVT_CC),
2170                                            LHS.getOperand(0),
2171                                            LHS.getOperand(1));
2172       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2173       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2174       return ANDSNode.getValue(1);
2175     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2176       // Use result of ANDS
2177       return LHS.getValue(1);
2178     }
2179   }
2180 
2181   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2182       .getValue(1);
2183 }
2184 
2185 /// \defgroup AArch64CCMP CMP;CCMP matching
2186 ///
2187 /// These functions deal with the formation of CMP;CCMP;... sequences.
2188 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2189 /// a comparison. They set the NZCV flags to a predefined value if their
2190 /// predicate is false. This allows to express arbitrary conjunctions, for
2191 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2192 /// expressed as:
2193 ///   cmp A
2194 ///   ccmp B, inv(CB), CA
2195 ///   check for CB flags
2196 ///
2197 /// This naturally lets us implement chains of AND operations with SETCC
2198 /// operands. And we can even implement some other situations by transforming
2199 /// them:
2200 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2201 ///     negating the flags used in a CCMP/FCCMP operations.
2202 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2203 ///     by negating the flags we test for afterwards. i.e.
2204 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2205 ///   - Note that we can only ever negate all previously processed results.
2206 ///     What we can not implement by flipping the flags to test is a negation
2207 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2208 ///     far, so the 2nd sub-tree we emit would also affect the first).
2209 /// With those tools we can implement some OR operations:
2210 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2211 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2212 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2213 ///     elimination rules from earlier to implement the whole thing as a
2214 ///     CCMP/FCCMP chain.
2215 ///
2216 /// As complete example:
2217 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2218 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2219 /// can be reassociated to:
2220 ///     or (and (setCC (cmp C)) setCD (cmp D))
2221 //         (or (setCA (cmp A)) (setCB (cmp B)))
2222 /// can be transformed to:
2223 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2224 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2225 /// which can be implemented as:
2226 ///   cmp C
2227 ///   ccmp D, inv(CD), CC
2228 ///   ccmp A, CA, inv(CD)
2229 ///   ccmp B, CB, inv(CA)
2230 ///   check for CB flags
2231 ///
2232 /// A counterexample is "or (and A B) (and C D)" which translates to
2233 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2234 /// can only implement 1 of the inner (not) operations, but not both!
2235 /// @{
2236 
2237 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2238 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2239                                          ISD::CondCode CC, SDValue CCOp,
2240                                          AArch64CC::CondCode Predicate,
2241                                          AArch64CC::CondCode OutCC,
2242                                          const SDLoc &DL, SelectionDAG &DAG) {
2243   unsigned Opcode = 0;
2244   const bool FullFP16 =
2245     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2246 
2247   if (LHS.getValueType().isFloatingPoint()) {
2248     assert(LHS.getValueType() != MVT::f128);
2249     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2250       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2251       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2252     }
2253     Opcode = AArch64ISD::FCCMP;
2254   } else if (RHS.getOpcode() == ISD::SUB) {
2255     SDValue SubOp0 = RHS.getOperand(0);
2256     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2257       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2258       Opcode = AArch64ISD::CCMN;
2259       RHS = RHS.getOperand(1);
2260     }
2261   }
2262   if (Opcode == 0)
2263     Opcode = AArch64ISD::CCMP;
2264 
2265   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2266   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2267   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2268   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2269   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2270 }
2271 
2272 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2273 /// expressed as a conjunction. See \ref AArch64CCMP.
2274 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2275 ///                     changing the conditions on the SETCC tests.
2276 ///                     (this means we can call emitConjunctionRec() with
2277 ///                      Negate==true on this sub-tree)
2278 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2279 ///                     cannot do the negation naturally. We are required to
2280 ///                     emit the subtree first in this case.
2281 /// \param WillNegate   Is true if are called when the result of this
2282 ///                     subexpression must be negated. This happens when the
2283 ///                     outer expression is an OR. We can use this fact to know
2284 ///                     that we have a double negation (or (or ...) ...) that
2285 ///                     can be implemented for free.
2286 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2287                                bool &MustBeFirst, bool WillNegate,
2288                                unsigned Depth = 0) {
2289   if (!Val.hasOneUse())
2290     return false;
2291   unsigned Opcode = Val->getOpcode();
2292   if (Opcode == ISD::SETCC) {
2293     if (Val->getOperand(0).getValueType() == MVT::f128)
2294       return false;
2295     CanNegate = true;
2296     MustBeFirst = false;
2297     return true;
2298   }
2299   // Protect against exponential runtime and stack overflow.
2300   if (Depth > 6)
2301     return false;
2302   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2303     bool IsOR = Opcode == ISD::OR;
2304     SDValue O0 = Val->getOperand(0);
2305     SDValue O1 = Val->getOperand(1);
2306     bool CanNegateL;
2307     bool MustBeFirstL;
2308     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2309       return false;
2310     bool CanNegateR;
2311     bool MustBeFirstR;
2312     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2313       return false;
2314 
2315     if (MustBeFirstL && MustBeFirstR)
2316       return false;
2317 
2318     if (IsOR) {
2319       // For an OR expression we need to be able to naturally negate at least
2320       // one side or we cannot do the transformation at all.
2321       if (!CanNegateL && !CanNegateR)
2322         return false;
2323       // If we the result of the OR will be negated and we can naturally negate
2324       // the leafs, then this sub-tree as a whole negates naturally.
2325       CanNegate = WillNegate && CanNegateL && CanNegateR;
2326       // If we cannot naturally negate the whole sub-tree, then this must be
2327       // emitted first.
2328       MustBeFirst = !CanNegate;
2329     } else {
2330       assert(Opcode == ISD::AND && "Must be OR or AND");
2331       // We cannot naturally negate an AND operation.
2332       CanNegate = false;
2333       MustBeFirst = MustBeFirstL || MustBeFirstR;
2334     }
2335     return true;
2336   }
2337   return false;
2338 }
2339 
2340 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2341 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2342 /// Tries to transform the given i1 producing node @p Val to a series compare
2343 /// and conditional compare operations. @returns an NZCV flags producing node
2344 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2345 /// transformation was not possible.
2346 /// \p Negate is true if we want this sub-tree being negated just by changing
2347 /// SETCC conditions.
2348 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2349     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2350     AArch64CC::CondCode Predicate) {
2351   // We're at a tree leaf, produce a conditional comparison operation.
2352   unsigned Opcode = Val->getOpcode();
2353   if (Opcode == ISD::SETCC) {
2354     SDValue LHS = Val->getOperand(0);
2355     SDValue RHS = Val->getOperand(1);
2356     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2357     bool isInteger = LHS.getValueType().isInteger();
2358     if (Negate)
2359       CC = getSetCCInverse(CC, LHS.getValueType());
2360     SDLoc DL(Val);
2361     // Determine OutCC and handle FP special case.
2362     if (isInteger) {
2363       OutCC = changeIntCCToAArch64CC(CC);
2364     } else {
2365       assert(LHS.getValueType().isFloatingPoint());
2366       AArch64CC::CondCode ExtraCC;
2367       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2368       // Some floating point conditions can't be tested with a single condition
2369       // code. Construct an additional comparison in this case.
2370       if (ExtraCC != AArch64CC::AL) {
2371         SDValue ExtraCmp;
2372         if (!CCOp.getNode())
2373           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2374         else
2375           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2376                                                ExtraCC, DL, DAG);
2377         CCOp = ExtraCmp;
2378         Predicate = ExtraCC;
2379       }
2380     }
2381 
2382     // Produce a normal comparison if we are first in the chain
2383     if (!CCOp)
2384       return emitComparison(LHS, RHS, CC, DL, DAG);
2385     // Otherwise produce a ccmp.
2386     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2387                                      DAG);
2388   }
2389   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2390 
2391   bool IsOR = Opcode == ISD::OR;
2392 
2393   SDValue LHS = Val->getOperand(0);
2394   bool CanNegateL;
2395   bool MustBeFirstL;
2396   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2397   assert(ValidL && "Valid conjunction/disjunction tree");
2398   (void)ValidL;
2399 
2400   SDValue RHS = Val->getOperand(1);
2401   bool CanNegateR;
2402   bool MustBeFirstR;
2403   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2404   assert(ValidR && "Valid conjunction/disjunction tree");
2405   (void)ValidR;
2406 
2407   // Swap sub-tree that must come first to the right side.
2408   if (MustBeFirstL) {
2409     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2410     std::swap(LHS, RHS);
2411     std::swap(CanNegateL, CanNegateR);
2412     std::swap(MustBeFirstL, MustBeFirstR);
2413   }
2414 
2415   bool NegateR;
2416   bool NegateAfterR;
2417   bool NegateL;
2418   bool NegateAfterAll;
2419   if (Opcode == ISD::OR) {
2420     // Swap the sub-tree that we can negate naturally to the left.
2421     if (!CanNegateL) {
2422       assert(CanNegateR && "at least one side must be negatable");
2423       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2424       assert(!Negate);
2425       std::swap(LHS, RHS);
2426       NegateR = false;
2427       NegateAfterR = true;
2428     } else {
2429       // Negate the left sub-tree if possible, otherwise negate the result.
2430       NegateR = CanNegateR;
2431       NegateAfterR = !CanNegateR;
2432     }
2433     NegateL = true;
2434     NegateAfterAll = !Negate;
2435   } else {
2436     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2437     assert(!Negate && "Valid conjunction/disjunction tree");
2438 
2439     NegateL = false;
2440     NegateR = false;
2441     NegateAfterR = false;
2442     NegateAfterAll = false;
2443   }
2444 
2445   // Emit sub-trees.
2446   AArch64CC::CondCode RHSCC;
2447   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2448   if (NegateAfterR)
2449     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2450   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2451   if (NegateAfterAll)
2452     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2453   return CmpL;
2454 }
2455 
2456 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2457 /// In some cases this is even possible with OR operations in the expression.
2458 /// See \ref AArch64CCMP.
2459 /// \see emitConjunctionRec().
2460 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2461                                AArch64CC::CondCode &OutCC) {
2462   bool DummyCanNegate;
2463   bool DummyMustBeFirst;
2464   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2465     return SDValue();
2466 
2467   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2468 }
2469 
2470 /// @}
2471 
2472 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2473 /// extension operations.
2474 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2475   auto isSupportedExtend = [&](SDValue V) {
2476     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2477       return true;
2478 
2479     if (V.getOpcode() == ISD::AND)
2480       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2481         uint64_t Mask = MaskCst->getZExtValue();
2482         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2483       }
2484 
2485     return false;
2486   };
2487 
2488   if (!Op.hasOneUse())
2489     return 0;
2490 
2491   if (isSupportedExtend(Op))
2492     return 1;
2493 
2494   unsigned Opc = Op.getOpcode();
2495   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2496     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2497       uint64_t Shift = ShiftCst->getZExtValue();
2498       if (isSupportedExtend(Op.getOperand(0)))
2499         return (Shift <= 4) ? 2 : 1;
2500       EVT VT = Op.getValueType();
2501       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2502         return 1;
2503     }
2504 
2505   return 0;
2506 }
2507 
2508 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2509                              SDValue &AArch64cc, SelectionDAG &DAG,
2510                              const SDLoc &dl) {
2511   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2512     EVT VT = RHS.getValueType();
2513     uint64_t C = RHSC->getZExtValue();
2514     if (!isLegalArithImmed(C)) {
2515       // Constant does not fit, try adjusting it by one?
2516       switch (CC) {
2517       default:
2518         break;
2519       case ISD::SETLT:
2520       case ISD::SETGE:
2521         if ((VT == MVT::i32 && C != 0x80000000 &&
2522              isLegalArithImmed((uint32_t)(C - 1))) ||
2523             (VT == MVT::i64 && C != 0x80000000ULL &&
2524              isLegalArithImmed(C - 1ULL))) {
2525           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2526           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2527           RHS = DAG.getConstant(C, dl, VT);
2528         }
2529         break;
2530       case ISD::SETULT:
2531       case ISD::SETUGE:
2532         if ((VT == MVT::i32 && C != 0 &&
2533              isLegalArithImmed((uint32_t)(C - 1))) ||
2534             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2535           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2536           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2537           RHS = DAG.getConstant(C, dl, VT);
2538         }
2539         break;
2540       case ISD::SETLE:
2541       case ISD::SETGT:
2542         if ((VT == MVT::i32 && C != INT32_MAX &&
2543              isLegalArithImmed((uint32_t)(C + 1))) ||
2544             (VT == MVT::i64 && C != INT64_MAX &&
2545              isLegalArithImmed(C + 1ULL))) {
2546           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2547           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2548           RHS = DAG.getConstant(C, dl, VT);
2549         }
2550         break;
2551       case ISD::SETULE:
2552       case ISD::SETUGT:
2553         if ((VT == MVT::i32 && C != UINT32_MAX &&
2554              isLegalArithImmed((uint32_t)(C + 1))) ||
2555             (VT == MVT::i64 && C != UINT64_MAX &&
2556              isLegalArithImmed(C + 1ULL))) {
2557           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2558           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2559           RHS = DAG.getConstant(C, dl, VT);
2560         }
2561         break;
2562       }
2563     }
2564   }
2565 
2566   // Comparisons are canonicalized so that the RHS operand is simpler than the
2567   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2568   // can fold some shift+extend operations on the RHS operand, so swap the
2569   // operands if that can be done.
2570   //
2571   // For example:
2572   //    lsl     w13, w11, #1
2573   //    cmp     w13, w12
2574   // can be turned into:
2575   //    cmp     w12, w11, lsl #1
2576   if (!isa<ConstantSDNode>(RHS) ||
2577       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2578     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2579 
2580     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2581       std::swap(LHS, RHS);
2582       CC = ISD::getSetCCSwappedOperands(CC);
2583     }
2584   }
2585 
2586   SDValue Cmp;
2587   AArch64CC::CondCode AArch64CC;
2588   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2589     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2590 
2591     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2592     // For the i8 operand, the largest immediate is 255, so this can be easily
2593     // encoded in the compare instruction. For the i16 operand, however, the
2594     // largest immediate cannot be encoded in the compare.
2595     // Therefore, use a sign extending load and cmn to avoid materializing the
2596     // -1 constant. For example,
2597     // movz w1, #65535
2598     // ldrh w0, [x0, #0]
2599     // cmp w0, w1
2600     // >
2601     // ldrsh w0, [x0, #0]
2602     // cmn w0, #1
2603     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2604     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2605     // ensure both the LHS and RHS are truly zero extended and to make sure the
2606     // transformation is profitable.
2607     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2608         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2609         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2610         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2611       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2612       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2613         SDValue SExt =
2614             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2615                         DAG.getValueType(MVT::i16));
2616         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2617                                                    RHS.getValueType()),
2618                              CC, dl, DAG);
2619         AArch64CC = changeIntCCToAArch64CC(CC);
2620       }
2621     }
2622 
2623     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2624       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2625         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2626           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2627       }
2628     }
2629   }
2630 
2631   if (!Cmp) {
2632     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2633     AArch64CC = changeIntCCToAArch64CC(CC);
2634   }
2635   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2636   return Cmp;
2637 }
2638 
2639 static std::pair<SDValue, SDValue>
2640 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2641   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2642          "Unsupported value type");
2643   SDValue Value, Overflow;
2644   SDLoc DL(Op);
2645   SDValue LHS = Op.getOperand(0);
2646   SDValue RHS = Op.getOperand(1);
2647   unsigned Opc = 0;
2648   switch (Op.getOpcode()) {
2649   default:
2650     llvm_unreachable("Unknown overflow instruction!");
2651   case ISD::SADDO:
2652     Opc = AArch64ISD::ADDS;
2653     CC = AArch64CC::VS;
2654     break;
2655   case ISD::UADDO:
2656     Opc = AArch64ISD::ADDS;
2657     CC = AArch64CC::HS;
2658     break;
2659   case ISD::SSUBO:
2660     Opc = AArch64ISD::SUBS;
2661     CC = AArch64CC::VS;
2662     break;
2663   case ISD::USUBO:
2664     Opc = AArch64ISD::SUBS;
2665     CC = AArch64CC::LO;
2666     break;
2667   // Multiply needs a little bit extra work.
2668   case ISD::SMULO:
2669   case ISD::UMULO: {
2670     CC = AArch64CC::NE;
2671     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2672     if (Op.getValueType() == MVT::i32) {
2673       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2674       // For a 32 bit multiply with overflow check we want the instruction
2675       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2676       // need to generate the following pattern:
2677       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2678       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2679       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2680       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2681       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2682                                 DAG.getConstant(0, DL, MVT::i64));
2683       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2684       // operation. We need to clear out the upper 32 bits, because we used a
2685       // widening multiply that wrote all 64 bits. In the end this should be a
2686       // noop.
2687       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2688       if (IsSigned) {
2689         // The signed overflow check requires more than just a simple check for
2690         // any bit set in the upper 32 bits of the result. These bits could be
2691         // just the sign bits of a negative number. To perform the overflow
2692         // check we have to arithmetic shift right the 32nd bit of the result by
2693         // 31 bits. Then we compare the result to the upper 32 bits.
2694         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2695                                         DAG.getConstant(32, DL, MVT::i64));
2696         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2697         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2698                                         DAG.getConstant(31, DL, MVT::i64));
2699         // It is important that LowerBits is last, otherwise the arithmetic
2700         // shift will not be folded into the compare (SUBS).
2701         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2702         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2703                        .getValue(1);
2704       } else {
2705         // The overflow check for unsigned multiply is easy. We only need to
2706         // check if any of the upper 32 bits are set. This can be done with a
2707         // CMP (shifted register). For that we need to generate the following
2708         // pattern:
2709         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2710         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2711                                         DAG.getConstant(32, DL, MVT::i64));
2712         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2713         Overflow =
2714             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2715                         DAG.getConstant(0, DL, MVT::i64),
2716                         UpperBits).getValue(1);
2717       }
2718       break;
2719     }
2720     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2721     // For the 64 bit multiply
2722     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2723     if (IsSigned) {
2724       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2725       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2726                                       DAG.getConstant(63, DL, MVT::i64));
2727       // It is important that LowerBits is last, otherwise the arithmetic
2728       // shift will not be folded into the compare (SUBS).
2729       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2730       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2731                      .getValue(1);
2732     } else {
2733       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2734       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2735       Overflow =
2736           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2737                       DAG.getConstant(0, DL, MVT::i64),
2738                       UpperBits).getValue(1);
2739     }
2740     break;
2741   }
2742   } // switch (...)
2743 
2744   if (Opc) {
2745     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2746 
2747     // Emit the AArch64 operation with overflow check.
2748     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2749     Overflow = Value.getValue(1);
2750   }
2751   return std::make_pair(Value, Overflow);
2752 }
2753 
2754 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2755                                              RTLIB::Libcall Call) const {
2756   bool IsStrict = Op->isStrictFPOpcode();
2757   unsigned Offset = IsStrict ? 1 : 0;
2758   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2759   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2760   MakeLibCallOptions CallOptions;
2761   SDValue Result;
2762   SDLoc dl(Op);
2763   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2764                                         CallOptions, dl, Chain);
2765   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2766 }
2767 
2768 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
2769   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
2770     return LowerToScalableOp(Op, DAG);
2771 
2772   SDValue Sel = Op.getOperand(0);
2773   SDValue Other = Op.getOperand(1);
2774   SDLoc dl(Sel);
2775 
2776   // If the operand is an overflow checking operation, invert the condition
2777   // code and kill the Not operation. I.e., transform:
2778   // (xor (overflow_op_bool, 1))
2779   //   -->
2780   // (csel 1, 0, invert(cc), overflow_op_bool)
2781   // ... which later gets transformed to just a cset instruction with an
2782   // inverted condition code, rather than a cset + eor sequence.
2783   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2784     // Only lower legal XALUO ops.
2785     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2786       return SDValue();
2787 
2788     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2789     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2790     AArch64CC::CondCode CC;
2791     SDValue Value, Overflow;
2792     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2793     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2794     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2795                        CCVal, Overflow);
2796   }
2797   // If neither operand is a SELECT_CC, give up.
2798   if (Sel.getOpcode() != ISD::SELECT_CC)
2799     std::swap(Sel, Other);
2800   if (Sel.getOpcode() != ISD::SELECT_CC)
2801     return Op;
2802 
2803   // The folding we want to perform is:
2804   // (xor x, (select_cc a, b, cc, 0, -1) )
2805   //   -->
2806   // (csel x, (xor x, -1), cc ...)
2807   //
2808   // The latter will get matched to a CSINV instruction.
2809 
2810   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2811   SDValue LHS = Sel.getOperand(0);
2812   SDValue RHS = Sel.getOperand(1);
2813   SDValue TVal = Sel.getOperand(2);
2814   SDValue FVal = Sel.getOperand(3);
2815 
2816   // FIXME: This could be generalized to non-integer comparisons.
2817   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2818     return Op;
2819 
2820   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2821   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2822 
2823   // The values aren't constants, this isn't the pattern we're looking for.
2824   if (!CFVal || !CTVal)
2825     return Op;
2826 
2827   // We can commute the SELECT_CC by inverting the condition.  This
2828   // might be needed to make this fit into a CSINV pattern.
2829   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2830     std::swap(TVal, FVal);
2831     std::swap(CTVal, CFVal);
2832     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2833   }
2834 
2835   // If the constants line up, perform the transform!
2836   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2837     SDValue CCVal;
2838     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2839 
2840     FVal = Other;
2841     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2842                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2843 
2844     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2845                        CCVal, Cmp);
2846   }
2847 
2848   return Op;
2849 }
2850 
2851 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2852   EVT VT = Op.getValueType();
2853 
2854   // Let legalize expand this if it isn't a legal type yet.
2855   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2856     return SDValue();
2857 
2858   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2859 
2860   unsigned Opc;
2861   bool ExtraOp = false;
2862   switch (Op.getOpcode()) {
2863   default:
2864     llvm_unreachable("Invalid code");
2865   case ISD::ADDC:
2866     Opc = AArch64ISD::ADDS;
2867     break;
2868   case ISD::SUBC:
2869     Opc = AArch64ISD::SUBS;
2870     break;
2871   case ISD::ADDE:
2872     Opc = AArch64ISD::ADCS;
2873     ExtraOp = true;
2874     break;
2875   case ISD::SUBE:
2876     Opc = AArch64ISD::SBCS;
2877     ExtraOp = true;
2878     break;
2879   }
2880 
2881   if (!ExtraOp)
2882     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2883   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2884                      Op.getOperand(2));
2885 }
2886 
2887 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2888   // Let legalize expand this if it isn't a legal type yet.
2889   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2890     return SDValue();
2891 
2892   SDLoc dl(Op);
2893   AArch64CC::CondCode CC;
2894   // The actual operation that sets the overflow or carry flag.
2895   SDValue Value, Overflow;
2896   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2897 
2898   // We use 0 and 1 as false and true values.
2899   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2900   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2901 
2902   // We use an inverted condition, because the conditional select is inverted
2903   // too. This will allow it to be selected to a single instruction:
2904   // CSINC Wd, WZR, WZR, invert(cond).
2905   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2906   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2907                          CCVal, Overflow);
2908 
2909   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2910   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2911 }
2912 
2913 // Prefetch operands are:
2914 // 1: Address to prefetch
2915 // 2: bool isWrite
2916 // 3: int locality (0 = no locality ... 3 = extreme locality)
2917 // 4: bool isDataCache
2918 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2919   SDLoc DL(Op);
2920   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2921   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2922   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2923 
2924   bool IsStream = !Locality;
2925   // When the locality number is set
2926   if (Locality) {
2927     // The front-end should have filtered out the out-of-range values
2928     assert(Locality <= 3 && "Prefetch locality out-of-range");
2929     // The locality degree is the opposite of the cache speed.
2930     // Put the number the other way around.
2931     // The encoding starts at 0 for level 1
2932     Locality = 3 - Locality;
2933   }
2934 
2935   // built the mask value encoding the expected behavior.
2936   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2937                    (!IsData << 3) |     // IsDataCache bit
2938                    (Locality << 1) |    // Cache level bits
2939                    (unsigned)IsStream;  // Stream bit
2940   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2941                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2942 }
2943 
2944 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2945                                               SelectionDAG &DAG) const {
2946   if (Op.getValueType().isScalableVector())
2947     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
2948 
2949   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2950 
2951   RTLIB::Libcall LC;
2952   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2953 
2954   return LowerF128Call(Op, DAG, LC);
2955 }
2956 
2957 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2958                                              SelectionDAG &DAG) const {
2959   if (Op.getValueType().isScalableVector())
2960     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
2961 
2962   bool IsStrict = Op->isStrictFPOpcode();
2963   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2964   EVT SrcVT = SrcVal.getValueType();
2965 
2966   if (SrcVT != MVT::f128) {
2967     // Expand cases where the input is a vector bigger than NEON.
2968     if (useSVEForFixedLengthVectorVT(SrcVT))
2969       return SDValue();
2970 
2971     // It's legal except when f128 is involved
2972     return Op;
2973   }
2974 
2975   RTLIB::Libcall LC;
2976   LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2977 
2978   // FP_ROUND node has a second operand indicating whether it is known to be
2979   // precise. That doesn't take part in the LibCall so we can't directly use
2980   // LowerF128Call.
2981   MakeLibCallOptions CallOptions;
2982   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2983   SDValue Result;
2984   SDLoc dl(Op);
2985   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2986                                         CallOptions, dl, Chain);
2987   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2988 }
2989 
2990 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2991                                                     SelectionDAG &DAG) const {
2992   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2993   // Any additional optimization in this function should be recorded
2994   // in the cost tables.
2995   EVT InVT = Op.getOperand(0).getValueType();
2996   EVT VT = Op.getValueType();
2997 
2998   if (VT.isScalableVector()) {
2999     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3000                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3001                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3002     return LowerToPredicatedOp(Op, DAG, Opcode);
3003   }
3004 
3005   unsigned NumElts = InVT.getVectorNumElements();
3006 
3007   // f16 conversions are promoted to f32 when full fp16 is not supported.
3008   if (InVT.getVectorElementType() == MVT::f16 &&
3009       !Subtarget->hasFullFP16()) {
3010     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3011     SDLoc dl(Op);
3012     return DAG.getNode(
3013         Op.getOpcode(), dl, Op.getValueType(),
3014         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3015   }
3016 
3017   uint64_t VTSize = VT.getFixedSizeInBits();
3018   uint64_t InVTSize = InVT.getFixedSizeInBits();
3019   if (VTSize < InVTSize) {
3020     SDLoc dl(Op);
3021     SDValue Cv =
3022         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3023                     Op.getOperand(0));
3024     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3025   }
3026 
3027   if (VTSize > InVTSize) {
3028     SDLoc dl(Op);
3029     MVT ExtVT =
3030         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3031                          VT.getVectorNumElements());
3032     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3033     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3034   }
3035 
3036   // Type changing conversions are illegal.
3037   return Op;
3038 }
3039 
3040 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3041                                               SelectionDAG &DAG) const {
3042   bool IsStrict = Op->isStrictFPOpcode();
3043   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3044 
3045   if (SrcVal.getValueType().isVector())
3046     return LowerVectorFP_TO_INT(Op, DAG);
3047 
3048   // f16 conversions are promoted to f32 when full fp16 is not supported.
3049   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3050     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3051     SDLoc dl(Op);
3052     return DAG.getNode(
3053         Op.getOpcode(), dl, Op.getValueType(),
3054         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3055   }
3056 
3057   if (SrcVal.getValueType() != MVT::f128) {
3058     // It's legal except when f128 is involved
3059     return Op;
3060   }
3061 
3062   RTLIB::Libcall LC;
3063   if (Op.getOpcode() == ISD::FP_TO_SINT ||
3064       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
3065     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
3066   else
3067     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
3068 
3069   return LowerF128Call(Op, DAG, LC);
3070 }
3071 
3072 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3073                                                     SelectionDAG &DAG) const {
3074   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3075   // Any additional optimization in this function should be recorded
3076   // in the cost tables.
3077   EVT VT = Op.getValueType();
3078   SDLoc dl(Op);
3079   SDValue In = Op.getOperand(0);
3080   EVT InVT = In.getValueType();
3081 
3082   if (VT.isScalableVector()) {
3083     unsigned Opcode = Op.getOpcode() == ISD::UINT_TO_FP
3084                           ? AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU
3085                           : AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU;
3086     return LowerToPredicatedOp(Op, DAG, Opcode);
3087   }
3088 
3089   uint64_t VTSize = VT.getFixedSizeInBits();
3090   uint64_t InVTSize = InVT.getFixedSizeInBits();
3091   if (VTSize < InVTSize) {
3092     MVT CastVT =
3093         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3094                          InVT.getVectorNumElements());
3095     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
3096     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3097   }
3098 
3099   if (VTSize > InVTSize) {
3100     unsigned CastOpc =
3101         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3102     EVT CastVT = VT.changeVectorElementTypeToInteger();
3103     In = DAG.getNode(CastOpc, dl, CastVT, In);
3104     return DAG.getNode(Op.getOpcode(), dl, VT, In);
3105   }
3106 
3107   return Op;
3108 }
3109 
3110 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3111                                             SelectionDAG &DAG) const {
3112   if (Op.getValueType().isVector())
3113     return LowerVectorINT_TO_FP(Op, DAG);
3114 
3115   bool IsStrict = Op->isStrictFPOpcode();
3116   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3117 
3118   // f16 conversions are promoted to f32 when full fp16 is not supported.
3119   if (Op.getValueType() == MVT::f16 &&
3120       !Subtarget->hasFullFP16()) {
3121     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3122     SDLoc dl(Op);
3123     return DAG.getNode(
3124         ISD::FP_ROUND, dl, MVT::f16,
3125         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3126         DAG.getIntPtrConstant(0, dl));
3127   }
3128 
3129   // i128 conversions are libcalls.
3130   if (SrcVal.getValueType() == MVT::i128)
3131     return SDValue();
3132 
3133   // Other conversions are legal, unless it's to the completely software-based
3134   // fp128.
3135   if (Op.getValueType() != MVT::f128)
3136     return Op;
3137 
3138   RTLIB::Libcall LC;
3139   if (Op.getOpcode() == ISD::SINT_TO_FP ||
3140       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
3141     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
3142   else
3143     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
3144 
3145   return LowerF128Call(Op, DAG, LC);
3146 }
3147 
3148 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3149                                             SelectionDAG &DAG) const {
3150   // For iOS, we want to call an alternative entry point: __sincos_stret,
3151   // which returns the values in two S / D registers.
3152   SDLoc dl(Op);
3153   SDValue Arg = Op.getOperand(0);
3154   EVT ArgVT = Arg.getValueType();
3155   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3156 
3157   ArgListTy Args;
3158   ArgListEntry Entry;
3159 
3160   Entry.Node = Arg;
3161   Entry.Ty = ArgTy;
3162   Entry.IsSExt = false;
3163   Entry.IsZExt = false;
3164   Args.push_back(Entry);
3165 
3166   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3167                                         : RTLIB::SINCOS_STRET_F32;
3168   const char *LibcallName = getLibcallName(LC);
3169   SDValue Callee =
3170       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3171 
3172   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3173   TargetLowering::CallLoweringInfo CLI(DAG);
3174   CLI.setDebugLoc(dl)
3175       .setChain(DAG.getEntryNode())
3176       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3177 
3178   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3179   return CallResult.first;
3180 }
3181 
3182 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
3183   EVT OpVT = Op.getValueType();
3184   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3185     return SDValue();
3186 
3187   assert(Op.getOperand(0).getValueType() == MVT::i16);
3188   SDLoc DL(Op);
3189 
3190   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3191   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3192   return SDValue(
3193       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3194                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3195       0);
3196 }
3197 
3198 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3199   if (OrigVT.getSizeInBits() >= 64)
3200     return OrigVT;
3201 
3202   assert(OrigVT.isSimple() && "Expecting a simple value type");
3203 
3204   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3205   switch (OrigSimpleTy) {
3206   default: llvm_unreachable("Unexpected Vector Type");
3207   case MVT::v2i8:
3208   case MVT::v2i16:
3209      return MVT::v2i32;
3210   case MVT::v4i8:
3211     return  MVT::v4i16;
3212   }
3213 }
3214 
3215 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3216                                                  const EVT &OrigTy,
3217                                                  const EVT &ExtTy,
3218                                                  unsigned ExtOpcode) {
3219   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3220   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3221   // 64-bits we need to insert a new extension so that it will be 64-bits.
3222   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3223   if (OrigTy.getSizeInBits() >= 64)
3224     return N;
3225 
3226   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3227   EVT NewVT = getExtensionTo64Bits(OrigTy);
3228 
3229   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3230 }
3231 
3232 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3233                                    bool isSigned) {
3234   EVT VT = N->getValueType(0);
3235 
3236   if (N->getOpcode() != ISD::BUILD_VECTOR)
3237     return false;
3238 
3239   for (const SDValue &Elt : N->op_values()) {
3240     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3241       unsigned EltSize = VT.getScalarSizeInBits();
3242       unsigned HalfSize = EltSize / 2;
3243       if (isSigned) {
3244         if (!isIntN(HalfSize, C->getSExtValue()))
3245           return false;
3246       } else {
3247         if (!isUIntN(HalfSize, C->getZExtValue()))
3248           return false;
3249       }
3250       continue;
3251     }
3252     return false;
3253   }
3254 
3255   return true;
3256 }
3257 
3258 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3259   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
3260     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3261                                              N->getOperand(0)->getValueType(0),
3262                                              N->getValueType(0),
3263                                              N->getOpcode());
3264 
3265   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3266   EVT VT = N->getValueType(0);
3267   SDLoc dl(N);
3268   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3269   unsigned NumElts = VT.getVectorNumElements();
3270   MVT TruncVT = MVT::getIntegerVT(EltSize);
3271   SmallVector<SDValue, 8> Ops;
3272   for (unsigned i = 0; i != NumElts; ++i) {
3273     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3274     const APInt &CInt = C->getAPIntValue();
3275     // Element types smaller than 32 bits are not legal, so use i32 elements.
3276     // The values are implicitly truncated so sext vs. zext doesn't matter.
3277     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3278   }
3279   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3280 }
3281 
3282 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3283   return N->getOpcode() == ISD::SIGN_EXTEND ||
3284          isExtendedBUILD_VECTOR(N, DAG, true);
3285 }
3286 
3287 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3288   return N->getOpcode() == ISD::ZERO_EXTEND ||
3289          isExtendedBUILD_VECTOR(N, DAG, false);
3290 }
3291 
3292 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3293   unsigned Opcode = N->getOpcode();
3294   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3295     SDNode *N0 = N->getOperand(0).getNode();
3296     SDNode *N1 = N->getOperand(1).getNode();
3297     return N0->hasOneUse() && N1->hasOneUse() &&
3298       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3299   }
3300   return false;
3301 }
3302 
3303 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3304   unsigned Opcode = N->getOpcode();
3305   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3306     SDNode *N0 = N->getOperand(0).getNode();
3307     SDNode *N1 = N->getOperand(1).getNode();
3308     return N0->hasOneUse() && N1->hasOneUse() &&
3309       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3310   }
3311   return false;
3312 }
3313 
3314 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3315                                                 SelectionDAG &DAG) const {
3316   // The rounding mode is in bits 23:22 of the FPSCR.
3317   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3318   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3319   // so that the shift + and get folded into a bitfield extract.
3320   SDLoc dl(Op);
3321 
3322   SDValue Chain = Op.getOperand(0);
3323   SDValue FPCR_64 = DAG.getNode(
3324       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3325       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3326   Chain = FPCR_64.getValue(1);
3327   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3328   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3329                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3330   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3331                               DAG.getConstant(22, dl, MVT::i32));
3332   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3333                             DAG.getConstant(3, dl, MVT::i32));
3334   return DAG.getMergeValues({AND, Chain}, dl);
3335 }
3336 
3337 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3338   EVT VT = Op.getValueType();
3339 
3340   // If SVE is available then i64 vector multiplications can also be made legal.
3341   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3342 
3343   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3344     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3345 
3346   // Multiplications are only custom-lowered for 128-bit vectors so that
3347   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3348   assert(VT.is128BitVector() && VT.isInteger() &&
3349          "unexpected type for custom-lowering ISD::MUL");
3350   SDNode *N0 = Op.getOperand(0).getNode();
3351   SDNode *N1 = Op.getOperand(1).getNode();
3352   unsigned NewOpc = 0;
3353   bool isMLA = false;
3354   bool isN0SExt = isSignExtended(N0, DAG);
3355   bool isN1SExt = isSignExtended(N1, DAG);
3356   if (isN0SExt && isN1SExt)
3357     NewOpc = AArch64ISD::SMULL;
3358   else {
3359     bool isN0ZExt = isZeroExtended(N0, DAG);
3360     bool isN1ZExt = isZeroExtended(N1, DAG);
3361     if (isN0ZExt && isN1ZExt)
3362       NewOpc = AArch64ISD::UMULL;
3363     else if (isN1SExt || isN1ZExt) {
3364       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3365       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3366       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3367         NewOpc = AArch64ISD::SMULL;
3368         isMLA = true;
3369       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3370         NewOpc =  AArch64ISD::UMULL;
3371         isMLA = true;
3372       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3373         std::swap(N0, N1);
3374         NewOpc =  AArch64ISD::UMULL;
3375         isMLA = true;
3376       }
3377     }
3378 
3379     if (!NewOpc) {
3380       if (VT == MVT::v2i64)
3381         // Fall through to expand this.  It is not legal.
3382         return SDValue();
3383       else
3384         // Other vector multiplications are legal.
3385         return Op;
3386     }
3387   }
3388 
3389   // Legalize to a S/UMULL instruction
3390   SDLoc DL(Op);
3391   SDValue Op0;
3392   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3393   if (!isMLA) {
3394     Op0 = skipExtensionForVectorMULL(N0, DAG);
3395     assert(Op0.getValueType().is64BitVector() &&
3396            Op1.getValueType().is64BitVector() &&
3397            "unexpected types for extended operands to VMULL");
3398     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3399   }
3400   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3401   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3402   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3403   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3404   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3405   EVT Op1VT = Op1.getValueType();
3406   return DAG.getNode(N0->getOpcode(), DL, VT,
3407                      DAG.getNode(NewOpc, DL, VT,
3408                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3409                      DAG.getNode(NewOpc, DL, VT,
3410                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3411 }
3412 
3413 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3414                                int Pattern) {
3415   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3416                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3417 }
3418 
3419 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3420                                                      SelectionDAG &DAG) const {
3421   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3422   SDLoc dl(Op);
3423   switch (IntNo) {
3424   default: return SDValue();    // Don't custom lower most intrinsics.
3425   case Intrinsic::thread_pointer: {
3426     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3427     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3428   }
3429   case Intrinsic::aarch64_neon_abs: {
3430     EVT Ty = Op.getValueType();
3431     if (Ty == MVT::i64) {
3432       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3433                                    Op.getOperand(1));
3434       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3435       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3436     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3437       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3438     } else {
3439       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3440     }
3441   }
3442   case Intrinsic::aarch64_neon_smax:
3443     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3444                        Op.getOperand(1), Op.getOperand(2));
3445   case Intrinsic::aarch64_neon_umax:
3446     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3447                        Op.getOperand(1), Op.getOperand(2));
3448   case Intrinsic::aarch64_neon_smin:
3449     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3450                        Op.getOperand(1), Op.getOperand(2));
3451   case Intrinsic::aarch64_neon_umin:
3452     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3453                        Op.getOperand(1), Op.getOperand(2));
3454 
3455   case Intrinsic::aarch64_sve_sunpkhi:
3456     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3457                        Op.getOperand(1));
3458   case Intrinsic::aarch64_sve_sunpklo:
3459     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3460                        Op.getOperand(1));
3461   case Intrinsic::aarch64_sve_uunpkhi:
3462     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3463                        Op.getOperand(1));
3464   case Intrinsic::aarch64_sve_uunpklo:
3465     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3466                        Op.getOperand(1));
3467   case Intrinsic::aarch64_sve_clasta_n:
3468     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3469                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3470   case Intrinsic::aarch64_sve_clastb_n:
3471     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3472                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3473   case Intrinsic::aarch64_sve_lasta:
3474     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3475                        Op.getOperand(1), Op.getOperand(2));
3476   case Intrinsic::aarch64_sve_lastb:
3477     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3478                        Op.getOperand(1), Op.getOperand(2));
3479   case Intrinsic::aarch64_sve_rev:
3480     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3481                        Op.getOperand(1));
3482   case Intrinsic::aarch64_sve_tbl:
3483     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3484                        Op.getOperand(1), Op.getOperand(2));
3485   case Intrinsic::aarch64_sve_trn1:
3486     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3487                        Op.getOperand(1), Op.getOperand(2));
3488   case Intrinsic::aarch64_sve_trn2:
3489     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3490                        Op.getOperand(1), Op.getOperand(2));
3491   case Intrinsic::aarch64_sve_uzp1:
3492     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3493                        Op.getOperand(1), Op.getOperand(2));
3494   case Intrinsic::aarch64_sve_uzp2:
3495     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3496                        Op.getOperand(1), Op.getOperand(2));
3497   case Intrinsic::aarch64_sve_zip1:
3498     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3499                        Op.getOperand(1), Op.getOperand(2));
3500   case Intrinsic::aarch64_sve_zip2:
3501     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3502                        Op.getOperand(1), Op.getOperand(2));
3503   case Intrinsic::aarch64_sve_ptrue:
3504     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3505                        Op.getOperand(1));
3506   case Intrinsic::aarch64_sve_dupq_lane:
3507     return LowerDUPQLane(Op, DAG);
3508   case Intrinsic::aarch64_sve_convert_from_svbool:
3509     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3510                        Op.getOperand(1));
3511   case Intrinsic::aarch64_sve_fneg:
3512     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
3513                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3514   case Intrinsic::aarch64_sve_frintp:
3515     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
3516                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3517   case Intrinsic::aarch64_sve_frintm:
3518     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
3519                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3520   case Intrinsic::aarch64_sve_frinti:
3521     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3522                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3523   case Intrinsic::aarch64_sve_frintx:
3524     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3525                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3526   case Intrinsic::aarch64_sve_frinta:
3527     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
3528                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3529   case Intrinsic::aarch64_sve_frintn:
3530     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
3531                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3532   case Intrinsic::aarch64_sve_frintz:
3533     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
3534                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3535   case Intrinsic::aarch64_sve_ucvtf:
3536     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
3537                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3538                        Op.getOperand(1));
3539   case Intrinsic::aarch64_sve_scvtf:
3540     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
3541                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3542                        Op.getOperand(1));
3543   case Intrinsic::aarch64_sve_fcvtzu:
3544     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
3545                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3546                        Op.getOperand(1));
3547   case Intrinsic::aarch64_sve_fcvtzs:
3548     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
3549                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3550                        Op.getOperand(1));
3551   case Intrinsic::aarch64_sve_fsqrt:
3552     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
3553                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3554   case Intrinsic::aarch64_sve_frecpx:
3555     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
3556                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3557   case Intrinsic::aarch64_sve_fabs:
3558     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
3559                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3560   case Intrinsic::aarch64_sve_convert_to_svbool: {
3561     EVT OutVT = Op.getValueType();
3562     EVT InVT = Op.getOperand(1).getValueType();
3563     // Return the operand if the cast isn't changing type,
3564     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3565     if (InVT == OutVT)
3566       return Op.getOperand(1);
3567     // Otherwise, zero the newly introduced lanes.
3568     SDValue Reinterpret =
3569         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3570     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3571     SDValue MaskReinterpret =
3572         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3573     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3574   }
3575 
3576   case Intrinsic::aarch64_sve_insr: {
3577     SDValue Scalar = Op.getOperand(2);
3578     EVT ScalarTy = Scalar.getValueType();
3579     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3580       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3581 
3582     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3583                        Op.getOperand(1), Scalar);
3584   }
3585 
3586   case Intrinsic::aarch64_sve_sxtb:
3587     return DAG.getNode(
3588         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3589         Op.getOperand(2), Op.getOperand(3),
3590         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3591         Op.getOperand(1));
3592   case Intrinsic::aarch64_sve_sxth:
3593     return DAG.getNode(
3594         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3595         Op.getOperand(2), Op.getOperand(3),
3596         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3597         Op.getOperand(1));
3598   case Intrinsic::aarch64_sve_sxtw:
3599     return DAG.getNode(
3600         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3601         Op.getOperand(2), Op.getOperand(3),
3602         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3603         Op.getOperand(1));
3604   case Intrinsic::aarch64_sve_uxtb:
3605     return DAG.getNode(
3606         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3607         Op.getOperand(2), Op.getOperand(3),
3608         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3609         Op.getOperand(1));
3610   case Intrinsic::aarch64_sve_uxth:
3611     return DAG.getNode(
3612         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3613         Op.getOperand(2), Op.getOperand(3),
3614         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3615         Op.getOperand(1));
3616   case Intrinsic::aarch64_sve_uxtw:
3617     return DAG.getNode(
3618         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3619         Op.getOperand(2), Op.getOperand(3),
3620         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3621         Op.getOperand(1));
3622 
3623   case Intrinsic::localaddress: {
3624     const auto &MF = DAG.getMachineFunction();
3625     const auto *RegInfo = Subtarget->getRegisterInfo();
3626     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3627     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3628                               Op.getSimpleValueType());
3629   }
3630 
3631   case Intrinsic::eh_recoverfp: {
3632     // FIXME: This needs to be implemented to correctly handle highly aligned
3633     // stack objects. For now we simply return the incoming FP. Refer D53541
3634     // for more details.
3635     SDValue FnOp = Op.getOperand(1);
3636     SDValue IncomingFPOp = Op.getOperand(2);
3637     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3638     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3639     if (!Fn)
3640       report_fatal_error(
3641           "llvm.eh.recoverfp must take a function as the first argument");
3642     return IncomingFPOp;
3643   }
3644 
3645   case Intrinsic::aarch64_neon_vsri:
3646   case Intrinsic::aarch64_neon_vsli: {
3647     EVT Ty = Op.getValueType();
3648 
3649     if (!Ty.isVector())
3650       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3651 
3652     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3653 
3654     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3655     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3656     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3657                        Op.getOperand(3));
3658   }
3659 
3660   case Intrinsic::aarch64_neon_srhadd:
3661   case Intrinsic::aarch64_neon_urhadd:
3662   case Intrinsic::aarch64_neon_shadd:
3663   case Intrinsic::aarch64_neon_uhadd: {
3664     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3665                         IntNo == Intrinsic::aarch64_neon_shadd);
3666     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3667                           IntNo == Intrinsic::aarch64_neon_urhadd);
3668     unsigned Opcode =
3669         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
3670                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
3671     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3672                        Op.getOperand(2));
3673   }
3674 
3675   case Intrinsic::aarch64_neon_uabd: {
3676     return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(),
3677                        Op.getOperand(1), Op.getOperand(2));
3678   }
3679   case Intrinsic::aarch64_neon_sabd: {
3680     return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(),
3681                        Op.getOperand(1), Op.getOperand(2));
3682   }
3683   }
3684 }
3685 
3686 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3687   return ExtVal.getValueType().isScalableVector();
3688 }
3689 
3690 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3691 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3692                                         EVT VT, EVT MemVT,
3693                                         SelectionDAG &DAG) {
3694   assert(VT.isVector() && "VT should be a vector type");
3695   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3696 
3697   SDValue Value = ST->getValue();
3698 
3699   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3700   // the word lane which represent the v4i8 subvector.  It optimizes the store
3701   // to:
3702   //
3703   //   xtn  v0.8b, v0.8h
3704   //   str  s0, [x0]
3705 
3706   SDValue Undef = DAG.getUNDEF(MVT::i16);
3707   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3708                                         {Undef, Undef, Undef, Undef});
3709 
3710   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3711                                  Value, UndefVec);
3712   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3713 
3714   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3715   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3716                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3717 
3718   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3719                       ST->getBasePtr(), ST->getMemOperand());
3720 }
3721 
3722 // Custom lowering for any store, vector or scalar and/or default or with
3723 // a truncate operations.  Currently only custom lower truncate operation
3724 // from vector v4i16 to v4i8 or volatile stores of i128.
3725 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3726                                           SelectionDAG &DAG) const {
3727   SDLoc Dl(Op);
3728   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3729   assert (StoreNode && "Can only custom lower store nodes");
3730 
3731   SDValue Value = StoreNode->getValue();
3732 
3733   EVT VT = Value.getValueType();
3734   EVT MemVT = StoreNode->getMemoryVT();
3735 
3736   if (VT.isVector()) {
3737     if (useSVEForFixedLengthVectorVT(VT))
3738       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3739 
3740     unsigned AS = StoreNode->getAddressSpace();
3741     Align Alignment = StoreNode->getAlign();
3742     if (Alignment < MemVT.getStoreSize() &&
3743         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3744                                         StoreNode->getMemOperand()->getFlags(),
3745                                         nullptr)) {
3746       return scalarizeVectorStore(StoreNode, DAG);
3747     }
3748 
3749     if (StoreNode->isTruncatingStore()) {
3750       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3751     }
3752     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3753     // the custom lowering, as there are no un-paired non-temporal stores and
3754     // legalization will break up 256 bit inputs.
3755     ElementCount EC = MemVT.getVectorElementCount();
3756     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3757         EC.isKnownEven() &&
3758         ((MemVT.getScalarSizeInBits() == 8u ||
3759           MemVT.getScalarSizeInBits() == 16u ||
3760           MemVT.getScalarSizeInBits() == 32u ||
3761           MemVT.getScalarSizeInBits() == 64u))) {
3762       SDValue Lo =
3763           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3764                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3765                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3766       SDValue Hi =
3767           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3768                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3769                       StoreNode->getValue(),
3770                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
3771       SDValue Result = DAG.getMemIntrinsicNode(
3772           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3773           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3774           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3775       return Result;
3776     }
3777   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3778     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3779     SDValue Lo =
3780         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3781                     DAG.getConstant(0, Dl, MVT::i64));
3782     SDValue Hi =
3783         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3784                     DAG.getConstant(1, Dl, MVT::i64));
3785     SDValue Result = DAG.getMemIntrinsicNode(
3786         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3787         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3788         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3789     return Result;
3790   }
3791 
3792   return SDValue();
3793 }
3794 
3795 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3796                                               SelectionDAG &DAG) const {
3797   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3798   LLVM_DEBUG(Op.dump());
3799 
3800   switch (Op.getOpcode()) {
3801   default:
3802     llvm_unreachable("unimplemented operand");
3803     return SDValue();
3804   case ISD::BITCAST:
3805     return LowerBITCAST(Op, DAG);
3806   case ISD::GlobalAddress:
3807     return LowerGlobalAddress(Op, DAG);
3808   case ISD::GlobalTLSAddress:
3809     return LowerGlobalTLSAddress(Op, DAG);
3810   case ISD::SETCC:
3811   case ISD::STRICT_FSETCC:
3812   case ISD::STRICT_FSETCCS:
3813     return LowerSETCC(Op, DAG);
3814   case ISD::BR_CC:
3815     return LowerBR_CC(Op, DAG);
3816   case ISD::SELECT:
3817     return LowerSELECT(Op, DAG);
3818   case ISD::SELECT_CC:
3819     return LowerSELECT_CC(Op, DAG);
3820   case ISD::JumpTable:
3821     return LowerJumpTable(Op, DAG);
3822   case ISD::BR_JT:
3823     return LowerBR_JT(Op, DAG);
3824   case ISD::ConstantPool:
3825     return LowerConstantPool(Op, DAG);
3826   case ISD::BlockAddress:
3827     return LowerBlockAddress(Op, DAG);
3828   case ISD::VASTART:
3829     return LowerVASTART(Op, DAG);
3830   case ISD::VACOPY:
3831     return LowerVACOPY(Op, DAG);
3832   case ISD::VAARG:
3833     return LowerVAARG(Op, DAG);
3834   case ISD::ADDC:
3835   case ISD::ADDE:
3836   case ISD::SUBC:
3837   case ISD::SUBE:
3838     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3839   case ISD::SADDO:
3840   case ISD::UADDO:
3841   case ISD::SSUBO:
3842   case ISD::USUBO:
3843   case ISD::SMULO:
3844   case ISD::UMULO:
3845     return LowerXALUO(Op, DAG);
3846   case ISD::FADD:
3847     if (Op.getValueType() == MVT::f128)
3848       return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3849     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3850   case ISD::FSUB:
3851     if (Op.getValueType() == MVT::f128)
3852       return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3853     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
3854   case ISD::FMUL:
3855     if (Op.getValueType() == MVT::f128)
3856       return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3857     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
3858   case ISD::FMA:
3859     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3860   case ISD::FDIV:
3861     if (Op.getValueType() == MVT::f128)
3862       return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3863     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
3864   case ISD::FNEG:
3865     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
3866   case ISD::FCEIL:
3867     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
3868   case ISD::FFLOOR:
3869     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
3870   case ISD::FNEARBYINT:
3871     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
3872   case ISD::FRINT:
3873     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
3874   case ISD::FROUND:
3875     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
3876   case ISD::FROUNDEVEN:
3877     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
3878   case ISD::FTRUNC:
3879     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
3880   case ISD::FSQRT:
3881     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
3882   case ISD::FABS:
3883     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
3884   case ISD::FP_ROUND:
3885   case ISD::STRICT_FP_ROUND:
3886     return LowerFP_ROUND(Op, DAG);
3887   case ISD::FP_EXTEND:
3888     return LowerFP_EXTEND(Op, DAG);
3889   case ISD::FRAMEADDR:
3890     return LowerFRAMEADDR(Op, DAG);
3891   case ISD::SPONENTRY:
3892     return LowerSPONENTRY(Op, DAG);
3893   case ISD::RETURNADDR:
3894     return LowerRETURNADDR(Op, DAG);
3895   case ISD::ADDROFRETURNADDR:
3896     return LowerADDROFRETURNADDR(Op, DAG);
3897   case ISD::CONCAT_VECTORS:
3898     return LowerCONCAT_VECTORS(Op, DAG);
3899   case ISD::INSERT_VECTOR_ELT:
3900     return LowerINSERT_VECTOR_ELT(Op, DAG);
3901   case ISD::EXTRACT_VECTOR_ELT:
3902     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3903   case ISD::BUILD_VECTOR:
3904     return LowerBUILD_VECTOR(Op, DAG);
3905   case ISD::VECTOR_SHUFFLE:
3906     return LowerVECTOR_SHUFFLE(Op, DAG);
3907   case ISD::SPLAT_VECTOR:
3908     return LowerSPLAT_VECTOR(Op, DAG);
3909   case ISD::EXTRACT_SUBVECTOR:
3910     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3911   case ISD::INSERT_SUBVECTOR:
3912     return LowerINSERT_SUBVECTOR(Op, DAG);
3913   case ISD::SDIV:
3914   case ISD::UDIV:
3915     return LowerDIV(Op, DAG);
3916   case ISD::SMIN:
3917     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
3918                                /*OverrideNEON=*/true);
3919   case ISD::UMIN:
3920     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
3921                                /*OverrideNEON=*/true);
3922   case ISD::SMAX:
3923     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
3924                                /*OverrideNEON=*/true);
3925   case ISD::UMAX:
3926     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
3927                                /*OverrideNEON=*/true);
3928   case ISD::SRA:
3929   case ISD::SRL:
3930   case ISD::SHL:
3931     return LowerVectorSRA_SRL_SHL(Op, DAG);
3932   case ISD::SHL_PARTS:
3933     return LowerShiftLeftParts(Op, DAG);
3934   case ISD::SRL_PARTS:
3935   case ISD::SRA_PARTS:
3936     return LowerShiftRightParts(Op, DAG);
3937   case ISD::CTPOP:
3938     return LowerCTPOP(Op, DAG);
3939   case ISD::FCOPYSIGN:
3940     return LowerFCOPYSIGN(Op, DAG);
3941   case ISD::OR:
3942     return LowerVectorOR(Op, DAG);
3943   case ISD::XOR:
3944     return LowerXOR(Op, DAG);
3945   case ISD::PREFETCH:
3946     return LowerPREFETCH(Op, DAG);
3947   case ISD::SINT_TO_FP:
3948   case ISD::UINT_TO_FP:
3949   case ISD::STRICT_SINT_TO_FP:
3950   case ISD::STRICT_UINT_TO_FP:
3951     return LowerINT_TO_FP(Op, DAG);
3952   case ISD::FP_TO_SINT:
3953   case ISD::FP_TO_UINT:
3954   case ISD::STRICT_FP_TO_SINT:
3955   case ISD::STRICT_FP_TO_UINT:
3956     return LowerFP_TO_INT(Op, DAG);
3957   case ISD::FSINCOS:
3958     return LowerFSINCOS(Op, DAG);
3959   case ISD::FLT_ROUNDS_:
3960     return LowerFLT_ROUNDS_(Op, DAG);
3961   case ISD::MUL:
3962     return LowerMUL(Op, DAG);
3963   case ISD::INTRINSIC_WO_CHAIN:
3964     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3965   case ISD::STORE:
3966     return LowerSTORE(Op, DAG);
3967   case ISD::VECREDUCE_ADD:
3968   case ISD::VECREDUCE_AND:
3969   case ISD::VECREDUCE_OR:
3970   case ISD::VECREDUCE_XOR:
3971   case ISD::VECREDUCE_SMAX:
3972   case ISD::VECREDUCE_SMIN:
3973   case ISD::VECREDUCE_UMAX:
3974   case ISD::VECREDUCE_UMIN:
3975   case ISD::VECREDUCE_FADD:
3976   case ISD::VECREDUCE_FMAX:
3977   case ISD::VECREDUCE_FMIN:
3978     return LowerVECREDUCE(Op, DAG);
3979   case ISD::ATOMIC_LOAD_SUB:
3980     return LowerATOMIC_LOAD_SUB(Op, DAG);
3981   case ISD::ATOMIC_LOAD_AND:
3982     return LowerATOMIC_LOAD_AND(Op, DAG);
3983   case ISD::DYNAMIC_STACKALLOC:
3984     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3985   case ISD::VSCALE:
3986     return LowerVSCALE(Op, DAG);
3987   case ISD::ANY_EXTEND:
3988   case ISD::SIGN_EXTEND:
3989   case ISD::ZERO_EXTEND:
3990     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
3991   case ISD::SIGN_EXTEND_INREG: {
3992     // Only custom lower when ExtraVT has a legal byte based element type.
3993     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3994     EVT ExtraEltVT = ExtraVT.getVectorElementType();
3995     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
3996         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
3997       return SDValue();
3998 
3999     return LowerToPredicatedOp(Op, DAG,
4000                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
4001   }
4002   case ISD::TRUNCATE:
4003     return LowerTRUNCATE(Op, DAG);
4004   case ISD::LOAD:
4005     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
4006       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
4007     llvm_unreachable("Unexpected request to lower ISD::LOAD");
4008   case ISD::ADD:
4009     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
4010   case ISD::AND:
4011     return LowerToScalableOp(Op, DAG);
4012   case ISD::SUB:
4013     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
4014   case ISD::FMAXNUM:
4015     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
4016   case ISD::FMINNUM:
4017     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
4018   case ISD::VSELECT:
4019     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
4020   }
4021 }
4022 
4023 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
4024   // Prefer NEON unless larger SVE registers are available.
4025   return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
4026 }
4027 
4028 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
4029     EVT VT, bool OverrideNEON) const {
4030   if (!useSVEForFixedLengthVectors())
4031     return false;
4032 
4033   if (!VT.isFixedLengthVector())
4034     return false;
4035 
4036   // Don't use SVE for vectors we cannot scalarize if required.
4037   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
4038   // Fixed length predicates should be promoted to i8.
4039   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
4040   case MVT::i1:
4041   default:
4042     return false;
4043   case MVT::i8:
4044   case MVT::i16:
4045   case MVT::i32:
4046   case MVT::i64:
4047   case MVT::f16:
4048   case MVT::f32:
4049   case MVT::f64:
4050     break;
4051   }
4052 
4053   // All SVE implementations support NEON sized vectors.
4054   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
4055     return true;
4056 
4057   // Ensure NEON MVTs only belong to a single register class.
4058   if (VT.getFixedSizeInBits() <= 128)
4059     return false;
4060 
4061   // Don't use SVE for types that don't fit.
4062   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
4063     return false;
4064 
4065   // TODO: Perhaps an artificial restriction, but worth having whilst getting
4066   // the base fixed length SVE support in place.
4067   if (!VT.isPow2VectorType())
4068     return false;
4069 
4070   return true;
4071 }
4072 
4073 //===----------------------------------------------------------------------===//
4074 //                      Calling Convention Implementation
4075 //===----------------------------------------------------------------------===//
4076 
4077 /// Selects the correct CCAssignFn for a given CallingConvention value.
4078 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
4079                                                      bool IsVarArg) const {
4080   switch (CC) {
4081   default:
4082     report_fatal_error("Unsupported calling convention.");
4083   case CallingConv::WebKit_JS:
4084     return CC_AArch64_WebKit_JS;
4085   case CallingConv::GHC:
4086     return CC_AArch64_GHC;
4087   case CallingConv::C:
4088   case CallingConv::Fast:
4089   case CallingConv::PreserveMost:
4090   case CallingConv::CXX_FAST_TLS:
4091   case CallingConv::Swift:
4092     if (Subtarget->isTargetWindows() && IsVarArg)
4093       return CC_AArch64_Win64_VarArg;
4094     if (!Subtarget->isTargetDarwin())
4095       return CC_AArch64_AAPCS;
4096     if (!IsVarArg)
4097       return CC_AArch64_DarwinPCS;
4098     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
4099                                       : CC_AArch64_DarwinPCS_VarArg;
4100    case CallingConv::Win64:
4101     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
4102    case CallingConv::CFGuard_Check:
4103      return CC_AArch64_Win64_CFGuard_Check;
4104    case CallingConv::AArch64_VectorCall:
4105    case CallingConv::AArch64_SVE_VectorCall:
4106      return CC_AArch64_AAPCS;
4107   }
4108 }
4109 
4110 CCAssignFn *
4111 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
4112   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
4113                                       : RetCC_AArch64_AAPCS;
4114 }
4115 
4116 SDValue AArch64TargetLowering::LowerFormalArguments(
4117     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4118     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4119     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4120   MachineFunction &MF = DAG.getMachineFunction();
4121   MachineFrameInfo &MFI = MF.getFrameInfo();
4122   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4123 
4124   // Assign locations to all of the incoming arguments.
4125   SmallVector<CCValAssign, 16> ArgLocs;
4126   DenseMap<unsigned, SDValue> CopiedRegs;
4127   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4128                  *DAG.getContext());
4129 
4130   // At this point, Ins[].VT may already be promoted to i32. To correctly
4131   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4132   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4133   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
4134   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
4135   // LocVT.
4136   unsigned NumArgs = Ins.size();
4137   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4138   unsigned CurArgIdx = 0;
4139   for (unsigned i = 0; i != NumArgs; ++i) {
4140     MVT ValVT = Ins[i].VT;
4141     if (Ins[i].isOrigArg()) {
4142       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
4143       CurArgIdx = Ins[i].getOrigArgIndex();
4144 
4145       // Get type of the original argument.
4146       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
4147                                   /*AllowUnknown*/ true);
4148       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
4149       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4150       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4151         ValVT = MVT::i8;
4152       else if (ActualMVT == MVT::i16)
4153         ValVT = MVT::i16;
4154     }
4155     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4156     bool Res =
4157         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
4158     assert(!Res && "Call operand has unhandled type");
4159     (void)Res;
4160   }
4161   assert(ArgLocs.size() == Ins.size());
4162   SmallVector<SDValue, 16> ArgValues;
4163   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4164     CCValAssign &VA = ArgLocs[i];
4165 
4166     if (Ins[i].Flags.isByVal()) {
4167       // Byval is used for HFAs in the PCS, but the system should work in a
4168       // non-compliant manner for larger structs.
4169       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4170       int Size = Ins[i].Flags.getByValSize();
4171       unsigned NumRegs = (Size + 7) / 8;
4172 
4173       // FIXME: This works on big-endian for composite byvals, which are the common
4174       // case. It should also work for fundamental types too.
4175       unsigned FrameIdx =
4176         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
4177       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
4178       InVals.push_back(FrameIdxN);
4179 
4180       continue;
4181     }
4182 
4183     SDValue ArgValue;
4184     if (VA.isRegLoc()) {
4185       // Arguments stored in registers.
4186       EVT RegVT = VA.getLocVT();
4187       const TargetRegisterClass *RC;
4188 
4189       if (RegVT == MVT::i32)
4190         RC = &AArch64::GPR32RegClass;
4191       else if (RegVT == MVT::i64)
4192         RC = &AArch64::GPR64RegClass;
4193       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4194         RC = &AArch64::FPR16RegClass;
4195       else if (RegVT == MVT::f32)
4196         RC = &AArch64::FPR32RegClass;
4197       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
4198         RC = &AArch64::FPR64RegClass;
4199       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
4200         RC = &AArch64::FPR128RegClass;
4201       else if (RegVT.isScalableVector() &&
4202                RegVT.getVectorElementType() == MVT::i1)
4203         RC = &AArch64::PPRRegClass;
4204       else if (RegVT.isScalableVector())
4205         RC = &AArch64::ZPRRegClass;
4206       else
4207         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4208 
4209       // Transform the arguments in physical registers into virtual ones.
4210       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4211       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
4212 
4213       // If this is an 8, 16 or 32-bit value, it is really passed promoted
4214       // to 64 bits.  Insert an assert[sz]ext to capture this, then
4215       // truncate to the right size.
4216       switch (VA.getLocInfo()) {
4217       default:
4218         llvm_unreachable("Unknown loc info!");
4219       case CCValAssign::Full:
4220         break;
4221       case CCValAssign::Indirect:
4222         assert(VA.getValVT().isScalableVector() &&
4223                "Only scalable vectors can be passed indirectly");
4224         break;
4225       case CCValAssign::BCvt:
4226         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
4227         break;
4228       case CCValAssign::AExt:
4229       case CCValAssign::SExt:
4230       case CCValAssign::ZExt:
4231         break;
4232       case CCValAssign::AExtUpper:
4233         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
4234                                DAG.getConstant(32, DL, RegVT));
4235         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
4236         break;
4237       }
4238     } else { // VA.isRegLoc()
4239       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
4240       unsigned ArgOffset = VA.getLocMemOffset();
4241       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
4242                               ? VA.getLocVT().getSizeInBits()
4243                               : VA.getValVT().getSizeInBits()) / 8;
4244 
4245       uint32_t BEAlign = 0;
4246       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
4247           !Ins[i].Flags.isInConsecutiveRegs())
4248         BEAlign = 8 - ArgSize;
4249 
4250       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
4251 
4252       // Create load nodes to retrieve arguments from the stack.
4253       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4254 
4255       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
4256       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4257       MVT MemVT = VA.getValVT();
4258 
4259       switch (VA.getLocInfo()) {
4260       default:
4261         break;
4262       case CCValAssign::Trunc:
4263       case CCValAssign::BCvt:
4264         MemVT = VA.getLocVT();
4265         break;
4266       case CCValAssign::Indirect:
4267         assert(VA.getValVT().isScalableVector() &&
4268                "Only scalable vectors can be passed indirectly");
4269         MemVT = VA.getLocVT();
4270         break;
4271       case CCValAssign::SExt:
4272         ExtType = ISD::SEXTLOAD;
4273         break;
4274       case CCValAssign::ZExt:
4275         ExtType = ISD::ZEXTLOAD;
4276         break;
4277       case CCValAssign::AExt:
4278         ExtType = ISD::EXTLOAD;
4279         break;
4280       }
4281 
4282       ArgValue = DAG.getExtLoad(
4283           ExtType, DL, VA.getLocVT(), Chain, FIN,
4284           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
4285           MemVT);
4286 
4287     }
4288 
4289     if (VA.getLocInfo() == CCValAssign::Indirect) {
4290       assert(VA.getValVT().isScalableVector() &&
4291            "Only scalable vectors can be passed indirectly");
4292       // If value is passed via pointer - do a load.
4293       ArgValue =
4294           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
4295     }
4296 
4297     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
4298       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
4299                              ArgValue, DAG.getValueType(MVT::i32));
4300     InVals.push_back(ArgValue);
4301   }
4302 
4303   // varargs
4304   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4305   if (isVarArg) {
4306     if (!Subtarget->isTargetDarwin() || IsWin64) {
4307       // The AAPCS variadic function ABI is identical to the non-variadic
4308       // one. As a result there may be more arguments in registers and we should
4309       // save them for future reference.
4310       // Win64 variadic functions also pass arguments in registers, but all float
4311       // arguments are passed in integer registers.
4312       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
4313     }
4314 
4315     // This will point to the next argument passed via stack.
4316     unsigned StackOffset = CCInfo.getNextStackOffset();
4317     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
4318     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
4319     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
4320 
4321     if (MFI.hasMustTailInVarArgFunc()) {
4322       SmallVector<MVT, 2> RegParmTypes;
4323       RegParmTypes.push_back(MVT::i64);
4324       RegParmTypes.push_back(MVT::f128);
4325       // Compute the set of forwarded registers. The rest are scratch.
4326       SmallVectorImpl<ForwardedRegister> &Forwards =
4327                                        FuncInfo->getForwardedMustTailRegParms();
4328       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
4329                                                CC_AArch64_AAPCS);
4330 
4331       // Conservatively forward X8, since it might be used for aggregate return.
4332       if (!CCInfo.isAllocated(AArch64::X8)) {
4333         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
4334         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
4335       }
4336     }
4337   }
4338 
4339   // On Windows, InReg pointers must be returned, so record the pointer in a
4340   // virtual register at the start of the function so it can be returned in the
4341   // epilogue.
4342   if (IsWin64) {
4343     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4344       if (Ins[I].Flags.isInReg()) {
4345         assert(!FuncInfo->getSRetReturnReg());
4346 
4347         MVT PtrTy = getPointerTy(DAG.getDataLayout());
4348         Register Reg =
4349             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4350         FuncInfo->setSRetReturnReg(Reg);
4351 
4352         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
4353         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4354         break;
4355       }
4356     }
4357   }
4358 
4359   unsigned StackArgSize = CCInfo.getNextStackOffset();
4360   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4361   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
4362     // This is a non-standard ABI so by fiat I say we're allowed to make full
4363     // use of the stack area to be popped, which must be aligned to 16 bytes in
4364     // any case:
4365     StackArgSize = alignTo(StackArgSize, 16);
4366 
4367     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
4368     // a multiple of 16.
4369     FuncInfo->setArgumentStackToRestore(StackArgSize);
4370 
4371     // This realignment carries over to the available bytes below. Our own
4372     // callers will guarantee the space is free by giving an aligned value to
4373     // CALLSEQ_START.
4374   }
4375   // Even if we're not expected to free up the space, it's useful to know how
4376   // much is there while considering tail calls (because we can reuse it).
4377   FuncInfo->setBytesInStackArgArea(StackArgSize);
4378 
4379   if (Subtarget->hasCustomCallingConv())
4380     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
4381 
4382   return Chain;
4383 }
4384 
4385 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
4386                                                 SelectionDAG &DAG,
4387                                                 const SDLoc &DL,
4388                                                 SDValue &Chain) const {
4389   MachineFunction &MF = DAG.getMachineFunction();
4390   MachineFrameInfo &MFI = MF.getFrameInfo();
4391   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4392   auto PtrVT = getPointerTy(DAG.getDataLayout());
4393   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4394 
4395   SmallVector<SDValue, 8> MemOps;
4396 
4397   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
4398                                           AArch64::X3, AArch64::X4, AArch64::X5,
4399                                           AArch64::X6, AArch64::X7 };
4400   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
4401   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
4402 
4403   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
4404   int GPRIdx = 0;
4405   if (GPRSaveSize != 0) {
4406     if (IsWin64) {
4407       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
4408       if (GPRSaveSize & 15)
4409         // The extra size here, if triggered, will always be 8.
4410         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
4411     } else
4412       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
4413 
4414     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
4415 
4416     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
4417       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
4418       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
4419       SDValue Store = DAG.getStore(
4420           Val.getValue(1), DL, Val, FIN,
4421           IsWin64
4422               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
4423                                                   GPRIdx,
4424                                                   (i - FirstVariadicGPR) * 8)
4425               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
4426       MemOps.push_back(Store);
4427       FIN =
4428           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
4429     }
4430   }
4431   FuncInfo->setVarArgsGPRIndex(GPRIdx);
4432   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4433 
4434   if (Subtarget->hasFPARMv8() && !IsWin64) {
4435     static const MCPhysReg FPRArgRegs[] = {
4436         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4437         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4438     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4439     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4440 
4441     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4442     int FPRIdx = 0;
4443     if (FPRSaveSize != 0) {
4444       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4445 
4446       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4447 
4448       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4449         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4450         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4451 
4452         SDValue Store = DAG.getStore(
4453             Val.getValue(1), DL, Val, FIN,
4454             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4455         MemOps.push_back(Store);
4456         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4457                           DAG.getConstant(16, DL, PtrVT));
4458       }
4459     }
4460     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4461     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4462   }
4463 
4464   if (!MemOps.empty()) {
4465     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4466   }
4467 }
4468 
4469 /// LowerCallResult - Lower the result values of a call into the
4470 /// appropriate copies out of appropriate physical registers.
4471 SDValue AArch64TargetLowering::LowerCallResult(
4472     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4473     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4474     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4475     SDValue ThisVal) const {
4476   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
4477   // Assign locations to each value returned by this call.
4478   SmallVector<CCValAssign, 16> RVLocs;
4479   DenseMap<unsigned, SDValue> CopiedRegs;
4480   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4481                  *DAG.getContext());
4482   CCInfo.AnalyzeCallResult(Ins, RetCC);
4483 
4484   // Copy all of the result registers out of their specified physreg.
4485   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4486     CCValAssign VA = RVLocs[i];
4487 
4488     // Pass 'this' value directly from the argument to return value, to avoid
4489     // reg unit interference
4490     if (i == 0 && isThisReturn) {
4491       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4492              "unexpected return calling convention register assignment");
4493       InVals.push_back(ThisVal);
4494       continue;
4495     }
4496 
4497     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4498     // allows one use of a physreg per block.
4499     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4500     if (!Val) {
4501       Val =
4502           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4503       Chain = Val.getValue(1);
4504       InFlag = Val.getValue(2);
4505       CopiedRegs[VA.getLocReg()] = Val;
4506     }
4507 
4508     switch (VA.getLocInfo()) {
4509     default:
4510       llvm_unreachable("Unknown loc info!");
4511     case CCValAssign::Full:
4512       break;
4513     case CCValAssign::BCvt:
4514       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4515       break;
4516     case CCValAssign::AExtUpper:
4517       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4518                         DAG.getConstant(32, DL, VA.getLocVT()));
4519       LLVM_FALLTHROUGH;
4520     case CCValAssign::AExt:
4521       LLVM_FALLTHROUGH;
4522     case CCValAssign::ZExt:
4523       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4524       break;
4525     }
4526 
4527     InVals.push_back(Val);
4528   }
4529 
4530   return Chain;
4531 }
4532 
4533 /// Return true if the calling convention is one that we can guarantee TCO for.
4534 static bool canGuaranteeTCO(CallingConv::ID CC) {
4535   return CC == CallingConv::Fast;
4536 }
4537 
4538 /// Return true if we might ever do TCO for calls with this calling convention.
4539 static bool mayTailCallThisCC(CallingConv::ID CC) {
4540   switch (CC) {
4541   case CallingConv::C:
4542   case CallingConv::AArch64_SVE_VectorCall:
4543   case CallingConv::PreserveMost:
4544   case CallingConv::Swift:
4545     return true;
4546   default:
4547     return canGuaranteeTCO(CC);
4548   }
4549 }
4550 
4551 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4552     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4553     const SmallVectorImpl<ISD::OutputArg> &Outs,
4554     const SmallVectorImpl<SDValue> &OutVals,
4555     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4556   if (!mayTailCallThisCC(CalleeCC))
4557     return false;
4558 
4559   MachineFunction &MF = DAG.getMachineFunction();
4560   const Function &CallerF = MF.getFunction();
4561   CallingConv::ID CallerCC = CallerF.getCallingConv();
4562 
4563   // If this function uses the C calling convention but has an SVE signature,
4564   // then it preserves more registers and should assume the SVE_VectorCall CC.
4565   // The check for matching callee-saved regs will determine whether it is
4566   // eligible for TCO.
4567   if (CallerCC == CallingConv::C &&
4568       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
4569     CallerCC = CallingConv::AArch64_SVE_VectorCall;
4570 
4571   bool CCMatch = CallerCC == CalleeCC;
4572 
4573   // When using the Windows calling convention on a non-windows OS, we want
4574   // to back up and restore X18 in such functions; we can't do a tail call
4575   // from those functions.
4576   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4577       CalleeCC != CallingConv::Win64)
4578     return false;
4579 
4580   // Byval parameters hand the function a pointer directly into the stack area
4581   // we want to reuse during a tail call. Working around this *is* possible (see
4582   // X86) but less efficient and uglier in LowerCall.
4583   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4584                                     e = CallerF.arg_end();
4585        i != e; ++i) {
4586     if (i->hasByValAttr())
4587       return false;
4588 
4589     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4590     // In this case, it is necessary to save/restore X0 in the callee. Tail
4591     // call opt interferes with this. So we disable tail call opt when the
4592     // caller has an argument with "inreg" attribute.
4593 
4594     // FIXME: Check whether the callee also has an "inreg" argument.
4595     if (i->hasInRegAttr())
4596       return false;
4597   }
4598 
4599   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4600     return canGuaranteeTCO(CalleeCC) && CCMatch;
4601 
4602   // Externally-defined functions with weak linkage should not be
4603   // tail-called on AArch64 when the OS does not support dynamic
4604   // pre-emption of symbols, as the AAELF spec requires normal calls
4605   // to undefined weak functions to be replaced with a NOP or jump to the
4606   // next instruction. The behaviour of branch instructions in this
4607   // situation (as used for tail calls) is implementation-defined, so we
4608   // cannot rely on the linker replacing the tail call with a return.
4609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4610     const GlobalValue *GV = G->getGlobal();
4611     const Triple &TT = getTargetMachine().getTargetTriple();
4612     if (GV->hasExternalWeakLinkage() &&
4613         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4614       return false;
4615   }
4616 
4617   // Now we search for cases where we can use a tail call without changing the
4618   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4619   // concept.
4620 
4621   // I want anyone implementing a new calling convention to think long and hard
4622   // about this assert.
4623   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4624          "Unexpected variadic calling convention");
4625 
4626   LLVMContext &C = *DAG.getContext();
4627   if (isVarArg && !Outs.empty()) {
4628     // At least two cases here: if caller is fastcc then we can't have any
4629     // memory arguments (we'd be expected to clean up the stack afterwards). If
4630     // caller is C then we could potentially use its argument area.
4631 
4632     // FIXME: for now we take the most conservative of these in both cases:
4633     // disallow all variadic memory operands.
4634     SmallVector<CCValAssign, 16> ArgLocs;
4635     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4636 
4637     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4638     for (const CCValAssign &ArgLoc : ArgLocs)
4639       if (!ArgLoc.isRegLoc())
4640         return false;
4641   }
4642 
4643   // Check that the call results are passed in the same way.
4644   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4645                                   CCAssignFnForCall(CalleeCC, isVarArg),
4646                                   CCAssignFnForCall(CallerCC, isVarArg)))
4647     return false;
4648   // The callee has to preserve all registers the caller needs to preserve.
4649   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4650   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4651   if (!CCMatch) {
4652     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4653     if (Subtarget->hasCustomCallingConv()) {
4654       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4655       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4656     }
4657     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4658       return false;
4659   }
4660 
4661   // Nothing more to check if the callee is taking no arguments
4662   if (Outs.empty())
4663     return true;
4664 
4665   SmallVector<CCValAssign, 16> ArgLocs;
4666   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4667 
4668   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4669 
4670   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4671 
4672   // If any of the arguments is passed indirectly, it must be SVE, so the
4673   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4674   // allocate space on the stack. That is why we determine this explicitly here
4675   // the call cannot be a tailcall.
4676   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4677         assert((A.getLocInfo() != CCValAssign::Indirect ||
4678                 A.getValVT().isScalableVector()) &&
4679                "Expected value to be scalable");
4680         return A.getLocInfo() == CCValAssign::Indirect;
4681       }))
4682     return false;
4683 
4684   // If the stack arguments for this call do not fit into our own save area then
4685   // the call cannot be made tail.
4686   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4687     return false;
4688 
4689   const MachineRegisterInfo &MRI = MF.getRegInfo();
4690   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4691     return false;
4692 
4693   return true;
4694 }
4695 
4696 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4697                                                    SelectionDAG &DAG,
4698                                                    MachineFrameInfo &MFI,
4699                                                    int ClobberedFI) const {
4700   SmallVector<SDValue, 8> ArgChains;
4701   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4702   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4703 
4704   // Include the original chain at the beginning of the list. When this is
4705   // used by target LowerCall hooks, this helps legalize find the
4706   // CALLSEQ_BEGIN node.
4707   ArgChains.push_back(Chain);
4708 
4709   // Add a chain value for each stack argument corresponding
4710   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4711                             UE = DAG.getEntryNode().getNode()->use_end();
4712        U != UE; ++U)
4713     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4714       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4715         if (FI->getIndex() < 0) {
4716           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4717           int64_t InLastByte = InFirstByte;
4718           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4719 
4720           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4721               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4722             ArgChains.push_back(SDValue(L, 1));
4723         }
4724 
4725   // Build a tokenfactor for all the chains.
4726   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4727 }
4728 
4729 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4730                                                    bool TailCallOpt) const {
4731   return CallCC == CallingConv::Fast && TailCallOpt;
4732 }
4733 
4734 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4735 /// and add input and output parameter nodes.
4736 SDValue
4737 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4738                                  SmallVectorImpl<SDValue> &InVals) const {
4739   SelectionDAG &DAG = CLI.DAG;
4740   SDLoc &DL = CLI.DL;
4741   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4742   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4743   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4744   SDValue Chain = CLI.Chain;
4745   SDValue Callee = CLI.Callee;
4746   bool &IsTailCall = CLI.IsTailCall;
4747   CallingConv::ID CallConv = CLI.CallConv;
4748   bool IsVarArg = CLI.IsVarArg;
4749 
4750   MachineFunction &MF = DAG.getMachineFunction();
4751   MachineFunction::CallSiteInfo CSInfo;
4752   bool IsThisReturn = false;
4753 
4754   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4755   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4756   bool IsSibCall = false;
4757 
4758   // Check callee args/returns for SVE registers and set calling convention
4759   // accordingly.
4760   if (CallConv == CallingConv::C) {
4761     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4762       return Out.VT.isScalableVector();
4763     });
4764     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4765       return In.VT.isScalableVector();
4766     });
4767 
4768     if (CalleeInSVE || CalleeOutSVE)
4769       CallConv = CallingConv::AArch64_SVE_VectorCall;
4770   }
4771 
4772   if (IsTailCall) {
4773     // Check if it's really possible to do a tail call.
4774     IsTailCall = isEligibleForTailCallOptimization(
4775         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4776     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4777       report_fatal_error("failed to perform tail call elimination on a call "
4778                          "site marked musttail");
4779 
4780     // A sibling call is one where we're under the usual C ABI and not planning
4781     // to change that but can still do a tail call:
4782     if (!TailCallOpt && IsTailCall)
4783       IsSibCall = true;
4784 
4785     if (IsTailCall)
4786       ++NumTailCalls;
4787   }
4788 
4789   // Analyze operands of the call, assigning locations to each operand.
4790   SmallVector<CCValAssign, 16> ArgLocs;
4791   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4792                  *DAG.getContext());
4793 
4794   if (IsVarArg) {
4795     // Handle fixed and variable vector arguments differently.
4796     // Variable vector arguments always go into memory.
4797     unsigned NumArgs = Outs.size();
4798 
4799     for (unsigned i = 0; i != NumArgs; ++i) {
4800       MVT ArgVT = Outs[i].VT;
4801       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4802       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4803                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4804       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4805       assert(!Res && "Call operand has unhandled type");
4806       (void)Res;
4807     }
4808   } else {
4809     // At this point, Outs[].VT may already be promoted to i32. To correctly
4810     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4811     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4812     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4813     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4814     // LocVT.
4815     unsigned NumArgs = Outs.size();
4816     for (unsigned i = 0; i != NumArgs; ++i) {
4817       MVT ValVT = Outs[i].VT;
4818       // Get type of the original argument.
4819       EVT ActualVT = getValueType(DAG.getDataLayout(),
4820                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4821                                   /*AllowUnknown*/ true);
4822       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4823       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4824       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4825       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4826         ValVT = MVT::i8;
4827       else if (ActualMVT == MVT::i16)
4828         ValVT = MVT::i16;
4829 
4830       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4831       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4832       assert(!Res && "Call operand has unhandled type");
4833       (void)Res;
4834     }
4835   }
4836 
4837   // Get a count of how many bytes are to be pushed on the stack.
4838   unsigned NumBytes = CCInfo.getNextStackOffset();
4839 
4840   if (IsSibCall) {
4841     // Since we're not changing the ABI to make this a tail call, the memory
4842     // operands are already available in the caller's incoming argument space.
4843     NumBytes = 0;
4844   }
4845 
4846   // FPDiff is the byte offset of the call's argument area from the callee's.
4847   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4848   // by this amount for a tail call. In a sibling call it must be 0 because the
4849   // caller will deallocate the entire stack and the callee still expects its
4850   // arguments to begin at SP+0. Completely unused for non-tail calls.
4851   int FPDiff = 0;
4852 
4853   if (IsTailCall && !IsSibCall) {
4854     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4855 
4856     // Since callee will pop argument stack as a tail call, we must keep the
4857     // popped size 16-byte aligned.
4858     NumBytes = alignTo(NumBytes, 16);
4859 
4860     // FPDiff will be negative if this tail call requires more space than we
4861     // would automatically have in our incoming argument space. Positive if we
4862     // can actually shrink the stack.
4863     FPDiff = NumReusableBytes - NumBytes;
4864 
4865     // The stack pointer must be 16-byte aligned at all times it's used for a
4866     // memory operation, which in practice means at *all* times and in
4867     // particular across call boundaries. Therefore our own arguments started at
4868     // a 16-byte aligned SP and the delta applied for the tail call should
4869     // satisfy the same constraint.
4870     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4871   }
4872 
4873   // Adjust the stack pointer for the new arguments...
4874   // These operations are automatically eliminated by the prolog/epilog pass
4875   if (!IsSibCall)
4876     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4877 
4878   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4879                                         getPointerTy(DAG.getDataLayout()));
4880 
4881   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4882   SmallSet<unsigned, 8> RegsUsed;
4883   SmallVector<SDValue, 8> MemOpChains;
4884   auto PtrVT = getPointerTy(DAG.getDataLayout());
4885 
4886   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4887     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4888     for (const auto &F : Forwards) {
4889       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4890        RegsToPass.emplace_back(F.PReg, Val);
4891     }
4892   }
4893 
4894   // Walk the register/memloc assignments, inserting copies/loads.
4895   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4896     CCValAssign &VA = ArgLocs[i];
4897     SDValue Arg = OutVals[i];
4898     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4899 
4900     // Promote the value if needed.
4901     switch (VA.getLocInfo()) {
4902     default:
4903       llvm_unreachable("Unknown loc info!");
4904     case CCValAssign::Full:
4905       break;
4906     case CCValAssign::SExt:
4907       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4908       break;
4909     case CCValAssign::ZExt:
4910       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4911       break;
4912     case CCValAssign::AExt:
4913       if (Outs[i].ArgVT == MVT::i1) {
4914         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4915         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4916         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4917       }
4918       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4919       break;
4920     case CCValAssign::AExtUpper:
4921       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4922       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4923       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4924                         DAG.getConstant(32, DL, VA.getLocVT()));
4925       break;
4926     case CCValAssign::BCvt:
4927       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4928       break;
4929     case CCValAssign::Trunc:
4930       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4931       break;
4932     case CCValAssign::FPExt:
4933       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4934       break;
4935     case CCValAssign::Indirect:
4936       assert(VA.getValVT().isScalableVector() &&
4937              "Only scalable vectors can be passed indirectly");
4938       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4939       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4940       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4941       int FI = MFI.CreateStackObject(
4942           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4943       MFI.setStackID(FI, TargetStackID::SVEVector);
4944 
4945       SDValue SpillSlot = DAG.getFrameIndex(
4946           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4947       Chain = DAG.getStore(
4948           Chain, DL, Arg, SpillSlot,
4949           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4950       Arg = SpillSlot;
4951       break;
4952     }
4953 
4954     if (VA.isRegLoc()) {
4955       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4956           Outs[0].VT == MVT::i64) {
4957         assert(VA.getLocVT() == MVT::i64 &&
4958                "unexpected calling convention register assignment");
4959         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4960                "unexpected use of 'returned'");
4961         IsThisReturn = true;
4962       }
4963       if (RegsUsed.count(VA.getLocReg())) {
4964         // If this register has already been used then we're trying to pack
4965         // parts of an [N x i32] into an X-register. The extension type will
4966         // take care of putting the two halves in the right place but we have to
4967         // combine them.
4968         SDValue &Bits =
4969             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4970                          [=](const std::pair<unsigned, SDValue> &Elt) {
4971                            return Elt.first == VA.getLocReg();
4972                          })
4973                 ->second;
4974         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4975         // Call site info is used for function's parameter entry value
4976         // tracking. For now we track only simple cases when parameter
4977         // is transferred through whole register.
4978         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4979                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4980                                       return ArgReg.Reg == VA.getLocReg();
4981                                     }),
4982                      CSInfo.end());
4983       } else {
4984         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4985         RegsUsed.insert(VA.getLocReg());
4986         const TargetOptions &Options = DAG.getTarget().Options;
4987         if (Options.EmitCallSiteInfo)
4988           CSInfo.emplace_back(VA.getLocReg(), i);
4989       }
4990     } else {
4991       assert(VA.isMemLoc());
4992 
4993       SDValue DstAddr;
4994       MachinePointerInfo DstInfo;
4995 
4996       // FIXME: This works on big-endian for composite byvals, which are the
4997       // common case. It should also work for fundamental types too.
4998       uint32_t BEAlign = 0;
4999       unsigned OpSize;
5000       if (VA.getLocInfo() == CCValAssign::Indirect)
5001         OpSize = VA.getLocVT().getSizeInBits();
5002       else
5003         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
5004                                  : VA.getValVT().getSizeInBits();
5005       OpSize = (OpSize + 7) / 8;
5006       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
5007           !Flags.isInConsecutiveRegs()) {
5008         if (OpSize < 8)
5009           BEAlign = 8 - OpSize;
5010       }
5011       unsigned LocMemOffset = VA.getLocMemOffset();
5012       int32_t Offset = LocMemOffset + BEAlign;
5013       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5014       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5015 
5016       if (IsTailCall) {
5017         Offset = Offset + FPDiff;
5018         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5019 
5020         DstAddr = DAG.getFrameIndex(FI, PtrVT);
5021         DstInfo =
5022             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
5023 
5024         // Make sure any stack arguments overlapping with where we're storing
5025         // are loaded before this eventual operation. Otherwise they'll be
5026         // clobbered.
5027         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
5028       } else {
5029         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5030 
5031         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5032         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
5033                                                LocMemOffset);
5034       }
5035 
5036       if (Outs[i].Flags.isByVal()) {
5037         SDValue SizeNode =
5038             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
5039         SDValue Cpy = DAG.getMemcpy(
5040             Chain, DL, DstAddr, Arg, SizeNode,
5041             Outs[i].Flags.getNonZeroByValAlign(),
5042             /*isVol = */ false, /*AlwaysInline = */ false,
5043             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
5044 
5045         MemOpChains.push_back(Cpy);
5046       } else {
5047         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
5048         // promoted to a legal register type i32, we should truncate Arg back to
5049         // i1/i8/i16.
5050         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
5051             VA.getValVT() == MVT::i16)
5052           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
5053 
5054         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
5055         MemOpChains.push_back(Store);
5056       }
5057     }
5058   }
5059 
5060   if (!MemOpChains.empty())
5061     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
5062 
5063   // Build a sequence of copy-to-reg nodes chained together with token chain
5064   // and flag operands which copy the outgoing args into the appropriate regs.
5065   SDValue InFlag;
5066   for (auto &RegToPass : RegsToPass) {
5067     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
5068                              RegToPass.second, InFlag);
5069     InFlag = Chain.getValue(1);
5070   }
5071 
5072   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
5073   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
5074   // node so that legalize doesn't hack it.
5075   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5076     auto GV = G->getGlobal();
5077     unsigned OpFlags =
5078         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
5079     if (OpFlags & AArch64II::MO_GOT) {
5080       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
5081       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5082     } else {
5083       const GlobalValue *GV = G->getGlobal();
5084       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
5085     }
5086   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5087     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5088         Subtarget->isTargetMachO()) {
5089       const char *Sym = S->getSymbol();
5090       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
5091       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5092     } else {
5093       const char *Sym = S->getSymbol();
5094       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
5095     }
5096   }
5097 
5098   // We don't usually want to end the call-sequence here because we would tidy
5099   // the frame up *after* the call, however in the ABI-changing tail-call case
5100   // we've carefully laid out the parameters so that when sp is reset they'll be
5101   // in the correct location.
5102   if (IsTailCall && !IsSibCall) {
5103     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5104                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
5105     InFlag = Chain.getValue(1);
5106   }
5107 
5108   std::vector<SDValue> Ops;
5109   Ops.push_back(Chain);
5110   Ops.push_back(Callee);
5111 
5112   if (IsTailCall) {
5113     // Each tail call may have to adjust the stack by a different amount, so
5114     // this information must travel along with the operation for eventual
5115     // consumption by emitEpilogue.
5116     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
5117   }
5118 
5119   // Add argument registers to the end of the list so that they are known live
5120   // into the call.
5121   for (auto &RegToPass : RegsToPass)
5122     Ops.push_back(DAG.getRegister(RegToPass.first,
5123                                   RegToPass.second.getValueType()));
5124 
5125   // Add a register mask operand representing the call-preserved registers.
5126   const uint32_t *Mask;
5127   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5128   if (IsThisReturn) {
5129     // For 'this' returns, use the X0-preserving mask if applicable
5130     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
5131     if (!Mask) {
5132       IsThisReturn = false;
5133       Mask = TRI->getCallPreservedMask(MF, CallConv);
5134     }
5135   } else
5136     Mask = TRI->getCallPreservedMask(MF, CallConv);
5137 
5138   if (Subtarget->hasCustomCallingConv())
5139     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
5140 
5141   if (TRI->isAnyArgRegReserved(MF))
5142     TRI->emitReservedArgRegCallError(MF);
5143 
5144   assert(Mask && "Missing call preserved mask for calling convention");
5145   Ops.push_back(DAG.getRegisterMask(Mask));
5146 
5147   if (InFlag.getNode())
5148     Ops.push_back(InFlag);
5149 
5150   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5151 
5152   // If we're doing a tall call, use a TC_RETURN here rather than an
5153   // actual call instruction.
5154   if (IsTailCall) {
5155     MF.getFrameInfo().setHasTailCall();
5156     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
5157     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
5158     return Ret;
5159   }
5160 
5161   // Returns a chain and a flag for retval copy to use.
5162   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
5163   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5164   InFlag = Chain.getValue(1);
5165   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
5166 
5167   uint64_t CalleePopBytes =
5168       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
5169 
5170   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5171                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
5172                              InFlag, DL);
5173   if (!Ins.empty())
5174     InFlag = Chain.getValue(1);
5175 
5176   // Handle result values, copying them out of physregs into vregs that we
5177   // return.
5178   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
5179                          InVals, IsThisReturn,
5180                          IsThisReturn ? OutVals[0] : SDValue());
5181 }
5182 
5183 bool AArch64TargetLowering::CanLowerReturn(
5184     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
5185     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
5186   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5187   SmallVector<CCValAssign, 16> RVLocs;
5188   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5189   return CCInfo.CheckReturn(Outs, RetCC);
5190 }
5191 
5192 SDValue
5193 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5194                                    bool isVarArg,
5195                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
5196                                    const SmallVectorImpl<SDValue> &OutVals,
5197                                    const SDLoc &DL, SelectionDAG &DAG) const {
5198   auto &MF = DAG.getMachineFunction();
5199   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5200 
5201   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5202   SmallVector<CCValAssign, 16> RVLocs;
5203   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5204                  *DAG.getContext());
5205   CCInfo.AnalyzeReturn(Outs, RetCC);
5206 
5207   // Copy the result values into the output registers.
5208   SDValue Flag;
5209   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
5210   SmallSet<unsigned, 4> RegsUsed;
5211   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
5212        ++i, ++realRVLocIdx) {
5213     CCValAssign &VA = RVLocs[i];
5214     assert(VA.isRegLoc() && "Can only return in registers!");
5215     SDValue Arg = OutVals[realRVLocIdx];
5216 
5217     switch (VA.getLocInfo()) {
5218     default:
5219       llvm_unreachable("Unknown loc info!");
5220     case CCValAssign::Full:
5221       if (Outs[i].ArgVT == MVT::i1) {
5222         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
5223         // value. This is strictly redundant on Darwin (which uses "zeroext
5224         // i1"), but will be optimised out before ISel.
5225         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5226         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5227       }
5228       break;
5229     case CCValAssign::BCvt:
5230       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
5231       break;
5232     case CCValAssign::AExt:
5233     case CCValAssign::ZExt:
5234       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5235       break;
5236     case CCValAssign::AExtUpper:
5237       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5238       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5239       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5240                         DAG.getConstant(32, DL, VA.getLocVT()));
5241       break;
5242     }
5243 
5244     if (RegsUsed.count(VA.getLocReg())) {
5245       SDValue &Bits =
5246           std::find_if(RetVals.begin(), RetVals.end(),
5247                        [=](const std::pair<unsigned, SDValue> &Elt) {
5248                          return Elt.first == VA.getLocReg();
5249                        })
5250               ->second;
5251       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5252     } else {
5253       RetVals.emplace_back(VA.getLocReg(), Arg);
5254       RegsUsed.insert(VA.getLocReg());
5255     }
5256   }
5257 
5258   SmallVector<SDValue, 4> RetOps(1, Chain);
5259   for (auto &RetVal : RetVals) {
5260     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
5261     Flag = Chain.getValue(1);
5262     RetOps.push_back(
5263         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
5264   }
5265 
5266   // Windows AArch64 ABIs require that for returning structs by value we copy
5267   // the sret argument into X0 for the return.
5268   // We saved the argument into a virtual register in the entry block,
5269   // so now we copy the value out and into X0.
5270   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
5271     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
5272                                      getPointerTy(MF.getDataLayout()));
5273 
5274     unsigned RetValReg = AArch64::X0;
5275     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
5276     Flag = Chain.getValue(1);
5277 
5278     RetOps.push_back(
5279       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
5280   }
5281 
5282   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5283   const MCPhysReg *I =
5284       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5285   if (I) {
5286     for (; *I; ++I) {
5287       if (AArch64::GPR64RegClass.contains(*I))
5288         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5289       else if (AArch64::FPR64RegClass.contains(*I))
5290         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5291       else
5292         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5293     }
5294   }
5295 
5296   RetOps[0] = Chain; // Update chain.
5297 
5298   // Add the flag if we have it.
5299   if (Flag.getNode())
5300     RetOps.push_back(Flag);
5301 
5302   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
5303 }
5304 
5305 //===----------------------------------------------------------------------===//
5306 //  Other Lowering Code
5307 //===----------------------------------------------------------------------===//
5308 
5309 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
5310                                              SelectionDAG &DAG,
5311                                              unsigned Flag) const {
5312   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
5313                                     N->getOffset(), Flag);
5314 }
5315 
5316 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
5317                                              SelectionDAG &DAG,
5318                                              unsigned Flag) const {
5319   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
5320 }
5321 
5322 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
5323                                              SelectionDAG &DAG,
5324                                              unsigned Flag) const {
5325   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
5326                                    N->getOffset(), Flag);
5327 }
5328 
5329 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
5330                                              SelectionDAG &DAG,
5331                                              unsigned Flag) const {
5332   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
5333 }
5334 
5335 // (loadGOT sym)
5336 template <class NodeTy>
5337 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
5338                                       unsigned Flags) const {
5339   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
5340   SDLoc DL(N);
5341   EVT Ty = getPointerTy(DAG.getDataLayout());
5342   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
5343   // FIXME: Once remat is capable of dealing with instructions with register
5344   // operands, expand this into two nodes instead of using a wrapper node.
5345   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
5346 }
5347 
5348 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
5349 template <class NodeTy>
5350 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
5351                                             unsigned Flags) const {
5352   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
5353   SDLoc DL(N);
5354   EVT Ty = getPointerTy(DAG.getDataLayout());
5355   const unsigned char MO_NC = AArch64II::MO_NC;
5356   return DAG.getNode(
5357       AArch64ISD::WrapperLarge, DL, Ty,
5358       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
5359       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
5360       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
5361       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
5362 }
5363 
5364 // (addlow (adrp %hi(sym)) %lo(sym))
5365 template <class NodeTy>
5366 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
5367                                        unsigned Flags) const {
5368   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
5369   SDLoc DL(N);
5370   EVT Ty = getPointerTy(DAG.getDataLayout());
5371   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
5372   SDValue Lo = getTargetNode(N, Ty, DAG,
5373                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
5374   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
5375   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
5376 }
5377 
5378 // (adr sym)
5379 template <class NodeTy>
5380 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
5381                                            unsigned Flags) const {
5382   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
5383   SDLoc DL(N);
5384   EVT Ty = getPointerTy(DAG.getDataLayout());
5385   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
5386   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
5387 }
5388 
5389 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
5390                                                   SelectionDAG &DAG) const {
5391   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
5392   const GlobalValue *GV = GN->getGlobal();
5393   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5394 
5395   if (OpFlags != AArch64II::MO_NO_FLAG)
5396     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
5397            "unexpected offset in global node");
5398 
5399   // This also catches the large code model case for Darwin, and tiny code
5400   // model with got relocations.
5401   if ((OpFlags & AArch64II::MO_GOT) != 0) {
5402     return getGOT(GN, DAG, OpFlags);
5403   }
5404 
5405   SDValue Result;
5406   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5407     Result = getAddrLarge(GN, DAG, OpFlags);
5408   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5409     Result = getAddrTiny(GN, DAG, OpFlags);
5410   } else {
5411     Result = getAddr(GN, DAG, OpFlags);
5412   }
5413   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5414   SDLoc DL(GN);
5415   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
5416     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
5417                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
5418   return Result;
5419 }
5420 
5421 /// Convert a TLS address reference into the correct sequence of loads
5422 /// and calls to compute the variable's address (for Darwin, currently) and
5423 /// return an SDValue containing the final node.
5424 
5425 /// Darwin only has one TLS scheme which must be capable of dealing with the
5426 /// fully general situation, in the worst case. This means:
5427 ///     + "extern __thread" declaration.
5428 ///     + Defined in a possibly unknown dynamic library.
5429 ///
5430 /// The general system is that each __thread variable has a [3 x i64] descriptor
5431 /// which contains information used by the runtime to calculate the address. The
5432 /// only part of this the compiler needs to know about is the first xword, which
5433 /// contains a function pointer that must be called with the address of the
5434 /// entire descriptor in "x0".
5435 ///
5436 /// Since this descriptor may be in a different unit, in general even the
5437 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5438 /// is:
5439 ///     adrp x0, _var@TLVPPAGE
5440 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5441 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5442 ///                                      ; the function pointer
5443 ///     blr x1                           ; Uses descriptor address in x0
5444 ///     ; Address of _var is now in x0.
5445 ///
5446 /// If the address of _var's descriptor *is* known to the linker, then it can
5447 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5448 /// a slight efficiency gain.
5449 SDValue
5450 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5451                                                    SelectionDAG &DAG) const {
5452   assert(Subtarget->isTargetDarwin() &&
5453          "This function expects a Darwin target");
5454 
5455   SDLoc DL(Op);
5456   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5457   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5458   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5459 
5460   SDValue TLVPAddr =
5461       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5462   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5463 
5464   // The first entry in the descriptor is a function pointer that we must call
5465   // to obtain the address of the variable.
5466   SDValue Chain = DAG.getEntryNode();
5467   SDValue FuncTLVGet = DAG.getLoad(
5468       PtrMemVT, DL, Chain, DescAddr,
5469       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5470       Align(PtrMemVT.getSizeInBits() / 8),
5471       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5472   Chain = FuncTLVGet.getValue(1);
5473 
5474   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5475   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5476 
5477   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5478   MFI.setAdjustsStack(true);
5479 
5480   // TLS calls preserve all registers except those that absolutely must be
5481   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5482   // silly).
5483   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5484   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5485   if (Subtarget->hasCustomCallingConv())
5486     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5487 
5488   // Finally, we can make the call. This is just a degenerate version of a
5489   // normal AArch64 call node: x0 takes the address of the descriptor, and
5490   // returns the address of the variable in this thread.
5491   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5492   Chain =
5493       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5494                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5495                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5496   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5497 }
5498 
5499 /// Convert a thread-local variable reference into a sequence of instructions to
5500 /// compute the variable's address for the local exec TLS model of ELF targets.
5501 /// The sequence depends on the maximum TLS area size.
5502 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5503                                                     SDValue ThreadBase,
5504                                                     const SDLoc &DL,
5505                                                     SelectionDAG &DAG) const {
5506   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5507   SDValue TPOff, Addr;
5508 
5509   switch (DAG.getTarget().Options.TLSSize) {
5510   default:
5511     llvm_unreachable("Unexpected TLS size");
5512 
5513   case 12: {
5514     // mrs   x0, TPIDR_EL0
5515     // add   x0, x0, :tprel_lo12:a
5516     SDValue Var = DAG.getTargetGlobalAddress(
5517         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5518     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5519                                       Var,
5520                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5521                    0);
5522   }
5523 
5524   case 24: {
5525     // mrs   x0, TPIDR_EL0
5526     // add   x0, x0, :tprel_hi12:a
5527     // add   x0, x0, :tprel_lo12_nc:a
5528     SDValue HiVar = DAG.getTargetGlobalAddress(
5529         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5530     SDValue LoVar = DAG.getTargetGlobalAddress(
5531         GV, DL, PtrVT, 0,
5532         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5533     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5534                                       HiVar,
5535                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5536                    0);
5537     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5538                                       LoVar,
5539                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5540                    0);
5541   }
5542 
5543   case 32: {
5544     // mrs   x1, TPIDR_EL0
5545     // movz  x0, #:tprel_g1:a
5546     // movk  x0, #:tprel_g0_nc:a
5547     // add   x0, x1, x0
5548     SDValue HiVar = DAG.getTargetGlobalAddress(
5549         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5550     SDValue LoVar = DAG.getTargetGlobalAddress(
5551         GV, DL, PtrVT, 0,
5552         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5553     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5554                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5555                     0);
5556     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5557                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5558                     0);
5559     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5560   }
5561 
5562   case 48: {
5563     // mrs   x1, TPIDR_EL0
5564     // movz  x0, #:tprel_g2:a
5565     // movk  x0, #:tprel_g1_nc:a
5566     // movk  x0, #:tprel_g0_nc:a
5567     // add   x0, x1, x0
5568     SDValue HiVar = DAG.getTargetGlobalAddress(
5569         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5570     SDValue MiVar = DAG.getTargetGlobalAddress(
5571         GV, DL, PtrVT, 0,
5572         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5573     SDValue LoVar = DAG.getTargetGlobalAddress(
5574         GV, DL, PtrVT, 0,
5575         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5576     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5577                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5578                     0);
5579     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5580                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5581                     0);
5582     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5583                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5584                     0);
5585     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5586   }
5587   }
5588 }
5589 
5590 /// When accessing thread-local variables under either the general-dynamic or
5591 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5592 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5593 /// is a function pointer to carry out the resolution.
5594 ///
5595 /// The sequence is:
5596 ///    adrp  x0, :tlsdesc:var
5597 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5598 ///    add   x0, x0, #:tlsdesc_lo12:var
5599 ///    .tlsdesccall var
5600 ///    blr   x1
5601 ///    (TPIDR_EL0 offset now in x0)
5602 ///
5603 ///  The above sequence must be produced unscheduled, to enable the linker to
5604 ///  optimize/relax this sequence.
5605 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5606 ///  above sequence, and expanded really late in the compilation flow, to ensure
5607 ///  the sequence is produced as per above.
5608 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5609                                                       const SDLoc &DL,
5610                                                       SelectionDAG &DAG) const {
5611   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5612 
5613   SDValue Chain = DAG.getEntryNode();
5614   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5615 
5616   Chain =
5617       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5618   SDValue Glue = Chain.getValue(1);
5619 
5620   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5621 }
5622 
5623 SDValue
5624 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5625                                                 SelectionDAG &DAG) const {
5626   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5627 
5628   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5629 
5630   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5631 
5632   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5633     if (Model == TLSModel::LocalDynamic)
5634       Model = TLSModel::GeneralDynamic;
5635   }
5636 
5637   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5638       Model != TLSModel::LocalExec)
5639     report_fatal_error("ELF TLS only supported in small memory model or "
5640                        "in local exec TLS model");
5641   // Different choices can be made for the maximum size of the TLS area for a
5642   // module. For the small address model, the default TLS size is 16MiB and the
5643   // maximum TLS size is 4GiB.
5644   // FIXME: add tiny and large code model support for TLS access models other
5645   // than local exec. We currently generate the same code as small for tiny,
5646   // which may be larger than needed.
5647 
5648   SDValue TPOff;
5649   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5650   SDLoc DL(Op);
5651   const GlobalValue *GV = GA->getGlobal();
5652 
5653   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5654 
5655   if (Model == TLSModel::LocalExec) {
5656     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5657   } else if (Model == TLSModel::InitialExec) {
5658     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5659     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5660   } else if (Model == TLSModel::LocalDynamic) {
5661     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5662     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5663     // the beginning of the module's TLS region, followed by a DTPREL offset
5664     // calculation.
5665 
5666     // These accesses will need deduplicating if there's more than one.
5667     AArch64FunctionInfo *MFI =
5668         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5669     MFI->incNumLocalDynamicTLSAccesses();
5670 
5671     // The call needs a relocation too for linker relaxation. It doesn't make
5672     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5673     // the address.
5674     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5675                                                   AArch64II::MO_TLS);
5676 
5677     // Now we can calculate the offset from TPIDR_EL0 to this module's
5678     // thread-local area.
5679     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5680 
5681     // Now use :dtprel_whatever: operations to calculate this variable's offset
5682     // in its thread-storage area.
5683     SDValue HiVar = DAG.getTargetGlobalAddress(
5684         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5685     SDValue LoVar = DAG.getTargetGlobalAddress(
5686         GV, DL, MVT::i64, 0,
5687         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5688 
5689     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5690                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5691                     0);
5692     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5693                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5694                     0);
5695   } else if (Model == TLSModel::GeneralDynamic) {
5696     // The call needs a relocation too for linker relaxation. It doesn't make
5697     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5698     // the address.
5699     SDValue SymAddr =
5700         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5701 
5702     // Finally we can make a call to calculate the offset from tpidr_el0.
5703     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5704   } else
5705     llvm_unreachable("Unsupported ELF TLS access model");
5706 
5707   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5708 }
5709 
5710 SDValue
5711 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5712                                                     SelectionDAG &DAG) const {
5713   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5714 
5715   SDValue Chain = DAG.getEntryNode();
5716   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5717   SDLoc DL(Op);
5718 
5719   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5720 
5721   // Load the ThreadLocalStoragePointer from the TEB
5722   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5723   SDValue TLSArray =
5724       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5725   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5726   Chain = TLSArray.getValue(1);
5727 
5728   // Load the TLS index from the C runtime;
5729   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5730   // This also does the same as LOADgot, but using a generic i32 load,
5731   // while LOADgot only loads i64.
5732   SDValue TLSIndexHi =
5733       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5734   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5735       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5736   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5737   SDValue TLSIndex =
5738       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5739   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5740   Chain = TLSIndex.getValue(1);
5741 
5742   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5743   // offset into the TLSArray.
5744   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5745   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5746                              DAG.getConstant(3, DL, PtrVT));
5747   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5748                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5749                             MachinePointerInfo());
5750   Chain = TLS.getValue(1);
5751 
5752   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5753   const GlobalValue *GV = GA->getGlobal();
5754   SDValue TGAHi = DAG.getTargetGlobalAddress(
5755       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5756   SDValue TGALo = DAG.getTargetGlobalAddress(
5757       GV, DL, PtrVT, 0,
5758       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5759 
5760   // Add the offset from the start of the .tls section (section base).
5761   SDValue Addr =
5762       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5763                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5764               0);
5765   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5766   return Addr;
5767 }
5768 
5769 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5770                                                      SelectionDAG &DAG) const {
5771   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5772   if (DAG.getTarget().useEmulatedTLS())
5773     return LowerToTLSEmulatedModel(GA, DAG);
5774 
5775   if (Subtarget->isTargetDarwin())
5776     return LowerDarwinGlobalTLSAddress(Op, DAG);
5777   if (Subtarget->isTargetELF())
5778     return LowerELFGlobalTLSAddress(Op, DAG);
5779   if (Subtarget->isTargetWindows())
5780     return LowerWindowsGlobalTLSAddress(Op, DAG);
5781 
5782   llvm_unreachable("Unexpected platform trying to use TLS");
5783 }
5784 
5785 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5786   SDValue Chain = Op.getOperand(0);
5787   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5788   SDValue LHS = Op.getOperand(2);
5789   SDValue RHS = Op.getOperand(3);
5790   SDValue Dest = Op.getOperand(4);
5791   SDLoc dl(Op);
5792 
5793   MachineFunction &MF = DAG.getMachineFunction();
5794   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5795   // will not be produced, as they are conditional branch instructions that do
5796   // not set flags.
5797   bool ProduceNonFlagSettingCondBr =
5798       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5799 
5800   // Handle f128 first, since lowering it will result in comparing the return
5801   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5802   // is expecting to deal with.
5803   if (LHS.getValueType() == MVT::f128) {
5804     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5805 
5806     // If softenSetCCOperands returned a scalar, we need to compare the result
5807     // against zero to select between true and false values.
5808     if (!RHS.getNode()) {
5809       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5810       CC = ISD::SETNE;
5811     }
5812   }
5813 
5814   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5815   // instruction.
5816   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5817       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5818     // Only lower legal XALUO ops.
5819     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5820       return SDValue();
5821 
5822     // The actual operation with overflow check.
5823     AArch64CC::CondCode OFCC;
5824     SDValue Value, Overflow;
5825     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5826 
5827     if (CC == ISD::SETNE)
5828       OFCC = getInvertedCondCode(OFCC);
5829     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5830 
5831     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5832                        Overflow);
5833   }
5834 
5835   if (LHS.getValueType().isInteger()) {
5836     assert((LHS.getValueType() == RHS.getValueType()) &&
5837            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5838 
5839     // If the RHS of the comparison is zero, we can potentially fold this
5840     // to a specialized branch.
5841     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5842     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5843       if (CC == ISD::SETEQ) {
5844         // See if we can use a TBZ to fold in an AND as well.
5845         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5846         // out of bounds, a late MI-layer pass rewrites branches.
5847         // 403.gcc is an example that hits this case.
5848         if (LHS.getOpcode() == ISD::AND &&
5849             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5850             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5851           SDValue Test = LHS.getOperand(0);
5852           uint64_t Mask = LHS.getConstantOperandVal(1);
5853           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5854                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5855                              Dest);
5856         }
5857 
5858         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5859       } else if (CC == ISD::SETNE) {
5860         // See if we can use a TBZ to fold in an AND as well.
5861         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5862         // out of bounds, a late MI-layer pass rewrites branches.
5863         // 403.gcc is an example that hits this case.
5864         if (LHS.getOpcode() == ISD::AND &&
5865             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5866             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5867           SDValue Test = LHS.getOperand(0);
5868           uint64_t Mask = LHS.getConstantOperandVal(1);
5869           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5870                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5871                              Dest);
5872         }
5873 
5874         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5875       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5876         // Don't combine AND since emitComparison converts the AND to an ANDS
5877         // (a.k.a. TST) and the test in the test bit and branch instruction
5878         // becomes redundant.  This would also increase register pressure.
5879         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5880         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5881                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5882       }
5883     }
5884     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5885         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5886       // Don't combine AND since emitComparison converts the AND to an ANDS
5887       // (a.k.a. TST) and the test in the test bit and branch instruction
5888       // becomes redundant.  This would also increase register pressure.
5889       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5890       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5891                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5892     }
5893 
5894     SDValue CCVal;
5895     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5896     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5897                        Cmp);
5898   }
5899 
5900   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5901          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5902 
5903   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5904   // clean.  Some of them require two branches to implement.
5905   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5906   AArch64CC::CondCode CC1, CC2;
5907   changeFPCCToAArch64CC(CC, CC1, CC2);
5908   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5909   SDValue BR1 =
5910       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5911   if (CC2 != AArch64CC::AL) {
5912     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5913     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5914                        Cmp);
5915   }
5916 
5917   return BR1;
5918 }
5919 
5920 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5921                                               SelectionDAG &DAG) const {
5922   EVT VT = Op.getValueType();
5923   SDLoc DL(Op);
5924 
5925   SDValue In1 = Op.getOperand(0);
5926   SDValue In2 = Op.getOperand(1);
5927   EVT SrcVT = In2.getValueType();
5928 
5929   if (SrcVT.bitsLT(VT))
5930     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5931   else if (SrcVT.bitsGT(VT))
5932     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5933 
5934   EVT VecVT;
5935   uint64_t EltMask;
5936   SDValue VecVal1, VecVal2;
5937 
5938   auto setVecVal = [&] (int Idx) {
5939     if (!VT.isVector()) {
5940       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5941                                           DAG.getUNDEF(VecVT), In1);
5942       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5943                                           DAG.getUNDEF(VecVT), In2);
5944     } else {
5945       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5946       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5947     }
5948   };
5949 
5950   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5951     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5952     EltMask = 0x80000000ULL;
5953     setVecVal(AArch64::ssub);
5954   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5955     VecVT = MVT::v2i64;
5956 
5957     // We want to materialize a mask with the high bit set, but the AdvSIMD
5958     // immediate moves cannot materialize that in a single instruction for
5959     // 64-bit elements. Instead, materialize zero and then negate it.
5960     EltMask = 0;
5961 
5962     setVecVal(AArch64::dsub);
5963   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5964     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5965     EltMask = 0x8000ULL;
5966     setVecVal(AArch64::hsub);
5967   } else {
5968     llvm_unreachable("Invalid type for copysign!");
5969   }
5970 
5971   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5972 
5973   // If we couldn't materialize the mask above, then the mask vector will be
5974   // the zero vector, and we need to negate it here.
5975   if (VT == MVT::f64 || VT == MVT::v2f64) {
5976     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5977     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5978     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5979   }
5980 
5981   SDValue Sel =
5982       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5983 
5984   if (VT == MVT::f16)
5985     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5986   if (VT == MVT::f32)
5987     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5988   else if (VT == MVT::f64)
5989     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5990   else
5991     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5992 }
5993 
5994 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5995   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5996           Attribute::NoImplicitFloat))
5997     return SDValue();
5998 
5999   if (!Subtarget->hasNEON())
6000     return SDValue();
6001 
6002   // While there is no integer popcount instruction, it can
6003   // be more efficiently lowered to the following sequence that uses
6004   // AdvSIMD registers/instructions as long as the copies to/from
6005   // the AdvSIMD registers are cheap.
6006   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
6007   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
6008   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
6009   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
6010   SDValue Val = Op.getOperand(0);
6011   SDLoc DL(Op);
6012   EVT VT = Op.getValueType();
6013 
6014   if (VT == MVT::i32 || VT == MVT::i64) {
6015     if (VT == MVT::i32)
6016       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
6017     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
6018 
6019     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
6020     SDValue UaddLV = DAG.getNode(
6021         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6022         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6023 
6024     if (VT == MVT::i64)
6025       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
6026     return UaddLV;
6027   } else if (VT == MVT::i128) {
6028     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
6029 
6030     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
6031     SDValue UaddLV = DAG.getNode(
6032         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6033         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6034 
6035     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
6036   }
6037 
6038   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6039           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6040          "Unexpected type for custom ctpop lowering");
6041 
6042   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6043   Val = DAG.getBitcast(VT8Bit, Val);
6044   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
6045 
6046   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6047   unsigned EltSize = 8;
6048   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6049   while (EltSize != VT.getScalarSizeInBits()) {
6050     EltSize *= 2;
6051     NumElts /= 2;
6052     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6053     Val = DAG.getNode(
6054         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
6055         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
6056   }
6057 
6058   return Val;
6059 }
6060 
6061 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6062 
6063   if (Op.getValueType().isVector())
6064     return LowerVSETCC(Op, DAG);
6065 
6066   bool IsStrict = Op->isStrictFPOpcode();
6067   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
6068   unsigned OpNo = IsStrict ? 1 : 0;
6069   SDValue Chain;
6070   if (IsStrict)
6071     Chain = Op.getOperand(0);
6072   SDValue LHS = Op.getOperand(OpNo + 0);
6073   SDValue RHS = Op.getOperand(OpNo + 1);
6074   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
6075   SDLoc dl(Op);
6076 
6077   // We chose ZeroOrOneBooleanContents, so use zero and one.
6078   EVT VT = Op.getValueType();
6079   SDValue TVal = DAG.getConstant(1, dl, VT);
6080   SDValue FVal = DAG.getConstant(0, dl, VT);
6081 
6082   // Handle f128 first, since one possible outcome is a normal integer
6083   // comparison which gets picked up by the next if statement.
6084   if (LHS.getValueType() == MVT::f128) {
6085     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
6086                         IsSignaling);
6087 
6088     // If softenSetCCOperands returned a scalar, use it.
6089     if (!RHS.getNode()) {
6090       assert(LHS.getValueType() == Op.getValueType() &&
6091              "Unexpected setcc expansion!");
6092       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
6093     }
6094   }
6095 
6096   if (LHS.getValueType().isInteger()) {
6097     SDValue CCVal;
6098     SDValue Cmp = getAArch64Cmp(
6099         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
6100 
6101     // Note that we inverted the condition above, so we reverse the order of
6102     // the true and false operands here.  This will allow the setcc to be
6103     // matched to a single CSINC instruction.
6104     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
6105     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
6106   }
6107 
6108   // Now we know we're dealing with FP values.
6109   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6110          LHS.getValueType() == MVT::f64);
6111 
6112   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
6113   // and do the comparison.
6114   SDValue Cmp;
6115   if (IsStrict)
6116     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
6117   else
6118     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6119 
6120   AArch64CC::CondCode CC1, CC2;
6121   changeFPCCToAArch64CC(CC, CC1, CC2);
6122   SDValue Res;
6123   if (CC2 == AArch64CC::AL) {
6124     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
6125                           CC2);
6126     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6127 
6128     // Note that we inverted the condition above, so we reverse the order of
6129     // the true and false operands here.  This will allow the setcc to be
6130     // matched to a single CSINC instruction.
6131     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
6132   } else {
6133     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
6134     // totally clean.  Some of them require two CSELs to implement.  As is in
6135     // this case, we emit the first CSEL and then emit a second using the output
6136     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
6137 
6138     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
6139     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6140     SDValue CS1 =
6141         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6142 
6143     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6144     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6145   }
6146   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
6147 }
6148 
6149 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
6150                                               SDValue RHS, SDValue TVal,
6151                                               SDValue FVal, const SDLoc &dl,
6152                                               SelectionDAG &DAG) const {
6153   // Handle f128 first, because it will result in a comparison of some RTLIB
6154   // call result against zero.
6155   if (LHS.getValueType() == MVT::f128) {
6156     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6157 
6158     // If softenSetCCOperands returned a scalar, we need to compare the result
6159     // against zero to select between true and false values.
6160     if (!RHS.getNode()) {
6161       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6162       CC = ISD::SETNE;
6163     }
6164   }
6165 
6166   // Also handle f16, for which we need to do a f32 comparison.
6167   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
6168     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
6169     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
6170   }
6171 
6172   // Next, handle integers.
6173   if (LHS.getValueType().isInteger()) {
6174     assert((LHS.getValueType() == RHS.getValueType()) &&
6175            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
6176 
6177     unsigned Opcode = AArch64ISD::CSEL;
6178 
6179     // If both the TVal and the FVal are constants, see if we can swap them in
6180     // order to for a CSINV or CSINC out of them.
6181     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
6182     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
6183 
6184     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
6185       std::swap(TVal, FVal);
6186       std::swap(CTVal, CFVal);
6187       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6188     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
6189       std::swap(TVal, FVal);
6190       std::swap(CTVal, CFVal);
6191       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6192     } else if (TVal.getOpcode() == ISD::XOR) {
6193       // If TVal is a NOT we want to swap TVal and FVal so that we can match
6194       // with a CSINV rather than a CSEL.
6195       if (isAllOnesConstant(TVal.getOperand(1))) {
6196         std::swap(TVal, FVal);
6197         std::swap(CTVal, CFVal);
6198         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6199       }
6200     } else if (TVal.getOpcode() == ISD::SUB) {
6201       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
6202       // that we can match with a CSNEG rather than a CSEL.
6203       if (isNullConstant(TVal.getOperand(0))) {
6204         std::swap(TVal, FVal);
6205         std::swap(CTVal, CFVal);
6206         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6207       }
6208     } else if (CTVal && CFVal) {
6209       const int64_t TrueVal = CTVal->getSExtValue();
6210       const int64_t FalseVal = CFVal->getSExtValue();
6211       bool Swap = false;
6212 
6213       // If both TVal and FVal are constants, see if FVal is the
6214       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
6215       // instead of a CSEL in that case.
6216       if (TrueVal == ~FalseVal) {
6217         Opcode = AArch64ISD::CSINV;
6218       } else if (TrueVal == -FalseVal) {
6219         Opcode = AArch64ISD::CSNEG;
6220       } else if (TVal.getValueType() == MVT::i32) {
6221         // If our operands are only 32-bit wide, make sure we use 32-bit
6222         // arithmetic for the check whether we can use CSINC. This ensures that
6223         // the addition in the check will wrap around properly in case there is
6224         // an overflow (which would not be the case if we do the check with
6225         // 64-bit arithmetic).
6226         const uint32_t TrueVal32 = CTVal->getZExtValue();
6227         const uint32_t FalseVal32 = CFVal->getZExtValue();
6228 
6229         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
6230           Opcode = AArch64ISD::CSINC;
6231 
6232           if (TrueVal32 > FalseVal32) {
6233             Swap = true;
6234           }
6235         }
6236         // 64-bit check whether we can use CSINC.
6237       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
6238         Opcode = AArch64ISD::CSINC;
6239 
6240         if (TrueVal > FalseVal) {
6241           Swap = true;
6242         }
6243       }
6244 
6245       // Swap TVal and FVal if necessary.
6246       if (Swap) {
6247         std::swap(TVal, FVal);
6248         std::swap(CTVal, CFVal);
6249         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6250       }
6251 
6252       if (Opcode != AArch64ISD::CSEL) {
6253         // Drop FVal since we can get its value by simply inverting/negating
6254         // TVal.
6255         FVal = TVal;
6256       }
6257     }
6258 
6259     // Avoid materializing a constant when possible by reusing a known value in
6260     // a register.  However, don't perform this optimization if the known value
6261     // is one, zero or negative one in the case of a CSEL.  We can always
6262     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
6263     // FVal, respectively.
6264     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
6265     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
6266         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
6267       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6268       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
6269       // "a != C ? x : a" to avoid materializing C.
6270       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
6271         TVal = LHS;
6272       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
6273         FVal = LHS;
6274     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
6275       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
6276       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
6277       // avoid materializing C.
6278       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6279       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
6280         Opcode = AArch64ISD::CSINV;
6281         TVal = LHS;
6282         FVal = DAG.getConstant(0, dl, FVal.getValueType());
6283       }
6284     }
6285 
6286     SDValue CCVal;
6287     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6288     EVT VT = TVal.getValueType();
6289     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
6290   }
6291 
6292   // Now we know we're dealing with FP values.
6293   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6294          LHS.getValueType() == MVT::f64);
6295   assert(LHS.getValueType() == RHS.getValueType());
6296   EVT VT = TVal.getValueType();
6297   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6298 
6299   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6300   // clean.  Some of them require two CSELs to implement.
6301   AArch64CC::CondCode CC1, CC2;
6302   changeFPCCToAArch64CC(CC, CC1, CC2);
6303 
6304   if (DAG.getTarget().Options.UnsafeFPMath) {
6305     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
6306     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
6307     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
6308     if (RHSVal && RHSVal->isZero()) {
6309       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
6310       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
6311 
6312       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
6313           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
6314         TVal = LHS;
6315       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
6316                CFVal && CFVal->isZero() &&
6317                FVal.getValueType() == LHS.getValueType())
6318         FVal = LHS;
6319     }
6320   }
6321 
6322   // Emit first, and possibly only, CSEL.
6323   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6324   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6325 
6326   // If we need a second CSEL, emit it, using the output of the first as the
6327   // RHS.  We're effectively OR'ing the two CC's together.
6328   if (CC2 != AArch64CC::AL) {
6329     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6330     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6331   }
6332 
6333   // Otherwise, return the output of the first CSEL.
6334   return CS1;
6335 }
6336 
6337 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
6338                                               SelectionDAG &DAG) const {
6339   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6340   SDValue LHS = Op.getOperand(0);
6341   SDValue RHS = Op.getOperand(1);
6342   SDValue TVal = Op.getOperand(2);
6343   SDValue FVal = Op.getOperand(3);
6344   SDLoc DL(Op);
6345   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6346 }
6347 
6348 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
6349                                            SelectionDAG &DAG) const {
6350   SDValue CCVal = Op->getOperand(0);
6351   SDValue TVal = Op->getOperand(1);
6352   SDValue FVal = Op->getOperand(2);
6353   SDLoc DL(Op);
6354 
6355   EVT Ty = Op.getValueType();
6356   if (Ty.isScalableVector()) {
6357     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
6358     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
6359     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
6360     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
6361   }
6362 
6363   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
6364   // instruction.
6365   if (ISD::isOverflowIntrOpRes(CCVal)) {
6366     // Only lower legal XALUO ops.
6367     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
6368       return SDValue();
6369 
6370     AArch64CC::CondCode OFCC;
6371     SDValue Value, Overflow;
6372     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
6373     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
6374 
6375     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
6376                        CCVal, Overflow);
6377   }
6378 
6379   // Lower it the same way as we would lower a SELECT_CC node.
6380   ISD::CondCode CC;
6381   SDValue LHS, RHS;
6382   if (CCVal.getOpcode() == ISD::SETCC) {
6383     LHS = CCVal.getOperand(0);
6384     RHS = CCVal.getOperand(1);
6385     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
6386   } else {
6387     LHS = CCVal;
6388     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
6389     CC = ISD::SETNE;
6390   }
6391   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6392 }
6393 
6394 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
6395                                               SelectionDAG &DAG) const {
6396   // Jump table entries as PC relative offsets. No additional tweaking
6397   // is necessary here. Just get the address of the jump table.
6398   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6399 
6400   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6401       !Subtarget->isTargetMachO()) {
6402     return getAddrLarge(JT, DAG);
6403   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6404     return getAddrTiny(JT, DAG);
6405   }
6406   return getAddr(JT, DAG);
6407 }
6408 
6409 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
6410                                           SelectionDAG &DAG) const {
6411   // Jump table entries as PC relative offsets. No additional tweaking
6412   // is necessary here. Just get the address of the jump table.
6413   SDLoc DL(Op);
6414   SDValue JT = Op.getOperand(1);
6415   SDValue Entry = Op.getOperand(2);
6416   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
6417 
6418   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6419   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
6420 
6421   SDNode *Dest =
6422       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
6423                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
6424   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
6425                      SDValue(Dest, 0));
6426 }
6427 
6428 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6429                                                  SelectionDAG &DAG) const {
6430   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6431 
6432   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6433     // Use the GOT for the large code model on iOS.
6434     if (Subtarget->isTargetMachO()) {
6435       return getGOT(CP, DAG);
6436     }
6437     return getAddrLarge(CP, DAG);
6438   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6439     return getAddrTiny(CP, DAG);
6440   } else {
6441     return getAddr(CP, DAG);
6442   }
6443 }
6444 
6445 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6446                                                SelectionDAG &DAG) const {
6447   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6448   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6449       !Subtarget->isTargetMachO()) {
6450     return getAddrLarge(BA, DAG);
6451   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6452     return getAddrTiny(BA, DAG);
6453   }
6454   return getAddr(BA, DAG);
6455 }
6456 
6457 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6458                                                  SelectionDAG &DAG) const {
6459   AArch64FunctionInfo *FuncInfo =
6460       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6461 
6462   SDLoc DL(Op);
6463   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6464                                  getPointerTy(DAG.getDataLayout()));
6465   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6466   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6467   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6468                       MachinePointerInfo(SV));
6469 }
6470 
6471 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6472                                                   SelectionDAG &DAG) const {
6473   AArch64FunctionInfo *FuncInfo =
6474       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6475 
6476   SDLoc DL(Op);
6477   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6478                                      ? FuncInfo->getVarArgsGPRIndex()
6479                                      : FuncInfo->getVarArgsStackIndex(),
6480                                  getPointerTy(DAG.getDataLayout()));
6481   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6482   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6483                       MachinePointerInfo(SV));
6484 }
6485 
6486 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6487                                                 SelectionDAG &DAG) const {
6488   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6489   // Standard, section B.3.
6490   MachineFunction &MF = DAG.getMachineFunction();
6491   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6492   auto PtrVT = getPointerTy(DAG.getDataLayout());
6493   SDLoc DL(Op);
6494 
6495   SDValue Chain = Op.getOperand(0);
6496   SDValue VAList = Op.getOperand(1);
6497   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6498   SmallVector<SDValue, 4> MemOps;
6499 
6500   // void *__stack at offset 0
6501   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6502   MemOps.push_back(
6503       DAG.getStore(Chain, DL, Stack, VAList, MachinePointerInfo(SV), Align(8)));
6504 
6505   // void *__gr_top at offset 8
6506   int GPRSize = FuncInfo->getVarArgsGPRSize();
6507   if (GPRSize > 0) {
6508     SDValue GRTop, GRTopAddr;
6509 
6510     GRTopAddr =
6511         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6512 
6513     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6514     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6515                         DAG.getConstant(GPRSize, DL, PtrVT));
6516 
6517     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6518                                   MachinePointerInfo(SV, 8), Align(8)));
6519   }
6520 
6521   // void *__vr_top at offset 16
6522   int FPRSize = FuncInfo->getVarArgsFPRSize();
6523   if (FPRSize > 0) {
6524     SDValue VRTop, VRTopAddr;
6525     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6526                             DAG.getConstant(16, DL, PtrVT));
6527 
6528     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6529     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6530                         DAG.getConstant(FPRSize, DL, PtrVT));
6531 
6532     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6533                                   MachinePointerInfo(SV, 16), Align(8)));
6534   }
6535 
6536   // int __gr_offs at offset 24
6537   SDValue GROffsAddr =
6538       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6539   MemOps.push_back(
6540       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
6541                    GROffsAddr, MachinePointerInfo(SV, 24), Align(4)));
6542 
6543   // int __vr_offs at offset 28
6544   SDValue VROffsAddr =
6545       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6546   MemOps.push_back(
6547       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
6548                    VROffsAddr, MachinePointerInfo(SV, 28), Align(4)));
6549 
6550   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6551 }
6552 
6553 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6554                                             SelectionDAG &DAG) const {
6555   MachineFunction &MF = DAG.getMachineFunction();
6556 
6557   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6558     return LowerWin64_VASTART(Op, DAG);
6559   else if (Subtarget->isTargetDarwin())
6560     return LowerDarwin_VASTART(Op, DAG);
6561   else
6562     return LowerAAPCS_VASTART(Op, DAG);
6563 }
6564 
6565 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6566                                            SelectionDAG &DAG) const {
6567   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6568   // pointer.
6569   SDLoc DL(Op);
6570   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6571   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6572                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6573   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6574   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6575 
6576   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6577                        DAG.getConstant(VaListSize, DL, MVT::i32),
6578                        Align(PtrSize), false, false, false,
6579                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6580 }
6581 
6582 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6583   assert(Subtarget->isTargetDarwin() &&
6584          "automatic va_arg instruction only works on Darwin");
6585 
6586   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6587   EVT VT = Op.getValueType();
6588   SDLoc DL(Op);
6589   SDValue Chain = Op.getOperand(0);
6590   SDValue Addr = Op.getOperand(1);
6591   MaybeAlign Align(Op.getConstantOperandVal(3));
6592   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6593   auto PtrVT = getPointerTy(DAG.getDataLayout());
6594   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6595   SDValue VAList =
6596       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6597   Chain = VAList.getValue(1);
6598   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6599 
6600   if (Align && *Align > MinSlotSize) {
6601     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6602                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6603     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6604                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6605   }
6606 
6607   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6608   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6609 
6610   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6611   // up to 64 bits.  At the very least, we have to increase the striding of the
6612   // vaargs list to match this, and for FP values we need to introduce
6613   // FP_ROUND nodes as well.
6614   if (VT.isInteger() && !VT.isVector())
6615     ArgSize = std::max(ArgSize, MinSlotSize);
6616   bool NeedFPTrunc = false;
6617   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6618     ArgSize = 8;
6619     NeedFPTrunc = true;
6620   }
6621 
6622   // Increment the pointer, VAList, to the next vaarg
6623   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6624                                DAG.getConstant(ArgSize, DL, PtrVT));
6625   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6626 
6627   // Store the incremented VAList to the legalized pointer
6628   SDValue APStore =
6629       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6630 
6631   // Load the actual argument out of the pointer VAList
6632   if (NeedFPTrunc) {
6633     // Load the value as an f64.
6634     SDValue WideFP =
6635         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6636     // Round the value down to an f32.
6637     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6638                                    DAG.getIntPtrConstant(1, DL));
6639     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6640     // Merge the rounded value with the chain output of the load.
6641     return DAG.getMergeValues(Ops, DL);
6642   }
6643 
6644   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6645 }
6646 
6647 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6648                                               SelectionDAG &DAG) const {
6649   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6650   MFI.setFrameAddressIsTaken(true);
6651 
6652   EVT VT = Op.getValueType();
6653   SDLoc DL(Op);
6654   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6655   SDValue FrameAddr =
6656       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6657   while (Depth--)
6658     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6659                             MachinePointerInfo());
6660 
6661   if (Subtarget->isTargetILP32())
6662     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6663                             DAG.getValueType(VT));
6664 
6665   return FrameAddr;
6666 }
6667 
6668 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6669                                               SelectionDAG &DAG) const {
6670   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6671 
6672   EVT VT = getPointerTy(DAG.getDataLayout());
6673   SDLoc DL(Op);
6674   int FI = MFI.CreateFixedObject(4, 0, false);
6675   return DAG.getFrameIndex(FI, VT);
6676 }
6677 
6678 #define GET_REGISTER_MATCHER
6679 #include "AArch64GenAsmMatcher.inc"
6680 
6681 // FIXME? Maybe this could be a TableGen attribute on some registers and
6682 // this table could be generated automatically from RegInfo.
6683 Register AArch64TargetLowering::
6684 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6685   Register Reg = MatchRegisterName(RegName);
6686   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6687     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6688     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6689     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6690       Reg = 0;
6691   }
6692   if (Reg)
6693     return Reg;
6694   report_fatal_error(Twine("Invalid register name \""
6695                               + StringRef(RegName)  + "\"."));
6696 }
6697 
6698 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6699                                                      SelectionDAG &DAG) const {
6700   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6701 
6702   EVT VT = Op.getValueType();
6703   SDLoc DL(Op);
6704 
6705   SDValue FrameAddr =
6706       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6707   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6708 
6709   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6710 }
6711 
6712 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6713                                                SelectionDAG &DAG) const {
6714   MachineFunction &MF = DAG.getMachineFunction();
6715   MachineFrameInfo &MFI = MF.getFrameInfo();
6716   MFI.setReturnAddressIsTaken(true);
6717 
6718   EVT VT = Op.getValueType();
6719   SDLoc DL(Op);
6720   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6721   SDValue ReturnAddress;
6722   if (Depth) {
6723     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6724     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6725     ReturnAddress = DAG.getLoad(
6726         VT, DL, DAG.getEntryNode(),
6727         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
6728   } else {
6729     // Return LR, which contains the return address. Mark it an implicit
6730     // live-in.
6731     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6732     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6733   }
6734 
6735   // The XPACLRI instruction assembles to a hint-space instruction before
6736   // Armv8.3-A therefore this instruction can be safely used for any pre
6737   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
6738   // that instead.
6739   SDNode *St;
6740   if (Subtarget->hasV8_3aOps()) {
6741     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
6742   } else {
6743     // XPACLRI operates on LR therefore we must move the operand accordingly.
6744     SDValue Chain =
6745         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
6746     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
6747   }
6748   return SDValue(St, 0);
6749 }
6750 
6751 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6752 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6753 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6754                                                     SelectionDAG &DAG) const {
6755   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6756   EVT VT = Op.getValueType();
6757   unsigned VTBits = VT.getSizeInBits();
6758   SDLoc dl(Op);
6759   SDValue ShOpLo = Op.getOperand(0);
6760   SDValue ShOpHi = Op.getOperand(1);
6761   SDValue ShAmt = Op.getOperand(2);
6762   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6763 
6764   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6765 
6766   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6767                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6768   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6769 
6770   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6771   // is "undef". We wanted 0, so CSEL it directly.
6772   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6773                                ISD::SETEQ, dl, DAG);
6774   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6775   HiBitsForLo =
6776       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6777                   HiBitsForLo, CCVal, Cmp);
6778 
6779   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6780                                    DAG.getConstant(VTBits, dl, MVT::i64));
6781 
6782   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6783   SDValue LoForNormalShift =
6784       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6785 
6786   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6787                        dl, DAG);
6788   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6789   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6790   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6791                            LoForNormalShift, CCVal, Cmp);
6792 
6793   // AArch64 shifts larger than the register width are wrapped rather than
6794   // clamped, so we can't just emit "hi >> x".
6795   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6796   SDValue HiForBigShift =
6797       Opc == ISD::SRA
6798           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6799                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6800           : DAG.getConstant(0, dl, VT);
6801   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6802                            HiForNormalShift, CCVal, Cmp);
6803 
6804   SDValue Ops[2] = { Lo, Hi };
6805   return DAG.getMergeValues(Ops, dl);
6806 }
6807 
6808 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6809 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6810 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6811                                                    SelectionDAG &DAG) const {
6812   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6813   EVT VT = Op.getValueType();
6814   unsigned VTBits = VT.getSizeInBits();
6815   SDLoc dl(Op);
6816   SDValue ShOpLo = Op.getOperand(0);
6817   SDValue ShOpHi = Op.getOperand(1);
6818   SDValue ShAmt = Op.getOperand(2);
6819 
6820   assert(Op.getOpcode() == ISD::SHL_PARTS);
6821   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6822                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6823   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6824 
6825   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6826   // is "undef". We wanted 0, so CSEL it directly.
6827   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6828                                ISD::SETEQ, dl, DAG);
6829   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6830   LoBitsForHi =
6831       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6832                   LoBitsForHi, CCVal, Cmp);
6833 
6834   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6835                                    DAG.getConstant(VTBits, dl, MVT::i64));
6836   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6837   SDValue HiForNormalShift =
6838       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6839 
6840   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6841 
6842   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6843                        dl, DAG);
6844   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6845   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6846                            HiForNormalShift, CCVal, Cmp);
6847 
6848   // AArch64 shifts of larger than register sizes are wrapped rather than
6849   // clamped, so we can't just emit "lo << a" if a is too big.
6850   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6851   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6852   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6853                            LoForNormalShift, CCVal, Cmp);
6854 
6855   SDValue Ops[2] = { Lo, Hi };
6856   return DAG.getMergeValues(Ops, dl);
6857 }
6858 
6859 bool AArch64TargetLowering::isOffsetFoldingLegal(
6860     const GlobalAddressSDNode *GA) const {
6861   // Offsets are folded in the DAG combine rather than here so that we can
6862   // intelligently choose an offset based on the uses.
6863   return false;
6864 }
6865 
6866 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6867                                          bool OptForSize) const {
6868   bool IsLegal = false;
6869   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6870   // 16-bit case when target has full fp16 support.
6871   // FIXME: We should be able to handle f128 as well with a clever lowering.
6872   const APInt ImmInt = Imm.bitcastToAPInt();
6873   if (VT == MVT::f64)
6874     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6875   else if (VT == MVT::f32)
6876     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6877   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6878     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6879   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6880   //       generate that fmov.
6881 
6882   // If we can not materialize in immediate field for fmov, check if the
6883   // value can be encoded as the immediate operand of a logical instruction.
6884   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6885   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6886     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6887     // however the mov+fmov sequence is always better because of the reduced
6888     // cache pressure. The timings are still the same if you consider
6889     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6890     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6891     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6892     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6893 			      Insn);
6894     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6895     IsLegal = Insn.size() <= Limit;
6896   }
6897 
6898   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6899                     << " imm value: "; Imm.dump(););
6900   return IsLegal;
6901 }
6902 
6903 //===----------------------------------------------------------------------===//
6904 //                          AArch64 Optimization Hooks
6905 //===----------------------------------------------------------------------===//
6906 
6907 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6908                            SDValue Operand, SelectionDAG &DAG,
6909                            int &ExtraSteps) {
6910   EVT VT = Operand.getValueType();
6911   if (ST->hasNEON() &&
6912       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6913        VT == MVT::f32 || VT == MVT::v1f32 ||
6914        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6915     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6916       // For the reciprocal estimates, convergence is quadratic, so the number
6917       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6918       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6919       // the result for float (23 mantissa bits) is 2 and for double (52
6920       // mantissa bits) is 3.
6921       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6922 
6923     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6924   }
6925 
6926   return SDValue();
6927 }
6928 
6929 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6930                                                SelectionDAG &DAG, int Enabled,
6931                                                int &ExtraSteps,
6932                                                bool &UseOneConst,
6933                                                bool Reciprocal) const {
6934   if (Enabled == ReciprocalEstimate::Enabled ||
6935       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6936     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6937                                        DAG, ExtraSteps)) {
6938       SDLoc DL(Operand);
6939       EVT VT = Operand.getValueType();
6940 
6941       SDNodeFlags Flags;
6942       Flags.setAllowReassociation(true);
6943 
6944       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6945       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6946       for (int i = ExtraSteps; i > 0; --i) {
6947         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6948                                    Flags);
6949         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6950         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6951       }
6952       if (!Reciprocal) {
6953         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6954                                       VT);
6955         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6956         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6957 
6958         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6959         // Correct the result if the operand is 0.0.
6960         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6961                                VT, Eq, Operand, Estimate);
6962       }
6963 
6964       ExtraSteps = 0;
6965       return Estimate;
6966     }
6967 
6968   return SDValue();
6969 }
6970 
6971 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6972                                                 SelectionDAG &DAG, int Enabled,
6973                                                 int &ExtraSteps) const {
6974   if (Enabled == ReciprocalEstimate::Enabled)
6975     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6976                                        DAG, ExtraSteps)) {
6977       SDLoc DL(Operand);
6978       EVT VT = Operand.getValueType();
6979 
6980       SDNodeFlags Flags;
6981       Flags.setAllowReassociation(true);
6982 
6983       // Newton reciprocal iteration: E * (2 - X * E)
6984       // AArch64 reciprocal iteration instruction: (2 - M * N)
6985       for (int i = ExtraSteps; i > 0; --i) {
6986         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6987                                    Estimate, Flags);
6988         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6989       }
6990 
6991       ExtraSteps = 0;
6992       return Estimate;
6993     }
6994 
6995   return SDValue();
6996 }
6997 
6998 //===----------------------------------------------------------------------===//
6999 //                          AArch64 Inline Assembly Support
7000 //===----------------------------------------------------------------------===//
7001 
7002 // Table of Constraints
7003 // TODO: This is the current set of constraints supported by ARM for the
7004 // compiler, not all of them may make sense.
7005 //
7006 // r - A general register
7007 // w - An FP/SIMD register of some size in the range v0-v31
7008 // x - An FP/SIMD register of some size in the range v0-v15
7009 // I - Constant that can be used with an ADD instruction
7010 // J - Constant that can be used with a SUB instruction
7011 // K - Constant that can be used with a 32-bit logical instruction
7012 // L - Constant that can be used with a 64-bit logical instruction
7013 // M - Constant that can be used as a 32-bit MOV immediate
7014 // N - Constant that can be used as a 64-bit MOV immediate
7015 // Q - A memory reference with base register and no offset
7016 // S - A symbolic address
7017 // Y - Floating point constant zero
7018 // Z - Integer constant zero
7019 //
7020 //   Note that general register operands will be output using their 64-bit x
7021 // register name, whatever the size of the variable, unless the asm operand
7022 // is prefixed by the %w modifier. Floating-point and SIMD register operands
7023 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
7024 // %q modifier.
7025 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
7026   // At this point, we have to lower this constraint to something else, so we
7027   // lower it to an "r" or "w". However, by doing this we will force the result
7028   // to be in register, while the X constraint is much more permissive.
7029   //
7030   // Although we are correct (we are free to emit anything, without
7031   // constraints), we might break use cases that would expect us to be more
7032   // efficient and emit something else.
7033   if (!Subtarget->hasFPARMv8())
7034     return "r";
7035 
7036   if (ConstraintVT.isFloatingPoint())
7037     return "w";
7038 
7039   if (ConstraintVT.isVector() &&
7040      (ConstraintVT.getSizeInBits() == 64 ||
7041       ConstraintVT.getSizeInBits() == 128))
7042     return "w";
7043 
7044   return "r";
7045 }
7046 
7047 enum PredicateConstraint {
7048   Upl,
7049   Upa,
7050   Invalid
7051 };
7052 
7053 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
7054   PredicateConstraint P = PredicateConstraint::Invalid;
7055   if (Constraint == "Upa")
7056     P = PredicateConstraint::Upa;
7057   if (Constraint == "Upl")
7058     P = PredicateConstraint::Upl;
7059   return P;
7060 }
7061 
7062 /// getConstraintType - Given a constraint letter, return the type of
7063 /// constraint it is for this target.
7064 AArch64TargetLowering::ConstraintType
7065 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
7066   if (Constraint.size() == 1) {
7067     switch (Constraint[0]) {
7068     default:
7069       break;
7070     case 'x':
7071     case 'w':
7072     case 'y':
7073       return C_RegisterClass;
7074     // An address with a single base register. Due to the way we
7075     // currently handle addresses it is the same as 'r'.
7076     case 'Q':
7077       return C_Memory;
7078     case 'I':
7079     case 'J':
7080     case 'K':
7081     case 'L':
7082     case 'M':
7083     case 'N':
7084     case 'Y':
7085     case 'Z':
7086       return C_Immediate;
7087     case 'z':
7088     case 'S': // A symbolic address
7089       return C_Other;
7090     }
7091   } else if (parsePredicateConstraint(Constraint) !=
7092              PredicateConstraint::Invalid)
7093       return C_RegisterClass;
7094   return TargetLowering::getConstraintType(Constraint);
7095 }
7096 
7097 /// Examine constraint type and operand type and determine a weight value.
7098 /// This object must already have been set up with the operand type
7099 /// and the current alternative constraint selected.
7100 TargetLowering::ConstraintWeight
7101 AArch64TargetLowering::getSingleConstraintMatchWeight(
7102     AsmOperandInfo &info, const char *constraint) const {
7103   ConstraintWeight weight = CW_Invalid;
7104   Value *CallOperandVal = info.CallOperandVal;
7105   // If we don't have a value, we can't do a match,
7106   // but allow it at the lowest weight.
7107   if (!CallOperandVal)
7108     return CW_Default;
7109   Type *type = CallOperandVal->getType();
7110   // Look at the constraint type.
7111   switch (*constraint) {
7112   default:
7113     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7114     break;
7115   case 'x':
7116   case 'w':
7117   case 'y':
7118     if (type->isFloatingPointTy() || type->isVectorTy())
7119       weight = CW_Register;
7120     break;
7121   case 'z':
7122     weight = CW_Constant;
7123     break;
7124   case 'U':
7125     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
7126       weight = CW_Register;
7127     break;
7128   }
7129   return weight;
7130 }
7131 
7132 std::pair<unsigned, const TargetRegisterClass *>
7133 AArch64TargetLowering::getRegForInlineAsmConstraint(
7134     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
7135   if (Constraint.size() == 1) {
7136     switch (Constraint[0]) {
7137     case 'r':
7138       if (VT.getSizeInBits() == 64)
7139         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
7140       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
7141     case 'w':
7142       if (!Subtarget->hasFPARMv8())
7143         break;
7144       if (VT.isScalableVector())
7145         return std::make_pair(0U, &AArch64::ZPRRegClass);
7146       if (VT.getSizeInBits() == 16)
7147         return std::make_pair(0U, &AArch64::FPR16RegClass);
7148       if (VT.getSizeInBits() == 32)
7149         return std::make_pair(0U, &AArch64::FPR32RegClass);
7150       if (VT.getSizeInBits() == 64)
7151         return std::make_pair(0U, &AArch64::FPR64RegClass);
7152       if (VT.getSizeInBits() == 128)
7153         return std::make_pair(0U, &AArch64::FPR128RegClass);
7154       break;
7155     // The instructions that this constraint is designed for can
7156     // only take 128-bit registers so just use that regclass.
7157     case 'x':
7158       if (!Subtarget->hasFPARMv8())
7159         break;
7160       if (VT.isScalableVector())
7161         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
7162       if (VT.getSizeInBits() == 128)
7163         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
7164       break;
7165     case 'y':
7166       if (!Subtarget->hasFPARMv8())
7167         break;
7168       if (VT.isScalableVector())
7169         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
7170       break;
7171     }
7172   } else {
7173     PredicateConstraint PC = parsePredicateConstraint(Constraint);
7174     if (PC != PredicateConstraint::Invalid) {
7175       assert(VT.isScalableVector());
7176       bool restricted = (PC == PredicateConstraint::Upl);
7177       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
7178                           : std::make_pair(0U, &AArch64::PPRRegClass);
7179     }
7180   }
7181   if (StringRef("{cc}").equals_lower(Constraint))
7182     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
7183 
7184   // Use the default implementation in TargetLowering to convert the register
7185   // constraint into a member of a register class.
7186   std::pair<unsigned, const TargetRegisterClass *> Res;
7187   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7188 
7189   // Not found as a standard register?
7190   if (!Res.second) {
7191     unsigned Size = Constraint.size();
7192     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
7193         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
7194       int RegNo;
7195       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
7196       if (!Failed && RegNo >= 0 && RegNo <= 31) {
7197         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
7198         // By default we'll emit v0-v31 for this unless there's a modifier where
7199         // we'll emit the correct register as well.
7200         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
7201           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
7202           Res.second = &AArch64::FPR64RegClass;
7203         } else {
7204           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
7205           Res.second = &AArch64::FPR128RegClass;
7206         }
7207       }
7208     }
7209   }
7210 
7211   if (Res.second && !Subtarget->hasFPARMv8() &&
7212       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
7213       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
7214     return std::make_pair(0U, nullptr);
7215 
7216   return Res;
7217 }
7218 
7219 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7220 /// vector.  If it is invalid, don't add anything to Ops.
7221 void AArch64TargetLowering::LowerAsmOperandForConstraint(
7222     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
7223     SelectionDAG &DAG) const {
7224   SDValue Result;
7225 
7226   // Currently only support length 1 constraints.
7227   if (Constraint.length() != 1)
7228     return;
7229 
7230   char ConstraintLetter = Constraint[0];
7231   switch (ConstraintLetter) {
7232   default:
7233     break;
7234 
7235   // This set of constraints deal with valid constants for various instructions.
7236   // Validate and return a target constant for them if we can.
7237   case 'z': {
7238     // 'z' maps to xzr or wzr so it needs an input of 0.
7239     if (!isNullConstant(Op))
7240       return;
7241 
7242     if (Op.getValueType() == MVT::i64)
7243       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
7244     else
7245       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
7246     break;
7247   }
7248   case 'S': {
7249     // An absolute symbolic address or label reference.
7250     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
7251       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
7252                                           GA->getValueType(0));
7253     } else if (const BlockAddressSDNode *BA =
7254                    dyn_cast<BlockAddressSDNode>(Op)) {
7255       Result =
7256           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
7257     } else if (const ExternalSymbolSDNode *ES =
7258                    dyn_cast<ExternalSymbolSDNode>(Op)) {
7259       Result =
7260           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
7261     } else
7262       return;
7263     break;
7264   }
7265 
7266   case 'I':
7267   case 'J':
7268   case 'K':
7269   case 'L':
7270   case 'M':
7271   case 'N':
7272     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7273     if (!C)
7274       return;
7275 
7276     // Grab the value and do some validation.
7277     uint64_t CVal = C->getZExtValue();
7278     switch (ConstraintLetter) {
7279     // The I constraint applies only to simple ADD or SUB immediate operands:
7280     // i.e. 0 to 4095 with optional shift by 12
7281     // The J constraint applies only to ADD or SUB immediates that would be
7282     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
7283     // instruction [or vice versa], in other words -1 to -4095 with optional
7284     // left shift by 12.
7285     case 'I':
7286       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
7287         break;
7288       return;
7289     case 'J': {
7290       uint64_t NVal = -C->getSExtValue();
7291       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
7292         CVal = C->getSExtValue();
7293         break;
7294       }
7295       return;
7296     }
7297     // The K and L constraints apply *only* to logical immediates, including
7298     // what used to be the MOVI alias for ORR (though the MOVI alias has now
7299     // been removed and MOV should be used). So these constraints have to
7300     // distinguish between bit patterns that are valid 32-bit or 64-bit
7301     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
7302     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
7303     // versa.
7304     case 'K':
7305       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7306         break;
7307       return;
7308     case 'L':
7309       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7310         break;
7311       return;
7312     // The M and N constraints are a superset of K and L respectively, for use
7313     // with the MOV (immediate) alias. As well as the logical immediates they
7314     // also match 32 or 64-bit immediates that can be loaded either using a
7315     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
7316     // (M) or 64-bit 0x1234000000000000 (N) etc.
7317     // As a note some of this code is liberally stolen from the asm parser.
7318     case 'M': {
7319       if (!isUInt<32>(CVal))
7320         return;
7321       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7322         break;
7323       if ((CVal & 0xFFFF) == CVal)
7324         break;
7325       if ((CVal & 0xFFFF0000ULL) == CVal)
7326         break;
7327       uint64_t NCVal = ~(uint32_t)CVal;
7328       if ((NCVal & 0xFFFFULL) == NCVal)
7329         break;
7330       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7331         break;
7332       return;
7333     }
7334     case 'N': {
7335       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7336         break;
7337       if ((CVal & 0xFFFFULL) == CVal)
7338         break;
7339       if ((CVal & 0xFFFF0000ULL) == CVal)
7340         break;
7341       if ((CVal & 0xFFFF00000000ULL) == CVal)
7342         break;
7343       if ((CVal & 0xFFFF000000000000ULL) == CVal)
7344         break;
7345       uint64_t NCVal = ~CVal;
7346       if ((NCVal & 0xFFFFULL) == NCVal)
7347         break;
7348       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7349         break;
7350       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
7351         break;
7352       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
7353         break;
7354       return;
7355     }
7356     default:
7357       return;
7358     }
7359 
7360     // All assembler immediates are 64-bit integers.
7361     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
7362     break;
7363   }
7364 
7365   if (Result.getNode()) {
7366     Ops.push_back(Result);
7367     return;
7368   }
7369 
7370   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7371 }
7372 
7373 //===----------------------------------------------------------------------===//
7374 //                     AArch64 Advanced SIMD Support
7375 //===----------------------------------------------------------------------===//
7376 
7377 /// WidenVector - Given a value in the V64 register class, produce the
7378 /// equivalent value in the V128 register class.
7379 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
7380   EVT VT = V64Reg.getValueType();
7381   unsigned NarrowSize = VT.getVectorNumElements();
7382   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7383   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
7384   SDLoc DL(V64Reg);
7385 
7386   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
7387                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
7388 }
7389 
7390 /// getExtFactor - Determine the adjustment factor for the position when
7391 /// generating an "extract from vector registers" instruction.
7392 static unsigned getExtFactor(SDValue &V) {
7393   EVT EltType = V.getValueType().getVectorElementType();
7394   return EltType.getSizeInBits() / 8;
7395 }
7396 
7397 /// NarrowVector - Given a value in the V128 register class, produce the
7398 /// equivalent value in the V64 register class.
7399 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
7400   EVT VT = V128Reg.getValueType();
7401   unsigned WideSize = VT.getVectorNumElements();
7402   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7403   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
7404   SDLoc DL(V128Reg);
7405 
7406   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
7407 }
7408 
7409 // Gather data to see if the operation can be modelled as a
7410 // shuffle in combination with VEXTs.
7411 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
7412                                                   SelectionDAG &DAG) const {
7413   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7414   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
7415   SDLoc dl(Op);
7416   EVT VT = Op.getValueType();
7417   assert(!VT.isScalableVector() &&
7418          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
7419   unsigned NumElts = VT.getVectorNumElements();
7420 
7421   struct ShuffleSourceInfo {
7422     SDValue Vec;
7423     unsigned MinElt;
7424     unsigned MaxElt;
7425 
7426     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7427     // be compatible with the shuffle we intend to construct. As a result
7428     // ShuffleVec will be some sliding window into the original Vec.
7429     SDValue ShuffleVec;
7430 
7431     // Code should guarantee that element i in Vec starts at element "WindowBase
7432     // + i * WindowScale in ShuffleVec".
7433     int WindowBase;
7434     int WindowScale;
7435 
7436     ShuffleSourceInfo(SDValue Vec)
7437       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
7438           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
7439 
7440     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7441   };
7442 
7443   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7444   // node.
7445   SmallVector<ShuffleSourceInfo, 2> Sources;
7446   for (unsigned i = 0; i < NumElts; ++i) {
7447     SDValue V = Op.getOperand(i);
7448     if (V.isUndef())
7449       continue;
7450     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7451              !isa<ConstantSDNode>(V.getOperand(1))) {
7452       LLVM_DEBUG(
7453           dbgs() << "Reshuffle failed: "
7454                     "a shuffle can only come from building a vector from "
7455                     "various elements of other vectors, provided their "
7456                     "indices are constant\n");
7457       return SDValue();
7458     }
7459 
7460     // Add this element source to the list if it's not already there.
7461     SDValue SourceVec = V.getOperand(0);
7462     auto Source = find(Sources, SourceVec);
7463     if (Source == Sources.end())
7464       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7465 
7466     // Update the minimum and maximum lane number seen.
7467     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7468     Source->MinElt = std::min(Source->MinElt, EltNo);
7469     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7470   }
7471 
7472   if (Sources.size() > 2) {
7473     LLVM_DEBUG(
7474         dbgs() << "Reshuffle failed: currently only do something sane when at "
7475                   "most two source vectors are involved\n");
7476     return SDValue();
7477   }
7478 
7479   // Find out the smallest element size among result and two sources, and use
7480   // it as element size to build the shuffle_vector.
7481   EVT SmallestEltTy = VT.getVectorElementType();
7482   for (auto &Source : Sources) {
7483     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7484     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7485       SmallestEltTy = SrcEltTy;
7486     }
7487   }
7488   unsigned ResMultiplier =
7489       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
7490   uint64_t VTSize = VT.getFixedSizeInBits();
7491   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
7492   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7493 
7494   // If the source vector is too wide or too narrow, we may nevertheless be able
7495   // to construct a compatible shuffle either by concatenating it with UNDEF or
7496   // extracting a suitable range of elements.
7497   for (auto &Src : Sources) {
7498     EVT SrcVT = Src.ShuffleVec.getValueType();
7499 
7500     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7501     if (SrcVTSize == VTSize)
7502       continue;
7503 
7504     // This stage of the search produces a source with the same element type as
7505     // the original, but with a total width matching the BUILD_VECTOR output.
7506     EVT EltVT = SrcVT.getVectorElementType();
7507     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7508     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7509 
7510     if (SrcVTSize < VTSize) {
7511       assert(2 * SrcVTSize == VTSize);
7512       // We can pad out the smaller vector for free, so if it's part of a
7513       // shuffle...
7514       Src.ShuffleVec =
7515           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7516                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7517       continue;
7518     }
7519 
7520     if (SrcVTSize != 2 * VTSize) {
7521       LLVM_DEBUG(
7522           dbgs() << "Reshuffle failed: result vector too small to extract\n");
7523       return SDValue();
7524     }
7525 
7526     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7527       LLVM_DEBUG(
7528           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7529       return SDValue();
7530     }
7531 
7532     if (Src.MinElt >= NumSrcElts) {
7533       // The extraction can just take the second half
7534       Src.ShuffleVec =
7535           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7536                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7537       Src.WindowBase = -NumSrcElts;
7538     } else if (Src.MaxElt < NumSrcElts) {
7539       // The extraction can just take the first half
7540       Src.ShuffleVec =
7541           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7542                       DAG.getConstant(0, dl, MVT::i64));
7543     } else {
7544       // An actual VEXT is needed
7545       SDValue VEXTSrc1 =
7546           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7547                       DAG.getConstant(0, dl, MVT::i64));
7548       SDValue VEXTSrc2 =
7549           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7550                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7551       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7552 
7553       if (!SrcVT.is64BitVector()) {
7554         LLVM_DEBUG(
7555           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
7556                     "for SVE vectors.");
7557         return SDValue();
7558       }
7559 
7560       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7561                                    VEXTSrc2,
7562                                    DAG.getConstant(Imm, dl, MVT::i32));
7563       Src.WindowBase = -Src.MinElt;
7564     }
7565   }
7566 
7567   // Another possible incompatibility occurs from the vector element types. We
7568   // can fix this by bitcasting the source vectors to the same type we intend
7569   // for the shuffle.
7570   for (auto &Src : Sources) {
7571     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7572     if (SrcEltTy == SmallestEltTy)
7573       continue;
7574     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7575     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7576     Src.WindowScale =
7577         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
7578     Src.WindowBase *= Src.WindowScale;
7579   }
7580 
7581   // Final sanity check before we try to actually produce a shuffle.
7582   LLVM_DEBUG(for (auto Src
7583                   : Sources)
7584                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7585 
7586   // The stars all align, our next step is to produce the mask for the shuffle.
7587   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7588   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7589   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7590     SDValue Entry = Op.getOperand(i);
7591     if (Entry.isUndef())
7592       continue;
7593 
7594     auto Src = find(Sources, Entry.getOperand(0));
7595     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7596 
7597     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7598     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7599     // segment.
7600     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7601     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7602                                VT.getScalarSizeInBits());
7603     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7604 
7605     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7606     // starting at the appropriate offset.
7607     int *LaneMask = &Mask[i * ResMultiplier];
7608 
7609     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7610     ExtractBase += NumElts * (Src - Sources.begin());
7611     for (int j = 0; j < LanesDefined; ++j)
7612       LaneMask[j] = ExtractBase + j;
7613   }
7614 
7615   // Final check before we try to produce nonsense...
7616   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7617     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7618     return SDValue();
7619   }
7620 
7621   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7622   for (unsigned i = 0; i < Sources.size(); ++i)
7623     ShuffleOps[i] = Sources[i].ShuffleVec;
7624 
7625   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7626                                          ShuffleOps[1], Mask);
7627   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7628 
7629   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7630              dbgs() << "Reshuffle, creating node: "; V.dump(););
7631 
7632   return V;
7633 }
7634 
7635 // check if an EXT instruction can handle the shuffle mask when the
7636 // vector sources of the shuffle are the same.
7637 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7638   unsigned NumElts = VT.getVectorNumElements();
7639 
7640   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7641   if (M[0] < 0)
7642     return false;
7643 
7644   Imm = M[0];
7645 
7646   // If this is a VEXT shuffle, the immediate value is the index of the first
7647   // element.  The other shuffle indices must be the successive elements after
7648   // the first one.
7649   unsigned ExpectedElt = Imm;
7650   for (unsigned i = 1; i < NumElts; ++i) {
7651     // Increment the expected index.  If it wraps around, just follow it
7652     // back to index zero and keep going.
7653     ++ExpectedElt;
7654     if (ExpectedElt == NumElts)
7655       ExpectedElt = 0;
7656 
7657     if (M[i] < 0)
7658       continue; // ignore UNDEF indices
7659     if (ExpectedElt != static_cast<unsigned>(M[i]))
7660       return false;
7661   }
7662 
7663   return true;
7664 }
7665 
7666 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
7667 /// element width than the vector lane type. If that is the case the function
7668 /// returns true and writes the value of the DUP instruction lane operand into
7669 /// DupLaneOp
7670 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
7671                           unsigned &DupLaneOp) {
7672   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7673          "Only possible block sizes for wide DUP are: 16, 32, 64");
7674 
7675   if (BlockSize <= VT.getScalarSizeInBits())
7676     return false;
7677   if (BlockSize % VT.getScalarSizeInBits() != 0)
7678     return false;
7679   if (VT.getSizeInBits() % BlockSize != 0)
7680     return false;
7681 
7682   size_t SingleVecNumElements = VT.getVectorNumElements();
7683   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
7684   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
7685 
7686   // We are looking for masks like
7687   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
7688   // might be replaced by 'undefined'. BlockIndices will eventually contain
7689   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
7690   // for the above examples)
7691   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
7692   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
7693     for (size_t I = 0; I < NumEltsPerBlock; I++) {
7694       int Elt = M[BlockIndex * NumEltsPerBlock + I];
7695       if (Elt < 0)
7696         continue;
7697       // For now we don't support shuffles that use the second operand
7698       if ((unsigned)Elt >= SingleVecNumElements)
7699         return false;
7700       if (BlockElts[I] < 0)
7701         BlockElts[I] = Elt;
7702       else if (BlockElts[I] != Elt)
7703         return false;
7704     }
7705 
7706   // We found a candidate block (possibly with some undefs). It must be a
7707   // sequence of consecutive integers starting with a value divisible by
7708   // NumEltsPerBlock with some values possibly replaced by undef-s.
7709 
7710   // Find first non-undef element
7711   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
7712   assert(FirstRealEltIter != BlockElts.end() &&
7713          "Shuffle with all-undefs must have been caught by previous cases, "
7714          "e.g. isSplat()");
7715   if (FirstRealEltIter == BlockElts.end()) {
7716     DupLaneOp = 0;
7717     return true;
7718   }
7719 
7720   // Index of FirstRealElt in BlockElts
7721   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
7722 
7723   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
7724     return false;
7725   // BlockElts[0] must have the following value if it isn't undef:
7726   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
7727 
7728   // Check the first element
7729   if (Elt0 % NumEltsPerBlock != 0)
7730     return false;
7731   // Check that the sequence indeed consists of consecutive integers (modulo
7732   // undefs)
7733   for (size_t I = 0; I < NumEltsPerBlock; I++)
7734     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
7735       return false;
7736 
7737   DupLaneOp = Elt0 / NumEltsPerBlock;
7738   return true;
7739 }
7740 
7741 // check if an EXT instruction can handle the shuffle mask when the
7742 // vector sources of the shuffle are different.
7743 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7744                       unsigned &Imm) {
7745   // Look for the first non-undef element.
7746   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7747 
7748   // Benefit form APInt to handle overflow when calculating expected element.
7749   unsigned NumElts = VT.getVectorNumElements();
7750   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7751   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7752   // The following shuffle indices must be the successive elements after the
7753   // first real element.
7754   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7755       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7756   if (FirstWrongElt != M.end())
7757     return false;
7758 
7759   // The index of an EXT is the first element if it is not UNDEF.
7760   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7761   // value of the first element.  E.g.
7762   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7763   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7764   // ExpectedElt is the last mask index plus 1.
7765   Imm = ExpectedElt.getZExtValue();
7766 
7767   // There are two difference cases requiring to reverse input vectors.
7768   // For example, for vector <4 x i32> we have the following cases,
7769   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7770   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7771   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7772   // to reverse two input vectors.
7773   if (Imm < NumElts)
7774     ReverseEXT = true;
7775   else
7776     Imm -= NumElts;
7777 
7778   return true;
7779 }
7780 
7781 /// isREVMask - Check if a vector shuffle corresponds to a REV
7782 /// instruction with the specified blocksize.  (The order of the elements
7783 /// within each block of the vector is reversed.)
7784 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7785   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7786          "Only possible block sizes for REV are: 16, 32, 64");
7787 
7788   unsigned EltSz = VT.getScalarSizeInBits();
7789   if (EltSz == 64)
7790     return false;
7791 
7792   unsigned NumElts = VT.getVectorNumElements();
7793   unsigned BlockElts = M[0] + 1;
7794   // If the first shuffle index is UNDEF, be optimistic.
7795   if (M[0] < 0)
7796     BlockElts = BlockSize / EltSz;
7797 
7798   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7799     return false;
7800 
7801   for (unsigned i = 0; i < NumElts; ++i) {
7802     if (M[i] < 0)
7803       continue; // ignore UNDEF indices
7804     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7805       return false;
7806   }
7807 
7808   return true;
7809 }
7810 
7811 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7812   unsigned NumElts = VT.getVectorNumElements();
7813   if (NumElts % 2 != 0)
7814     return false;
7815   WhichResult = (M[0] == 0 ? 0 : 1);
7816   unsigned Idx = WhichResult * NumElts / 2;
7817   for (unsigned i = 0; i != NumElts; i += 2) {
7818     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7819         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7820       return false;
7821     Idx += 1;
7822   }
7823 
7824   return true;
7825 }
7826 
7827 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7828   unsigned NumElts = VT.getVectorNumElements();
7829   WhichResult = (M[0] == 0 ? 0 : 1);
7830   for (unsigned i = 0; i != NumElts; ++i) {
7831     if (M[i] < 0)
7832       continue; // ignore UNDEF indices
7833     if ((unsigned)M[i] != 2 * i + WhichResult)
7834       return false;
7835   }
7836 
7837   return true;
7838 }
7839 
7840 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7841   unsigned NumElts = VT.getVectorNumElements();
7842   if (NumElts % 2 != 0)
7843     return false;
7844   WhichResult = (M[0] == 0 ? 0 : 1);
7845   for (unsigned i = 0; i < NumElts; i += 2) {
7846     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7847         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7848       return false;
7849   }
7850   return true;
7851 }
7852 
7853 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7854 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7855 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7856 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7857   unsigned NumElts = VT.getVectorNumElements();
7858   if (NumElts % 2 != 0)
7859     return false;
7860   WhichResult = (M[0] == 0 ? 0 : 1);
7861   unsigned Idx = WhichResult * NumElts / 2;
7862   for (unsigned i = 0; i != NumElts; i += 2) {
7863     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7864         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7865       return false;
7866     Idx += 1;
7867   }
7868 
7869   return true;
7870 }
7871 
7872 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7873 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7874 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7875 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7876   unsigned Half = VT.getVectorNumElements() / 2;
7877   WhichResult = (M[0] == 0 ? 0 : 1);
7878   for (unsigned j = 0; j != 2; ++j) {
7879     unsigned Idx = WhichResult;
7880     for (unsigned i = 0; i != Half; ++i) {
7881       int MIdx = M[i + j * Half];
7882       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7883         return false;
7884       Idx += 2;
7885     }
7886   }
7887 
7888   return true;
7889 }
7890 
7891 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7892 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7893 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7894 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7895   unsigned NumElts = VT.getVectorNumElements();
7896   if (NumElts % 2 != 0)
7897     return false;
7898   WhichResult = (M[0] == 0 ? 0 : 1);
7899   for (unsigned i = 0; i < NumElts; i += 2) {
7900     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7901         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7902       return false;
7903   }
7904   return true;
7905 }
7906 
7907 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7908                       bool &DstIsLeft, int &Anomaly) {
7909   if (M.size() != static_cast<size_t>(NumInputElements))
7910     return false;
7911 
7912   int NumLHSMatch = 0, NumRHSMatch = 0;
7913   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7914 
7915   for (int i = 0; i < NumInputElements; ++i) {
7916     if (M[i] == -1) {
7917       ++NumLHSMatch;
7918       ++NumRHSMatch;
7919       continue;
7920     }
7921 
7922     if (M[i] == i)
7923       ++NumLHSMatch;
7924     else
7925       LastLHSMismatch = i;
7926 
7927     if (M[i] == i + NumInputElements)
7928       ++NumRHSMatch;
7929     else
7930       LastRHSMismatch = i;
7931   }
7932 
7933   if (NumLHSMatch == NumInputElements - 1) {
7934     DstIsLeft = true;
7935     Anomaly = LastLHSMismatch;
7936     return true;
7937   } else if (NumRHSMatch == NumInputElements - 1) {
7938     DstIsLeft = false;
7939     Anomaly = LastRHSMismatch;
7940     return true;
7941   }
7942 
7943   return false;
7944 }
7945 
7946 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7947   if (VT.getSizeInBits() != 128)
7948     return false;
7949 
7950   unsigned NumElts = VT.getVectorNumElements();
7951 
7952   for (int I = 0, E = NumElts / 2; I != E; I++) {
7953     if (Mask[I] != I)
7954       return false;
7955   }
7956 
7957   int Offset = NumElts / 2;
7958   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7959     if (Mask[I] != I + SplitLHS * Offset)
7960       return false;
7961   }
7962 
7963   return true;
7964 }
7965 
7966 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7967   SDLoc DL(Op);
7968   EVT VT = Op.getValueType();
7969   SDValue V0 = Op.getOperand(0);
7970   SDValue V1 = Op.getOperand(1);
7971   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7972 
7973   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7974       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7975     return SDValue();
7976 
7977   bool SplitV0 = V0.getValueSizeInBits() == 128;
7978 
7979   if (!isConcatMask(Mask, VT, SplitV0))
7980     return SDValue();
7981 
7982   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7983   if (SplitV0) {
7984     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7985                      DAG.getConstant(0, DL, MVT::i64));
7986   }
7987   if (V1.getValueSizeInBits() == 128) {
7988     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7989                      DAG.getConstant(0, DL, MVT::i64));
7990   }
7991   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7992 }
7993 
7994 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7995 /// the specified operations to build the shuffle.
7996 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7997                                       SDValue RHS, SelectionDAG &DAG,
7998                                       const SDLoc &dl) {
7999   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8000   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
8001   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
8002 
8003   enum {
8004     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8005     OP_VREV,
8006     OP_VDUP0,
8007     OP_VDUP1,
8008     OP_VDUP2,
8009     OP_VDUP3,
8010     OP_VEXT1,
8011     OP_VEXT2,
8012     OP_VEXT3,
8013     OP_VUZPL, // VUZP, left result
8014     OP_VUZPR, // VUZP, right result
8015     OP_VZIPL, // VZIP, left result
8016     OP_VZIPR, // VZIP, right result
8017     OP_VTRNL, // VTRN, left result
8018     OP_VTRNR  // VTRN, right result
8019   };
8020 
8021   if (OpNum == OP_COPY) {
8022     if (LHSID == (1 * 9 + 2) * 9 + 3)
8023       return LHS;
8024     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
8025     return RHS;
8026   }
8027 
8028   SDValue OpLHS, OpRHS;
8029   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8030   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8031   EVT VT = OpLHS.getValueType();
8032 
8033   switch (OpNum) {
8034   default:
8035     llvm_unreachable("Unknown shuffle opcode!");
8036   case OP_VREV:
8037     // VREV divides the vector in half and swaps within the half.
8038     if (VT.getVectorElementType() == MVT::i32 ||
8039         VT.getVectorElementType() == MVT::f32)
8040       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
8041     // vrev <4 x i16> -> REV32
8042     if (VT.getVectorElementType() == MVT::i16 ||
8043         VT.getVectorElementType() == MVT::f16 ||
8044         VT.getVectorElementType() == MVT::bf16)
8045       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
8046     // vrev <4 x i8> -> REV16
8047     assert(VT.getVectorElementType() == MVT::i8);
8048     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
8049   case OP_VDUP0:
8050   case OP_VDUP1:
8051   case OP_VDUP2:
8052   case OP_VDUP3: {
8053     EVT EltTy = VT.getVectorElementType();
8054     unsigned Opcode;
8055     if (EltTy == MVT::i8)
8056       Opcode = AArch64ISD::DUPLANE8;
8057     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
8058       Opcode = AArch64ISD::DUPLANE16;
8059     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
8060       Opcode = AArch64ISD::DUPLANE32;
8061     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
8062       Opcode = AArch64ISD::DUPLANE64;
8063     else
8064       llvm_unreachable("Invalid vector element type?");
8065 
8066     if (VT.getSizeInBits() == 64)
8067       OpLHS = WidenVector(OpLHS, DAG);
8068     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
8069     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
8070   }
8071   case OP_VEXT1:
8072   case OP_VEXT2:
8073   case OP_VEXT3: {
8074     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
8075     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
8076                        DAG.getConstant(Imm, dl, MVT::i32));
8077   }
8078   case OP_VUZPL:
8079     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
8080                        OpRHS);
8081   case OP_VUZPR:
8082     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
8083                        OpRHS);
8084   case OP_VZIPL:
8085     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
8086                        OpRHS);
8087   case OP_VZIPR:
8088     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
8089                        OpRHS);
8090   case OP_VTRNL:
8091     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
8092                        OpRHS);
8093   case OP_VTRNR:
8094     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
8095                        OpRHS);
8096   }
8097 }
8098 
8099 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
8100                            SelectionDAG &DAG) {
8101   // Check to see if we can use the TBL instruction.
8102   SDValue V1 = Op.getOperand(0);
8103   SDValue V2 = Op.getOperand(1);
8104   SDLoc DL(Op);
8105 
8106   EVT EltVT = Op.getValueType().getVectorElementType();
8107   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
8108 
8109   SmallVector<SDValue, 8> TBLMask;
8110   for (int Val : ShuffleMask) {
8111     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
8112       unsigned Offset = Byte + Val * BytesPerElt;
8113       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
8114     }
8115   }
8116 
8117   MVT IndexVT = MVT::v8i8;
8118   unsigned IndexLen = 8;
8119   if (Op.getValueSizeInBits() == 128) {
8120     IndexVT = MVT::v16i8;
8121     IndexLen = 16;
8122   }
8123 
8124   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
8125   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
8126 
8127   SDValue Shuffle;
8128   if (V2.getNode()->isUndef()) {
8129     if (IndexLen == 8)
8130       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
8131     Shuffle = DAG.getNode(
8132         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8133         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8134         DAG.getBuildVector(IndexVT, DL,
8135                            makeArrayRef(TBLMask.data(), IndexLen)));
8136   } else {
8137     if (IndexLen == 8) {
8138       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
8139       Shuffle = DAG.getNode(
8140           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8141           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8142           DAG.getBuildVector(IndexVT, DL,
8143                              makeArrayRef(TBLMask.data(), IndexLen)));
8144     } else {
8145       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
8146       // cannot currently represent the register constraints on the input
8147       // table registers.
8148       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
8149       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
8150       //                   IndexLen));
8151       Shuffle = DAG.getNode(
8152           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8153           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
8154           V2Cst, DAG.getBuildVector(IndexVT, DL,
8155                                     makeArrayRef(TBLMask.data(), IndexLen)));
8156     }
8157   }
8158   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
8159 }
8160 
8161 static unsigned getDUPLANEOp(EVT EltType) {
8162   if (EltType == MVT::i8)
8163     return AArch64ISD::DUPLANE8;
8164   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
8165     return AArch64ISD::DUPLANE16;
8166   if (EltType == MVT::i32 || EltType == MVT::f32)
8167     return AArch64ISD::DUPLANE32;
8168   if (EltType == MVT::i64 || EltType == MVT::f64)
8169     return AArch64ISD::DUPLANE64;
8170 
8171   llvm_unreachable("Invalid vector element type?");
8172 }
8173 
8174 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
8175                             unsigned Opcode, SelectionDAG &DAG) {
8176   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
8177   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
8178     // Match: dup (bitcast (extract_subv X, C)), LaneC
8179     if (BitCast.getOpcode() != ISD::BITCAST ||
8180         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
8181       return false;
8182 
8183     // The extract index must align in the destination type. That may not
8184     // happen if the bitcast is from narrow to wide type.
8185     SDValue Extract = BitCast.getOperand(0);
8186     unsigned ExtIdx = Extract.getConstantOperandVal(1);
8187     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
8188     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
8189     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
8190     if (ExtIdxInBits % CastedEltBitWidth != 0)
8191       return false;
8192 
8193     // Update the lane value by offsetting with the scaled extract index.
8194     LaneC += ExtIdxInBits / CastedEltBitWidth;
8195 
8196     // Determine the casted vector type of the wide vector input.
8197     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
8198     // Examples:
8199     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
8200     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
8201     unsigned SrcVecNumElts =
8202         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
8203     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
8204                               SrcVecNumElts);
8205     return true;
8206   };
8207   MVT CastVT;
8208   if (getScaledOffsetDup(V, Lane, CastVT)) {
8209     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
8210   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8211     // The lane is incremented by the index of the extract.
8212     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
8213     Lane += V.getConstantOperandVal(1);
8214     V = V.getOperand(0);
8215   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
8216     // The lane is decremented if we are splatting from the 2nd operand.
8217     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
8218     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
8219     Lane -= Idx * VT.getVectorNumElements() / 2;
8220     V = WidenVector(V.getOperand(Idx), DAG);
8221   } else if (VT.getSizeInBits() == 64) {
8222     // Widen the operand to 128-bit register with undef.
8223     V = WidenVector(V, DAG);
8224   }
8225   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
8226 }
8227 
8228 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8229                                                    SelectionDAG &DAG) const {
8230   SDLoc dl(Op);
8231   EVT VT = Op.getValueType();
8232 
8233   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8234 
8235   // Convert shuffles that are directly supported on NEON to target-specific
8236   // DAG nodes, instead of keeping them as shuffles and matching them again
8237   // during code selection.  This is more efficient and avoids the possibility
8238   // of inconsistencies between legalization and selection.
8239   ArrayRef<int> ShuffleMask = SVN->getMask();
8240 
8241   SDValue V1 = Op.getOperand(0);
8242   SDValue V2 = Op.getOperand(1);
8243 
8244   if (SVN->isSplat()) {
8245     int Lane = SVN->getSplatIndex();
8246     // If this is undef splat, generate it via "just" vdup, if possible.
8247     if (Lane == -1)
8248       Lane = 0;
8249 
8250     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
8251       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
8252                          V1.getOperand(0));
8253     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
8254     // constant. If so, we can just reference the lane's definition directly.
8255     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
8256         !isa<ConstantSDNode>(V1.getOperand(Lane)))
8257       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
8258 
8259     // Otherwise, duplicate from the lane of the input vector.
8260     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
8261     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
8262   }
8263 
8264   // Check if the mask matches a DUP for a wider element
8265   for (unsigned LaneSize : {64U, 32U, 16U}) {
8266     unsigned Lane = 0;
8267     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
8268       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
8269                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
8270                                                         : AArch64ISD::DUPLANE16;
8271       // Cast V1 to an integer vector with required lane size
8272       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
8273       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
8274       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
8275       V1 = DAG.getBitcast(NewVecTy, V1);
8276       // Constuct the DUP instruction
8277       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
8278       // Cast back to the original type
8279       return DAG.getBitcast(VT, V1);
8280     }
8281   }
8282 
8283   if (isREVMask(ShuffleMask, VT, 64))
8284     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
8285   if (isREVMask(ShuffleMask, VT, 32))
8286     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
8287   if (isREVMask(ShuffleMask, VT, 16))
8288     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
8289 
8290   bool ReverseEXT = false;
8291   unsigned Imm;
8292   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
8293     if (ReverseEXT)
8294       std::swap(V1, V2);
8295     Imm *= getExtFactor(V1);
8296     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
8297                        DAG.getConstant(Imm, dl, MVT::i32));
8298   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
8299     Imm *= getExtFactor(V1);
8300     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
8301                        DAG.getConstant(Imm, dl, MVT::i32));
8302   }
8303 
8304   unsigned WhichResult;
8305   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
8306     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8307     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8308   }
8309   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
8310     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8311     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8312   }
8313   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
8314     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8315     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8316   }
8317 
8318   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8319     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8320     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8321   }
8322   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8323     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8324     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8325   }
8326   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8327     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8328     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8329   }
8330 
8331   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
8332     return Concat;
8333 
8334   bool DstIsLeft;
8335   int Anomaly;
8336   int NumInputElements = V1.getValueType().getVectorNumElements();
8337   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
8338     SDValue DstVec = DstIsLeft ? V1 : V2;
8339     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
8340 
8341     SDValue SrcVec = V1;
8342     int SrcLane = ShuffleMask[Anomaly];
8343     if (SrcLane >= NumInputElements) {
8344       SrcVec = V2;
8345       SrcLane -= VT.getVectorNumElements();
8346     }
8347     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
8348 
8349     EVT ScalarVT = VT.getVectorElementType();
8350 
8351     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
8352       ScalarVT = MVT::i32;
8353 
8354     return DAG.getNode(
8355         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8356         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
8357         DstLaneV);
8358   }
8359 
8360   // If the shuffle is not directly supported and it has 4 elements, use
8361   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8362   unsigned NumElts = VT.getVectorNumElements();
8363   if (NumElts == 4) {
8364     unsigned PFIndexes[4];
8365     for (unsigned i = 0; i != 4; ++i) {
8366       if (ShuffleMask[i] < 0)
8367         PFIndexes[i] = 8;
8368       else
8369         PFIndexes[i] = ShuffleMask[i];
8370     }
8371 
8372     // Compute the index in the perfect shuffle table.
8373     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8374                             PFIndexes[2] * 9 + PFIndexes[3];
8375     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8376     unsigned Cost = (PFEntry >> 30);
8377 
8378     if (Cost <= 4)
8379       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8380   }
8381 
8382   return GenerateTBL(Op, ShuffleMask, DAG);
8383 }
8384 
8385 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
8386                                                  SelectionDAG &DAG) const {
8387   SDLoc dl(Op);
8388   EVT VT = Op.getValueType();
8389   EVT ElemVT = VT.getScalarType();
8390   SDValue SplatVal = Op.getOperand(0);
8391 
8392   if (useSVEForFixedLengthVectorVT(VT))
8393     return LowerToScalableOp(Op, DAG);
8394 
8395   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
8396   // FPRs don't have this restriction.
8397   switch (ElemVT.getSimpleVT().SimpleTy) {
8398   case MVT::i1: {
8399     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
8400     // lowering code.
8401     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
8402       if (ConstVal->isOne())
8403         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
8404       // TODO: Add special case for constant false
8405     }
8406     // The general case of i1.  There isn't any natural way to do this,
8407     // so we use some trickery with whilelo.
8408     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8409     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
8410                            DAG.getValueType(MVT::i1));
8411     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
8412                                        MVT::i64);
8413     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
8414                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
8415   }
8416   case MVT::i8:
8417   case MVT::i16:
8418   case MVT::i32:
8419     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
8420     break;
8421   case MVT::i64:
8422     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8423     break;
8424   case MVT::f16:
8425   case MVT::bf16:
8426   case MVT::f32:
8427   case MVT::f64:
8428     // Fine as is
8429     break;
8430   default:
8431     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
8432   }
8433 
8434   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
8435 }
8436 
8437 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
8438                                              SelectionDAG &DAG) const {
8439   SDLoc DL(Op);
8440 
8441   EVT VT = Op.getValueType();
8442   if (!isTypeLegal(VT) || !VT.isScalableVector())
8443     return SDValue();
8444 
8445   // Current lowering only supports the SVE-ACLE types.
8446   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
8447     return SDValue();
8448 
8449   // The DUPQ operation is indepedent of element type so normalise to i64s.
8450   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
8451   SDValue Idx128 = Op.getOperand(2);
8452 
8453   // DUPQ can be used when idx is in range.
8454   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
8455   if (CIdx && (CIdx->getZExtValue() <= 3)) {
8456     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
8457     SDNode *DUPQ =
8458         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
8459     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
8460   }
8461 
8462   // The ACLE says this must produce the same result as:
8463   //   svtbl(data, svadd_x(svptrue_b64(),
8464   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
8465   //                       index * 2))
8466   SDValue One = DAG.getConstant(1, DL, MVT::i64);
8467   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
8468 
8469   // create the vector 0,1,0,1,...
8470   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
8471   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
8472                            DL, MVT::nxv2i64, Zero, One);
8473   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
8474 
8475   // create the vector idx64,idx64+1,idx64,idx64+1,...
8476   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
8477   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
8478   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
8479 
8480   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
8481   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
8482   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
8483 }
8484 
8485 
8486 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
8487                                APInt &UndefBits) {
8488   EVT VT = BVN->getValueType(0);
8489   APInt SplatBits, SplatUndef;
8490   unsigned SplatBitSize;
8491   bool HasAnyUndefs;
8492   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8493     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
8494 
8495     for (unsigned i = 0; i < NumSplats; ++i) {
8496       CnstBits <<= SplatBitSize;
8497       UndefBits <<= SplatBitSize;
8498       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
8499       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
8500     }
8501 
8502     return true;
8503   }
8504 
8505   return false;
8506 }
8507 
8508 // Try 64-bit splatted SIMD immediate.
8509 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8510                                  const APInt &Bits) {
8511   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8512     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8513     EVT VT = Op.getValueType();
8514     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
8515 
8516     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
8517       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
8518 
8519       SDLoc dl(Op);
8520       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8521                                 DAG.getConstant(Value, dl, MVT::i32));
8522       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8523     }
8524   }
8525 
8526   return SDValue();
8527 }
8528 
8529 // Try 32-bit splatted SIMD immediate.
8530 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8531                                   const APInt &Bits,
8532                                   const SDValue *LHS = nullptr) {
8533   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8534     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8535     EVT VT = Op.getValueType();
8536     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8537     bool isAdvSIMDModImm = false;
8538     uint64_t Shift;
8539 
8540     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
8541       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
8542       Shift = 0;
8543     }
8544     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
8545       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
8546       Shift = 8;
8547     }
8548     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
8549       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
8550       Shift = 16;
8551     }
8552     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
8553       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
8554       Shift = 24;
8555     }
8556 
8557     if (isAdvSIMDModImm) {
8558       SDLoc dl(Op);
8559       SDValue Mov;
8560 
8561       if (LHS)
8562         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8563                           DAG.getConstant(Value, dl, MVT::i32),
8564                           DAG.getConstant(Shift, dl, MVT::i32));
8565       else
8566         Mov = DAG.getNode(NewOp, dl, MovTy,
8567                           DAG.getConstant(Value, dl, MVT::i32),
8568                           DAG.getConstant(Shift, dl, MVT::i32));
8569 
8570       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8571     }
8572   }
8573 
8574   return SDValue();
8575 }
8576 
8577 // Try 16-bit splatted SIMD immediate.
8578 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8579                                   const APInt &Bits,
8580                                   const SDValue *LHS = nullptr) {
8581   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8582     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8583     EVT VT = Op.getValueType();
8584     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8585     bool isAdvSIMDModImm = false;
8586     uint64_t Shift;
8587 
8588     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8589       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8590       Shift = 0;
8591     }
8592     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8593       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8594       Shift = 8;
8595     }
8596 
8597     if (isAdvSIMDModImm) {
8598       SDLoc dl(Op);
8599       SDValue Mov;
8600 
8601       if (LHS)
8602         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8603                           DAG.getConstant(Value, dl, MVT::i32),
8604                           DAG.getConstant(Shift, dl, MVT::i32));
8605       else
8606         Mov = DAG.getNode(NewOp, dl, MovTy,
8607                           DAG.getConstant(Value, dl, MVT::i32),
8608                           DAG.getConstant(Shift, dl, MVT::i32));
8609 
8610       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8611     }
8612   }
8613 
8614   return SDValue();
8615 }
8616 
8617 // Try 32-bit splatted SIMD immediate with shifted ones.
8618 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8619                                     SelectionDAG &DAG, const APInt &Bits) {
8620   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8621     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8622     EVT VT = Op.getValueType();
8623     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8624     bool isAdvSIMDModImm = false;
8625     uint64_t Shift;
8626 
8627     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8628       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8629       Shift = 264;
8630     }
8631     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8632       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8633       Shift = 272;
8634     }
8635 
8636     if (isAdvSIMDModImm) {
8637       SDLoc dl(Op);
8638       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8639                                 DAG.getConstant(Value, dl, MVT::i32),
8640                                 DAG.getConstant(Shift, dl, MVT::i32));
8641       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8642     }
8643   }
8644 
8645   return SDValue();
8646 }
8647 
8648 // Try 8-bit splatted SIMD immediate.
8649 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8650                                  const APInt &Bits) {
8651   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8652     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8653     EVT VT = Op.getValueType();
8654     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8655 
8656     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8657       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8658 
8659       SDLoc dl(Op);
8660       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8661                                 DAG.getConstant(Value, dl, MVT::i32));
8662       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8663     }
8664   }
8665 
8666   return SDValue();
8667 }
8668 
8669 // Try FP splatted SIMD immediate.
8670 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8671                                   const APInt &Bits) {
8672   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8673     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8674     EVT VT = Op.getValueType();
8675     bool isWide = (VT.getSizeInBits() == 128);
8676     MVT MovTy;
8677     bool isAdvSIMDModImm = false;
8678 
8679     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8680       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8681       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8682     }
8683     else if (isWide &&
8684              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8685       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8686       MovTy = MVT::v2f64;
8687     }
8688 
8689     if (isAdvSIMDModImm) {
8690       SDLoc dl(Op);
8691       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8692                                 DAG.getConstant(Value, dl, MVT::i32));
8693       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8694     }
8695   }
8696 
8697   return SDValue();
8698 }
8699 
8700 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8701 // consists of only the same constant int value, returned in reference arg
8702 // ConstVal
8703 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8704                                      uint64_t &ConstVal) {
8705   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8706   if (!Bvec)
8707     return false;
8708   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8709   if (!FirstElt)
8710     return false;
8711   EVT VT = Bvec->getValueType(0);
8712   unsigned NumElts = VT.getVectorNumElements();
8713   for (unsigned i = 1; i < NumElts; ++i)
8714     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8715       return false;
8716   ConstVal = FirstElt->getZExtValue();
8717   return true;
8718 }
8719 
8720 static unsigned getIntrinsicID(const SDNode *N) {
8721   unsigned Opcode = N->getOpcode();
8722   switch (Opcode) {
8723   default:
8724     return Intrinsic::not_intrinsic;
8725   case ISD::INTRINSIC_WO_CHAIN: {
8726     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8727     if (IID < Intrinsic::num_intrinsics)
8728       return IID;
8729     return Intrinsic::not_intrinsic;
8730   }
8731   }
8732 }
8733 
8734 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8735 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8736 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8737 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8738 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8739 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8740 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8741   EVT VT = N->getValueType(0);
8742 
8743   if (!VT.isVector())
8744     return SDValue();
8745 
8746   SDLoc DL(N);
8747 
8748   SDValue And;
8749   SDValue Shift;
8750 
8751   SDValue FirstOp = N->getOperand(0);
8752   unsigned FirstOpc = FirstOp.getOpcode();
8753   SDValue SecondOp = N->getOperand(1);
8754   unsigned SecondOpc = SecondOp.getOpcode();
8755 
8756   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8757   // a BICi in order to use an immediate instead of a register.
8758   // Is the other operand an shl or lshr? This will have been turned into:
8759   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8760   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8761       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8762     And = FirstOp;
8763     Shift = SecondOp;
8764 
8765   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8766              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8767     And = SecondOp;
8768     Shift = FirstOp;
8769   } else
8770     return SDValue();
8771 
8772   bool IsAnd = And.getOpcode() == ISD::AND;
8773   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8774 
8775   // Is the shift amount constant?
8776   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8777   if (!C2node)
8778     return SDValue();
8779 
8780   uint64_t C1;
8781   if (IsAnd) {
8782     // Is the and mask vector all constant?
8783     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8784       return SDValue();
8785   } else {
8786     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8787     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8788     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8789     assert(C1nodeImm && C1nodeShift);
8790     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8791   }
8792 
8793   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8794   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8795   // how much one can shift elements of a particular size?
8796   uint64_t C2 = C2node->getZExtValue();
8797   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8798   if (C2 > ElemSizeInBits)
8799     return SDValue();
8800 
8801   APInt C1AsAPInt(ElemSizeInBits, C1);
8802   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8803                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8804   if (C1AsAPInt != RequiredC1)
8805     return SDValue();
8806 
8807   SDValue X = And.getOperand(0);
8808   SDValue Y = Shift.getOperand(0);
8809 
8810   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8811   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8812 
8813   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8814   LLVM_DEBUG(N->dump(&DAG));
8815   LLVM_DEBUG(dbgs() << "into: \n");
8816   LLVM_DEBUG(ResultSLI->dump(&DAG));
8817 
8818   ++NumShiftInserts;
8819   return ResultSLI;
8820 }
8821 
8822 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8823                                              SelectionDAG &DAG) const {
8824   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
8825     return LowerToScalableOp(Op, DAG);
8826 
8827   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8828   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8829     return Res;
8830 
8831   EVT VT = Op.getValueType();
8832 
8833   SDValue LHS = Op.getOperand(0);
8834   BuildVectorSDNode *BVN =
8835       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8836   if (!BVN) {
8837     // OR commutes, so try swapping the operands.
8838     LHS = Op.getOperand(1);
8839     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8840   }
8841   if (!BVN)
8842     return Op;
8843 
8844   APInt DefBits(VT.getSizeInBits(), 0);
8845   APInt UndefBits(VT.getSizeInBits(), 0);
8846   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8847     SDValue NewOp;
8848 
8849     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8850                                     DefBits, &LHS)) ||
8851         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8852                                     DefBits, &LHS)))
8853       return NewOp;
8854 
8855     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8856                                     UndefBits, &LHS)) ||
8857         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8858                                     UndefBits, &LHS)))
8859       return NewOp;
8860   }
8861 
8862   // We can always fall back to a non-immediate OR.
8863   return Op;
8864 }
8865 
8866 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8867 // be truncated to fit element width.
8868 static SDValue NormalizeBuildVector(SDValue Op,
8869                                     SelectionDAG &DAG) {
8870   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8871   SDLoc dl(Op);
8872   EVT VT = Op.getValueType();
8873   EVT EltTy= VT.getVectorElementType();
8874 
8875   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8876     return Op;
8877 
8878   SmallVector<SDValue, 16> Ops;
8879   for (SDValue Lane : Op->ops()) {
8880     // For integer vectors, type legalization would have promoted the
8881     // operands already. Otherwise, if Op is a floating-point splat
8882     // (with operands cast to integers), then the only possibilities
8883     // are constants and UNDEFs.
8884     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8885       APInt LowBits(EltTy.getSizeInBits(),
8886                     CstLane->getZExtValue());
8887       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8888     } else if (Lane.getNode()->isUndef()) {
8889       Lane = DAG.getUNDEF(MVT::i32);
8890     } else {
8891       assert(Lane.getValueType() == MVT::i32 &&
8892              "Unexpected BUILD_VECTOR operand type");
8893     }
8894     Ops.push_back(Lane);
8895   }
8896   return DAG.getBuildVector(VT, dl, Ops);
8897 }
8898 
8899 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8900   EVT VT = Op.getValueType();
8901 
8902   APInt DefBits(VT.getSizeInBits(), 0);
8903   APInt UndefBits(VT.getSizeInBits(), 0);
8904   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8905   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8906     SDValue NewOp;
8907     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8908         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8909         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8910         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8911         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8912         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8913       return NewOp;
8914 
8915     DefBits = ~DefBits;
8916     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8917         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8918         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8919       return NewOp;
8920 
8921     DefBits = UndefBits;
8922     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8923         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8924         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8925         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8926         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8927         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8928       return NewOp;
8929 
8930     DefBits = ~UndefBits;
8931     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8932         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8933         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8934       return NewOp;
8935   }
8936 
8937   return SDValue();
8938 }
8939 
8940 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8941                                                  SelectionDAG &DAG) const {
8942   EVT VT = Op.getValueType();
8943 
8944   // Try to build a simple constant vector.
8945   Op = NormalizeBuildVector(Op, DAG);
8946   if (VT.isInteger()) {
8947     // Certain vector constants, used to express things like logical NOT and
8948     // arithmetic NEG, are passed through unmodified.  This allows special
8949     // patterns for these operations to match, which will lower these constants
8950     // to whatever is proven necessary.
8951     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8952     if (BVN->isConstant())
8953       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8954         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8955         APInt Val(BitSize,
8956                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8957         if (Val.isNullValue() || Val.isAllOnesValue())
8958           return Op;
8959       }
8960   }
8961 
8962   if (SDValue V = ConstantBuildVector(Op, DAG))
8963     return V;
8964 
8965   // Scan through the operands to find some interesting properties we can
8966   // exploit:
8967   //   1) If only one value is used, we can use a DUP, or
8968   //   2) if only the low element is not undef, we can just insert that, or
8969   //   3) if only one constant value is used (w/ some non-constant lanes),
8970   //      we can splat the constant value into the whole vector then fill
8971   //      in the non-constant lanes.
8972   //   4) FIXME: If different constant values are used, but we can intelligently
8973   //             select the values we'll be overwriting for the non-constant
8974   //             lanes such that we can directly materialize the vector
8975   //             some other way (MOVI, e.g.), we can be sneaky.
8976   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8977   SDLoc dl(Op);
8978   unsigned NumElts = VT.getVectorNumElements();
8979   bool isOnlyLowElement = true;
8980   bool usesOnlyOneValue = true;
8981   bool usesOnlyOneConstantValue = true;
8982   bool isConstant = true;
8983   bool AllLanesExtractElt = true;
8984   unsigned NumConstantLanes = 0;
8985   SDValue Value;
8986   SDValue ConstantValue;
8987   for (unsigned i = 0; i < NumElts; ++i) {
8988     SDValue V = Op.getOperand(i);
8989     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8990       AllLanesExtractElt = false;
8991     if (V.isUndef())
8992       continue;
8993     if (i > 0)
8994       isOnlyLowElement = false;
8995     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8996       isConstant = false;
8997 
8998     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8999       ++NumConstantLanes;
9000       if (!ConstantValue.getNode())
9001         ConstantValue = V;
9002       else if (ConstantValue != V)
9003         usesOnlyOneConstantValue = false;
9004     }
9005 
9006     if (!Value.getNode())
9007       Value = V;
9008     else if (V != Value)
9009       usesOnlyOneValue = false;
9010   }
9011 
9012   if (!Value.getNode()) {
9013     LLVM_DEBUG(
9014         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
9015     return DAG.getUNDEF(VT);
9016   }
9017 
9018   // Convert BUILD_VECTOR where all elements but the lowest are undef into
9019   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
9020   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
9021   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
9022     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
9023                          "SCALAR_TO_VECTOR node\n");
9024     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
9025   }
9026 
9027   if (AllLanesExtractElt) {
9028     SDNode *Vector = nullptr;
9029     bool Even = false;
9030     bool Odd = false;
9031     // Check whether the extract elements match the Even pattern <0,2,4,...> or
9032     // the Odd pattern <1,3,5,...>.
9033     for (unsigned i = 0; i < NumElts; ++i) {
9034       SDValue V = Op.getOperand(i);
9035       const SDNode *N = V.getNode();
9036       if (!isa<ConstantSDNode>(N->getOperand(1)))
9037         break;
9038       SDValue N0 = N->getOperand(0);
9039 
9040       // All elements are extracted from the same vector.
9041       if (!Vector) {
9042         Vector = N0.getNode();
9043         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
9044         // BUILD_VECTOR.
9045         if (VT.getVectorElementType() !=
9046             N0.getValueType().getVectorElementType())
9047           break;
9048       } else if (Vector != N0.getNode()) {
9049         Odd = false;
9050         Even = false;
9051         break;
9052       }
9053 
9054       // Extracted values are either at Even indices <0,2,4,...> or at Odd
9055       // indices <1,3,5,...>.
9056       uint64_t Val = N->getConstantOperandVal(1);
9057       if (Val == 2 * i) {
9058         Even = true;
9059         continue;
9060       }
9061       if (Val - 1 == 2 * i) {
9062         Odd = true;
9063         continue;
9064       }
9065 
9066       // Something does not match: abort.
9067       Odd = false;
9068       Even = false;
9069       break;
9070     }
9071     if (Even || Odd) {
9072       SDValue LHS =
9073           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9074                       DAG.getConstant(0, dl, MVT::i64));
9075       SDValue RHS =
9076           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9077                       DAG.getConstant(NumElts, dl, MVT::i64));
9078 
9079       if (Even && !Odd)
9080         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
9081                            RHS);
9082       if (Odd && !Even)
9083         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
9084                            RHS);
9085     }
9086   }
9087 
9088   // Use DUP for non-constant splats. For f32 constant splats, reduce to
9089   // i32 and try again.
9090   if (usesOnlyOneValue) {
9091     if (!isConstant) {
9092       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9093           Value.getValueType() != VT) {
9094         LLVM_DEBUG(
9095             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
9096         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
9097       }
9098 
9099       // This is actually a DUPLANExx operation, which keeps everything vectory.
9100 
9101       SDValue Lane = Value.getOperand(1);
9102       Value = Value.getOperand(0);
9103       if (Value.getValueSizeInBits() == 64) {
9104         LLVM_DEBUG(
9105             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
9106                       "widening it\n");
9107         Value = WidenVector(Value, DAG);
9108       }
9109 
9110       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
9111       return DAG.getNode(Opcode, dl, VT, Value, Lane);
9112     }
9113 
9114     if (VT.getVectorElementType().isFloatingPoint()) {
9115       SmallVector<SDValue, 8> Ops;
9116       EVT EltTy = VT.getVectorElementType();
9117       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
9118                EltTy == MVT::f64) && "Unsupported floating-point vector type");
9119       LLVM_DEBUG(
9120           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
9121                     "BITCASTS, and try again\n");
9122       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
9123       for (unsigned i = 0; i < NumElts; ++i)
9124         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
9125       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
9126       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
9127       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
9128                  Val.dump(););
9129       Val = LowerBUILD_VECTOR(Val, DAG);
9130       if (Val.getNode())
9131         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9132     }
9133   }
9134 
9135   // If there was only one constant value used and for more than one lane,
9136   // start by splatting that value, then replace the non-constant lanes. This
9137   // is better than the default, which will perform a separate initialization
9138   // for each lane.
9139   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
9140     // Firstly, try to materialize the splat constant.
9141     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
9142             Val = ConstantBuildVector(Vec, DAG);
9143     if (!Val) {
9144       // Otherwise, materialize the constant and splat it.
9145       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
9146       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
9147     }
9148 
9149     // Now insert the non-constant lanes.
9150     for (unsigned i = 0; i < NumElts; ++i) {
9151       SDValue V = Op.getOperand(i);
9152       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9153       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
9154         // Note that type legalization likely mucked about with the VT of the
9155         // source operand, so we may have to convert it here before inserting.
9156         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
9157     }
9158     return Val;
9159   }
9160 
9161   // This will generate a load from the constant pool.
9162   if (isConstant) {
9163     LLVM_DEBUG(
9164         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
9165                   "expansion\n");
9166     return SDValue();
9167   }
9168 
9169   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
9170   if (NumElts >= 4) {
9171     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
9172       return shuffle;
9173   }
9174 
9175   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
9176   // know the default expansion would otherwise fall back on something even
9177   // worse. For a vector with one or two non-undef values, that's
9178   // scalar_to_vector for the elements followed by a shuffle (provided the
9179   // shuffle is valid for the target) and materialization element by element
9180   // on the stack followed by a load for everything else.
9181   if (!isConstant && !usesOnlyOneValue) {
9182     LLVM_DEBUG(
9183         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
9184                   "of INSERT_VECTOR_ELT\n");
9185 
9186     SDValue Vec = DAG.getUNDEF(VT);
9187     SDValue Op0 = Op.getOperand(0);
9188     unsigned i = 0;
9189 
9190     // Use SCALAR_TO_VECTOR for lane zero to
9191     // a) Avoid a RMW dependency on the full vector register, and
9192     // b) Allow the register coalescer to fold away the copy if the
9193     //    value is already in an S or D register, and we're forced to emit an
9194     //    INSERT_SUBREG that we can't fold anywhere.
9195     //
9196     // We also allow types like i8 and i16 which are illegal scalar but legal
9197     // vector element types. After type-legalization the inserted value is
9198     // extended (i32) and it is safe to cast them to the vector type by ignoring
9199     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
9200     if (!Op0.isUndef()) {
9201       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
9202       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
9203       ++i;
9204     }
9205     LLVM_DEBUG(if (i < NumElts) dbgs()
9206                    << "Creating nodes for the other vector elements:\n";);
9207     for (; i < NumElts; ++i) {
9208       SDValue V = Op.getOperand(i);
9209       if (V.isUndef())
9210         continue;
9211       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9212       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
9213     }
9214     return Vec;
9215   }
9216 
9217   LLVM_DEBUG(
9218       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
9219                 "better alternative\n");
9220   return SDValue();
9221 }
9222 
9223 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
9224                                                    SelectionDAG &DAG) const {
9225   assert(Op.getValueType().isScalableVector() &&
9226          isTypeLegal(Op.getValueType()) &&
9227          "Expected legal scalable vector type!");
9228 
9229   if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2)
9230     return Op;
9231 
9232   return SDValue();
9233 }
9234 
9235 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9236                                                       SelectionDAG &DAG) const {
9237   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
9238 
9239   // Check for non-constant or out of range lane.
9240   EVT VT = Op.getOperand(0).getValueType();
9241   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9242   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9243     return SDValue();
9244 
9245 
9246   // Insertion/extraction are legal for V128 types.
9247   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9248       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9249       VT == MVT::v8f16 || VT == MVT::v8bf16)
9250     return Op;
9251 
9252   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9253       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9254       VT != MVT::v4bf16)
9255     return SDValue();
9256 
9257   // For V64 types, we perform insertion by expanding the value
9258   // to a V128 type and perform the insertion on that.
9259   SDLoc DL(Op);
9260   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9261   EVT WideTy = WideVec.getValueType();
9262 
9263   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
9264                              Op.getOperand(1), Op.getOperand(2));
9265   // Re-narrow the resultant vector.
9266   return NarrowVector(Node, DAG);
9267 }
9268 
9269 SDValue
9270 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9271                                                SelectionDAG &DAG) const {
9272   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
9273 
9274   // Check for non-constant or out of range lane.
9275   EVT VT = Op.getOperand(0).getValueType();
9276   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9277   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9278     return SDValue();
9279 
9280 
9281   // Insertion/extraction are legal for V128 types.
9282   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9283       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9284       VT == MVT::v8f16 || VT == MVT::v8bf16)
9285     return Op;
9286 
9287   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9288       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9289       VT != MVT::v4bf16)
9290     return SDValue();
9291 
9292   // For V64 types, we perform extraction by expanding the value
9293   // to a V128 type and perform the extraction on that.
9294   SDLoc DL(Op);
9295   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9296   EVT WideTy = WideVec.getValueType();
9297 
9298   EVT ExtrTy = WideTy.getVectorElementType();
9299   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
9300     ExtrTy = MVT::i32;
9301 
9302   // For extractions, we just return the result directly.
9303   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
9304                      Op.getOperand(1));
9305 }
9306 
9307 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
9308                                                       SelectionDAG &DAG) const {
9309   assert(Op.getValueType().isFixedLengthVector() &&
9310          "Only cases that extract a fixed length vector are supported!");
9311 
9312   EVT InVT = Op.getOperand(0).getValueType();
9313   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9314   unsigned Size = Op.getValueSizeInBits();
9315 
9316   if (InVT.isScalableVector()) {
9317     // This will be matched by custom code during ISelDAGToDAG.
9318     if (Idx == 0 && isPackedVectorType(InVT, DAG))
9319       return Op;
9320 
9321     return SDValue();
9322   }
9323 
9324   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
9325   if (Idx == 0 && InVT.getSizeInBits() <= 128)
9326     return Op;
9327 
9328   // If this is extracting the upper 64-bits of a 128-bit vector, we match
9329   // that directly.
9330   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
9331       InVT.getSizeInBits() == 128)
9332     return Op;
9333 
9334   return SDValue();
9335 }
9336 
9337 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
9338                                                      SelectionDAG &DAG) const {
9339   assert(Op.getValueType().isScalableVector() &&
9340          "Only expect to lower inserts into scalable vectors!");
9341 
9342   EVT InVT = Op.getOperand(1).getValueType();
9343   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9344 
9345   if (InVT.isScalableVector()) {
9346     SDLoc DL(Op);
9347     EVT VT = Op.getValueType();
9348 
9349     if (!isTypeLegal(VT) || !VT.isInteger())
9350       return SDValue();
9351 
9352     SDValue Vec0 = Op.getOperand(0);
9353     SDValue Vec1 = Op.getOperand(1);
9354 
9355     // Ensure the subvector is half the size of the main vector.
9356     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
9357       return SDValue();
9358 
9359     // Extend elements of smaller vector...
9360     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
9361     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
9362 
9363     if (Idx == 0) {
9364       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
9365       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
9366     } else if (Idx == InVT.getVectorMinNumElements()) {
9367       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
9368       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
9369     }
9370 
9371     return SDValue();
9372   }
9373 
9374   // This will be matched by custom code during ISelDAGToDAG.
9375   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
9376     return Op;
9377 
9378   return SDValue();
9379 }
9380 
9381 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
9382   EVT VT = Op.getValueType();
9383 
9384   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
9385     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
9386 
9387   assert(VT.isScalableVector() && "Expected a scalable vector.");
9388 
9389   bool Signed = Op.getOpcode() == ISD::SDIV;
9390   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
9391 
9392   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
9393     return LowerToPredicatedOp(Op, DAG, PredOpcode);
9394 
9395   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
9396   // operations, and truncate the result.
9397   EVT WidenedVT;
9398   if (VT == MVT::nxv16i8)
9399     WidenedVT = MVT::nxv8i16;
9400   else if (VT == MVT::nxv8i16)
9401     WidenedVT = MVT::nxv4i32;
9402   else
9403     llvm_unreachable("Unexpected Custom DIV operation");
9404 
9405   SDLoc dl(Op);
9406   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
9407   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
9408   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
9409   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
9410   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
9411   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
9412   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
9413   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
9414   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
9415 }
9416 
9417 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
9418   // Currently no fixed length shuffles that require SVE are legal.
9419   if (useSVEForFixedLengthVectorVT(VT))
9420     return false;
9421 
9422   if (VT.getVectorNumElements() == 4 &&
9423       (VT.is128BitVector() || VT.is64BitVector())) {
9424     unsigned PFIndexes[4];
9425     for (unsigned i = 0; i != 4; ++i) {
9426       if (M[i] < 0)
9427         PFIndexes[i] = 8;
9428       else
9429         PFIndexes[i] = M[i];
9430     }
9431 
9432     // Compute the index in the perfect shuffle table.
9433     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
9434                             PFIndexes[2] * 9 + PFIndexes[3];
9435     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9436     unsigned Cost = (PFEntry >> 30);
9437 
9438     if (Cost <= 4)
9439       return true;
9440   }
9441 
9442   bool DummyBool;
9443   int DummyInt;
9444   unsigned DummyUnsigned;
9445 
9446   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
9447           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
9448           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
9449           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
9450           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
9451           isZIPMask(M, VT, DummyUnsigned) ||
9452           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
9453           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
9454           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
9455           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
9456           isConcatMask(M, VT, VT.getSizeInBits() == 128));
9457 }
9458 
9459 /// getVShiftImm - Check if this is a valid build_vector for the immediate
9460 /// operand of a vector shift operation, where all the elements of the
9461 /// build_vector must have the same constant integer value.
9462 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9463   // Ignore bit_converts.
9464   while (Op.getOpcode() == ISD::BITCAST)
9465     Op = Op.getOperand(0);
9466   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9467   APInt SplatBits, SplatUndef;
9468   unsigned SplatBitSize;
9469   bool HasAnyUndefs;
9470   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9471                                     HasAnyUndefs, ElementBits) ||
9472       SplatBitSize > ElementBits)
9473     return false;
9474   Cnt = SplatBits.getSExtValue();
9475   return true;
9476 }
9477 
9478 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9479 /// operand of a vector shift left operation.  That value must be in the range:
9480 ///   0 <= Value < ElementBits for a left shift; or
9481 ///   0 <= Value <= ElementBits for a long left shift.
9482 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9483   assert(VT.isVector() && "vector shift count is not a vector type");
9484   int64_t ElementBits = VT.getScalarSizeInBits();
9485   if (!getVShiftImm(Op, ElementBits, Cnt))
9486     return false;
9487   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
9488 }
9489 
9490 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9491 /// operand of a vector shift right operation. The value must be in the range:
9492 ///   1 <= Value <= ElementBits for a right shift; or
9493 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
9494   assert(VT.isVector() && "vector shift count is not a vector type");
9495   int64_t ElementBits = VT.getScalarSizeInBits();
9496   if (!getVShiftImm(Op, ElementBits, Cnt))
9497     return false;
9498   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
9499 }
9500 
9501 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
9502                                              SelectionDAG &DAG) const {
9503   EVT VT = Op.getValueType();
9504 
9505   if (VT.getScalarType() == MVT::i1) {
9506     // Lower i1 truncate to `(x & 1) != 0`.
9507     SDLoc dl(Op);
9508     EVT OpVT = Op.getOperand(0).getValueType();
9509     SDValue Zero = DAG.getConstant(0, dl, OpVT);
9510     SDValue One = DAG.getConstant(1, dl, OpVT);
9511     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
9512     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
9513   }
9514 
9515   if (!VT.isVector() || VT.isScalableVector())
9516     return SDValue();
9517 
9518   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9519     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
9520 
9521   return SDValue();
9522 }
9523 
9524 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
9525                                                       SelectionDAG &DAG) const {
9526   EVT VT = Op.getValueType();
9527   SDLoc DL(Op);
9528   int64_t Cnt;
9529 
9530   if (!Op.getOperand(1).getValueType().isVector())
9531     return Op;
9532   unsigned EltSize = VT.getScalarSizeInBits();
9533 
9534   switch (Op.getOpcode()) {
9535   default:
9536     llvm_unreachable("unexpected shift opcode");
9537 
9538   case ISD::SHL:
9539     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
9540       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
9541 
9542     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
9543       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
9544                          DAG.getConstant(Cnt, DL, MVT::i32));
9545     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9546                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
9547                                        MVT::i32),
9548                        Op.getOperand(0), Op.getOperand(1));
9549   case ISD::SRA:
9550   case ISD::SRL:
9551     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
9552       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
9553                                                 : AArch64ISD::SRL_PRED;
9554       return LowerToPredicatedOp(Op, DAG, Opc);
9555     }
9556 
9557     // Right shift immediate
9558     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
9559       unsigned Opc =
9560           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
9561       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
9562                          DAG.getConstant(Cnt, DL, MVT::i32));
9563     }
9564 
9565     // Right shift register.  Note, there is not a shift right register
9566     // instruction, but the shift left register instruction takes a signed
9567     // value, where negative numbers specify a right shift.
9568     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
9569                                                 : Intrinsic::aarch64_neon_ushl;
9570     // negate the shift amount
9571     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
9572     SDValue NegShiftLeft =
9573         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9574                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
9575                     NegShift);
9576     return NegShiftLeft;
9577   }
9578 
9579   return SDValue();
9580 }
9581 
9582 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
9583                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
9584                                     const SDLoc &dl, SelectionDAG &DAG) {
9585   EVT SrcVT = LHS.getValueType();
9586   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9587          "function only supposed to emit natural comparisons");
9588 
9589   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9590   APInt CnstBits(VT.getSizeInBits(), 0);
9591   APInt UndefBits(VT.getSizeInBits(), 0);
9592   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9593   bool IsZero = IsCnst && (CnstBits == 0);
9594 
9595   if (SrcVT.getVectorElementType().isFloatingPoint()) {
9596     switch (CC) {
9597     default:
9598       return SDValue();
9599     case AArch64CC::NE: {
9600       SDValue Fcmeq;
9601       if (IsZero)
9602         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9603       else
9604         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9605       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9606     }
9607     case AArch64CC::EQ:
9608       if (IsZero)
9609         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9610       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9611     case AArch64CC::GE:
9612       if (IsZero)
9613         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9614       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9615     case AArch64CC::GT:
9616       if (IsZero)
9617         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9618       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9619     case AArch64CC::LS:
9620       if (IsZero)
9621         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9622       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9623     case AArch64CC::LT:
9624       if (!NoNans)
9625         return SDValue();
9626       // If we ignore NaNs then we can use to the MI implementation.
9627       LLVM_FALLTHROUGH;
9628     case AArch64CC::MI:
9629       if (IsZero)
9630         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9631       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9632     }
9633   }
9634 
9635   switch (CC) {
9636   default:
9637     return SDValue();
9638   case AArch64CC::NE: {
9639     SDValue Cmeq;
9640     if (IsZero)
9641       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9642     else
9643       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9644     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9645   }
9646   case AArch64CC::EQ:
9647     if (IsZero)
9648       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9649     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9650   case AArch64CC::GE:
9651     if (IsZero)
9652       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9653     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9654   case AArch64CC::GT:
9655     if (IsZero)
9656       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9657     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9658   case AArch64CC::LE:
9659     if (IsZero)
9660       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9661     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9662   case AArch64CC::LS:
9663     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9664   case AArch64CC::LO:
9665     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9666   case AArch64CC::LT:
9667     if (IsZero)
9668       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9669     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9670   case AArch64CC::HI:
9671     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9672   case AArch64CC::HS:
9673     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9674   }
9675 }
9676 
9677 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9678                                            SelectionDAG &DAG) const {
9679   if (Op.getValueType().isScalableVector()) {
9680     if (Op.getOperand(0).getValueType().isFloatingPoint())
9681       return Op;
9682     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9683   }
9684 
9685   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9686     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
9687 
9688   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9689   SDValue LHS = Op.getOperand(0);
9690   SDValue RHS = Op.getOperand(1);
9691   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9692   SDLoc dl(Op);
9693 
9694   if (LHS.getValueType().getVectorElementType().isInteger()) {
9695     assert(LHS.getValueType() == RHS.getValueType());
9696     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9697     SDValue Cmp =
9698         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9699     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9700   }
9701 
9702   const bool FullFP16 =
9703     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9704 
9705   // Make v4f16 (only) fcmp operations utilise vector instructions
9706   // v8f16 support will be a litle more complicated
9707   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9708     if (LHS.getValueType().getVectorNumElements() == 4) {
9709       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9710       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9711       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9712       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9713       CmpVT = MVT::v4i32;
9714     } else
9715       return SDValue();
9716   }
9717 
9718   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9719           LHS.getValueType().getVectorElementType() != MVT::f128);
9720 
9721   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9722   // clean.  Some of them require two branches to implement.
9723   AArch64CC::CondCode CC1, CC2;
9724   bool ShouldInvert;
9725   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9726 
9727   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9728   SDValue Cmp =
9729       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9730   if (!Cmp.getNode())
9731     return SDValue();
9732 
9733   if (CC2 != AArch64CC::AL) {
9734     SDValue Cmp2 =
9735         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9736     if (!Cmp2.getNode())
9737       return SDValue();
9738 
9739     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9740   }
9741 
9742   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9743 
9744   if (ShouldInvert)
9745     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9746 
9747   return Cmp;
9748 }
9749 
9750 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9751                                   SelectionDAG &DAG) {
9752   SDValue VecOp = ScalarOp.getOperand(0);
9753   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9754   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9755                      DAG.getConstant(0, DL, MVT::i64));
9756 }
9757 
9758 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9759                                               SelectionDAG &DAG) const {
9760   SDValue Src = Op.getOperand(0);
9761 
9762   // Try to lower fixed length reductions to SVE.
9763   EVT SrcVT = Src.getValueType();
9764   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
9765                       Op.getOpcode() == ISD::VECREDUCE_OR ||
9766                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
9767                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
9768                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
9769                        SrcVT.getVectorElementType() == MVT::i64);
9770   if (useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
9771     switch (Op.getOpcode()) {
9772     case ISD::VECREDUCE_ADD:
9773       return LowerFixedLengthReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
9774     case ISD::VECREDUCE_AND:
9775       return LowerFixedLengthReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
9776     case ISD::VECREDUCE_OR:
9777       return LowerFixedLengthReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
9778     case ISD::VECREDUCE_SMAX:
9779       return LowerFixedLengthReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
9780     case ISD::VECREDUCE_SMIN:
9781       return LowerFixedLengthReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
9782     case ISD::VECREDUCE_UMAX:
9783       return LowerFixedLengthReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
9784     case ISD::VECREDUCE_UMIN:
9785       return LowerFixedLengthReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
9786     case ISD::VECREDUCE_XOR:
9787       return LowerFixedLengthReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
9788     case ISD::VECREDUCE_FADD:
9789       return LowerFixedLengthReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
9790     case ISD::VECREDUCE_FMAX:
9791       return LowerFixedLengthReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
9792     case ISD::VECREDUCE_FMIN:
9793       return LowerFixedLengthReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
9794     default:
9795       llvm_unreachable("Unhandled fixed length reduction");
9796     }
9797   }
9798 
9799   // Lower NEON reductions.
9800   SDLoc dl(Op);
9801   switch (Op.getOpcode()) {
9802   case ISD::VECREDUCE_ADD:
9803     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9804   case ISD::VECREDUCE_SMAX:
9805     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9806   case ISD::VECREDUCE_SMIN:
9807     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9808   case ISD::VECREDUCE_UMAX:
9809     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9810   case ISD::VECREDUCE_UMIN:
9811     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9812   case ISD::VECREDUCE_FMAX: {
9813     return DAG.getNode(
9814         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9815         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9816         Src);
9817   }
9818   case ISD::VECREDUCE_FMIN: {
9819     return DAG.getNode(
9820         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9821         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9822         Src);
9823   }
9824   default:
9825     llvm_unreachable("Unhandled reduction");
9826   }
9827 }
9828 
9829 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9830                                                     SelectionDAG &DAG) const {
9831   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9832   if (!Subtarget.hasLSE())
9833     return SDValue();
9834 
9835   // LSE has an atomic load-add instruction, but not a load-sub.
9836   SDLoc dl(Op);
9837   MVT VT = Op.getSimpleValueType();
9838   SDValue RHS = Op.getOperand(2);
9839   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9840   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9841   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9842                        Op.getOperand(0), Op.getOperand(1), RHS,
9843                        AN->getMemOperand());
9844 }
9845 
9846 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9847                                                     SelectionDAG &DAG) const {
9848   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9849   if (!Subtarget.hasLSE())
9850     return SDValue();
9851 
9852   // LSE has an atomic load-clear instruction, but not a load-and.
9853   SDLoc dl(Op);
9854   MVT VT = Op.getSimpleValueType();
9855   SDValue RHS = Op.getOperand(2);
9856   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9857   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9858   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9859                        Op.getOperand(0), Op.getOperand(1), RHS,
9860                        AN->getMemOperand());
9861 }
9862 
9863 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9864     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9865   SDLoc dl(Op);
9866   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9867   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9868 
9869   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9870   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9871   if (Subtarget->hasCustomCallingConv())
9872     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9873 
9874   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9875                      DAG.getConstant(4, dl, MVT::i64));
9876   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9877   Chain =
9878       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9879                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9880                   DAG.getRegisterMask(Mask), Chain.getValue(1));
9881   // To match the actual intent better, we should read the output from X15 here
9882   // again (instead of potentially spilling it to the stack), but rereading Size
9883   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9884   // here.
9885 
9886   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9887                      DAG.getConstant(4, dl, MVT::i64));
9888   return Chain;
9889 }
9890 
9891 SDValue
9892 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9893                                                SelectionDAG &DAG) const {
9894   assert(Subtarget->isTargetWindows() &&
9895          "Only Windows alloca probing supported");
9896   SDLoc dl(Op);
9897   // Get the inputs.
9898   SDNode *Node = Op.getNode();
9899   SDValue Chain = Op.getOperand(0);
9900   SDValue Size = Op.getOperand(1);
9901   MaybeAlign Align =
9902       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9903   EVT VT = Node->getValueType(0);
9904 
9905   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9906           "no-stack-arg-probe")) {
9907     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9908     Chain = SP.getValue(1);
9909     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9910     if (Align)
9911       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9912                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9913     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9914     SDValue Ops[2] = {SP, Chain};
9915     return DAG.getMergeValues(Ops, dl);
9916   }
9917 
9918   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9919 
9920   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9921 
9922   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9923   Chain = SP.getValue(1);
9924   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9925   if (Align)
9926     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9927                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9928   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9929 
9930   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9931                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9932 
9933   SDValue Ops[2] = {SP, Chain};
9934   return DAG.getMergeValues(Ops, dl);
9935 }
9936 
9937 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9938                                            SelectionDAG &DAG) const {
9939   EVT VT = Op.getValueType();
9940   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9941 
9942   SDLoc DL(Op);
9943   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9944   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9945                             DL, VT);
9946 }
9947 
9948 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9949 template <unsigned NumVecs>
9950 static bool
9951 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
9952               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
9953   Info.opc = ISD::INTRINSIC_VOID;
9954   // Retrieve EC from first vector argument.
9955   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
9956   ElementCount EC = VT.getVectorElementCount();
9957 #ifndef NDEBUG
9958   // Check the assumption that all input vectors are the same type.
9959   for (unsigned I = 0; I < NumVecs; ++I)
9960     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
9961            "Invalid type.");
9962 #endif
9963   // memVT is `NumVecs * VT`.
9964   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9965                                 EC * NumVecs);
9966   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9967   Info.offset = 0;
9968   Info.align.reset();
9969   Info.flags = MachineMemOperand::MOStore;
9970   return true;
9971 }
9972 
9973 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9974 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9975 /// specified in the intrinsic calls.
9976 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9977                                                const CallInst &I,
9978                                                MachineFunction &MF,
9979                                                unsigned Intrinsic) const {
9980   auto &DL = I.getModule()->getDataLayout();
9981   switch (Intrinsic) {
9982   case Intrinsic::aarch64_sve_st2:
9983     return setInfoSVEStN<2>(*this, DL, Info, I);
9984   case Intrinsic::aarch64_sve_st3:
9985     return setInfoSVEStN<3>(*this, DL, Info, I);
9986   case Intrinsic::aarch64_sve_st4:
9987     return setInfoSVEStN<4>(*this, DL, Info, I);
9988   case Intrinsic::aarch64_neon_ld2:
9989   case Intrinsic::aarch64_neon_ld3:
9990   case Intrinsic::aarch64_neon_ld4:
9991   case Intrinsic::aarch64_neon_ld1x2:
9992   case Intrinsic::aarch64_neon_ld1x3:
9993   case Intrinsic::aarch64_neon_ld1x4:
9994   case Intrinsic::aarch64_neon_ld2lane:
9995   case Intrinsic::aarch64_neon_ld3lane:
9996   case Intrinsic::aarch64_neon_ld4lane:
9997   case Intrinsic::aarch64_neon_ld2r:
9998   case Intrinsic::aarch64_neon_ld3r:
9999   case Intrinsic::aarch64_neon_ld4r: {
10000     Info.opc = ISD::INTRINSIC_W_CHAIN;
10001     // Conservatively set memVT to the entire set of vectors loaded.
10002     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
10003     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10004     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10005     Info.offset = 0;
10006     Info.align.reset();
10007     // volatile loads with NEON intrinsics not supported
10008     Info.flags = MachineMemOperand::MOLoad;
10009     return true;
10010   }
10011   case Intrinsic::aarch64_neon_st2:
10012   case Intrinsic::aarch64_neon_st3:
10013   case Intrinsic::aarch64_neon_st4:
10014   case Intrinsic::aarch64_neon_st1x2:
10015   case Intrinsic::aarch64_neon_st1x3:
10016   case Intrinsic::aarch64_neon_st1x4:
10017   case Intrinsic::aarch64_neon_st2lane:
10018   case Intrinsic::aarch64_neon_st3lane:
10019   case Intrinsic::aarch64_neon_st4lane: {
10020     Info.opc = ISD::INTRINSIC_VOID;
10021     // Conservatively set memVT to the entire set of vectors stored.
10022     unsigned NumElts = 0;
10023     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10024       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10025       if (!ArgTy->isVectorTy())
10026         break;
10027       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
10028     }
10029     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10030     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10031     Info.offset = 0;
10032     Info.align.reset();
10033     // volatile stores with NEON intrinsics not supported
10034     Info.flags = MachineMemOperand::MOStore;
10035     return true;
10036   }
10037   case Intrinsic::aarch64_ldaxr:
10038   case Intrinsic::aarch64_ldxr: {
10039     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10040     Info.opc = ISD::INTRINSIC_W_CHAIN;
10041     Info.memVT = MVT::getVT(PtrTy->getElementType());
10042     Info.ptrVal = I.getArgOperand(0);
10043     Info.offset = 0;
10044     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10045     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10046     return true;
10047   }
10048   case Intrinsic::aarch64_stlxr:
10049   case Intrinsic::aarch64_stxr: {
10050     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10051     Info.opc = ISD::INTRINSIC_W_CHAIN;
10052     Info.memVT = MVT::getVT(PtrTy->getElementType());
10053     Info.ptrVal = I.getArgOperand(1);
10054     Info.offset = 0;
10055     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10056     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10057     return true;
10058   }
10059   case Intrinsic::aarch64_ldaxp:
10060   case Intrinsic::aarch64_ldxp:
10061     Info.opc = ISD::INTRINSIC_W_CHAIN;
10062     Info.memVT = MVT::i128;
10063     Info.ptrVal = I.getArgOperand(0);
10064     Info.offset = 0;
10065     Info.align = Align(16);
10066     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10067     return true;
10068   case Intrinsic::aarch64_stlxp:
10069   case Intrinsic::aarch64_stxp:
10070     Info.opc = ISD::INTRINSIC_W_CHAIN;
10071     Info.memVT = MVT::i128;
10072     Info.ptrVal = I.getArgOperand(2);
10073     Info.offset = 0;
10074     Info.align = Align(16);
10075     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10076     return true;
10077   case Intrinsic::aarch64_sve_ldnt1: {
10078     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10079     Info.opc = ISD::INTRINSIC_W_CHAIN;
10080     Info.memVT = MVT::getVT(I.getType());
10081     Info.ptrVal = I.getArgOperand(1);
10082     Info.offset = 0;
10083     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10084     Info.flags = MachineMemOperand::MOLoad;
10085     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
10086       Info.flags |= MachineMemOperand::MONonTemporal;
10087     return true;
10088   }
10089   case Intrinsic::aarch64_sve_stnt1: {
10090     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
10091     Info.opc = ISD::INTRINSIC_W_CHAIN;
10092     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
10093     Info.ptrVal = I.getArgOperand(2);
10094     Info.offset = 0;
10095     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10096     Info.flags = MachineMemOperand::MOStore;
10097     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
10098       Info.flags |= MachineMemOperand::MONonTemporal;
10099     return true;
10100   }
10101   default:
10102     break;
10103   }
10104 
10105   return false;
10106 }
10107 
10108 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
10109                                                   ISD::LoadExtType ExtTy,
10110                                                   EVT NewVT) const {
10111   // TODO: This may be worth removing. Check regression tests for diffs.
10112   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
10113     return false;
10114 
10115   // If we're reducing the load width in order to avoid having to use an extra
10116   // instruction to do extension then it's probably a good idea.
10117   if (ExtTy != ISD::NON_EXTLOAD)
10118     return true;
10119   // Don't reduce load width if it would prevent us from combining a shift into
10120   // the offset.
10121   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
10122   assert(Mem);
10123   const SDValue &Base = Mem->getBasePtr();
10124   if (Base.getOpcode() == ISD::ADD &&
10125       Base.getOperand(1).getOpcode() == ISD::SHL &&
10126       Base.getOperand(1).hasOneUse() &&
10127       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
10128     // The shift can be combined if it matches the size of the value being
10129     // loaded (and so reducing the width would make it not match).
10130     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
10131     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
10132     if (ShiftAmount == Log2_32(LoadBytes))
10133       return false;
10134   }
10135   // We have no reason to disallow reducing the load width, so allow it.
10136   return true;
10137 }
10138 
10139 // Truncations from 64-bit GPR to 32-bit GPR is free.
10140 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10141   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10142     return false;
10143   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
10144   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
10145   return NumBits1 > NumBits2;
10146 }
10147 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10148   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10149     return false;
10150   uint64_t NumBits1 = VT1.getFixedSizeInBits();
10151   uint64_t NumBits2 = VT2.getFixedSizeInBits();
10152   return NumBits1 > NumBits2;
10153 }
10154 
10155 /// Check if it is profitable to hoist instruction in then/else to if.
10156 /// Not profitable if I and it's user can form a FMA instruction
10157 /// because we prefer FMSUB/FMADD.
10158 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
10159   if (I->getOpcode() != Instruction::FMul)
10160     return true;
10161 
10162   if (!I->hasOneUse())
10163     return true;
10164 
10165   Instruction *User = I->user_back();
10166 
10167   if (User &&
10168       !(User->getOpcode() == Instruction::FSub ||
10169         User->getOpcode() == Instruction::FAdd))
10170     return true;
10171 
10172   const TargetOptions &Options = getTargetMachine().Options;
10173   const Function *F = I->getFunction();
10174   const DataLayout &DL = F->getParent()->getDataLayout();
10175   Type *Ty = User->getOperand(0)->getType();
10176 
10177   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
10178            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
10179            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
10180             Options.UnsafeFPMath));
10181 }
10182 
10183 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
10184 // 64-bit GPR.
10185 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10186   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10187     return false;
10188   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10189   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10190   return NumBits1 == 32 && NumBits2 == 64;
10191 }
10192 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10193   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10194     return false;
10195   unsigned NumBits1 = VT1.getSizeInBits();
10196   unsigned NumBits2 = VT2.getSizeInBits();
10197   return NumBits1 == 32 && NumBits2 == 64;
10198 }
10199 
10200 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10201   EVT VT1 = Val.getValueType();
10202   if (isZExtFree(VT1, VT2)) {
10203     return true;
10204   }
10205 
10206   if (Val.getOpcode() != ISD::LOAD)
10207     return false;
10208 
10209   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
10210   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
10211           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
10212           VT1.getSizeInBits() <= 32);
10213 }
10214 
10215 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
10216   if (isa<FPExtInst>(Ext))
10217     return false;
10218 
10219   // Vector types are not free.
10220   if (Ext->getType()->isVectorTy())
10221     return false;
10222 
10223   for (const Use &U : Ext->uses()) {
10224     // The extension is free if we can fold it with a left shift in an
10225     // addressing mode or an arithmetic operation: add, sub, and cmp.
10226 
10227     // Is there a shift?
10228     const Instruction *Instr = cast<Instruction>(U.getUser());
10229 
10230     // Is this a constant shift?
10231     switch (Instr->getOpcode()) {
10232     case Instruction::Shl:
10233       if (!isa<ConstantInt>(Instr->getOperand(1)))
10234         return false;
10235       break;
10236     case Instruction::GetElementPtr: {
10237       gep_type_iterator GTI = gep_type_begin(Instr);
10238       auto &DL = Ext->getModule()->getDataLayout();
10239       std::advance(GTI, U.getOperandNo()-1);
10240       Type *IdxTy = GTI.getIndexedType();
10241       // This extension will end up with a shift because of the scaling factor.
10242       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
10243       // Get the shift amount based on the scaling factor:
10244       // log2(sizeof(IdxTy)) - log2(8).
10245       uint64_t ShiftAmt =
10246         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
10247       // Is the constant foldable in the shift of the addressing mode?
10248       // I.e., shift amount is between 1 and 4 inclusive.
10249       if (ShiftAmt == 0 || ShiftAmt > 4)
10250         return false;
10251       break;
10252     }
10253     case Instruction::Trunc:
10254       // Check if this is a noop.
10255       // trunc(sext ty1 to ty2) to ty1.
10256       if (Instr->getType() == Ext->getOperand(0)->getType())
10257         continue;
10258       LLVM_FALLTHROUGH;
10259     default:
10260       return false;
10261     }
10262 
10263     // At this point we can use the bfm family, so this extension is free
10264     // for that use.
10265   }
10266   return true;
10267 }
10268 
10269 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
10270 /// or upper half of the vector elements.
10271 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
10272   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
10273     auto *FullTy = FullV->getType();
10274     auto *HalfTy = HalfV->getType();
10275     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
10276            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
10277   };
10278 
10279   auto extractHalf = [](Value *FullV, Value *HalfV) {
10280     auto *FullVT = cast<FixedVectorType>(FullV->getType());
10281     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
10282     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
10283   };
10284 
10285   ArrayRef<int> M1, M2;
10286   Value *S1Op1, *S2Op1;
10287   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
10288       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
10289     return false;
10290 
10291   // Check that the operands are half as wide as the result and we extract
10292   // half of the elements of the input vectors.
10293   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
10294       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
10295     return false;
10296 
10297   // Check the mask extracts either the lower or upper half of vector
10298   // elements.
10299   int M1Start = -1;
10300   int M2Start = -1;
10301   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
10302   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
10303       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
10304       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
10305     return false;
10306 
10307   return true;
10308 }
10309 
10310 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
10311 /// of the vector elements.
10312 static bool areExtractExts(Value *Ext1, Value *Ext2) {
10313   auto areExtDoubled = [](Instruction *Ext) {
10314     return Ext->getType()->getScalarSizeInBits() ==
10315            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
10316   };
10317 
10318   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
10319       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
10320       !areExtDoubled(cast<Instruction>(Ext1)) ||
10321       !areExtDoubled(cast<Instruction>(Ext2)))
10322     return false;
10323 
10324   return true;
10325 }
10326 
10327 /// Check if Op could be used with vmull_high_p64 intrinsic.
10328 static bool isOperandOfVmullHighP64(Value *Op) {
10329   Value *VectorOperand = nullptr;
10330   ConstantInt *ElementIndex = nullptr;
10331   return match(Op, m_ExtractElt(m_Value(VectorOperand),
10332                                 m_ConstantInt(ElementIndex))) &&
10333          ElementIndex->getValue() == 1 &&
10334          isa<FixedVectorType>(VectorOperand->getType()) &&
10335          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
10336 }
10337 
10338 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
10339 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
10340   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
10341 }
10342 
10343 /// Check if sinking \p I's operands to I's basic block is profitable, because
10344 /// the operands can be folded into a target instruction, e.g.
10345 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
10346 bool AArch64TargetLowering::shouldSinkOperands(
10347     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
10348   if (!I->getType()->isVectorTy())
10349     return false;
10350 
10351   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
10352     switch (II->getIntrinsicID()) {
10353     case Intrinsic::aarch64_neon_umull:
10354       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
10355         return false;
10356       Ops.push_back(&II->getOperandUse(0));
10357       Ops.push_back(&II->getOperandUse(1));
10358       return true;
10359 
10360     case Intrinsic::aarch64_neon_pmull64:
10361       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
10362                                      II->getArgOperand(1)))
10363         return false;
10364       Ops.push_back(&II->getArgOperandUse(0));
10365       Ops.push_back(&II->getArgOperandUse(1));
10366       return true;
10367 
10368     default:
10369       return false;
10370     }
10371   }
10372 
10373   switch (I->getOpcode()) {
10374   case Instruction::Sub:
10375   case Instruction::Add: {
10376     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
10377       return false;
10378 
10379     // If the exts' operands extract either the lower or upper elements, we
10380     // can sink them too.
10381     auto Ext1 = cast<Instruction>(I->getOperand(0));
10382     auto Ext2 = cast<Instruction>(I->getOperand(1));
10383     if (areExtractShuffleVectors(Ext1, Ext2)) {
10384       Ops.push_back(&Ext1->getOperandUse(0));
10385       Ops.push_back(&Ext2->getOperandUse(0));
10386     }
10387 
10388     Ops.push_back(&I->getOperandUse(0));
10389     Ops.push_back(&I->getOperandUse(1));
10390 
10391     return true;
10392   }
10393   default:
10394     return false;
10395   }
10396   return false;
10397 }
10398 
10399 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
10400                                           Align &RequiredAligment) const {
10401   if (!LoadedType.isSimple() ||
10402       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
10403     return false;
10404   // Cyclone supports unaligned accesses.
10405   RequiredAligment = Align(1);
10406   unsigned NumBits = LoadedType.getSizeInBits();
10407   return NumBits == 32 || NumBits == 64;
10408 }
10409 
10410 /// A helper function for determining the number of interleaved accesses we
10411 /// will generate when lowering accesses of the given type.
10412 unsigned
10413 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
10414                                                  const DataLayout &DL) const {
10415   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
10416 }
10417 
10418 MachineMemOperand::Flags
10419 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
10420   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
10421       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
10422     return MOStridedAccess;
10423   return MachineMemOperand::MONone;
10424 }
10425 
10426 bool AArch64TargetLowering::isLegalInterleavedAccessType(
10427     VectorType *VecTy, const DataLayout &DL) const {
10428 
10429   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
10430   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
10431 
10432   // Ensure the number of vector elements is greater than 1.
10433   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
10434     return false;
10435 
10436   // Ensure the element type is legal.
10437   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
10438     return false;
10439 
10440   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
10441   // 128 will be split into multiple interleaved accesses.
10442   return VecSize == 64 || VecSize % 128 == 0;
10443 }
10444 
10445 /// Lower an interleaved load into a ldN intrinsic.
10446 ///
10447 /// E.g. Lower an interleaved load (Factor = 2):
10448 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
10449 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
10450 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
10451 ///
10452 ///      Into:
10453 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
10454 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
10455 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
10456 bool AArch64TargetLowering::lowerInterleavedLoad(
10457     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
10458     ArrayRef<unsigned> Indices, unsigned Factor) const {
10459   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10460          "Invalid interleave factor");
10461   assert(!Shuffles.empty() && "Empty shufflevector input");
10462   assert(Shuffles.size() == Indices.size() &&
10463          "Unmatched number of shufflevectors and indices");
10464 
10465   const DataLayout &DL = LI->getModule()->getDataLayout();
10466 
10467   VectorType *VTy = Shuffles[0]->getType();
10468 
10469   // Skip if we do not have NEON and skip illegal vector types. We can
10470   // "legalize" wide vector types into multiple interleaved accesses as long as
10471   // the vector types are divisible by 128.
10472   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
10473     return false;
10474 
10475   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
10476 
10477   auto *FVTy = cast<FixedVectorType>(VTy);
10478 
10479   // A pointer vector can not be the return type of the ldN intrinsics. Need to
10480   // load integer vectors first and then convert to pointer vectors.
10481   Type *EltTy = FVTy->getElementType();
10482   if (EltTy->isPointerTy())
10483     FVTy =
10484         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
10485 
10486   IRBuilder<> Builder(LI);
10487 
10488   // The base address of the load.
10489   Value *BaseAddr = LI->getPointerOperand();
10490 
10491   if (NumLoads > 1) {
10492     // If we're going to generate more than one load, reset the sub-vector type
10493     // to something legal.
10494     FVTy = FixedVectorType::get(FVTy->getElementType(),
10495                                 FVTy->getNumElements() / NumLoads);
10496 
10497     // We will compute the pointer operand of each load from the original base
10498     // address using GEPs. Cast the base address to a pointer to the scalar
10499     // element type.
10500     BaseAddr = Builder.CreateBitCast(
10501         BaseAddr,
10502         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
10503   }
10504 
10505   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
10506   Type *Tys[2] = {FVTy, PtrTy};
10507   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
10508                                             Intrinsic::aarch64_neon_ld3,
10509                                             Intrinsic::aarch64_neon_ld4};
10510   Function *LdNFunc =
10511       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
10512 
10513   // Holds sub-vectors extracted from the load intrinsic return values. The
10514   // sub-vectors are associated with the shufflevector instructions they will
10515   // replace.
10516   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
10517 
10518   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
10519 
10520     // If we're generating more than one load, compute the base address of
10521     // subsequent loads as an offset from the previous.
10522     if (LoadCount > 0)
10523       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
10524                                             FVTy->getNumElements() * Factor);
10525 
10526     CallInst *LdN = Builder.CreateCall(
10527         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
10528 
10529     // Extract and store the sub-vectors returned by the load intrinsic.
10530     for (unsigned i = 0; i < Shuffles.size(); i++) {
10531       ShuffleVectorInst *SVI = Shuffles[i];
10532       unsigned Index = Indices[i];
10533 
10534       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
10535 
10536       // Convert the integer vector to pointer vector if the element is pointer.
10537       if (EltTy->isPointerTy())
10538         SubVec = Builder.CreateIntToPtr(
10539             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
10540                                          FVTy->getNumElements()));
10541       SubVecs[SVI].push_back(SubVec);
10542     }
10543   }
10544 
10545   // Replace uses of the shufflevector instructions with the sub-vectors
10546   // returned by the load intrinsic. If a shufflevector instruction is
10547   // associated with more than one sub-vector, those sub-vectors will be
10548   // concatenated into a single wide vector.
10549   for (ShuffleVectorInst *SVI : Shuffles) {
10550     auto &SubVec = SubVecs[SVI];
10551     auto *WideVec =
10552         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
10553     SVI->replaceAllUsesWith(WideVec);
10554   }
10555 
10556   return true;
10557 }
10558 
10559 /// Lower an interleaved store into a stN intrinsic.
10560 ///
10561 /// E.g. Lower an interleaved store (Factor = 3):
10562 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
10563 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
10564 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10565 ///
10566 ///      Into:
10567 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
10568 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
10569 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
10570 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10571 ///
10572 /// Note that the new shufflevectors will be removed and we'll only generate one
10573 /// st3 instruction in CodeGen.
10574 ///
10575 /// Example for a more general valid mask (Factor 3). Lower:
10576 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
10577 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
10578 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10579 ///
10580 ///      Into:
10581 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
10582 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
10583 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
10584 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10585 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
10586                                                   ShuffleVectorInst *SVI,
10587                                                   unsigned Factor) const {
10588   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10589          "Invalid interleave factor");
10590 
10591   auto *VecTy = cast<FixedVectorType>(SVI->getType());
10592   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
10593 
10594   unsigned LaneLen = VecTy->getNumElements() / Factor;
10595   Type *EltTy = VecTy->getElementType();
10596   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
10597 
10598   const DataLayout &DL = SI->getModule()->getDataLayout();
10599 
10600   // Skip if we do not have NEON and skip illegal vector types. We can
10601   // "legalize" wide vector types into multiple interleaved accesses as long as
10602   // the vector types are divisible by 128.
10603   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
10604     return false;
10605 
10606   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
10607 
10608   Value *Op0 = SVI->getOperand(0);
10609   Value *Op1 = SVI->getOperand(1);
10610   IRBuilder<> Builder(SI);
10611 
10612   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
10613   // vectors to integer vectors.
10614   if (EltTy->isPointerTy()) {
10615     Type *IntTy = DL.getIntPtrType(EltTy);
10616     unsigned NumOpElts =
10617         cast<FixedVectorType>(Op0->getType())->getNumElements();
10618 
10619     // Convert to the corresponding integer vector.
10620     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
10621     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
10622     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
10623 
10624     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
10625   }
10626 
10627   // The base address of the store.
10628   Value *BaseAddr = SI->getPointerOperand();
10629 
10630   if (NumStores > 1) {
10631     // If we're going to generate more than one store, reset the lane length
10632     // and sub-vector type to something legal.
10633     LaneLen /= NumStores;
10634     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10635 
10636     // We will compute the pointer operand of each store from the original base
10637     // address using GEPs. Cast the base address to a pointer to the scalar
10638     // element type.
10639     BaseAddr = Builder.CreateBitCast(
10640         BaseAddr,
10641         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10642   }
10643 
10644   auto Mask = SVI->getShuffleMask();
10645 
10646   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10647   Type *Tys[2] = {SubVecTy, PtrTy};
10648   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10649                                              Intrinsic::aarch64_neon_st3,
10650                                              Intrinsic::aarch64_neon_st4};
10651   Function *StNFunc =
10652       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10653 
10654   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10655 
10656     SmallVector<Value *, 5> Ops;
10657 
10658     // Split the shufflevector operands into sub vectors for the new stN call.
10659     for (unsigned i = 0; i < Factor; i++) {
10660       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10661       if (Mask[IdxI] >= 0) {
10662         Ops.push_back(Builder.CreateShuffleVector(
10663             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10664       } else {
10665         unsigned StartMask = 0;
10666         for (unsigned j = 1; j < LaneLen; j++) {
10667           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10668           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10669             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10670             break;
10671           }
10672         }
10673         // Note: Filling undef gaps with random elements is ok, since
10674         // those elements were being written anyway (with undefs).
10675         // In the case of all undefs we're defaulting to using elems from 0
10676         // Note: StartMask cannot be negative, it's checked in
10677         // isReInterleaveMask
10678         Ops.push_back(Builder.CreateShuffleVector(
10679             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10680       }
10681     }
10682 
10683     // If we generating more than one store, we compute the base address of
10684     // subsequent stores as an offset from the previous.
10685     if (StoreCount > 0)
10686       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10687                                             BaseAddr, LaneLen * Factor);
10688 
10689     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10690     Builder.CreateCall(StNFunc, Ops);
10691   }
10692   return true;
10693 }
10694 
10695 // Lower an SVE structured load intrinsic returning a tuple type to target
10696 // specific intrinsic taking the same input but returning a multi-result value
10697 // of the split tuple type.
10698 //
10699 // E.g. Lowering an LD3:
10700 //
10701 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10702 //                                                    <vscale x 4 x i1> %pred,
10703 //                                                    <vscale x 4 x i32>* %addr)
10704 //
10705 //  Output DAG:
10706 //
10707 //    t0: ch = EntryToken
10708 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10709 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10710 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10711 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10712 //
10713 // This is called pre-legalization to avoid widening/splitting issues with
10714 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10715 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10716                                                   ArrayRef<SDValue> LoadOps,
10717                                                   EVT VT, SelectionDAG &DAG,
10718                                                   const SDLoc &DL) const {
10719   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10720 
10721   unsigned N, Opcode;
10722   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10723       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10724       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10725       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10726 
10727   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10728   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
10729          "invalid tuple vector type!");
10730 
10731   EVT SplitVT =
10732       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10733                        VT.getVectorElementCount().divideCoefficientBy(N));
10734   assert(isTypeLegal(SplitVT));
10735 
10736   SmallVector<EVT, 5> VTs(N, SplitVT);
10737   VTs.push_back(MVT::Other); // Chain
10738   SDVTList NodeTys = DAG.getVTList(VTs);
10739 
10740   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10741   SmallVector<SDValue, 4> PseudoLoadOps;
10742   for (unsigned I = 0; I < N; ++I)
10743     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10744   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10745 }
10746 
10747 EVT AArch64TargetLowering::getOptimalMemOpType(
10748     const MemOp &Op, const AttributeList &FuncAttributes) const {
10749   bool CanImplicitFloat =
10750       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10751   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10752   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10753   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10754   // taken one instruction to materialize the v2i64 zero and one store (with
10755   // restrictive addressing mode). Just do i64 stores.
10756   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10757   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10758     if (Op.isAligned(AlignCheck))
10759       return true;
10760     bool Fast;
10761     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10762                                           &Fast) &&
10763            Fast;
10764   };
10765 
10766   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10767       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10768     return MVT::v2i64;
10769   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10770     return MVT::f128;
10771   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10772     return MVT::i64;
10773   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10774     return MVT::i32;
10775   return MVT::Other;
10776 }
10777 
10778 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10779     const MemOp &Op, const AttributeList &FuncAttributes) const {
10780   bool CanImplicitFloat =
10781       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10782   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10783   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10784   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10785   // taken one instruction to materialize the v2i64 zero and one store (with
10786   // restrictive addressing mode). Just do i64 stores.
10787   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10788   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10789     if (Op.isAligned(AlignCheck))
10790       return true;
10791     bool Fast;
10792     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10793                                           &Fast) &&
10794            Fast;
10795   };
10796 
10797   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10798       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10799     return LLT::vector(2, 64);
10800   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10801     return LLT::scalar(128);
10802   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10803     return LLT::scalar(64);
10804   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10805     return LLT::scalar(32);
10806   return LLT();
10807 }
10808 
10809 // 12-bit optionally shifted immediates are legal for adds.
10810 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10811   if (Immed == std::numeric_limits<int64_t>::min()) {
10812     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10813                       << ": avoid UB for INT64_MIN\n");
10814     return false;
10815   }
10816   // Same encoding for add/sub, just flip the sign.
10817   Immed = std::abs(Immed);
10818   bool IsLegal = ((Immed >> 12) == 0 ||
10819                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10820   LLVM_DEBUG(dbgs() << "Is " << Immed
10821                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10822   return IsLegal;
10823 }
10824 
10825 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10826 // immediates is the same as for an add or a sub.
10827 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10828   return isLegalAddImmediate(Immed);
10829 }
10830 
10831 /// isLegalAddressingMode - Return true if the addressing mode represented
10832 /// by AM is legal for this target, for a load/store of the specified type.
10833 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10834                                                   const AddrMode &AM, Type *Ty,
10835                                                   unsigned AS, Instruction *I) const {
10836   // AArch64 has five basic addressing modes:
10837   //  reg
10838   //  reg + 9-bit signed offset
10839   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
10840   //  reg1 + reg2
10841   //  reg + SIZE_IN_BYTES * reg
10842 
10843   // No global is ever allowed as a base.
10844   if (AM.BaseGV)
10845     return false;
10846 
10847   // No reg+reg+imm addressing.
10848   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10849     return false;
10850 
10851   // FIXME: Update this method to support scalable addressing modes.
10852   if (isa<ScalableVectorType>(Ty))
10853     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10854 
10855   // check reg + imm case:
10856   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10857   uint64_t NumBytes = 0;
10858   if (Ty->isSized()) {
10859     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10860     NumBytes = NumBits / 8;
10861     if (!isPowerOf2_64(NumBits))
10862       NumBytes = 0;
10863   }
10864 
10865   if (!AM.Scale) {
10866     int64_t Offset = AM.BaseOffs;
10867 
10868     // 9-bit signed offset
10869     if (isInt<9>(Offset))
10870       return true;
10871 
10872     // 12-bit unsigned offset
10873     unsigned shift = Log2_64(NumBytes);
10874     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10875         // Must be a multiple of NumBytes (NumBytes is a power of 2)
10876         (Offset >> shift) << shift == Offset)
10877       return true;
10878     return false;
10879   }
10880 
10881   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10882 
10883   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10884 }
10885 
10886 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10887   // Consider splitting large offset of struct or array.
10888   return true;
10889 }
10890 
10891 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10892                                                 const AddrMode &AM, Type *Ty,
10893                                                 unsigned AS) const {
10894   // Scaling factors are not free at all.
10895   // Operands                     | Rt Latency
10896   // -------------------------------------------
10897   // Rt, [Xn, Xm]                 | 4
10898   // -------------------------------------------
10899   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
10900   // Rt, [Xn, Wm, <extend> #imm]  |
10901   if (isLegalAddressingMode(DL, AM, Ty, AS))
10902     // Scale represents reg2 * scale, thus account for 1 if
10903     // it is not equal to 0 or 1.
10904     return AM.Scale != 0 && AM.Scale != 1;
10905   return -1;
10906 }
10907 
10908 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10909     const MachineFunction &MF, EVT VT) const {
10910   VT = VT.getScalarType();
10911 
10912   if (!VT.isSimple())
10913     return false;
10914 
10915   switch (VT.getSimpleVT().SimpleTy) {
10916   case MVT::f32:
10917   case MVT::f64:
10918     return true;
10919   default:
10920     break;
10921   }
10922 
10923   return false;
10924 }
10925 
10926 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10927                                                        Type *Ty) const {
10928   switch (Ty->getScalarType()->getTypeID()) {
10929   case Type::FloatTyID:
10930   case Type::DoubleTyID:
10931     return true;
10932   default:
10933     return false;
10934   }
10935 }
10936 
10937 const MCPhysReg *
10938 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10939   // LR is a callee-save register, but we must treat it as clobbered by any call
10940   // site. Hence we include LR in the scratch registers, which are in turn added
10941   // as implicit-defs for stackmaps and patchpoints.
10942   static const MCPhysReg ScratchRegs[] = {
10943     AArch64::X16, AArch64::X17, AArch64::LR, 0
10944   };
10945   return ScratchRegs;
10946 }
10947 
10948 bool
10949 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10950                                                      CombineLevel Level) const {
10951   N = N->getOperand(0).getNode();
10952   EVT VT = N->getValueType(0);
10953     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10954     // it with shift to let it be lowered to UBFX.
10955   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10956       isa<ConstantSDNode>(N->getOperand(1))) {
10957     uint64_t TruncMask = N->getConstantOperandVal(1);
10958     if (isMask_64(TruncMask) &&
10959       N->getOperand(0).getOpcode() == ISD::SRL &&
10960       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10961       return false;
10962   }
10963   return true;
10964 }
10965 
10966 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10967                                                               Type *Ty) const {
10968   assert(Ty->isIntegerTy());
10969 
10970   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10971   if (BitSize == 0)
10972     return false;
10973 
10974   int64_t Val = Imm.getSExtValue();
10975   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10976     return true;
10977 
10978   if ((int64_t)Val < 0)
10979     Val = ~Val;
10980   if (BitSize == 32)
10981     Val &= (1LL << 32) - 1;
10982 
10983   unsigned LZ = countLeadingZeros((uint64_t)Val);
10984   unsigned Shift = (63 - LZ) / 16;
10985   // MOVZ is free so return true for one or fewer MOVK.
10986   return Shift < 3;
10987 }
10988 
10989 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10990                                                     unsigned Index) const {
10991   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10992     return false;
10993 
10994   return (Index == 0 || Index == ResVT.getVectorNumElements());
10995 }
10996 
10997 /// Turn vector tests of the signbit in the form of:
10998 ///   xor (sra X, elt_size(X)-1), -1
10999 /// into:
11000 ///   cmge X, X, #0
11001 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
11002                                          const AArch64Subtarget *Subtarget) {
11003   EVT VT = N->getValueType(0);
11004   if (!Subtarget->hasNEON() || !VT.isVector())
11005     return SDValue();
11006 
11007   // There must be a shift right algebraic before the xor, and the xor must be a
11008   // 'not' operation.
11009   SDValue Shift = N->getOperand(0);
11010   SDValue Ones = N->getOperand(1);
11011   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
11012       !ISD::isBuildVectorAllOnes(Ones.getNode()))
11013     return SDValue();
11014 
11015   // The shift should be smearing the sign bit across each vector element.
11016   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
11017   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
11018   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
11019     return SDValue();
11020 
11021   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
11022 }
11023 
11024 // Generate SUBS and CSEL for integer abs.
11025 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
11026   EVT VT = N->getValueType(0);
11027 
11028   SDValue N0 = N->getOperand(0);
11029   SDValue N1 = N->getOperand(1);
11030   SDLoc DL(N);
11031 
11032   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
11033   // and change it to SUB and CSEL.
11034   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
11035       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
11036       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
11037     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
11038       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
11039         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
11040                                   N0.getOperand(0));
11041         // Generate SUBS & CSEL.
11042         SDValue Cmp =
11043             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
11044                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
11045         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
11046                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
11047                            SDValue(Cmp.getNode(), 1));
11048       }
11049   return SDValue();
11050 }
11051 
11052 // VECREDUCE_ADD( EXTEND(v16i8_type) ) to
11053 // VECREDUCE_ADD( DOTv16i8(v16i8_type) )
11054 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
11055                                           const AArch64Subtarget *ST) {
11056   SDValue Op0 = N->getOperand(0);
11057   if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32)
11058     return SDValue();
11059 
11060   if (Op0.getValueType().getVectorElementType() != MVT::i32)
11061     return SDValue();
11062 
11063   unsigned ExtOpcode = Op0.getOpcode();
11064   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
11065     return SDValue();
11066 
11067   EVT Op0VT = Op0.getOperand(0).getValueType();
11068   if (Op0VT != MVT::v16i8)
11069     return SDValue();
11070 
11071   SDLoc DL(Op0);
11072   SDValue Ones = DAG.getConstant(1, DL, Op0VT);
11073   SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
11074   auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND)
11075                          ? Intrinsic::aarch64_neon_udot
11076                          : Intrinsic::aarch64_neon_sdot;
11077   SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(),
11078                             DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros,
11079                             Ones, Op0.getOperand(0));
11080   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
11081 }
11082 
11083 // Given a ABS node, detect the following pattern:
11084 // (ABS (SUB (EXTEND a), (EXTEND b))).
11085 // Generates UABD/SABD instruction.
11086 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG,
11087                                  TargetLowering::DAGCombinerInfo &DCI,
11088                                  const AArch64Subtarget *Subtarget) {
11089   SDValue AbsOp1 = N->getOperand(0);
11090   SDValue Op0, Op1;
11091 
11092   if (AbsOp1.getOpcode() != ISD::SUB)
11093     return SDValue();
11094 
11095   Op0 = AbsOp1.getOperand(0);
11096   Op1 = AbsOp1.getOperand(1);
11097 
11098   unsigned Opc0 = Op0.getOpcode();
11099   // Check if the operands of the sub are (zero|sign)-extended.
11100   if (Opc0 != Op1.getOpcode() ||
11101       (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
11102     return SDValue();
11103 
11104   EVT VectorT1 = Op0.getOperand(0).getValueType();
11105   EVT VectorT2 = Op1.getOperand(0).getValueType();
11106   // Check if vectors are of same type and valid size.
11107   uint64_t Size = VectorT1.getFixedSizeInBits();
11108   if (VectorT1 != VectorT2 || (Size != 64 && Size != 128))
11109     return SDValue();
11110 
11111   // Check if vector element types are valid.
11112   EVT VT1 = VectorT1.getVectorElementType();
11113   if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32)
11114     return SDValue();
11115 
11116   Op0 = Op0.getOperand(0);
11117   Op1 = Op1.getOperand(0);
11118   unsigned ABDOpcode =
11119       (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD;
11120   SDValue ABD =
11121       DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
11122   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
11123 }
11124 
11125 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
11126                                  TargetLowering::DAGCombinerInfo &DCI,
11127                                  const AArch64Subtarget *Subtarget) {
11128   if (DCI.isBeforeLegalizeOps())
11129     return SDValue();
11130 
11131   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
11132     return Cmp;
11133 
11134   return performIntegerAbsCombine(N, DAG);
11135 }
11136 
11137 SDValue
11138 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11139                                      SelectionDAG &DAG,
11140                                      SmallVectorImpl<SDNode *> &Created) const {
11141   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11142   if (isIntDivCheap(N->getValueType(0), Attr))
11143     return SDValue(N,0); // Lower SDIV as SDIV
11144 
11145   // fold (sdiv X, pow2)
11146   EVT VT = N->getValueType(0);
11147   if ((VT != MVT::i32 && VT != MVT::i64) ||
11148       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11149     return SDValue();
11150 
11151   SDLoc DL(N);
11152   SDValue N0 = N->getOperand(0);
11153   unsigned Lg2 = Divisor.countTrailingZeros();
11154   SDValue Zero = DAG.getConstant(0, DL, VT);
11155   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11156 
11157   // Add (N0 < 0) ? Pow2 - 1 : 0;
11158   SDValue CCVal;
11159   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
11160   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11161   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
11162 
11163   Created.push_back(Cmp.getNode());
11164   Created.push_back(Add.getNode());
11165   Created.push_back(CSel.getNode());
11166 
11167   // Divide by pow2.
11168   SDValue SRA =
11169       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
11170 
11171   // If we're dividing by a positive value, we're done.  Otherwise, we must
11172   // negate the result.
11173   if (Divisor.isNonNegative())
11174     return SRA;
11175 
11176   Created.push_back(SRA.getNode());
11177   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11178 }
11179 
11180 static bool IsSVECntIntrinsic(SDValue S) {
11181   switch(getIntrinsicID(S.getNode())) {
11182   default:
11183     break;
11184   case Intrinsic::aarch64_sve_cntb:
11185   case Intrinsic::aarch64_sve_cnth:
11186   case Intrinsic::aarch64_sve_cntw:
11187   case Intrinsic::aarch64_sve_cntd:
11188     return true;
11189   }
11190   return false;
11191 }
11192 
11193 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
11194                                  TargetLowering::DAGCombinerInfo &DCI,
11195                                  const AArch64Subtarget *Subtarget) {
11196   if (DCI.isBeforeLegalizeOps())
11197     return SDValue();
11198 
11199   // The below optimizations require a constant RHS.
11200   if (!isa<ConstantSDNode>(N->getOperand(1)))
11201     return SDValue();
11202 
11203   SDValue N0 = N->getOperand(0);
11204   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
11205   const APInt &ConstValue = C->getAPIntValue();
11206 
11207   // Allow the scaling to be folded into the `cnt` instruction by preventing
11208   // the scaling to be obscured here. This makes it easier to pattern match.
11209   if (IsSVECntIntrinsic(N0) ||
11210      (N0->getOpcode() == ISD::TRUNCATE &&
11211       (IsSVECntIntrinsic(N0->getOperand(0)))))
11212        if (ConstValue.sge(1) && ConstValue.sle(16))
11213          return SDValue();
11214 
11215   // Multiplication of a power of two plus/minus one can be done more
11216   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
11217   // future CPUs have a cheaper MADD instruction, this may need to be
11218   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
11219   // 64-bit is 5 cycles, so this is always a win.
11220   // More aggressively, some multiplications N0 * C can be lowered to
11221   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
11222   // e.g. 6=3*2=(2+1)*2.
11223   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
11224   // which equals to (1+2)*16-(1+2).
11225   // TrailingZeroes is used to test if the mul can be lowered to
11226   // shift+add+shift.
11227   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
11228   if (TrailingZeroes) {
11229     // Conservatively do not lower to shift+add+shift if the mul might be
11230     // folded into smul or umul.
11231     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
11232                             isZeroExtended(N0.getNode(), DAG)))
11233       return SDValue();
11234     // Conservatively do not lower to shift+add+shift if the mul might be
11235     // folded into madd or msub.
11236     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
11237                            N->use_begin()->getOpcode() == ISD::SUB))
11238       return SDValue();
11239   }
11240   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
11241   // and shift+add+shift.
11242   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
11243 
11244   unsigned ShiftAmt, AddSubOpc;
11245   // Is the shifted value the LHS operand of the add/sub?
11246   bool ShiftValUseIsN0 = true;
11247   // Do we need to negate the result?
11248   bool NegateResult = false;
11249 
11250   if (ConstValue.isNonNegative()) {
11251     // (mul x, 2^N + 1) => (add (shl x, N), x)
11252     // (mul x, 2^N - 1) => (sub (shl x, N), x)
11253     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
11254     APInt SCVMinus1 = ShiftedConstValue - 1;
11255     APInt CVPlus1 = ConstValue + 1;
11256     if (SCVMinus1.isPowerOf2()) {
11257       ShiftAmt = SCVMinus1.logBase2();
11258       AddSubOpc = ISD::ADD;
11259     } else if (CVPlus1.isPowerOf2()) {
11260       ShiftAmt = CVPlus1.logBase2();
11261       AddSubOpc = ISD::SUB;
11262     } else
11263       return SDValue();
11264   } else {
11265     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11266     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11267     APInt CVNegPlus1 = -ConstValue + 1;
11268     APInt CVNegMinus1 = -ConstValue - 1;
11269     if (CVNegPlus1.isPowerOf2()) {
11270       ShiftAmt = CVNegPlus1.logBase2();
11271       AddSubOpc = ISD::SUB;
11272       ShiftValUseIsN0 = false;
11273     } else if (CVNegMinus1.isPowerOf2()) {
11274       ShiftAmt = CVNegMinus1.logBase2();
11275       AddSubOpc = ISD::ADD;
11276       NegateResult = true;
11277     } else
11278       return SDValue();
11279   }
11280 
11281   SDLoc DL(N);
11282   EVT VT = N->getValueType(0);
11283   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
11284                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
11285 
11286   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
11287   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
11288   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
11289   assert(!(NegateResult && TrailingZeroes) &&
11290          "NegateResult and TrailingZeroes cannot both be true for now.");
11291   // Negate the result.
11292   if (NegateResult)
11293     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
11294   // Shift the result.
11295   if (TrailingZeroes)
11296     return DAG.getNode(ISD::SHL, DL, VT, Res,
11297                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
11298   return Res;
11299 }
11300 
11301 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
11302                                                          SelectionDAG &DAG) {
11303   // Take advantage of vector comparisons producing 0 or -1 in each lane to
11304   // optimize away operation when it's from a constant.
11305   //
11306   // The general transformation is:
11307   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
11308   //       AND(VECTOR_CMP(x,y), constant2)
11309   //    constant2 = UNARYOP(constant)
11310 
11311   // Early exit if this isn't a vector operation, the operand of the
11312   // unary operation isn't a bitwise AND, or if the sizes of the operations
11313   // aren't the same.
11314   EVT VT = N->getValueType(0);
11315   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
11316       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
11317       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
11318     return SDValue();
11319 
11320   // Now check that the other operand of the AND is a constant. We could
11321   // make the transformation for non-constant splats as well, but it's unclear
11322   // that would be a benefit as it would not eliminate any operations, just
11323   // perform one more step in scalar code before moving to the vector unit.
11324   if (BuildVectorSDNode *BV =
11325           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
11326     // Bail out if the vector isn't a constant.
11327     if (!BV->isConstant())
11328       return SDValue();
11329 
11330     // Everything checks out. Build up the new and improved node.
11331     SDLoc DL(N);
11332     EVT IntVT = BV->getValueType(0);
11333     // Create a new constant of the appropriate type for the transformed
11334     // DAG.
11335     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
11336     // The AND node needs bitcasts to/from an integer vector type around it.
11337     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
11338     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
11339                                  N->getOperand(0)->getOperand(0), MaskConst);
11340     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
11341     return Res;
11342   }
11343 
11344   return SDValue();
11345 }
11346 
11347 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
11348                                      const AArch64Subtarget *Subtarget) {
11349   // First try to optimize away the conversion when it's conditionally from
11350   // a constant. Vectors only.
11351   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
11352     return Res;
11353 
11354   EVT VT = N->getValueType(0);
11355   if (VT != MVT::f32 && VT != MVT::f64)
11356     return SDValue();
11357 
11358   // Only optimize when the source and destination types have the same width.
11359   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
11360     return SDValue();
11361 
11362   // If the result of an integer load is only used by an integer-to-float
11363   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
11364   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
11365   SDValue N0 = N->getOperand(0);
11366   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11367       // Do not change the width of a volatile load.
11368       !cast<LoadSDNode>(N0)->isVolatile()) {
11369     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11370     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
11371                                LN0->getPointerInfo(), LN0->getAlignment(),
11372                                LN0->getMemOperand()->getFlags());
11373 
11374     // Make sure successors of the original load stay after it by updating them
11375     // to use the new Chain.
11376     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
11377 
11378     unsigned Opcode =
11379         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
11380     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
11381   }
11382 
11383   return SDValue();
11384 }
11385 
11386 /// Fold a floating-point multiply by power of two into floating-point to
11387 /// fixed-point conversion.
11388 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
11389                                      TargetLowering::DAGCombinerInfo &DCI,
11390                                      const AArch64Subtarget *Subtarget) {
11391   if (!Subtarget->hasNEON())
11392     return SDValue();
11393 
11394   if (!N->getValueType(0).isSimple())
11395     return SDValue();
11396 
11397   SDValue Op = N->getOperand(0);
11398   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11399       Op.getOpcode() != ISD::FMUL)
11400     return SDValue();
11401 
11402   SDValue ConstVec = Op->getOperand(1);
11403   if (!isa<BuildVectorSDNode>(ConstVec))
11404     return SDValue();
11405 
11406   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11407   uint32_t FloatBits = FloatTy.getSizeInBits();
11408   if (FloatBits != 32 && FloatBits != 64)
11409     return SDValue();
11410 
11411   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11412   uint32_t IntBits = IntTy.getSizeInBits();
11413   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11414     return SDValue();
11415 
11416   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
11417   if (IntBits > FloatBits)
11418     return SDValue();
11419 
11420   BitVector UndefElements;
11421   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11422   int32_t Bits = IntBits == 64 ? 64 : 32;
11423   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
11424   if (C == -1 || C == 0 || C > Bits)
11425     return SDValue();
11426 
11427   MVT ResTy;
11428   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11429   switch (NumLanes) {
11430   default:
11431     return SDValue();
11432   case 2:
11433     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11434     break;
11435   case 4:
11436     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11437     break;
11438   }
11439 
11440   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11441     return SDValue();
11442 
11443   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
11444          "Illegal vector type after legalization");
11445 
11446   SDLoc DL(N);
11447   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11448   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
11449                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
11450   SDValue FixConv =
11451       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
11452                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
11453                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
11454   // We can handle smaller integers by generating an extra trunc.
11455   if (IntBits < FloatBits)
11456     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
11457 
11458   return FixConv;
11459 }
11460 
11461 /// Fold a floating-point divide by power of two into fixed-point to
11462 /// floating-point conversion.
11463 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
11464                                   TargetLowering::DAGCombinerInfo &DCI,
11465                                   const AArch64Subtarget *Subtarget) {
11466   if (!Subtarget->hasNEON())
11467     return SDValue();
11468 
11469   SDValue Op = N->getOperand(0);
11470   unsigned Opc = Op->getOpcode();
11471   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11472       !Op.getOperand(0).getValueType().isSimple() ||
11473       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
11474     return SDValue();
11475 
11476   SDValue ConstVec = N->getOperand(1);
11477   if (!isa<BuildVectorSDNode>(ConstVec))
11478     return SDValue();
11479 
11480   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11481   int32_t IntBits = IntTy.getSizeInBits();
11482   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11483     return SDValue();
11484 
11485   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11486   int32_t FloatBits = FloatTy.getSizeInBits();
11487   if (FloatBits != 32 && FloatBits != 64)
11488     return SDValue();
11489 
11490   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
11491   if (IntBits > FloatBits)
11492     return SDValue();
11493 
11494   BitVector UndefElements;
11495   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11496   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
11497   if (C == -1 || C == 0 || C > FloatBits)
11498     return SDValue();
11499 
11500   MVT ResTy;
11501   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11502   switch (NumLanes) {
11503   default:
11504     return SDValue();
11505   case 2:
11506     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11507     break;
11508   case 4:
11509     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11510     break;
11511   }
11512 
11513   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11514     return SDValue();
11515 
11516   SDLoc DL(N);
11517   SDValue ConvInput = Op.getOperand(0);
11518   bool IsSigned = Opc == ISD::SINT_TO_FP;
11519   if (IntBits < FloatBits)
11520     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
11521                             ResTy, ConvInput);
11522 
11523   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
11524                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
11525   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
11526                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
11527                      DAG.getConstant(C, DL, MVT::i32));
11528 }
11529 
11530 /// An EXTR instruction is made up of two shifts, ORed together. This helper
11531 /// searches for and classifies those shifts.
11532 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
11533                          bool &FromHi) {
11534   if (N.getOpcode() == ISD::SHL)
11535     FromHi = false;
11536   else if (N.getOpcode() == ISD::SRL)
11537     FromHi = true;
11538   else
11539     return false;
11540 
11541   if (!isa<ConstantSDNode>(N.getOperand(1)))
11542     return false;
11543 
11544   ShiftAmount = N->getConstantOperandVal(1);
11545   Src = N->getOperand(0);
11546   return true;
11547 }
11548 
11549 /// EXTR instruction extracts a contiguous chunk of bits from two existing
11550 /// registers viewed as a high/low pair. This function looks for the pattern:
11551 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
11552 /// with an EXTR. Can't quite be done in TableGen because the two immediates
11553 /// aren't independent.
11554 static SDValue tryCombineToEXTR(SDNode *N,
11555                                 TargetLowering::DAGCombinerInfo &DCI) {
11556   SelectionDAG &DAG = DCI.DAG;
11557   SDLoc DL(N);
11558   EVT VT = N->getValueType(0);
11559 
11560   assert(N->getOpcode() == ISD::OR && "Unexpected root");
11561 
11562   if (VT != MVT::i32 && VT != MVT::i64)
11563     return SDValue();
11564 
11565   SDValue LHS;
11566   uint32_t ShiftLHS = 0;
11567   bool LHSFromHi = false;
11568   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
11569     return SDValue();
11570 
11571   SDValue RHS;
11572   uint32_t ShiftRHS = 0;
11573   bool RHSFromHi = false;
11574   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
11575     return SDValue();
11576 
11577   // If they're both trying to come from the high part of the register, they're
11578   // not really an EXTR.
11579   if (LHSFromHi == RHSFromHi)
11580     return SDValue();
11581 
11582   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
11583     return SDValue();
11584 
11585   if (LHSFromHi) {
11586     std::swap(LHS, RHS);
11587     std::swap(ShiftLHS, ShiftRHS);
11588   }
11589 
11590   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
11591                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
11592 }
11593 
11594 static SDValue tryCombineToBSL(SDNode *N,
11595                                 TargetLowering::DAGCombinerInfo &DCI) {
11596   EVT VT = N->getValueType(0);
11597   SelectionDAG &DAG = DCI.DAG;
11598   SDLoc DL(N);
11599 
11600   if (!VT.isVector())
11601     return SDValue();
11602 
11603   SDValue N0 = N->getOperand(0);
11604   if (N0.getOpcode() != ISD::AND)
11605     return SDValue();
11606 
11607   SDValue N1 = N->getOperand(1);
11608   if (N1.getOpcode() != ISD::AND)
11609     return SDValue();
11610 
11611   // We only have to look for constant vectors here since the general, variable
11612   // case can be handled in TableGen.
11613   unsigned Bits = VT.getScalarSizeInBits();
11614   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
11615   for (int i = 1; i >= 0; --i)
11616     for (int j = 1; j >= 0; --j) {
11617       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
11618       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
11619       if (!BVN0 || !BVN1)
11620         continue;
11621 
11622       bool FoundMatch = true;
11623       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
11624         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
11625         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
11626         if (!CN0 || !CN1 ||
11627             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
11628           FoundMatch = false;
11629           break;
11630         }
11631       }
11632 
11633       if (FoundMatch)
11634         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
11635                            N0->getOperand(1 - i), N1->getOperand(1 - j));
11636     }
11637 
11638   return SDValue();
11639 }
11640 
11641 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11642                                 const AArch64Subtarget *Subtarget) {
11643   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
11644   SelectionDAG &DAG = DCI.DAG;
11645   EVT VT = N->getValueType(0);
11646 
11647   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11648     return SDValue();
11649 
11650   if (SDValue Res = tryCombineToEXTR(N, DCI))
11651     return Res;
11652 
11653   if (SDValue Res = tryCombineToBSL(N, DCI))
11654     return Res;
11655 
11656   return SDValue();
11657 }
11658 
11659 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
11660   if (!MemVT.getVectorElementType().isSimple())
11661     return false;
11662 
11663   uint64_t MaskForTy = 0ull;
11664   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
11665   case MVT::i8:
11666     MaskForTy = 0xffull;
11667     break;
11668   case MVT::i16:
11669     MaskForTy = 0xffffull;
11670     break;
11671   case MVT::i32:
11672     MaskForTy = 0xffffffffull;
11673     break;
11674   default:
11675     return false;
11676     break;
11677   }
11678 
11679   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
11680     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
11681       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
11682 
11683   return false;
11684 }
11685 
11686 static SDValue performSVEAndCombine(SDNode *N,
11687                                     TargetLowering::DAGCombinerInfo &DCI) {
11688   if (DCI.isBeforeLegalizeOps())
11689     return SDValue();
11690 
11691   SelectionDAG &DAG = DCI.DAG;
11692   SDValue Src = N->getOperand(0);
11693   unsigned Opc = Src->getOpcode();
11694 
11695   // Zero/any extend of an unsigned unpack
11696   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
11697     SDValue UnpkOp = Src->getOperand(0);
11698     SDValue Dup = N->getOperand(1);
11699 
11700     if (Dup.getOpcode() != AArch64ISD::DUP)
11701       return SDValue();
11702 
11703     SDLoc DL(N);
11704     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11705     uint64_t ExtVal = C->getZExtValue();
11706 
11707     // If the mask is fully covered by the unpack, we don't need to push
11708     // a new AND onto the operand
11709     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11710     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11711         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11712         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11713       return Src;
11714 
11715     // Truncate to prevent a DUP with an over wide constant
11716     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11717 
11718     // Otherwise, make sure we propagate the AND to the operand
11719     // of the unpack
11720     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11721                       UnpkOp->getValueType(0),
11722                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11723 
11724     SDValue And = DAG.getNode(ISD::AND, DL,
11725                               UnpkOp->getValueType(0), UnpkOp, Dup);
11726 
11727     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11728   }
11729 
11730   SDValue Mask = N->getOperand(1);
11731 
11732   if (!Src.hasOneUse())
11733     return SDValue();
11734 
11735   EVT MemVT;
11736 
11737   // SVE load instructions perform an implicit zero-extend, which makes them
11738   // perfect candidates for combining.
11739   switch (Opc) {
11740   case AArch64ISD::LD1_MERGE_ZERO:
11741   case AArch64ISD::LDNF1_MERGE_ZERO:
11742   case AArch64ISD::LDFF1_MERGE_ZERO:
11743     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11744     break;
11745   case AArch64ISD::GLD1_MERGE_ZERO:
11746   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11747   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11748   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11749   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11750   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11751   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11752   case AArch64ISD::GLDFF1_MERGE_ZERO:
11753   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11754   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11755   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11756   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11757   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11758   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11759   case AArch64ISD::GLDNT1_MERGE_ZERO:
11760     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11761     break;
11762   default:
11763     return SDValue();
11764   }
11765 
11766   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11767     return Src;
11768 
11769   return SDValue();
11770 }
11771 
11772 static SDValue performANDCombine(SDNode *N,
11773                                  TargetLowering::DAGCombinerInfo &DCI) {
11774   SelectionDAG &DAG = DCI.DAG;
11775   SDValue LHS = N->getOperand(0);
11776   EVT VT = N->getValueType(0);
11777   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11778     return SDValue();
11779 
11780   if (VT.isScalableVector())
11781     return performSVEAndCombine(N, DCI);
11782 
11783   // The combining code below works only for NEON vectors. In particular, it
11784   // does not work for SVE when dealing with vectors wider than 128 bits.
11785   if (!(VT.is64BitVector() || VT.is128BitVector()))
11786     return SDValue();
11787 
11788   BuildVectorSDNode *BVN =
11789       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11790   if (!BVN)
11791     return SDValue();
11792 
11793   // AND does not accept an immediate, so check if we can use a BIC immediate
11794   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11795   // pattern in isel, because some immediates may be lowered to the preferred
11796   // (and x, (movi imm)) form, even though an mvni representation also exists.
11797   APInt DefBits(VT.getSizeInBits(), 0);
11798   APInt UndefBits(VT.getSizeInBits(), 0);
11799   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11800     SDValue NewOp;
11801 
11802     DefBits = ~DefBits;
11803     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11804                                     DefBits, &LHS)) ||
11805         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11806                                     DefBits, &LHS)))
11807       return NewOp;
11808 
11809     UndefBits = ~UndefBits;
11810     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11811                                     UndefBits, &LHS)) ||
11812         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11813                                     UndefBits, &LHS)))
11814       return NewOp;
11815   }
11816 
11817   return SDValue();
11818 }
11819 
11820 static SDValue performSRLCombine(SDNode *N,
11821                                  TargetLowering::DAGCombinerInfo &DCI) {
11822   SelectionDAG &DAG = DCI.DAG;
11823   EVT VT = N->getValueType(0);
11824   if (VT != MVT::i32 && VT != MVT::i64)
11825     return SDValue();
11826 
11827   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11828   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11829   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11830   SDValue N0 = N->getOperand(0);
11831   if (N0.getOpcode() == ISD::BSWAP) {
11832     SDLoc DL(N);
11833     SDValue N1 = N->getOperand(1);
11834     SDValue N00 = N0.getOperand(0);
11835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11836       uint64_t ShiftAmt = C->getZExtValue();
11837       if (VT == MVT::i32 && ShiftAmt == 16 &&
11838           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11839         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11840       if (VT == MVT::i64 && ShiftAmt == 32 &&
11841           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11842         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11843     }
11844   }
11845   return SDValue();
11846 }
11847 
11848 // Attempt to form urhadd(OpA, OpB) from
11849 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
11850 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
11851 // The original form of the first expression is
11852 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
11853 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
11854 // Before this function is called the srl will have been lowered to
11855 // AArch64ISD::VLSHR.
11856 // This pass can also recognize signed variants of the patterns that use sign
11857 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
11858 // shadd(OpA, OpB) from them.
11859 static SDValue
11860 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11861                              SelectionDAG &DAG) {
11862   EVT VT = N->getValueType(0);
11863 
11864   // Since we are looking for a right shift by a constant value of 1 and we are
11865   // operating on types at least 16 bits in length (sign/zero extended OpA and
11866   // OpB, which are at least 8 bits), it follows that the truncate will always
11867   // discard the shifted-in bit and therefore the right shift will be logical
11868   // regardless of the signedness of OpA and OpB.
11869   SDValue Shift = N->getOperand(0);
11870   if (Shift.getOpcode() != AArch64ISD::VLSHR)
11871     return SDValue();
11872 
11873   // Is the right shift using an immediate value of 1?
11874   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
11875   if (ShiftAmount != 1)
11876     return SDValue();
11877 
11878   SDValue ExtendOpA, ExtendOpB;
11879   SDValue ShiftOp0 = Shift.getOperand(0);
11880   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
11881   if (ShiftOp0Opc == ISD::SUB) {
11882 
11883     SDValue Xor = ShiftOp0.getOperand(1);
11884     if (Xor.getOpcode() != ISD::XOR)
11885       return SDValue();
11886 
11887     // Is the XOR using a constant amount of all ones in the right hand side?
11888     uint64_t C;
11889     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
11890       return SDValue();
11891 
11892     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
11893     APInt CAsAPInt(ElemSizeInBits, C);
11894     if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
11895       return SDValue();
11896 
11897     ExtendOpA = Xor.getOperand(0);
11898     ExtendOpB = ShiftOp0.getOperand(0);
11899   } else if (ShiftOp0Opc == ISD::ADD) {
11900     ExtendOpA = ShiftOp0.getOperand(0);
11901     ExtendOpB = ShiftOp0.getOperand(1);
11902   } else
11903     return SDValue();
11904 
11905   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
11906   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
11907   if (!(ExtendOpAOpc == ExtendOpBOpc &&
11908         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
11909     return SDValue();
11910 
11911   // Is the result of the right shift being truncated to the same value type as
11912   // the original operands, OpA and OpB?
11913   SDValue OpA = ExtendOpA.getOperand(0);
11914   SDValue OpB = ExtendOpB.getOperand(0);
11915   EVT OpAVT = OpA.getValueType();
11916   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
11917   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
11918     return SDValue();
11919 
11920   SDLoc DL(N);
11921   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
11922   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
11923   unsigned HADDOpc = IsSignExtend
11924                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
11925                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
11926   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
11927 
11928   return ResultHADD;
11929 }
11930 
11931 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
11932   switch (Opcode) {
11933   case ISD::FADD:
11934     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
11935   case ISD::ADD:
11936     return VT == MVT::i64;
11937   default:
11938     return false;
11939   }
11940 }
11941 
11942 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
11943   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11944   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
11945 
11946   EVT VT = N->getValueType(0);
11947   const bool FullFP16 =
11948       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
11949 
11950   // Rewrite for pairwise fadd pattern
11951   //   (f32 (extract_vector_elt
11952   //           (fadd (vXf32 Other)
11953   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
11954   // ->
11955   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
11956   //              (extract_vector_elt (vXf32 Other) 1))
11957   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
11958       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
11959     SDLoc DL(N0);
11960     SDValue N00 = N0->getOperand(0);
11961     SDValue N01 = N0->getOperand(1);
11962 
11963     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
11964     SDValue Other = N00;
11965 
11966     // And handle the commutative case.
11967     if (!Shuffle) {
11968       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
11969       Other = N01;
11970     }
11971 
11972     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
11973         Other == Shuffle->getOperand(0)) {
11974       return DAG.getNode(N0->getOpcode(), DL, VT,
11975                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
11976                                      DAG.getConstant(0, DL, MVT::i64)),
11977                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
11978                                      DAG.getConstant(1, DL, MVT::i64)));
11979     }
11980   }
11981 
11982   return SDValue();
11983 }
11984 
11985 static SDValue performConcatVectorsCombine(SDNode *N,
11986                                            TargetLowering::DAGCombinerInfo &DCI,
11987                                            SelectionDAG &DAG) {
11988   SDLoc dl(N);
11989   EVT VT = N->getValueType(0);
11990   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11991   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11992 
11993   // Optimize concat_vectors of truncated vectors, where the intermediate
11994   // type is illegal, to avoid said illegality,  e.g.,
11995   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11996   //                          (v2i16 (truncate (v2i64)))))
11997   // ->
11998   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11999   //                                    (v4i32 (bitcast (v2i64))),
12000   //                                    <0, 2, 4, 6>)))
12001   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
12002   // on both input and result type, so we might generate worse code.
12003   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
12004   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
12005       N1Opc == ISD::TRUNCATE) {
12006     SDValue N00 = N0->getOperand(0);
12007     SDValue N10 = N1->getOperand(0);
12008     EVT N00VT = N00.getValueType();
12009 
12010     if (N00VT == N10.getValueType() &&
12011         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
12012         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
12013       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
12014       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
12015       for (size_t i = 0; i < Mask.size(); ++i)
12016         Mask[i] = i * 2;
12017       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12018                          DAG.getVectorShuffle(
12019                              MidVT, dl,
12020                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
12021                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
12022     }
12023   }
12024 
12025   // Wait 'til after everything is legalized to try this. That way we have
12026   // legal vector types and such.
12027   if (DCI.isBeforeLegalizeOps())
12028     return SDValue();
12029 
12030   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
12031   // subvectors from the same original vectors. Combine these into a single
12032   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
12033   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
12034   //                                        extract_subvector (v16i8 OpB,
12035   //                                        <0>))),
12036   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
12037   //                                        extract_subvector (v16i8 OpB,
12038   //                                        <8>)))))
12039   // ->
12040   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
12041   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
12042       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
12043        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
12044     SDValue N00 = N0->getOperand(0);
12045     SDValue N01 = N0->getOperand(1);
12046     SDValue N10 = N1->getOperand(0);
12047     SDValue N11 = N1->getOperand(1);
12048 
12049     EVT N00VT = N00.getValueType();
12050     EVT N10VT = N10.getValueType();
12051 
12052     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12053         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12054         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12055         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
12056       SDValue N00Source = N00->getOperand(0);
12057       SDValue N01Source = N01->getOperand(0);
12058       SDValue N10Source = N10->getOperand(0);
12059       SDValue N11Source = N11->getOperand(0);
12060 
12061       if (N00Source == N10Source && N01Source == N11Source &&
12062           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
12063         assert(N0.getValueType() == N1.getValueType());
12064 
12065         uint64_t N00Index = N00.getConstantOperandVal(1);
12066         uint64_t N01Index = N01.getConstantOperandVal(1);
12067         uint64_t N10Index = N10.getConstantOperandVal(1);
12068         uint64_t N11Index = N11.getConstantOperandVal(1);
12069 
12070         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
12071             N10Index == N00VT.getVectorNumElements())
12072           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
12073       }
12074     }
12075   }
12076 
12077   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
12078   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
12079   // canonicalise to that.
12080   if (N0 == N1 && VT.getVectorNumElements() == 2) {
12081     assert(VT.getScalarSizeInBits() == 64);
12082     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
12083                        DAG.getConstant(0, dl, MVT::i64));
12084   }
12085 
12086   // Canonicalise concat_vectors so that the right-hand vector has as few
12087   // bit-casts as possible before its real operation. The primary matching
12088   // destination for these operations will be the narrowing "2" instructions,
12089   // which depend on the operation being performed on this right-hand vector.
12090   // For example,
12091   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
12092   // becomes
12093   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
12094 
12095   if (N1Opc != ISD::BITCAST)
12096     return SDValue();
12097   SDValue RHS = N1->getOperand(0);
12098   MVT RHSTy = RHS.getValueType().getSimpleVT();
12099   // If the RHS is not a vector, this is not the pattern we're looking for.
12100   if (!RHSTy.isVector())
12101     return SDValue();
12102 
12103   LLVM_DEBUG(
12104       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
12105 
12106   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
12107                                   RHSTy.getVectorNumElements() * 2);
12108   return DAG.getNode(ISD::BITCAST, dl, VT,
12109                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
12110                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
12111                                  RHS));
12112 }
12113 
12114 static SDValue tryCombineFixedPointConvert(SDNode *N,
12115                                            TargetLowering::DAGCombinerInfo &DCI,
12116                                            SelectionDAG &DAG) {
12117   // Wait until after everything is legalized to try this. That way we have
12118   // legal vector types and such.
12119   if (DCI.isBeforeLegalizeOps())
12120     return SDValue();
12121   // Transform a scalar conversion of a value from a lane extract into a
12122   // lane extract of a vector conversion. E.g., from foo1 to foo2:
12123   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
12124   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
12125   //
12126   // The second form interacts better with instruction selection and the
12127   // register allocator to avoid cross-class register copies that aren't
12128   // coalescable due to a lane reference.
12129 
12130   // Check the operand and see if it originates from a lane extract.
12131   SDValue Op1 = N->getOperand(1);
12132   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12133     // Yep, no additional predication needed. Perform the transform.
12134     SDValue IID = N->getOperand(0);
12135     SDValue Shift = N->getOperand(2);
12136     SDValue Vec = Op1.getOperand(0);
12137     SDValue Lane = Op1.getOperand(1);
12138     EVT ResTy = N->getValueType(0);
12139     EVT VecResTy;
12140     SDLoc DL(N);
12141 
12142     // The vector width should be 128 bits by the time we get here, even
12143     // if it started as 64 bits (the extract_vector handling will have
12144     // done so).
12145     assert(Vec.getValueSizeInBits() == 128 &&
12146            "unexpected vector size on extract_vector_elt!");
12147     if (Vec.getValueType() == MVT::v4i32)
12148       VecResTy = MVT::v4f32;
12149     else if (Vec.getValueType() == MVT::v2i64)
12150       VecResTy = MVT::v2f64;
12151     else
12152       llvm_unreachable("unexpected vector type!");
12153 
12154     SDValue Convert =
12155         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
12156     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
12157   }
12158   return SDValue();
12159 }
12160 
12161 // AArch64 high-vector "long" operations are formed by performing the non-high
12162 // version on an extract_subvector of each operand which gets the high half:
12163 //
12164 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
12165 //
12166 // However, there are cases which don't have an extract_high explicitly, but
12167 // have another operation that can be made compatible with one for free. For
12168 // example:
12169 //
12170 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
12171 //
12172 // This routine does the actual conversion of such DUPs, once outer routines
12173 // have determined that everything else is in order.
12174 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
12175 // similarly here.
12176 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
12177   switch (N.getOpcode()) {
12178   case AArch64ISD::DUP:
12179   case AArch64ISD::DUPLANE8:
12180   case AArch64ISD::DUPLANE16:
12181   case AArch64ISD::DUPLANE32:
12182   case AArch64ISD::DUPLANE64:
12183   case AArch64ISD::MOVI:
12184   case AArch64ISD::MOVIshift:
12185   case AArch64ISD::MOVIedit:
12186   case AArch64ISD::MOVImsl:
12187   case AArch64ISD::MVNIshift:
12188   case AArch64ISD::MVNImsl:
12189     break;
12190   default:
12191     // FMOV could be supported, but isn't very useful, as it would only occur
12192     // if you passed a bitcast' floating point immediate to an eligible long
12193     // integer op (addl, smull, ...).
12194     return SDValue();
12195   }
12196 
12197   MVT NarrowTy = N.getSimpleValueType();
12198   if (!NarrowTy.is64BitVector())
12199     return SDValue();
12200 
12201   MVT ElementTy = NarrowTy.getVectorElementType();
12202   unsigned NumElems = NarrowTy.getVectorNumElements();
12203   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
12204 
12205   SDLoc dl(N);
12206   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
12207                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
12208                      DAG.getConstant(NumElems, dl, MVT::i64));
12209 }
12210 
12211 static bool isEssentiallyExtractHighSubvector(SDValue N) {
12212   if (N.getOpcode() == ISD::BITCAST)
12213     N = N.getOperand(0);
12214   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12215     return false;
12216   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
12217          N.getOperand(0).getValueType().getVectorNumElements() / 2;
12218 }
12219 
12220 /// Helper structure to keep track of ISD::SET_CC operands.
12221 struct GenericSetCCInfo {
12222   const SDValue *Opnd0;
12223   const SDValue *Opnd1;
12224   ISD::CondCode CC;
12225 };
12226 
12227 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
12228 struct AArch64SetCCInfo {
12229   const SDValue *Cmp;
12230   AArch64CC::CondCode CC;
12231 };
12232 
12233 /// Helper structure to keep track of SetCC information.
12234 union SetCCInfo {
12235   GenericSetCCInfo Generic;
12236   AArch64SetCCInfo AArch64;
12237 };
12238 
12239 /// Helper structure to be able to read SetCC information.  If set to
12240 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
12241 /// GenericSetCCInfo.
12242 struct SetCCInfoAndKind {
12243   SetCCInfo Info;
12244   bool IsAArch64;
12245 };
12246 
12247 /// Check whether or not \p Op is a SET_CC operation, either a generic or
12248 /// an
12249 /// AArch64 lowered one.
12250 /// \p SetCCInfo is filled accordingly.
12251 /// \post SetCCInfo is meanginfull only when this function returns true.
12252 /// \return True when Op is a kind of SET_CC operation.
12253 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
12254   // If this is a setcc, this is straight forward.
12255   if (Op.getOpcode() == ISD::SETCC) {
12256     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
12257     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
12258     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12259     SetCCInfo.IsAArch64 = false;
12260     return true;
12261   }
12262   // Otherwise, check if this is a matching csel instruction.
12263   // In other words:
12264   // - csel 1, 0, cc
12265   // - csel 0, 1, !cc
12266   if (Op.getOpcode() != AArch64ISD::CSEL)
12267     return false;
12268   // Set the information about the operands.
12269   // TODO: we want the operands of the Cmp not the csel
12270   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
12271   SetCCInfo.IsAArch64 = true;
12272   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
12273       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12274 
12275   // Check that the operands matches the constraints:
12276   // (1) Both operands must be constants.
12277   // (2) One must be 1 and the other must be 0.
12278   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
12279   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12280 
12281   // Check (1).
12282   if (!TValue || !FValue)
12283     return false;
12284 
12285   // Check (2).
12286   if (!TValue->isOne()) {
12287     // Update the comparison when we are interested in !cc.
12288     std::swap(TValue, FValue);
12289     SetCCInfo.Info.AArch64.CC =
12290         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
12291   }
12292   return TValue->isOne() && FValue->isNullValue();
12293 }
12294 
12295 // Returns true if Op is setcc or zext of setcc.
12296 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
12297   if (isSetCC(Op, Info))
12298     return true;
12299   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
12300     isSetCC(Op->getOperand(0), Info));
12301 }
12302 
12303 // The folding we want to perform is:
12304 // (add x, [zext] (setcc cc ...) )
12305 //   -->
12306 // (csel x, (add x, 1), !cc ...)
12307 //
12308 // The latter will get matched to a CSINC instruction.
12309 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
12310   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
12311   SDValue LHS = Op->getOperand(0);
12312   SDValue RHS = Op->getOperand(1);
12313   SetCCInfoAndKind InfoAndKind;
12314 
12315   // If neither operand is a SET_CC, give up.
12316   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
12317     std::swap(LHS, RHS);
12318     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
12319       return SDValue();
12320   }
12321 
12322   // FIXME: This could be generatized to work for FP comparisons.
12323   EVT CmpVT = InfoAndKind.IsAArch64
12324                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
12325                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
12326   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
12327     return SDValue();
12328 
12329   SDValue CCVal;
12330   SDValue Cmp;
12331   SDLoc dl(Op);
12332   if (InfoAndKind.IsAArch64) {
12333     CCVal = DAG.getConstant(
12334         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
12335         MVT::i32);
12336     Cmp = *InfoAndKind.Info.AArch64.Cmp;
12337   } else
12338     Cmp = getAArch64Cmp(
12339         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
12340         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
12341         dl);
12342 
12343   EVT VT = Op->getValueType(0);
12344   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
12345   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
12346 }
12347 
12348 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
12349 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
12350   EVT VT = N->getValueType(0);
12351   // Only scalar integer and vector types.
12352   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
12353     return SDValue();
12354 
12355   SDValue LHS = N->getOperand(0);
12356   SDValue RHS = N->getOperand(1);
12357   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12358       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
12359     return SDValue();
12360 
12361   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12362   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
12363   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue())
12364     return SDValue();
12365 
12366   SDValue Op1 = LHS->getOperand(0);
12367   SDValue Op2 = RHS->getOperand(0);
12368   EVT OpVT1 = Op1.getValueType();
12369   EVT OpVT2 = Op2.getValueType();
12370   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
12371       Op2.getOpcode() != AArch64ISD::UADDV ||
12372       OpVT1.getVectorElementType() != VT)
12373     return SDValue();
12374 
12375   SDValue Val1 = Op1.getOperand(0);
12376   SDValue Val2 = Op2.getOperand(0);
12377   EVT ValVT = Val1->getValueType(0);
12378   SDLoc DL(N);
12379   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
12380   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
12381                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
12382                      DAG.getConstant(0, DL, MVT::i64));
12383 }
12384 
12385 // The basic add/sub long vector instructions have variants with "2" on the end
12386 // which act on the high-half of their inputs. They are normally matched by
12387 // patterns like:
12388 //
12389 // (add (zeroext (extract_high LHS)),
12390 //      (zeroext (extract_high RHS)))
12391 // -> uaddl2 vD, vN, vM
12392 //
12393 // However, if one of the extracts is something like a duplicate, this
12394 // instruction can still be used profitably. This function puts the DAG into a
12395 // more appropriate form for those patterns to trigger.
12396 static SDValue performAddSubLongCombine(SDNode *N,
12397                                         TargetLowering::DAGCombinerInfo &DCI,
12398                                         SelectionDAG &DAG) {
12399   if (DCI.isBeforeLegalizeOps())
12400     return SDValue();
12401 
12402   MVT VT = N->getSimpleValueType(0);
12403   if (!VT.is128BitVector()) {
12404     if (N->getOpcode() == ISD::ADD)
12405       return performSetccAddFolding(N, DAG);
12406     return SDValue();
12407   }
12408 
12409   // Make sure both branches are extended in the same way.
12410   SDValue LHS = N->getOperand(0);
12411   SDValue RHS = N->getOperand(1);
12412   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
12413        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
12414       LHS.getOpcode() != RHS.getOpcode())
12415     return SDValue();
12416 
12417   unsigned ExtType = LHS.getOpcode();
12418 
12419   // It's not worth doing if at least one of the inputs isn't already an
12420   // extract, but we don't know which it'll be so we have to try both.
12421   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
12422     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
12423     if (!RHS.getNode())
12424       return SDValue();
12425 
12426     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
12427   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
12428     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
12429     if (!LHS.getNode())
12430       return SDValue();
12431 
12432     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
12433   }
12434 
12435   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
12436 }
12437 
12438 static SDValue performAddSubCombine(SDNode *N,
12439                                     TargetLowering::DAGCombinerInfo &DCI,
12440                                     SelectionDAG &DAG) {
12441   // Try to change sum of two reductions.
12442   if (SDValue Val = performUADDVCombine(N, DAG))
12443     return Val;
12444 
12445   return performAddSubLongCombine(N, DCI, DAG);
12446 }
12447 
12448 // Massage DAGs which we can use the high-half "long" operations on into
12449 // something isel will recognize better. E.g.
12450 //
12451 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
12452 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
12453 //                     (extract_high (v2i64 (dup128 scalar)))))
12454 //
12455 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
12456                                        TargetLowering::DAGCombinerInfo &DCI,
12457                                        SelectionDAG &DAG) {
12458   if (DCI.isBeforeLegalizeOps())
12459     return SDValue();
12460 
12461   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
12462   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
12463   assert(LHS.getValueType().is64BitVector() &&
12464          RHS.getValueType().is64BitVector() &&
12465          "unexpected shape for long operation");
12466 
12467   // Either node could be a DUP, but it's not worth doing both of them (you'd
12468   // just as well use the non-high version) so look for a corresponding extract
12469   // operation on the other "wing".
12470   if (isEssentiallyExtractHighSubvector(LHS)) {
12471     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
12472     if (!RHS.getNode())
12473       return SDValue();
12474   } else if (isEssentiallyExtractHighSubvector(RHS)) {
12475     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
12476     if (!LHS.getNode())
12477       return SDValue();
12478   }
12479 
12480   if (IID == Intrinsic::not_intrinsic)
12481     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
12482 
12483   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
12484                      N->getOperand(0), LHS, RHS);
12485 }
12486 
12487 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
12488   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
12489   unsigned ElemBits = ElemTy.getSizeInBits();
12490 
12491   int64_t ShiftAmount;
12492   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
12493     APInt SplatValue, SplatUndef;
12494     unsigned SplatBitSize;
12495     bool HasAnyUndefs;
12496     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12497                               HasAnyUndefs, ElemBits) ||
12498         SplatBitSize != ElemBits)
12499       return SDValue();
12500 
12501     ShiftAmount = SplatValue.getSExtValue();
12502   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
12503     ShiftAmount = CVN->getSExtValue();
12504   } else
12505     return SDValue();
12506 
12507   unsigned Opcode;
12508   bool IsRightShift;
12509   switch (IID) {
12510   default:
12511     llvm_unreachable("Unknown shift intrinsic");
12512   case Intrinsic::aarch64_neon_sqshl:
12513     Opcode = AArch64ISD::SQSHL_I;
12514     IsRightShift = false;
12515     break;
12516   case Intrinsic::aarch64_neon_uqshl:
12517     Opcode = AArch64ISD::UQSHL_I;
12518     IsRightShift = false;
12519     break;
12520   case Intrinsic::aarch64_neon_srshl:
12521     Opcode = AArch64ISD::SRSHR_I;
12522     IsRightShift = true;
12523     break;
12524   case Intrinsic::aarch64_neon_urshl:
12525     Opcode = AArch64ISD::URSHR_I;
12526     IsRightShift = true;
12527     break;
12528   case Intrinsic::aarch64_neon_sqshlu:
12529     Opcode = AArch64ISD::SQSHLU_I;
12530     IsRightShift = false;
12531     break;
12532   case Intrinsic::aarch64_neon_sshl:
12533   case Intrinsic::aarch64_neon_ushl:
12534     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
12535     // left shift for positive shift amounts. Below, we only replace the current
12536     // node with VSHL, if this condition is met.
12537     Opcode = AArch64ISD::VSHL;
12538     IsRightShift = false;
12539     break;
12540   }
12541 
12542   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
12543     SDLoc dl(N);
12544     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12545                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
12546   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
12547     SDLoc dl(N);
12548     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12549                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
12550   }
12551 
12552   return SDValue();
12553 }
12554 
12555 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
12556 // the intrinsics must be legal and take an i32, this means there's almost
12557 // certainly going to be a zext in the DAG which we can eliminate.
12558 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
12559   SDValue AndN = N->getOperand(2);
12560   if (AndN.getOpcode() != ISD::AND)
12561     return SDValue();
12562 
12563   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
12564   if (!CMask || CMask->getZExtValue() != Mask)
12565     return SDValue();
12566 
12567   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
12568                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
12569 }
12570 
12571 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
12572                                            SelectionDAG &DAG) {
12573   SDLoc dl(N);
12574   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
12575                      DAG.getNode(Opc, dl,
12576                                  N->getOperand(1).getSimpleValueType(),
12577                                  N->getOperand(1)),
12578                      DAG.getConstant(0, dl, MVT::i64));
12579 }
12580 
12581 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
12582   SDLoc DL(N);
12583   SDValue Op1 = N->getOperand(1);
12584   SDValue Op2 = N->getOperand(2);
12585   EVT ScalarTy = Op1.getValueType();
12586 
12587   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
12588     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
12589     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
12590   }
12591 
12592   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
12593                      Op1, Op2);
12594 }
12595 
12596 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
12597   SDLoc dl(N);
12598   SDValue Scalar = N->getOperand(3);
12599   EVT ScalarTy = Scalar.getValueType();
12600 
12601   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
12602     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
12603 
12604   SDValue Passthru = N->getOperand(1);
12605   SDValue Pred = N->getOperand(2);
12606   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
12607                      Pred, Scalar, Passthru);
12608 }
12609 
12610 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
12611   SDLoc dl(N);
12612   LLVMContext &Ctx = *DAG.getContext();
12613   EVT VT = N->getValueType(0);
12614 
12615   assert(VT.isScalableVector() && "Expected a scalable vector.");
12616 
12617   // Current lowering only supports the SVE-ACLE types.
12618   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
12619     return SDValue();
12620 
12621   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
12622   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
12623   EVT ByteVT =
12624       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
12625 
12626   // Convert everything to the domain of EXT (i.e bytes).
12627   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
12628   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
12629   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
12630                             DAG.getConstant(ElemSize, dl, MVT::i32));
12631 
12632   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
12633   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
12634 }
12635 
12636 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
12637                                         TargetLowering::DAGCombinerInfo &DCI,
12638                                         SelectionDAG &DAG) {
12639   if (DCI.isBeforeLegalize())
12640     return SDValue();
12641 
12642   SDValue Comparator = N->getOperand(3);
12643   if (Comparator.getOpcode() == AArch64ISD::DUP ||
12644       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
12645     unsigned IID = getIntrinsicID(N);
12646     EVT VT = N->getValueType(0);
12647     EVT CmpVT = N->getOperand(2).getValueType();
12648     SDValue Pred = N->getOperand(1);
12649     SDValue Imm;
12650     SDLoc DL(N);
12651 
12652     switch (IID) {
12653     default:
12654       llvm_unreachable("Called with wrong intrinsic!");
12655       break;
12656 
12657     // Signed comparisons
12658     case Intrinsic::aarch64_sve_cmpeq_wide:
12659     case Intrinsic::aarch64_sve_cmpne_wide:
12660     case Intrinsic::aarch64_sve_cmpge_wide:
12661     case Intrinsic::aarch64_sve_cmpgt_wide:
12662     case Intrinsic::aarch64_sve_cmplt_wide:
12663     case Intrinsic::aarch64_sve_cmple_wide: {
12664       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12665         int64_t ImmVal = CN->getSExtValue();
12666         if (ImmVal >= -16 && ImmVal <= 15)
12667           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12668         else
12669           return SDValue();
12670       }
12671       break;
12672     }
12673     // Unsigned comparisons
12674     case Intrinsic::aarch64_sve_cmphs_wide:
12675     case Intrinsic::aarch64_sve_cmphi_wide:
12676     case Intrinsic::aarch64_sve_cmplo_wide:
12677     case Intrinsic::aarch64_sve_cmpls_wide:  {
12678       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12679         uint64_t ImmVal = CN->getZExtValue();
12680         if (ImmVal <= 127)
12681           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12682         else
12683           return SDValue();
12684       }
12685       break;
12686     }
12687     }
12688 
12689     if (!Imm)
12690       return SDValue();
12691 
12692     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
12693     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
12694                        N->getOperand(2), Splat, DAG.getCondCode(CC));
12695   }
12696 
12697   return SDValue();
12698 }
12699 
12700 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
12701                         AArch64CC::CondCode Cond) {
12702   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12703 
12704   SDLoc DL(Op);
12705   assert(Op.getValueType().isScalableVector() &&
12706          TLI.isTypeLegal(Op.getValueType()) &&
12707          "Expected legal scalable vector type!");
12708 
12709   // Ensure target specific opcodes are using legal type.
12710   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12711   SDValue TVal = DAG.getConstant(1, DL, OutVT);
12712   SDValue FVal = DAG.getConstant(0, DL, OutVT);
12713 
12714   // Set condition code (CC) flags.
12715   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
12716 
12717   // Convert CC to integer based on requested condition.
12718   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
12719   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
12720   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
12721   return DAG.getZExtOrTrunc(Res, DL, VT);
12722 }
12723 
12724 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
12725                                       SelectionDAG &DAG) {
12726   SDLoc DL(N);
12727 
12728   SDValue Pred = N->getOperand(1);
12729   SDValue VecToReduce = N->getOperand(2);
12730 
12731   // NOTE: The integer reduction's result type is not always linked to the
12732   // operand's element type so we construct it from the intrinsic's result type.
12733   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
12734   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12735 
12736   // SVE reductions set the whole vector register with the first element
12737   // containing the reduction result, which we'll now extract.
12738   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12739   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12740                      Zero);
12741 }
12742 
12743 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
12744                                      SelectionDAG &DAG) {
12745   SDLoc DL(N);
12746 
12747   SDValue Pred = N->getOperand(1);
12748   SDValue VecToReduce = N->getOperand(2);
12749 
12750   EVT ReduceVT = VecToReduce.getValueType();
12751   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12752 
12753   // SVE reductions set the whole vector register with the first element
12754   // containing the reduction result, which we'll now extract.
12755   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12756   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12757                      Zero);
12758 }
12759 
12760 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
12761                                             SelectionDAG &DAG) {
12762   SDLoc DL(N);
12763 
12764   SDValue Pred = N->getOperand(1);
12765   SDValue InitVal = N->getOperand(2);
12766   SDValue VecToReduce = N->getOperand(3);
12767   EVT ReduceVT = VecToReduce.getValueType();
12768 
12769   // Ordered reductions use the first lane of the result vector as the
12770   // reduction's initial value.
12771   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12772   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
12773                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
12774 
12775   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
12776 
12777   // SVE reductions set the whole vector register with the first element
12778   // containing the reduction result, which we'll now extract.
12779   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12780                      Zero);
12781 }
12782 
12783 // If a merged operation has no inactive lanes we can relax it to a predicated
12784 // or unpredicated operation, which potentially allows better isel (perhaps
12785 // using immediate forms) or relaxing register reuse requirements.
12786 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
12787                                        SelectionDAG &DAG) {
12788   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
12789   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
12790   SDValue Pg = N->getOperand(1);
12791 
12792   // ISD way to specify an all active predicate.
12793   if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
12794       (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
12795     return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
12796                        N->getOperand(2), N->getOperand(3));
12797 
12798   // FUTURE: SplatVector(true)
12799   return SDValue();
12800 }
12801 
12802 static SDValue performIntrinsicCombine(SDNode *N,
12803                                        TargetLowering::DAGCombinerInfo &DCI,
12804                                        const AArch64Subtarget *Subtarget) {
12805   SelectionDAG &DAG = DCI.DAG;
12806   unsigned IID = getIntrinsicID(N);
12807   switch (IID) {
12808   default:
12809     break;
12810   case Intrinsic::aarch64_neon_vcvtfxs2fp:
12811   case Intrinsic::aarch64_neon_vcvtfxu2fp:
12812     return tryCombineFixedPointConvert(N, DCI, DAG);
12813   case Intrinsic::aarch64_neon_saddv:
12814     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
12815   case Intrinsic::aarch64_neon_uaddv:
12816     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
12817   case Intrinsic::aarch64_neon_sminv:
12818     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
12819   case Intrinsic::aarch64_neon_uminv:
12820     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
12821   case Intrinsic::aarch64_neon_smaxv:
12822     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
12823   case Intrinsic::aarch64_neon_umaxv:
12824     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
12825   case Intrinsic::aarch64_neon_fmax:
12826     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
12827                        N->getOperand(1), N->getOperand(2));
12828   case Intrinsic::aarch64_neon_fmin:
12829     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
12830                        N->getOperand(1), N->getOperand(2));
12831   case Intrinsic::aarch64_neon_fmaxnm:
12832     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
12833                        N->getOperand(1), N->getOperand(2));
12834   case Intrinsic::aarch64_neon_fminnm:
12835     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
12836                        N->getOperand(1), N->getOperand(2));
12837   case Intrinsic::aarch64_neon_smull:
12838   case Intrinsic::aarch64_neon_umull:
12839   case Intrinsic::aarch64_neon_pmull:
12840   case Intrinsic::aarch64_neon_sqdmull:
12841     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
12842   case Intrinsic::aarch64_neon_sqshl:
12843   case Intrinsic::aarch64_neon_uqshl:
12844   case Intrinsic::aarch64_neon_sqshlu:
12845   case Intrinsic::aarch64_neon_srshl:
12846   case Intrinsic::aarch64_neon_urshl:
12847   case Intrinsic::aarch64_neon_sshl:
12848   case Intrinsic::aarch64_neon_ushl:
12849     return tryCombineShiftImm(IID, N, DAG);
12850   case Intrinsic::aarch64_crc32b:
12851   case Intrinsic::aarch64_crc32cb:
12852     return tryCombineCRC32(0xff, N, DAG);
12853   case Intrinsic::aarch64_crc32h:
12854   case Intrinsic::aarch64_crc32ch:
12855     return tryCombineCRC32(0xffff, N, DAG);
12856   case Intrinsic::aarch64_sve_saddv:
12857     // There is no i64 version of SADDV because the sign is irrelevant.
12858     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
12859       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
12860     else
12861       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
12862   case Intrinsic::aarch64_sve_uaddv:
12863     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
12864   case Intrinsic::aarch64_sve_smaxv:
12865     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
12866   case Intrinsic::aarch64_sve_umaxv:
12867     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
12868   case Intrinsic::aarch64_sve_sminv:
12869     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
12870   case Intrinsic::aarch64_sve_uminv:
12871     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
12872   case Intrinsic::aarch64_sve_orv:
12873     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
12874   case Intrinsic::aarch64_sve_eorv:
12875     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
12876   case Intrinsic::aarch64_sve_andv:
12877     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
12878   case Intrinsic::aarch64_sve_index:
12879     return LowerSVEIntrinsicIndex(N, DAG);
12880   case Intrinsic::aarch64_sve_dup:
12881     return LowerSVEIntrinsicDUP(N, DAG);
12882   case Intrinsic::aarch64_sve_dup_x:
12883     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
12884                        N->getOperand(1));
12885   case Intrinsic::aarch64_sve_ext:
12886     return LowerSVEIntrinsicEXT(N, DAG);
12887   case Intrinsic::aarch64_sve_smin:
12888     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
12889   case Intrinsic::aarch64_sve_umin:
12890     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
12891   case Intrinsic::aarch64_sve_smax:
12892     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
12893   case Intrinsic::aarch64_sve_umax:
12894     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
12895   case Intrinsic::aarch64_sve_lsl:
12896     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
12897   case Intrinsic::aarch64_sve_lsr:
12898     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
12899   case Intrinsic::aarch64_sve_asr:
12900     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
12901   case Intrinsic::aarch64_sve_cmphs:
12902     if (!N->getOperand(2).getValueType().isFloatingPoint())
12903       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12904                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12905                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
12906     break;
12907   case Intrinsic::aarch64_sve_cmphi:
12908     if (!N->getOperand(2).getValueType().isFloatingPoint())
12909       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12910                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12911                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
12912     break;
12913   case Intrinsic::aarch64_sve_cmpge:
12914     if (!N->getOperand(2).getValueType().isFloatingPoint())
12915       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12916                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12917                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
12918     break;
12919   case Intrinsic::aarch64_sve_cmpgt:
12920     if (!N->getOperand(2).getValueType().isFloatingPoint())
12921       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12922                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12923                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12924     break;
12925   case Intrinsic::aarch64_sve_cmpeq:
12926     if (!N->getOperand(2).getValueType().isFloatingPoint())
12927       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12928                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12929                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12930     break;
12931   case Intrinsic::aarch64_sve_cmpne:
12932     if (!N->getOperand(2).getValueType().isFloatingPoint())
12933       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12934                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12935                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12936     break;
12937   case Intrinsic::aarch64_sve_fadda:
12938     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12939   case Intrinsic::aarch64_sve_faddv:
12940     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12941   case Intrinsic::aarch64_sve_fmaxnmv:
12942     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12943   case Intrinsic::aarch64_sve_fmaxv:
12944     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12945   case Intrinsic::aarch64_sve_fminnmv:
12946     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12947   case Intrinsic::aarch64_sve_fminv:
12948     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12949   case Intrinsic::aarch64_sve_sel:
12950     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12951                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12952   case Intrinsic::aarch64_sve_cmpeq_wide:
12953     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12954   case Intrinsic::aarch64_sve_cmpne_wide:
12955     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12956   case Intrinsic::aarch64_sve_cmpge_wide:
12957     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12958   case Intrinsic::aarch64_sve_cmpgt_wide:
12959     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12960   case Intrinsic::aarch64_sve_cmplt_wide:
12961     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12962   case Intrinsic::aarch64_sve_cmple_wide:
12963     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12964   case Intrinsic::aarch64_sve_cmphs_wide:
12965     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12966   case Intrinsic::aarch64_sve_cmphi_wide:
12967     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12968   case Intrinsic::aarch64_sve_cmplo_wide:
12969     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12970   case Intrinsic::aarch64_sve_cmpls_wide:
12971     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12972   case Intrinsic::aarch64_sve_ptest_any:
12973     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12974                     AArch64CC::ANY_ACTIVE);
12975   case Intrinsic::aarch64_sve_ptest_first:
12976     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12977                     AArch64CC::FIRST_ACTIVE);
12978   case Intrinsic::aarch64_sve_ptest_last:
12979     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12980                     AArch64CC::LAST_ACTIVE);
12981   }
12982   return SDValue();
12983 }
12984 
12985 static SDValue performExtendCombine(SDNode *N,
12986                                     TargetLowering::DAGCombinerInfo &DCI,
12987                                     SelectionDAG &DAG) {
12988   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12989   // we can convert that DUP into another extract_high (of a bigger DUP), which
12990   // helps the backend to decide that an sabdl2 would be useful, saving a real
12991   // extract_high operation.
12992   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12993       (N->getOperand(0).getOpcode() == AArch64ISD::UABD ||
12994        N->getOperand(0).getOpcode() == AArch64ISD::SABD)) {
12995     SDNode *ABDNode = N->getOperand(0).getNode();
12996     SDValue NewABD =
12997         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
12998     if (!NewABD.getNode())
12999       return SDValue();
13000 
13001     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
13002   }
13003 
13004   // This is effectively a custom type legalization for AArch64.
13005   //
13006   // Type legalization will split an extend of a small, legal, type to a larger
13007   // illegal type by first splitting the destination type, often creating
13008   // illegal source types, which then get legalized in isel-confusing ways,
13009   // leading to really terrible codegen. E.g.,
13010   //   %result = v8i32 sext v8i8 %value
13011   // becomes
13012   //   %losrc = extract_subreg %value, ...
13013   //   %hisrc = extract_subreg %value, ...
13014   //   %lo = v4i32 sext v4i8 %losrc
13015   //   %hi = v4i32 sext v4i8 %hisrc
13016   // Things go rapidly downhill from there.
13017   //
13018   // For AArch64, the [sz]ext vector instructions can only go up one element
13019   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
13020   // take two instructions.
13021   //
13022   // This implies that the most efficient way to do the extend from v8i8
13023   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
13024   // the normal splitting to happen for the v8i16->v8i32.
13025 
13026   // This is pre-legalization to catch some cases where the default
13027   // type legalization will create ill-tempered code.
13028   if (!DCI.isBeforeLegalizeOps())
13029     return SDValue();
13030 
13031   // We're only interested in cleaning things up for non-legal vector types
13032   // here. If both the source and destination are legal, things will just
13033   // work naturally without any fiddling.
13034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13035   EVT ResVT = N->getValueType(0);
13036   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
13037     return SDValue();
13038   // If the vector type isn't a simple VT, it's beyond the scope of what
13039   // we're  worried about here. Let legalization do its thing and hope for
13040   // the best.
13041   SDValue Src = N->getOperand(0);
13042   EVT SrcVT = Src->getValueType(0);
13043   if (!ResVT.isSimple() || !SrcVT.isSimple())
13044     return SDValue();
13045 
13046   // If the source VT is a 64-bit fixed or scalable vector, we can play games
13047   // and get the better results we want.
13048   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
13049     return SDValue();
13050 
13051   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
13052   ElementCount SrcEC = SrcVT.getVectorElementCount();
13053   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
13054   SDLoc DL(N);
13055   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
13056 
13057   // Now split the rest of the operation into two halves, each with a 64
13058   // bit source.
13059   EVT LoVT, HiVT;
13060   SDValue Lo, Hi;
13061   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
13062 
13063   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
13064                                LoVT.getVectorElementCount());
13065   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13066                    DAG.getConstant(0, DL, MVT::i64));
13067   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13068                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
13069   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
13070   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
13071 
13072   // Now combine the parts back together so we still have a single result
13073   // like the combiner expects.
13074   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
13075 }
13076 
13077 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
13078                                SDValue SplatVal, unsigned NumVecElts) {
13079   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
13080   unsigned OrigAlignment = St.getAlignment();
13081   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
13082 
13083   // Create scalar stores. This is at least as good as the code sequence for a
13084   // split unaligned store which is a dup.s, ext.b, and two stores.
13085   // Most of the time the three stores should be replaced by store pair
13086   // instructions (stp).
13087   SDLoc DL(&St);
13088   SDValue BasePtr = St.getBasePtr();
13089   uint64_t BaseOffset = 0;
13090 
13091   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
13092   SDValue NewST1 =
13093       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
13094                    OrigAlignment, St.getMemOperand()->getFlags());
13095 
13096   // As this in ISel, we will not merge this add which may degrade results.
13097   if (BasePtr->getOpcode() == ISD::ADD &&
13098       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
13099     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
13100     BasePtr = BasePtr->getOperand(0);
13101   }
13102 
13103   unsigned Offset = EltOffset;
13104   while (--NumVecElts) {
13105     unsigned Alignment = MinAlign(OrigAlignment, Offset);
13106     SDValue OffsetPtr =
13107         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13108                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
13109     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
13110                           PtrInfo.getWithOffset(Offset), Alignment,
13111                           St.getMemOperand()->getFlags());
13112     Offset += EltOffset;
13113   }
13114   return NewST1;
13115 }
13116 
13117 // Returns an SVE type that ContentTy can be trivially sign or zero extended
13118 // into.
13119 static MVT getSVEContainerType(EVT ContentTy) {
13120   assert(ContentTy.isSimple() && "No SVE containers for extended types");
13121 
13122   switch (ContentTy.getSimpleVT().SimpleTy) {
13123   default:
13124     llvm_unreachable("No known SVE container for this MVT type");
13125   case MVT::nxv2i8:
13126   case MVT::nxv2i16:
13127   case MVT::nxv2i32:
13128   case MVT::nxv2i64:
13129   case MVT::nxv2f32:
13130   case MVT::nxv2f64:
13131     return MVT::nxv2i64;
13132   case MVT::nxv4i8:
13133   case MVT::nxv4i16:
13134   case MVT::nxv4i32:
13135   case MVT::nxv4f32:
13136     return MVT::nxv4i32;
13137   case MVT::nxv8i8:
13138   case MVT::nxv8i16:
13139   case MVT::nxv8f16:
13140   case MVT::nxv8bf16:
13141     return MVT::nxv8i16;
13142   case MVT::nxv16i8:
13143     return MVT::nxv16i8;
13144   }
13145 }
13146 
13147 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
13148   SDLoc DL(N);
13149   EVT VT = N->getValueType(0);
13150 
13151   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13152     return SDValue();
13153 
13154   EVT ContainerVT = VT;
13155   if (ContainerVT.isInteger())
13156     ContainerVT = getSVEContainerType(ContainerVT);
13157 
13158   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
13159   SDValue Ops[] = { N->getOperand(0), // Chain
13160                     N->getOperand(2), // Pg
13161                     N->getOperand(3), // Base
13162                     DAG.getValueType(VT) };
13163 
13164   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
13165   SDValue LoadChain = SDValue(Load.getNode(), 1);
13166 
13167   if (ContainerVT.isInteger() && (VT != ContainerVT))
13168     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
13169 
13170   return DAG.getMergeValues({ Load, LoadChain }, DL);
13171 }
13172 
13173 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
13174   SDLoc DL(N);
13175   EVT VT = N->getValueType(0);
13176   EVT PtrTy = N->getOperand(3).getValueType();
13177 
13178   if (VT == MVT::nxv8bf16 &&
13179       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13180     return SDValue();
13181 
13182   EVT LoadVT = VT;
13183   if (VT.isFloatingPoint())
13184     LoadVT = VT.changeTypeToInteger();
13185 
13186   auto *MINode = cast<MemIntrinsicSDNode>(N);
13187   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
13188   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
13189                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
13190                                 MINode->getOperand(2), PassThru,
13191                                 MINode->getMemoryVT(), MINode->getMemOperand(),
13192                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
13193 
13194    if (VT.isFloatingPoint()) {
13195      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
13196      return DAG.getMergeValues(Ops, DL);
13197    }
13198 
13199   return L;
13200 }
13201 
13202 template <unsigned Opcode>
13203 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
13204   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
13205                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
13206                 "Unsupported opcode.");
13207   SDLoc DL(N);
13208   EVT VT = N->getValueType(0);
13209   if (VT == MVT::nxv8bf16 &&
13210       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13211     return SDValue();
13212 
13213   EVT LoadVT = VT;
13214   if (VT.isFloatingPoint())
13215     LoadVT = VT.changeTypeToInteger();
13216 
13217   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
13218   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
13219   SDValue LoadChain = SDValue(Load.getNode(), 1);
13220 
13221   if (VT.isFloatingPoint())
13222     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
13223 
13224   return DAG.getMergeValues({Load, LoadChain}, DL);
13225 }
13226 
13227 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
13228   SDLoc DL(N);
13229   SDValue Data = N->getOperand(2);
13230   EVT DataVT = Data.getValueType();
13231   EVT HwSrcVt = getSVEContainerType(DataVT);
13232   SDValue InputVT = DAG.getValueType(DataVT);
13233 
13234   if (DataVT == MVT::nxv8bf16 &&
13235       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13236     return SDValue();
13237 
13238   if (DataVT.isFloatingPoint())
13239     InputVT = DAG.getValueType(HwSrcVt);
13240 
13241   SDValue SrcNew;
13242   if (Data.getValueType().isFloatingPoint())
13243     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
13244   else
13245     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
13246 
13247   SDValue Ops[] = { N->getOperand(0), // Chain
13248                     SrcNew,
13249                     N->getOperand(4), // Base
13250                     N->getOperand(3), // Pg
13251                     InputVT
13252                   };
13253 
13254   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
13255 }
13256 
13257 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
13258   SDLoc DL(N);
13259 
13260   SDValue Data = N->getOperand(2);
13261   EVT DataVT = Data.getValueType();
13262   EVT PtrTy = N->getOperand(4).getValueType();
13263 
13264   if (DataVT == MVT::nxv8bf16 &&
13265       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13266     return SDValue();
13267 
13268   if (DataVT.isFloatingPoint())
13269     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
13270 
13271   auto *MINode = cast<MemIntrinsicSDNode>(N);
13272   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
13273                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
13274                             MINode->getMemoryVT(), MINode->getMemOperand(),
13275                             ISD::UNINDEXED, false, false);
13276 }
13277 
13278 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
13279 /// load store optimizer pass will merge them to store pair stores.  This should
13280 /// be better than a movi to create the vector zero followed by a vector store
13281 /// if the zero constant is not re-used, since one instructions and one register
13282 /// live range will be removed.
13283 ///
13284 /// For example, the final generated code should be:
13285 ///
13286 ///   stp xzr, xzr, [x0]
13287 ///
13288 /// instead of:
13289 ///
13290 ///   movi v0.2d, #0
13291 ///   str q0, [x0]
13292 ///
13293 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13294   SDValue StVal = St.getValue();
13295   EVT VT = StVal.getValueType();
13296 
13297   // Avoid scalarizing zero splat stores for scalable vectors.
13298   if (VT.isScalableVector())
13299     return SDValue();
13300 
13301   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
13302   // 2, 3 or 4 i32 elements.
13303   int NumVecElts = VT.getVectorNumElements();
13304   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
13305          VT.getVectorElementType().getSizeInBits() == 64) ||
13306         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
13307          VT.getVectorElementType().getSizeInBits() == 32)))
13308     return SDValue();
13309 
13310   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
13311     return SDValue();
13312 
13313   // If the zero constant has more than one use then the vector store could be
13314   // better since the constant mov will be amortized and stp q instructions
13315   // should be able to be formed.
13316   if (!StVal.hasOneUse())
13317     return SDValue();
13318 
13319   // If the store is truncating then it's going down to i16 or smaller, which
13320   // means it can be implemented in a single store anyway.
13321   if (St.isTruncatingStore())
13322     return SDValue();
13323 
13324   // If the immediate offset of the address operand is too large for the stp
13325   // instruction, then bail out.
13326   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
13327     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
13328     if (Offset < -512 || Offset > 504)
13329       return SDValue();
13330   }
13331 
13332   for (int I = 0; I < NumVecElts; ++I) {
13333     SDValue EltVal = StVal.getOperand(I);
13334     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
13335       return SDValue();
13336   }
13337 
13338   // Use a CopyFromReg WZR/XZR here to prevent
13339   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
13340   SDLoc DL(&St);
13341   unsigned ZeroReg;
13342   EVT ZeroVT;
13343   if (VT.getVectorElementType().getSizeInBits() == 32) {
13344     ZeroReg = AArch64::WZR;
13345     ZeroVT = MVT::i32;
13346   } else {
13347     ZeroReg = AArch64::XZR;
13348     ZeroVT = MVT::i64;
13349   }
13350   SDValue SplatVal =
13351       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
13352   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13353 }
13354 
13355 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
13356 /// value. The load store optimizer pass will merge them to store pair stores.
13357 /// This has better performance than a splat of the scalar followed by a split
13358 /// vector store. Even if the stores are not merged it is four stores vs a dup,
13359 /// followed by an ext.b and two stores.
13360 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13361   SDValue StVal = St.getValue();
13362   EVT VT = StVal.getValueType();
13363 
13364   // Don't replace floating point stores, they possibly won't be transformed to
13365   // stp because of the store pair suppress pass.
13366   if (VT.isFloatingPoint())
13367     return SDValue();
13368 
13369   // We can express a splat as store pair(s) for 2 or 4 elements.
13370   unsigned NumVecElts = VT.getVectorNumElements();
13371   if (NumVecElts != 4 && NumVecElts != 2)
13372     return SDValue();
13373 
13374   // If the store is truncating then it's going down to i16 or smaller, which
13375   // means it can be implemented in a single store anyway.
13376   if (St.isTruncatingStore())
13377     return SDValue();
13378 
13379   // Check that this is a splat.
13380   // Make sure that each of the relevant vector element locations are inserted
13381   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
13382   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
13383   SDValue SplatVal;
13384   for (unsigned I = 0; I < NumVecElts; ++I) {
13385     // Check for insert vector elements.
13386     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
13387       return SDValue();
13388 
13389     // Check that same value is inserted at each vector element.
13390     if (I == 0)
13391       SplatVal = StVal.getOperand(1);
13392     else if (StVal.getOperand(1) != SplatVal)
13393       return SDValue();
13394 
13395     // Check insert element index.
13396     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
13397     if (!CIndex)
13398       return SDValue();
13399     uint64_t IndexVal = CIndex->getZExtValue();
13400     if (IndexVal >= NumVecElts)
13401       return SDValue();
13402     IndexNotInserted.reset(IndexVal);
13403 
13404     StVal = StVal.getOperand(0);
13405   }
13406   // Check that all vector element locations were inserted to.
13407   if (IndexNotInserted.any())
13408       return SDValue();
13409 
13410   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13411 }
13412 
13413 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13414                            SelectionDAG &DAG,
13415                            const AArch64Subtarget *Subtarget) {
13416 
13417   StoreSDNode *S = cast<StoreSDNode>(N);
13418   if (S->isVolatile() || S->isIndexed())
13419     return SDValue();
13420 
13421   SDValue StVal = S->getValue();
13422   EVT VT = StVal.getValueType();
13423 
13424   if (!VT.isFixedLengthVector())
13425     return SDValue();
13426 
13427   // If we get a splat of zeros, convert this vector store to a store of
13428   // scalars. They will be merged into store pairs of xzr thereby removing one
13429   // instruction and one register.
13430   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
13431     return ReplacedZeroSplat;
13432 
13433   // FIXME: The logic for deciding if an unaligned store should be split should
13434   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
13435   // a call to that function here.
13436 
13437   if (!Subtarget->isMisaligned128StoreSlow())
13438     return SDValue();
13439 
13440   // Don't split at -Oz.
13441   if (DAG.getMachineFunction().getFunction().hasMinSize())
13442     return SDValue();
13443 
13444   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
13445   // those up regresses performance on micro-benchmarks and olden/bh.
13446   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
13447     return SDValue();
13448 
13449   // Split unaligned 16B stores. They are terrible for performance.
13450   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
13451   // extensions can use this to mark that it does not want splitting to happen
13452   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
13453   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
13454   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
13455       S->getAlignment() <= 2)
13456     return SDValue();
13457 
13458   // If we get a splat of a scalar convert this vector store to a store of
13459   // scalars. They will be merged into store pairs thereby removing two
13460   // instructions.
13461   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
13462     return ReplacedSplat;
13463 
13464   SDLoc DL(S);
13465 
13466   // Split VT into two.
13467   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13468   unsigned NumElts = HalfVT.getVectorNumElements();
13469   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13470                                    DAG.getConstant(0, DL, MVT::i64));
13471   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13472                                    DAG.getConstant(NumElts, DL, MVT::i64));
13473   SDValue BasePtr = S->getBasePtr();
13474   SDValue NewST1 =
13475       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
13476                    S->getAlignment(), S->getMemOperand()->getFlags());
13477   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13478                                   DAG.getConstant(8, DL, MVT::i64));
13479   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
13480                       S->getPointerInfo(), S->getAlignment(),
13481                       S->getMemOperand()->getFlags());
13482 }
13483 
13484 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
13485   SDLoc DL(N);
13486   SDValue Op0 = N->getOperand(0);
13487   SDValue Op1 = N->getOperand(1);
13488   EVT ResVT = N->getValueType(0);
13489 
13490   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
13491   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
13492     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13493       SDValue X = Op0.getOperand(0).getOperand(0);
13494       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
13495     }
13496   }
13497 
13498   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
13499   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
13500     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13501       SDValue Z = Op1.getOperand(0).getOperand(1);
13502       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
13503     }
13504   }
13505 
13506   return SDValue();
13507 }
13508 
13509 /// Target-specific DAG combine function for post-increment LD1 (lane) and
13510 /// post-increment LD1R.
13511 static SDValue performPostLD1Combine(SDNode *N,
13512                                      TargetLowering::DAGCombinerInfo &DCI,
13513                                      bool IsLaneOp) {
13514   if (DCI.isBeforeLegalizeOps())
13515     return SDValue();
13516 
13517   SelectionDAG &DAG = DCI.DAG;
13518   EVT VT = N->getValueType(0);
13519 
13520   if (VT.isScalableVector())
13521     return SDValue();
13522 
13523   unsigned LoadIdx = IsLaneOp ? 1 : 0;
13524   SDNode *LD = N->getOperand(LoadIdx).getNode();
13525   // If it is not LOAD, can not do such combine.
13526   if (LD->getOpcode() != ISD::LOAD)
13527     return SDValue();
13528 
13529   // The vector lane must be a constant in the LD1LANE opcode.
13530   SDValue Lane;
13531   if (IsLaneOp) {
13532     Lane = N->getOperand(2);
13533     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
13534     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
13535       return SDValue();
13536   }
13537 
13538   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
13539   EVT MemVT = LoadSDN->getMemoryVT();
13540   // Check if memory operand is the same type as the vector element.
13541   if (MemVT != VT.getVectorElementType())
13542     return SDValue();
13543 
13544   // Check if there are other uses. If so, do not combine as it will introduce
13545   // an extra load.
13546   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
13547        ++UI) {
13548     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
13549       continue;
13550     if (*UI != N)
13551       return SDValue();
13552   }
13553 
13554   SDValue Addr = LD->getOperand(1);
13555   SDValue Vector = N->getOperand(0);
13556   // Search for a use of the address operand that is an increment.
13557   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
13558        Addr.getNode()->use_end(); UI != UE; ++UI) {
13559     SDNode *User = *UI;
13560     if (User->getOpcode() != ISD::ADD
13561         || UI.getUse().getResNo() != Addr.getResNo())
13562       continue;
13563 
13564     // If the increment is a constant, it must match the memory ref size.
13565     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13566     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13567       uint32_t IncVal = CInc->getZExtValue();
13568       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
13569       if (IncVal != NumBytes)
13570         continue;
13571       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13572     }
13573 
13574     // To avoid cycle construction make sure that neither the load nor the add
13575     // are predecessors to each other or the Vector.
13576     SmallPtrSet<const SDNode *, 32> Visited;
13577     SmallVector<const SDNode *, 16> Worklist;
13578     Visited.insert(Addr.getNode());
13579     Worklist.push_back(User);
13580     Worklist.push_back(LD);
13581     Worklist.push_back(Vector.getNode());
13582     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
13583         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13584       continue;
13585 
13586     SmallVector<SDValue, 8> Ops;
13587     Ops.push_back(LD->getOperand(0));  // Chain
13588     if (IsLaneOp) {
13589       Ops.push_back(Vector);           // The vector to be inserted
13590       Ops.push_back(Lane);             // The lane to be inserted in the vector
13591     }
13592     Ops.push_back(Addr);
13593     Ops.push_back(Inc);
13594 
13595     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
13596     SDVTList SDTys = DAG.getVTList(Tys);
13597     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
13598     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
13599                                            MemVT,
13600                                            LoadSDN->getMemOperand());
13601 
13602     // Update the uses.
13603     SDValue NewResults[] = {
13604         SDValue(LD, 0),            // The result of load
13605         SDValue(UpdN.getNode(), 2) // Chain
13606     };
13607     DCI.CombineTo(LD, NewResults);
13608     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
13609     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
13610 
13611     break;
13612   }
13613   return SDValue();
13614 }
13615 
13616 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
13617 /// address translation.
13618 static bool performTBISimplification(SDValue Addr,
13619                                      TargetLowering::DAGCombinerInfo &DCI,
13620                                      SelectionDAG &DAG) {
13621   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
13622   KnownBits Known;
13623   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13624                                         !DCI.isBeforeLegalizeOps());
13625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13626   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
13627     DCI.CommitTargetLoweringOpt(TLO);
13628     return true;
13629   }
13630   return false;
13631 }
13632 
13633 static SDValue performSTORECombine(SDNode *N,
13634                                    TargetLowering::DAGCombinerInfo &DCI,
13635                                    SelectionDAG &DAG,
13636                                    const AArch64Subtarget *Subtarget) {
13637   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
13638     return Split;
13639 
13640   if (Subtarget->supportsAddressTopByteIgnored() &&
13641       performTBISimplification(N->getOperand(2), DCI, DAG))
13642     return SDValue(N, 0);
13643 
13644   return SDValue();
13645 }
13646 
13647 
13648 /// Target-specific DAG combine function for NEON load/store intrinsics
13649 /// to merge base address updates.
13650 static SDValue performNEONPostLDSTCombine(SDNode *N,
13651                                           TargetLowering::DAGCombinerInfo &DCI,
13652                                           SelectionDAG &DAG) {
13653   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13654     return SDValue();
13655 
13656   unsigned AddrOpIdx = N->getNumOperands() - 1;
13657   SDValue Addr = N->getOperand(AddrOpIdx);
13658 
13659   // Search for a use of the address operand that is an increment.
13660   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13661        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13662     SDNode *User = *UI;
13663     if (User->getOpcode() != ISD::ADD ||
13664         UI.getUse().getResNo() != Addr.getResNo())
13665       continue;
13666 
13667     // Check that the add is independent of the load/store.  Otherwise, folding
13668     // it would create a cycle.
13669     SmallPtrSet<const SDNode *, 32> Visited;
13670     SmallVector<const SDNode *, 16> Worklist;
13671     Visited.insert(Addr.getNode());
13672     Worklist.push_back(N);
13673     Worklist.push_back(User);
13674     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13675         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13676       continue;
13677 
13678     // Find the new opcode for the updating load/store.
13679     bool IsStore = false;
13680     bool IsLaneOp = false;
13681     bool IsDupOp = false;
13682     unsigned NewOpc = 0;
13683     unsigned NumVecs = 0;
13684     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13685     switch (IntNo) {
13686     default: llvm_unreachable("unexpected intrinsic for Neon base update");
13687     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
13688       NumVecs = 2; break;
13689     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
13690       NumVecs = 3; break;
13691     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
13692       NumVecs = 4; break;
13693     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
13694       NumVecs = 2; IsStore = true; break;
13695     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
13696       NumVecs = 3; IsStore = true; break;
13697     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
13698       NumVecs = 4; IsStore = true; break;
13699     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
13700       NumVecs = 2; break;
13701     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
13702       NumVecs = 3; break;
13703     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
13704       NumVecs = 4; break;
13705     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
13706       NumVecs = 2; IsStore = true; break;
13707     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
13708       NumVecs = 3; IsStore = true; break;
13709     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
13710       NumVecs = 4; IsStore = true; break;
13711     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
13712       NumVecs = 2; IsDupOp = true; break;
13713     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
13714       NumVecs = 3; IsDupOp = true; break;
13715     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
13716       NumVecs = 4; IsDupOp = true; break;
13717     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
13718       NumVecs = 2; IsLaneOp = true; break;
13719     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
13720       NumVecs = 3; IsLaneOp = true; break;
13721     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
13722       NumVecs = 4; IsLaneOp = true; break;
13723     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
13724       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
13725     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
13726       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
13727     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
13728       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
13729     }
13730 
13731     EVT VecTy;
13732     if (IsStore)
13733       VecTy = N->getOperand(2).getValueType();
13734     else
13735       VecTy = N->getValueType(0);
13736 
13737     // If the increment is a constant, it must match the memory ref size.
13738     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13739     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13740       uint32_t IncVal = CInc->getZExtValue();
13741       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13742       if (IsLaneOp || IsDupOp)
13743         NumBytes /= VecTy.getVectorNumElements();
13744       if (IncVal != NumBytes)
13745         continue;
13746       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13747     }
13748     SmallVector<SDValue, 8> Ops;
13749     Ops.push_back(N->getOperand(0)); // Incoming chain
13750     // Load lane and store have vector list as input.
13751     if (IsLaneOp || IsStore)
13752       for (unsigned i = 2; i < AddrOpIdx; ++i)
13753         Ops.push_back(N->getOperand(i));
13754     Ops.push_back(Addr); // Base register
13755     Ops.push_back(Inc);
13756 
13757     // Return Types.
13758     EVT Tys[6];
13759     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
13760     unsigned n;
13761     for (n = 0; n < NumResultVecs; ++n)
13762       Tys[n] = VecTy;
13763     Tys[n++] = MVT::i64;  // Type of write back register
13764     Tys[n] = MVT::Other;  // Type of the chain
13765     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13766 
13767     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
13768     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
13769                                            MemInt->getMemoryVT(),
13770                                            MemInt->getMemOperand());
13771 
13772     // Update the uses.
13773     std::vector<SDValue> NewResults;
13774     for (unsigned i = 0; i < NumResultVecs; ++i) {
13775       NewResults.push_back(SDValue(UpdN.getNode(), i));
13776     }
13777     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
13778     DCI.CombineTo(N, NewResults);
13779     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13780 
13781     break;
13782   }
13783   return SDValue();
13784 }
13785 
13786 // Checks to see if the value is the prescribed width and returns information
13787 // about its extension mode.
13788 static
13789 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
13790   ExtType = ISD::NON_EXTLOAD;
13791   switch(V.getNode()->getOpcode()) {
13792   default:
13793     return false;
13794   case ISD::LOAD: {
13795     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
13796     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
13797        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
13798       ExtType = LoadNode->getExtensionType();
13799       return true;
13800     }
13801     return false;
13802   }
13803   case ISD::AssertSext: {
13804     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13805     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13806        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13807       ExtType = ISD::SEXTLOAD;
13808       return true;
13809     }
13810     return false;
13811   }
13812   case ISD::AssertZext: {
13813     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13814     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13815        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13816       ExtType = ISD::ZEXTLOAD;
13817       return true;
13818     }
13819     return false;
13820   }
13821   case ISD::Constant:
13822   case ISD::TargetConstant: {
13823     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
13824            1LL << (width - 1);
13825   }
13826   }
13827 
13828   return true;
13829 }
13830 
13831 // This function does a whole lot of voodoo to determine if the tests are
13832 // equivalent without and with a mask. Essentially what happens is that given a
13833 // DAG resembling:
13834 //
13835 //  +-------------+ +-------------+ +-------------+ +-------------+
13836 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
13837 //  +-------------+ +-------------+ +-------------+ +-------------+
13838 //           |           |           |               |
13839 //           V           V           |    +----------+
13840 //          +-------------+  +----+  |    |
13841 //          |     ADD     |  |0xff|  |    |
13842 //          +-------------+  +----+  |    |
13843 //                  |           |    |    |
13844 //                  V           V    |    |
13845 //                 +-------------+   |    |
13846 //                 |     AND     |   |    |
13847 //                 +-------------+   |    |
13848 //                      |            |    |
13849 //                      +-----+      |    |
13850 //                            |      |    |
13851 //                            V      V    V
13852 //                           +-------------+
13853 //                           |     CMP     |
13854 //                           +-------------+
13855 //
13856 // The AND node may be safely removed for some combinations of inputs. In
13857 // particular we need to take into account the extension type of the Input,
13858 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
13859 // width of the input (this can work for any width inputs, the above graph is
13860 // specific to 8 bits.
13861 //
13862 // The specific equations were worked out by generating output tables for each
13863 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
13864 // problem was simplified by working with 4 bit inputs, which means we only
13865 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
13866 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
13867 // patterns present in both extensions (0,7). For every distinct set of
13868 // AddConstant and CompConstants bit patterns we can consider the masked and
13869 // unmasked versions to be equivalent if the result of this function is true for
13870 // all 16 distinct bit patterns of for the current extension type of Input (w0).
13871 //
13872 //   sub      w8, w0, w1
13873 //   and      w10, w8, #0x0f
13874 //   cmp      w8, w2
13875 //   cset     w9, AArch64CC
13876 //   cmp      w10, w2
13877 //   cset     w11, AArch64CC
13878 //   cmp      w9, w11
13879 //   cset     w0, eq
13880 //   ret
13881 //
13882 // Since the above function shows when the outputs are equivalent it defines
13883 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
13884 // would be expensive to run during compiles. The equations below were written
13885 // in a test harness that confirmed they gave equivalent outputs to the above
13886 // for all inputs function, so they can be used determine if the removal is
13887 // legal instead.
13888 //
13889 // isEquivalentMaskless() is the code for testing if the AND can be removed
13890 // factored out of the DAG recognition as the DAG can take several forms.
13891 
13892 static bool isEquivalentMaskless(unsigned CC, unsigned width,
13893                                  ISD::LoadExtType ExtType, int AddConstant,
13894                                  int CompConstant) {
13895   // By being careful about our equations and only writing the in term
13896   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
13897   // make them generally applicable to all bit widths.
13898   int MaxUInt = (1 << width);
13899 
13900   // For the purposes of these comparisons sign extending the type is
13901   // equivalent to zero extending the add and displacing it by half the integer
13902   // width. Provided we are careful and make sure our equations are valid over
13903   // the whole range we can just adjust the input and avoid writing equations
13904   // for sign extended inputs.
13905   if (ExtType == ISD::SEXTLOAD)
13906     AddConstant -= (1 << (width-1));
13907 
13908   switch(CC) {
13909   case AArch64CC::LE:
13910   case AArch64CC::GT:
13911     if ((AddConstant == 0) ||
13912         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
13913         (AddConstant >= 0 && CompConstant < 0) ||
13914         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
13915       return true;
13916     break;
13917   case AArch64CC::LT:
13918   case AArch64CC::GE:
13919     if ((AddConstant == 0) ||
13920         (AddConstant >= 0 && CompConstant <= 0) ||
13921         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
13922       return true;
13923     break;
13924   case AArch64CC::HI:
13925   case AArch64CC::LS:
13926     if ((AddConstant >= 0 && CompConstant < 0) ||
13927        (AddConstant <= 0 && CompConstant >= -1 &&
13928         CompConstant < AddConstant + MaxUInt))
13929       return true;
13930    break;
13931   case AArch64CC::PL:
13932   case AArch64CC::MI:
13933     if ((AddConstant == 0) ||
13934         (AddConstant > 0 && CompConstant <= 0) ||
13935         (AddConstant < 0 && CompConstant <= AddConstant))
13936       return true;
13937     break;
13938   case AArch64CC::LO:
13939   case AArch64CC::HS:
13940     if ((AddConstant >= 0 && CompConstant <= 0) ||
13941         (AddConstant <= 0 && CompConstant >= 0 &&
13942          CompConstant <= AddConstant + MaxUInt))
13943       return true;
13944     break;
13945   case AArch64CC::EQ:
13946   case AArch64CC::NE:
13947     if ((AddConstant > 0 && CompConstant < 0) ||
13948         (AddConstant < 0 && CompConstant >= 0 &&
13949          CompConstant < AddConstant + MaxUInt) ||
13950         (AddConstant >= 0 && CompConstant >= 0 &&
13951          CompConstant >= AddConstant) ||
13952         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13953       return true;
13954     break;
13955   case AArch64CC::VS:
13956   case AArch64CC::VC:
13957   case AArch64CC::AL:
13958   case AArch64CC::NV:
13959     return true;
13960   case AArch64CC::Invalid:
13961     break;
13962   }
13963 
13964   return false;
13965 }
13966 
13967 static
13968 SDValue performCONDCombine(SDNode *N,
13969                            TargetLowering::DAGCombinerInfo &DCI,
13970                            SelectionDAG &DAG, unsigned CCIndex,
13971                            unsigned CmpIndex) {
13972   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13973   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13974   unsigned CondOpcode = SubsNode->getOpcode();
13975 
13976   if (CondOpcode != AArch64ISD::SUBS)
13977     return SDValue();
13978 
13979   // There is a SUBS feeding this condition. Is it fed by a mask we can
13980   // use?
13981 
13982   SDNode *AndNode = SubsNode->getOperand(0).getNode();
13983   unsigned MaskBits = 0;
13984 
13985   if (AndNode->getOpcode() != ISD::AND)
13986     return SDValue();
13987 
13988   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13989     uint32_t CNV = CN->getZExtValue();
13990     if (CNV == 255)
13991       MaskBits = 8;
13992     else if (CNV == 65535)
13993       MaskBits = 16;
13994   }
13995 
13996   if (!MaskBits)
13997     return SDValue();
13998 
13999   SDValue AddValue = AndNode->getOperand(0);
14000 
14001   if (AddValue.getOpcode() != ISD::ADD)
14002     return SDValue();
14003 
14004   // The basic dag structure is correct, grab the inputs and validate them.
14005 
14006   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
14007   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
14008   SDValue SubsInputValue = SubsNode->getOperand(1);
14009 
14010   // The mask is present and the provenance of all the values is a smaller type,
14011   // lets see if the mask is superfluous.
14012 
14013   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
14014       !isa<ConstantSDNode>(SubsInputValue.getNode()))
14015     return SDValue();
14016 
14017   ISD::LoadExtType ExtType;
14018 
14019   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
14020       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
14021       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
14022     return SDValue();
14023 
14024   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
14025                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
14026                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
14027     return SDValue();
14028 
14029   // The AND is not necessary, remove it.
14030 
14031   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
14032                                SubsNode->getValueType(1));
14033   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
14034 
14035   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
14036   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
14037 
14038   return SDValue(N, 0);
14039 }
14040 
14041 // Optimize compare with zero and branch.
14042 static SDValue performBRCONDCombine(SDNode *N,
14043                                     TargetLowering::DAGCombinerInfo &DCI,
14044                                     SelectionDAG &DAG) {
14045   MachineFunction &MF = DAG.getMachineFunction();
14046   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
14047   // will not be produced, as they are conditional branch instructions that do
14048   // not set flags.
14049   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
14050     return SDValue();
14051 
14052   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
14053     N = NV.getNode();
14054   SDValue Chain = N->getOperand(0);
14055   SDValue Dest = N->getOperand(1);
14056   SDValue CCVal = N->getOperand(2);
14057   SDValue Cmp = N->getOperand(3);
14058 
14059   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
14060   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
14061   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
14062     return SDValue();
14063 
14064   unsigned CmpOpc = Cmp.getOpcode();
14065   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
14066     return SDValue();
14067 
14068   // Only attempt folding if there is only one use of the flag and no use of the
14069   // value.
14070   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
14071     return SDValue();
14072 
14073   SDValue LHS = Cmp.getOperand(0);
14074   SDValue RHS = Cmp.getOperand(1);
14075 
14076   assert(LHS.getValueType() == RHS.getValueType() &&
14077          "Expected the value type to be the same for both operands!");
14078   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
14079     return SDValue();
14080 
14081   if (isNullConstant(LHS))
14082     std::swap(LHS, RHS);
14083 
14084   if (!isNullConstant(RHS))
14085     return SDValue();
14086 
14087   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
14088       LHS.getOpcode() == ISD::SRL)
14089     return SDValue();
14090 
14091   // Fold the compare into the branch instruction.
14092   SDValue BR;
14093   if (CC == AArch64CC::EQ)
14094     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14095   else
14096     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14097 
14098   // Do not add new nodes to DAG combiner worklist.
14099   DCI.CombineTo(N, BR, false);
14100 
14101   return SDValue();
14102 }
14103 
14104 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
14105 // as well as whether the test should be inverted.  This code is required to
14106 // catch these cases (as opposed to standard dag combines) because
14107 // AArch64ISD::TBZ is matched during legalization.
14108 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
14109                                  SelectionDAG &DAG) {
14110 
14111   if (!Op->hasOneUse())
14112     return Op;
14113 
14114   // We don't handle undef/constant-fold cases below, as they should have
14115   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
14116   // etc.)
14117 
14118   // (tbz (trunc x), b) -> (tbz x, b)
14119   // This case is just here to enable more of the below cases to be caught.
14120   if (Op->getOpcode() == ISD::TRUNCATE &&
14121       Bit < Op->getValueType(0).getSizeInBits()) {
14122     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14123   }
14124 
14125   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
14126   if (Op->getOpcode() == ISD::ANY_EXTEND &&
14127       Bit < Op->getOperand(0).getValueSizeInBits()) {
14128     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14129   }
14130 
14131   if (Op->getNumOperands() != 2)
14132     return Op;
14133 
14134   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14135   if (!C)
14136     return Op;
14137 
14138   switch (Op->getOpcode()) {
14139   default:
14140     return Op;
14141 
14142   // (tbz (and x, m), b) -> (tbz x, b)
14143   case ISD::AND:
14144     if ((C->getZExtValue() >> Bit) & 1)
14145       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14146     return Op;
14147 
14148   // (tbz (shl x, c), b) -> (tbz x, b-c)
14149   case ISD::SHL:
14150     if (C->getZExtValue() <= Bit &&
14151         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14152       Bit = Bit - C->getZExtValue();
14153       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14154     }
14155     return Op;
14156 
14157   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
14158   case ISD::SRA:
14159     Bit = Bit + C->getZExtValue();
14160     if (Bit >= Op->getValueType(0).getSizeInBits())
14161       Bit = Op->getValueType(0).getSizeInBits() - 1;
14162     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14163 
14164   // (tbz (srl x, c), b) -> (tbz x, b+c)
14165   case ISD::SRL:
14166     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14167       Bit = Bit + C->getZExtValue();
14168       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14169     }
14170     return Op;
14171 
14172   // (tbz (xor x, -1), b) -> (tbnz x, b)
14173   case ISD::XOR:
14174     if ((C->getZExtValue() >> Bit) & 1)
14175       Invert = !Invert;
14176     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14177   }
14178 }
14179 
14180 // Optimize test single bit zero/non-zero and branch.
14181 static SDValue performTBZCombine(SDNode *N,
14182                                  TargetLowering::DAGCombinerInfo &DCI,
14183                                  SelectionDAG &DAG) {
14184   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14185   bool Invert = false;
14186   SDValue TestSrc = N->getOperand(1);
14187   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
14188 
14189   if (TestSrc == NewTestSrc)
14190     return SDValue();
14191 
14192   unsigned NewOpc = N->getOpcode();
14193   if (Invert) {
14194     if (NewOpc == AArch64ISD::TBZ)
14195       NewOpc = AArch64ISD::TBNZ;
14196     else {
14197       assert(NewOpc == AArch64ISD::TBNZ);
14198       NewOpc = AArch64ISD::TBZ;
14199     }
14200   }
14201 
14202   SDLoc DL(N);
14203   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
14204                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
14205 }
14206 
14207 // vselect (v1i1 setcc) ->
14208 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
14209 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
14210 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
14211 // such VSELECT.
14212 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
14213   SDValue N0 = N->getOperand(0);
14214   EVT CCVT = N0.getValueType();
14215 
14216   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
14217       CCVT.getVectorElementType() != MVT::i1)
14218     return SDValue();
14219 
14220   EVT ResVT = N->getValueType(0);
14221   EVT CmpVT = N0.getOperand(0).getValueType();
14222   // Only combine when the result type is of the same size as the compared
14223   // operands.
14224   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
14225     return SDValue();
14226 
14227   SDValue IfTrue = N->getOperand(1);
14228   SDValue IfFalse = N->getOperand(2);
14229   SDValue SetCC =
14230       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
14231                    N0.getOperand(0), N0.getOperand(1),
14232                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
14233   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
14234                      IfTrue, IfFalse);
14235 }
14236 
14237 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
14238 /// the compare-mask instructions rather than going via NZCV, even if LHS and
14239 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
14240 /// with a vector one followed by a DUP shuffle on the result.
14241 static SDValue performSelectCombine(SDNode *N,
14242                                     TargetLowering::DAGCombinerInfo &DCI) {
14243   SelectionDAG &DAG = DCI.DAG;
14244   SDValue N0 = N->getOperand(0);
14245   EVT ResVT = N->getValueType(0);
14246 
14247   if (N0.getOpcode() != ISD::SETCC)
14248     return SDValue();
14249 
14250   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
14251   // scalar SetCCResultType. We also don't expect vectors, because we assume
14252   // that selects fed by vector SETCCs are canonicalized to VSELECT.
14253   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
14254          "Scalar-SETCC feeding SELECT has unexpected result type!");
14255 
14256   // If NumMaskElts == 0, the comparison is larger than select result. The
14257   // largest real NEON comparison is 64-bits per lane, which means the result is
14258   // at most 32-bits and an illegal vector. Just bail out for now.
14259   EVT SrcVT = N0.getOperand(0).getValueType();
14260 
14261   // Don't try to do this optimization when the setcc itself has i1 operands.
14262   // There are no legal vectors of i1, so this would be pointless.
14263   if (SrcVT == MVT::i1)
14264     return SDValue();
14265 
14266   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
14267   if (!ResVT.isVector() || NumMaskElts == 0)
14268     return SDValue();
14269 
14270   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
14271   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
14272 
14273   // Also bail out if the vector CCVT isn't the same size as ResVT.
14274   // This can happen if the SETCC operand size doesn't divide the ResVT size
14275   // (e.g., f64 vs v3f32).
14276   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
14277     return SDValue();
14278 
14279   // Make sure we didn't create illegal types, if we're not supposed to.
14280   assert(DCI.isBeforeLegalize() ||
14281          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
14282 
14283   // First perform a vector comparison, where lane 0 is the one we're interested
14284   // in.
14285   SDLoc DL(N0);
14286   SDValue LHS =
14287       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
14288   SDValue RHS =
14289       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
14290   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
14291 
14292   // Now duplicate the comparison mask we want across all other lanes.
14293   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
14294   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
14295   Mask = DAG.getNode(ISD::BITCAST, DL,
14296                      ResVT.changeVectorElementTypeToInteger(), Mask);
14297 
14298   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
14299 }
14300 
14301 /// Get rid of unnecessary NVCASTs (that don't change the type).
14302 static SDValue performNVCASTCombine(SDNode *N) {
14303   if (N->getValueType(0) == N->getOperand(0).getValueType())
14304     return N->getOperand(0);
14305 
14306   return SDValue();
14307 }
14308 
14309 // If all users of the globaladdr are of the form (globaladdr + constant), find
14310 // the smallest constant, fold it into the globaladdr's offset and rewrite the
14311 // globaladdr as (globaladdr + constant) - constant.
14312 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
14313                                            const AArch64Subtarget *Subtarget,
14314                                            const TargetMachine &TM) {
14315   auto *GN = cast<GlobalAddressSDNode>(N);
14316   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
14317       AArch64II::MO_NO_FLAG)
14318     return SDValue();
14319 
14320   uint64_t MinOffset = -1ull;
14321   for (SDNode *N : GN->uses()) {
14322     if (N->getOpcode() != ISD::ADD)
14323       return SDValue();
14324     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
14325     if (!C)
14326       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14327     if (!C)
14328       return SDValue();
14329     MinOffset = std::min(MinOffset, C->getZExtValue());
14330   }
14331   uint64_t Offset = MinOffset + GN->getOffset();
14332 
14333   // Require that the new offset is larger than the existing one. Otherwise, we
14334   // can end up oscillating between two possible DAGs, for example,
14335   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
14336   if (Offset <= uint64_t(GN->getOffset()))
14337     return SDValue();
14338 
14339   // Check whether folding this offset is legal. It must not go out of bounds of
14340   // the referenced object to avoid violating the code model, and must be
14341   // smaller than 2^21 because this is the largest offset expressible in all
14342   // object formats.
14343   //
14344   // This check also prevents us from folding negative offsets, which will end
14345   // up being treated in the same way as large positive ones. They could also
14346   // cause code model violations, and aren't really common enough to matter.
14347   if (Offset >= (1 << 21))
14348     return SDValue();
14349 
14350   const GlobalValue *GV = GN->getGlobal();
14351   Type *T = GV->getValueType();
14352   if (!T->isSized() ||
14353       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
14354     return SDValue();
14355 
14356   SDLoc DL(GN);
14357   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
14358   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
14359                      DAG.getConstant(MinOffset, DL, MVT::i64));
14360 }
14361 
14362 // Turns the vector of indices into a vector of byte offstes by scaling Offset
14363 // by (BitWidth / 8).
14364 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
14365                                           SDLoc DL, unsigned BitWidth) {
14366   assert(Offset.getValueType().isScalableVector() &&
14367          "This method is only for scalable vectors of offsets");
14368 
14369   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
14370   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
14371 
14372   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
14373 }
14374 
14375 /// Check if the value of \p OffsetInBytes can be used as an immediate for
14376 /// the gather load/prefetch and scatter store instructions with vector base and
14377 /// immediate offset addressing mode:
14378 ///
14379 ///      [<Zn>.[S|D]{, #<imm>}]
14380 ///
14381 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
14382 
14383 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
14384                                                   unsigned ScalarSizeInBytes) {
14385   // The immediate is not a multiple of the scalar size.
14386   if (OffsetInBytes % ScalarSizeInBytes)
14387     return false;
14388 
14389   // The immediate is out of range.
14390   if (OffsetInBytes / ScalarSizeInBytes > 31)
14391     return false;
14392 
14393   return true;
14394 }
14395 
14396 /// Check if the value of \p Offset represents a valid immediate for the SVE
14397 /// gather load/prefetch and scatter store instructiona with vector base and
14398 /// immediate offset addressing mode:
14399 ///
14400 ///      [<Zn>.[S|D]{, #<imm>}]
14401 ///
14402 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
14403 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
14404                                            unsigned ScalarSizeInBytes) {
14405   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
14406   return OffsetConst && isValidImmForSVEVecImmAddrMode(
14407                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
14408 }
14409 
14410 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
14411                                           unsigned Opcode,
14412                                           bool OnlyPackedOffsets = true) {
14413   const SDValue Src = N->getOperand(2);
14414   const EVT SrcVT = Src->getValueType(0);
14415   assert(SrcVT.isScalableVector() &&
14416          "Scatter stores are only possible for SVE vectors");
14417 
14418   SDLoc DL(N);
14419   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
14420 
14421   // Make sure that source data will fit into an SVE register
14422   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14423     return SDValue();
14424 
14425   // For FPs, ACLE only supports _packed_ single and double precision types.
14426   if (SrcElVT.isFloatingPoint())
14427     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
14428       return SDValue();
14429 
14430   // Depending on the addressing mode, this is either a pointer or a vector of
14431   // pointers (that fits into one register)
14432   SDValue Base = N->getOperand(4);
14433   // Depending on the addressing mode, this is either a single offset or a
14434   // vector of offsets  (that fits into one register)
14435   SDValue Offset = N->getOperand(5);
14436 
14437   // For "scalar + vector of indices", just scale the indices. This only
14438   // applies to non-temporal scatters because there's no instruction that takes
14439   // indicies.
14440   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
14441     Offset =
14442         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
14443     Opcode = AArch64ISD::SSTNT1_PRED;
14444   }
14445 
14446   // In the case of non-temporal gather loads there's only one SVE instruction
14447   // per data-size: "scalar + vector", i.e.
14448   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14449   // Since we do have intrinsics that allow the arguments to be in a different
14450   // order, we may need to swap them to match the spec.
14451   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
14452     std::swap(Base, Offset);
14453 
14454   // SST1_IMM requires that the offset is an immediate that is:
14455   //    * a multiple of #SizeInBytes,
14456   //    * in the range [0, 31 x #SizeInBytes],
14457   // where #SizeInBytes is the size in bytes of the stored items. For
14458   // immediates outside that range and non-immediate scalar offsets use SST1 or
14459   // SST1_UXTW instead.
14460   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
14461     if (!isValidImmForSVEVecImmAddrMode(Offset,
14462                                         SrcVT.getScalarSizeInBits() / 8)) {
14463       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14464         Opcode = AArch64ISD::SST1_UXTW_PRED;
14465       else
14466         Opcode = AArch64ISD::SST1_PRED;
14467 
14468       std::swap(Base, Offset);
14469     }
14470   }
14471 
14472   auto &TLI = DAG.getTargetLoweringInfo();
14473   if (!TLI.isTypeLegal(Base.getValueType()))
14474     return SDValue();
14475 
14476   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
14477   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14478   // nxv2i64. Legalize accordingly.
14479   if (!OnlyPackedOffsets &&
14480       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14481     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14482 
14483   if (!TLI.isTypeLegal(Offset.getValueType()))
14484     return SDValue();
14485 
14486   // Source value type that is representable in hardware
14487   EVT HwSrcVt = getSVEContainerType(SrcVT);
14488 
14489   // Keep the original type of the input data to store - this is needed to be
14490   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
14491   // FP values we want the integer equivalent, so just use HwSrcVt.
14492   SDValue InputVT = DAG.getValueType(SrcVT);
14493   if (SrcVT.isFloatingPoint())
14494     InputVT = DAG.getValueType(HwSrcVt);
14495 
14496   SDVTList VTs = DAG.getVTList(MVT::Other);
14497   SDValue SrcNew;
14498 
14499   if (Src.getValueType().isFloatingPoint())
14500     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
14501   else
14502     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
14503 
14504   SDValue Ops[] = {N->getOperand(0), // Chain
14505                    SrcNew,
14506                    N->getOperand(3), // Pg
14507                    Base,
14508                    Offset,
14509                    InputVT};
14510 
14511   return DAG.getNode(Opcode, DL, VTs, Ops);
14512 }
14513 
14514 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
14515                                         unsigned Opcode,
14516                                         bool OnlyPackedOffsets = true) {
14517   const EVT RetVT = N->getValueType(0);
14518   assert(RetVT.isScalableVector() &&
14519          "Gather loads are only possible for SVE vectors");
14520 
14521   SDLoc DL(N);
14522 
14523   // Make sure that the loaded data will fit into an SVE register
14524   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14525     return SDValue();
14526 
14527   // Depending on the addressing mode, this is either a pointer or a vector of
14528   // pointers (that fits into one register)
14529   SDValue Base = N->getOperand(3);
14530   // Depending on the addressing mode, this is either a single offset or a
14531   // vector of offsets  (that fits into one register)
14532   SDValue Offset = N->getOperand(4);
14533 
14534   // For "scalar + vector of indices", just scale the indices. This only
14535   // applies to non-temporal gathers because there's no instruction that takes
14536   // indicies.
14537   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
14538     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
14539                                         RetVT.getScalarSizeInBits());
14540     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
14541   }
14542 
14543   // In the case of non-temporal gather loads there's only one SVE instruction
14544   // per data-size: "scalar + vector", i.e.
14545   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14546   // Since we do have intrinsics that allow the arguments to be in a different
14547   // order, we may need to swap them to match the spec.
14548   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
14549       Offset.getValueType().isVector())
14550     std::swap(Base, Offset);
14551 
14552   // GLD{FF}1_IMM requires that the offset is an immediate that is:
14553   //    * a multiple of #SizeInBytes,
14554   //    * in the range [0, 31 x #SizeInBytes],
14555   // where #SizeInBytes is the size in bytes of the loaded items. For
14556   // immediates outside that range and non-immediate scalar offsets use
14557   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
14558   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
14559       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
14560     if (!isValidImmForSVEVecImmAddrMode(Offset,
14561                                         RetVT.getScalarSizeInBits() / 8)) {
14562       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14563         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14564                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
14565                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
14566       else
14567         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14568                      ? AArch64ISD::GLD1_MERGE_ZERO
14569                      : AArch64ISD::GLDFF1_MERGE_ZERO;
14570 
14571       std::swap(Base, Offset);
14572     }
14573   }
14574 
14575   auto &TLI = DAG.getTargetLoweringInfo();
14576   if (!TLI.isTypeLegal(Base.getValueType()))
14577     return SDValue();
14578 
14579   // Some gather load variants allow unpacked offsets, but only as nxv2i32
14580   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14581   // nxv2i64. Legalize accordingly.
14582   if (!OnlyPackedOffsets &&
14583       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14584     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14585 
14586   // Return value type that is representable in hardware
14587   EVT HwRetVt = getSVEContainerType(RetVT);
14588 
14589   // Keep the original output value type around - this is needed to be able to
14590   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
14591   // values we want the integer equivalent, so just use HwRetVT.
14592   SDValue OutVT = DAG.getValueType(RetVT);
14593   if (RetVT.isFloatingPoint())
14594     OutVT = DAG.getValueType(HwRetVt);
14595 
14596   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
14597   SDValue Ops[] = {N->getOperand(0), // Chain
14598                    N->getOperand(2), // Pg
14599                    Base, Offset, OutVT};
14600 
14601   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
14602   SDValue LoadChain = SDValue(Load.getNode(), 1);
14603 
14604   if (RetVT.isInteger() && (RetVT != HwRetVt))
14605     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
14606 
14607   // If the original return value was FP, bitcast accordingly. Doing it here
14608   // means that we can avoid adding TableGen patterns for FPs.
14609   if (RetVT.isFloatingPoint())
14610     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
14611 
14612   return DAG.getMergeValues({Load, LoadChain}, DL);
14613 }
14614 
14615 static SDValue
14616 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14617                               SelectionDAG &DAG) {
14618   if (DCI.isBeforeLegalizeOps())
14619     return SDValue();
14620 
14621   SDLoc DL(N);
14622   SDValue Src = N->getOperand(0);
14623   unsigned Opc = Src->getOpcode();
14624 
14625   // Sign extend of an unsigned unpack -> signed unpack
14626   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
14627 
14628     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
14629                                                : AArch64ISD::SUNPKLO;
14630 
14631     // Push the sign extend to the operand of the unpack
14632     // This is necessary where, for example, the operand of the unpack
14633     // is another unpack:
14634     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
14635     // ->
14636     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
14637     // ->
14638     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
14639     SDValue ExtOp = Src->getOperand(0);
14640     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
14641     EVT EltTy = VT.getVectorElementType();
14642     (void)EltTy;
14643 
14644     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
14645            "Sign extending from an invalid type");
14646 
14647     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
14648 
14649     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
14650                               ExtOp, DAG.getValueType(ExtVT));
14651 
14652     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
14653   }
14654 
14655   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
14656   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
14657   unsigned NewOpc;
14658   unsigned MemVTOpNum = 4;
14659   switch (Opc) {
14660   case AArch64ISD::LD1_MERGE_ZERO:
14661     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
14662     MemVTOpNum = 3;
14663     break;
14664   case AArch64ISD::LDNF1_MERGE_ZERO:
14665     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
14666     MemVTOpNum = 3;
14667     break;
14668   case AArch64ISD::LDFF1_MERGE_ZERO:
14669     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
14670     MemVTOpNum = 3;
14671     break;
14672   case AArch64ISD::GLD1_MERGE_ZERO:
14673     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
14674     break;
14675   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
14676     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
14677     break;
14678   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
14679     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
14680     break;
14681   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
14682     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
14683     break;
14684   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
14685     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
14686     break;
14687   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
14688     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
14689     break;
14690   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
14691     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
14692     break;
14693   case AArch64ISD::GLDFF1_MERGE_ZERO:
14694     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
14695     break;
14696   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
14697     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
14698     break;
14699   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
14700     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
14701     break;
14702   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
14703     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
14704     break;
14705   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
14706     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
14707     break;
14708   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
14709     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
14710     break;
14711   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
14712     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
14713     break;
14714   case AArch64ISD::GLDNT1_MERGE_ZERO:
14715     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
14716     break;
14717   default:
14718     return SDValue();
14719   }
14720 
14721   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
14722   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
14723 
14724   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
14725     return SDValue();
14726 
14727   EVT DstVT = N->getValueType(0);
14728   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
14729 
14730   SmallVector<SDValue, 5> Ops;
14731   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
14732     Ops.push_back(Src->getOperand(I));
14733 
14734   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
14735   DCI.CombineTo(N, ExtLoad);
14736   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
14737 
14738   // Return N so it doesn't get rechecked
14739   return SDValue(N, 0);
14740 }
14741 
14742 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
14743 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
14744 /// != nxv2i32) do not need legalization.
14745 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
14746   const unsigned OffsetPos = 4;
14747   SDValue Offset = N->getOperand(OffsetPos);
14748 
14749   // Not an unpacked vector, bail out.
14750   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
14751     return SDValue();
14752 
14753   // Extend the unpacked offset vector to 64-bit lanes.
14754   SDLoc DL(N);
14755   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
14756   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14757   // Replace the offset operand with the 64-bit one.
14758   Ops[OffsetPos] = Offset;
14759 
14760   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14761 }
14762 
14763 /// Combines a node carrying the intrinsic
14764 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
14765 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
14766 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
14767 /// sve gather prefetch instruction with vector plus immediate addressing mode.
14768 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
14769                                                unsigned ScalarSizeInBytes) {
14770   const unsigned ImmPos = 4, OffsetPos = 3;
14771   // No need to combine the node if the immediate is valid...
14772   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
14773     return SDValue();
14774 
14775   // ...otherwise swap the offset base with the offset...
14776   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14777   std::swap(Ops[ImmPos], Ops[OffsetPos]);
14778   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
14779   // `aarch64_sve_prfb_gather_uxtw_index`.
14780   SDLoc DL(N);
14781   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
14782                            MVT::i64);
14783 
14784   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14785 }
14786 
14787 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
14788                                                  DAGCombinerInfo &DCI) const {
14789   SelectionDAG &DAG = DCI.DAG;
14790   switch (N->getOpcode()) {
14791   default:
14792     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
14793     break;
14794   case ISD::ABS:
14795     return performABSCombine(N, DAG, DCI, Subtarget);
14796   case ISD::ADD:
14797   case ISD::SUB:
14798     return performAddSubCombine(N, DCI, DAG);
14799   case ISD::XOR:
14800     return performXorCombine(N, DAG, DCI, Subtarget);
14801   case ISD::MUL:
14802     return performMulCombine(N, DAG, DCI, Subtarget);
14803   case ISD::SINT_TO_FP:
14804   case ISD::UINT_TO_FP:
14805     return performIntToFpCombine(N, DAG, Subtarget);
14806   case ISD::FP_TO_SINT:
14807   case ISD::FP_TO_UINT:
14808     return performFpToIntCombine(N, DAG, DCI, Subtarget);
14809   case ISD::FDIV:
14810     return performFDivCombine(N, DAG, DCI, Subtarget);
14811   case ISD::OR:
14812     return performORCombine(N, DCI, Subtarget);
14813   case ISD::AND:
14814     return performANDCombine(N, DCI);
14815   case ISD::SRL:
14816     return performSRLCombine(N, DCI);
14817   case ISD::INTRINSIC_WO_CHAIN:
14818     return performIntrinsicCombine(N, DCI, Subtarget);
14819   case ISD::ANY_EXTEND:
14820   case ISD::ZERO_EXTEND:
14821   case ISD::SIGN_EXTEND:
14822     return performExtendCombine(N, DCI, DAG);
14823   case ISD::SIGN_EXTEND_INREG:
14824     return performSignExtendInRegCombine(N, DCI, DAG);
14825   case ISD::TRUNCATE:
14826     return performVectorTruncateCombine(N, DCI, DAG);
14827   case ISD::CONCAT_VECTORS:
14828     return performConcatVectorsCombine(N, DCI, DAG);
14829   case ISD::SELECT:
14830     return performSelectCombine(N, DCI);
14831   case ISD::VSELECT:
14832     return performVSelectCombine(N, DCI.DAG);
14833   case ISD::LOAD:
14834     if (performTBISimplification(N->getOperand(1), DCI, DAG))
14835       return SDValue(N, 0);
14836     break;
14837   case ISD::STORE:
14838     return performSTORECombine(N, DCI, DAG, Subtarget);
14839   case AArch64ISD::BRCOND:
14840     return performBRCONDCombine(N, DCI, DAG);
14841   case AArch64ISD::TBNZ:
14842   case AArch64ISD::TBZ:
14843     return performTBZCombine(N, DCI, DAG);
14844   case AArch64ISD::CSEL:
14845     return performCONDCombine(N, DCI, DAG, 2, 3);
14846   case AArch64ISD::DUP:
14847     return performPostLD1Combine(N, DCI, false);
14848   case AArch64ISD::NVCAST:
14849     return performNVCASTCombine(N);
14850   case AArch64ISD::UZP1:
14851     return performUzpCombine(N, DAG);
14852   case ISD::INSERT_VECTOR_ELT:
14853     return performPostLD1Combine(N, DCI, true);
14854   case ISD::EXTRACT_VECTOR_ELT:
14855     return performExtractVectorEltCombine(N, DAG);
14856   case ISD::VECREDUCE_ADD:
14857     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
14858   case ISD::INTRINSIC_VOID:
14859   case ISD::INTRINSIC_W_CHAIN:
14860     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14861     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
14862       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
14863     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
14864       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
14865     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
14866       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
14867     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
14868       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
14869     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
14870     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
14871     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
14872     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
14873     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
14874     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
14875     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
14876     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
14877       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
14878     case Intrinsic::aarch64_neon_ld2:
14879     case Intrinsic::aarch64_neon_ld3:
14880     case Intrinsic::aarch64_neon_ld4:
14881     case Intrinsic::aarch64_neon_ld1x2:
14882     case Intrinsic::aarch64_neon_ld1x3:
14883     case Intrinsic::aarch64_neon_ld1x4:
14884     case Intrinsic::aarch64_neon_ld2lane:
14885     case Intrinsic::aarch64_neon_ld3lane:
14886     case Intrinsic::aarch64_neon_ld4lane:
14887     case Intrinsic::aarch64_neon_ld2r:
14888     case Intrinsic::aarch64_neon_ld3r:
14889     case Intrinsic::aarch64_neon_ld4r:
14890     case Intrinsic::aarch64_neon_st2:
14891     case Intrinsic::aarch64_neon_st3:
14892     case Intrinsic::aarch64_neon_st4:
14893     case Intrinsic::aarch64_neon_st1x2:
14894     case Intrinsic::aarch64_neon_st1x3:
14895     case Intrinsic::aarch64_neon_st1x4:
14896     case Intrinsic::aarch64_neon_st2lane:
14897     case Intrinsic::aarch64_neon_st3lane:
14898     case Intrinsic::aarch64_neon_st4lane:
14899       return performNEONPostLDSTCombine(N, DCI, DAG);
14900     case Intrinsic::aarch64_sve_ldnt1:
14901       return performLDNT1Combine(N, DAG);
14902     case Intrinsic::aarch64_sve_ld1rq:
14903       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
14904     case Intrinsic::aarch64_sve_ld1ro:
14905       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
14906     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
14907       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14908     case Intrinsic::aarch64_sve_ldnt1_gather:
14909       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14910     case Intrinsic::aarch64_sve_ldnt1_gather_index:
14911       return performGatherLoadCombine(N, DAG,
14912                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
14913     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
14914       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14915     case Intrinsic::aarch64_sve_ld1:
14916       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
14917     case Intrinsic::aarch64_sve_ldnf1:
14918       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
14919     case Intrinsic::aarch64_sve_ldff1:
14920       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
14921     case Intrinsic::aarch64_sve_st1:
14922       return performST1Combine(N, DAG);
14923     case Intrinsic::aarch64_sve_stnt1:
14924       return performSTNT1Combine(N, DAG);
14925     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
14926       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14927     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
14928       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14929     case Intrinsic::aarch64_sve_stnt1_scatter:
14930       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14931     case Intrinsic::aarch64_sve_stnt1_scatter_index:
14932       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
14933     case Intrinsic::aarch64_sve_ld1_gather:
14934       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
14935     case Intrinsic::aarch64_sve_ld1_gather_index:
14936       return performGatherLoadCombine(N, DAG,
14937                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
14938     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
14939       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
14940                                       /*OnlyPackedOffsets=*/false);
14941     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
14942       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
14943                                       /*OnlyPackedOffsets=*/false);
14944     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
14945       return performGatherLoadCombine(N, DAG,
14946                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
14947                                       /*OnlyPackedOffsets=*/false);
14948     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
14949       return performGatherLoadCombine(N, DAG,
14950                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
14951                                       /*OnlyPackedOffsets=*/false);
14952     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
14953       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14954     case Intrinsic::aarch64_sve_ldff1_gather:
14955       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14956     case Intrinsic::aarch64_sve_ldff1_gather_index:
14957       return performGatherLoadCombine(N, DAG,
14958                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14959     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14960       return performGatherLoadCombine(N, DAG,
14961                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14962                                       /*OnlyPackedOffsets=*/false);
14963     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14964       return performGatherLoadCombine(N, DAG,
14965                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14966                                       /*OnlyPackedOffsets=*/false);
14967     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14968       return performGatherLoadCombine(N, DAG,
14969                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14970                                       /*OnlyPackedOffsets=*/false);
14971     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14972       return performGatherLoadCombine(N, DAG,
14973                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14974                                       /*OnlyPackedOffsets=*/false);
14975     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14976       return performGatherLoadCombine(N, DAG,
14977                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14978     case Intrinsic::aarch64_sve_st1_scatter:
14979       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14980     case Intrinsic::aarch64_sve_st1_scatter_index:
14981       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14982     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14983       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14984                                         /*OnlyPackedOffsets=*/false);
14985     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14986       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14987                                         /*OnlyPackedOffsets=*/false);
14988     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14989       return performScatterStoreCombine(N, DAG,
14990                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
14991                                         /*OnlyPackedOffsets=*/false);
14992     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14993       return performScatterStoreCombine(N, DAG,
14994                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
14995                                         /*OnlyPackedOffsets=*/false);
14996     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14997       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14998     case Intrinsic::aarch64_sve_tuple_get: {
14999       SDLoc DL(N);
15000       SDValue Chain = N->getOperand(0);
15001       SDValue Src1 = N->getOperand(2);
15002       SDValue Idx = N->getOperand(3);
15003 
15004       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15005       EVT ResVT = N->getValueType(0);
15006       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
15007       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
15008       SDValue Val =
15009           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
15010       return DAG.getMergeValues({Val, Chain}, DL);
15011     }
15012     case Intrinsic::aarch64_sve_tuple_set: {
15013       SDLoc DL(N);
15014       SDValue Chain = N->getOperand(0);
15015       SDValue Tuple = N->getOperand(2);
15016       SDValue Idx = N->getOperand(3);
15017       SDValue Vec = N->getOperand(4);
15018 
15019       EVT TupleVT = Tuple.getValueType();
15020       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
15021 
15022       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15023       uint64_t NumLanes =
15024           Vec.getValueType().getVectorElementCount().getKnownMinValue();
15025 
15026       if ((TupleLanes % NumLanes) != 0)
15027         report_fatal_error("invalid tuple vector!");
15028 
15029       uint64_t NumVecs = TupleLanes / NumLanes;
15030 
15031       SmallVector<SDValue, 4> Opnds;
15032       for (unsigned I = 0; I < NumVecs; ++I) {
15033         if (I == IdxConst)
15034           Opnds.push_back(Vec);
15035         else {
15036           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
15037           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
15038                                       Vec.getValueType(), Tuple, ExtIdx));
15039         }
15040       }
15041       SDValue Concat =
15042           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
15043       return DAG.getMergeValues({Concat, Chain}, DL);
15044     }
15045     case Intrinsic::aarch64_sve_tuple_create2:
15046     case Intrinsic::aarch64_sve_tuple_create3:
15047     case Intrinsic::aarch64_sve_tuple_create4: {
15048       SDLoc DL(N);
15049       SDValue Chain = N->getOperand(0);
15050 
15051       SmallVector<SDValue, 4> Opnds;
15052       for (unsigned I = 2; I < N->getNumOperands(); ++I)
15053         Opnds.push_back(N->getOperand(I));
15054 
15055       EVT VT = Opnds[0].getValueType();
15056       EVT EltVT = VT.getVectorElementType();
15057       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
15058                                     VT.getVectorElementCount() *
15059                                         (N->getNumOperands() - 2));
15060       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
15061       return DAG.getMergeValues({Concat, Chain}, DL);
15062     }
15063     case Intrinsic::aarch64_sve_ld2:
15064     case Intrinsic::aarch64_sve_ld3:
15065     case Intrinsic::aarch64_sve_ld4: {
15066       SDLoc DL(N);
15067       SDValue Chain = N->getOperand(0);
15068       SDValue Mask = N->getOperand(2);
15069       SDValue BasePtr = N->getOperand(3);
15070       SDValue LoadOps[] = {Chain, Mask, BasePtr};
15071       unsigned IntrinsicID =
15072           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15073       SDValue Result =
15074           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
15075       return DAG.getMergeValues({Result, Chain}, DL);
15076     }
15077     default:
15078       break;
15079     }
15080     break;
15081   case ISD::GlobalAddress:
15082     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
15083   }
15084   return SDValue();
15085 }
15086 
15087 // Check if the return value is used as only a return value, as otherwise
15088 // we can't perform a tail-call. In particular, we need to check for
15089 // target ISD nodes that are returns and any other "odd" constructs
15090 // that the generic analysis code won't necessarily catch.
15091 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
15092                                                SDValue &Chain) const {
15093   if (N->getNumValues() != 1)
15094     return false;
15095   if (!N->hasNUsesOfValue(1, 0))
15096     return false;
15097 
15098   SDValue TCChain = Chain;
15099   SDNode *Copy = *N->use_begin();
15100   if (Copy->getOpcode() == ISD::CopyToReg) {
15101     // If the copy has a glue operand, we conservatively assume it isn't safe to
15102     // perform a tail call.
15103     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
15104         MVT::Glue)
15105       return false;
15106     TCChain = Copy->getOperand(0);
15107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
15108     return false;
15109 
15110   bool HasRet = false;
15111   for (SDNode *Node : Copy->uses()) {
15112     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
15113       return false;
15114     HasRet = true;
15115   }
15116 
15117   if (!HasRet)
15118     return false;
15119 
15120   Chain = TCChain;
15121   return true;
15122 }
15123 
15124 // Return whether the an instruction can potentially be optimized to a tail
15125 // call. This will cause the optimizers to attempt to move, or duplicate,
15126 // return instructions to help enable tail call optimizations for this
15127 // instruction.
15128 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15129   return CI->isTailCall();
15130 }
15131 
15132 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
15133                                                    SDValue &Offset,
15134                                                    ISD::MemIndexedMode &AM,
15135                                                    bool &IsInc,
15136                                                    SelectionDAG &DAG) const {
15137   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
15138     return false;
15139 
15140   Base = Op->getOperand(0);
15141   // All of the indexed addressing mode instructions take a signed
15142   // 9 bit immediate offset.
15143   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
15144     int64_t RHSC = RHS->getSExtValue();
15145     if (Op->getOpcode() == ISD::SUB)
15146       RHSC = -(uint64_t)RHSC;
15147     if (!isInt<9>(RHSC))
15148       return false;
15149     IsInc = (Op->getOpcode() == ISD::ADD);
15150     Offset = Op->getOperand(1);
15151     return true;
15152   }
15153   return false;
15154 }
15155 
15156 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15157                                                       SDValue &Offset,
15158                                                       ISD::MemIndexedMode &AM,
15159                                                       SelectionDAG &DAG) const {
15160   EVT VT;
15161   SDValue Ptr;
15162   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15163     VT = LD->getMemoryVT();
15164     Ptr = LD->getBasePtr();
15165   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15166     VT = ST->getMemoryVT();
15167     Ptr = ST->getBasePtr();
15168   } else
15169     return false;
15170 
15171   bool IsInc;
15172   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
15173     return false;
15174   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
15175   return true;
15176 }
15177 
15178 bool AArch64TargetLowering::getPostIndexedAddressParts(
15179     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
15180     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
15181   EVT VT;
15182   SDValue Ptr;
15183   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15184     VT = LD->getMemoryVT();
15185     Ptr = LD->getBasePtr();
15186   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15187     VT = ST->getMemoryVT();
15188     Ptr = ST->getBasePtr();
15189   } else
15190     return false;
15191 
15192   bool IsInc;
15193   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
15194     return false;
15195   // Post-indexing updates the base, so it's not a valid transform
15196   // if that's not the same as the load's pointer.
15197   if (Ptr != Base)
15198     return false;
15199   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
15200   return true;
15201 }
15202 
15203 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
15204                                   SelectionDAG &DAG) {
15205   SDLoc DL(N);
15206   SDValue Op = N->getOperand(0);
15207 
15208   if (N->getValueType(0) != MVT::i16 ||
15209       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
15210     return;
15211 
15212   Op = SDValue(
15213       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
15214                          DAG.getUNDEF(MVT::i32), Op,
15215                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
15216       0);
15217   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
15218   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
15219 }
15220 
15221 static void ReplaceReductionResults(SDNode *N,
15222                                     SmallVectorImpl<SDValue> &Results,
15223                                     SelectionDAG &DAG, unsigned InterOp,
15224                                     unsigned AcrossOp) {
15225   EVT LoVT, HiVT;
15226   SDValue Lo, Hi;
15227   SDLoc dl(N);
15228   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
15229   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
15230   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
15231   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
15232   Results.push_back(SplitVal);
15233 }
15234 
15235 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
15236   SDLoc DL(N);
15237   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
15238   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
15239                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
15240                                        DAG.getConstant(64, DL, MVT::i64)));
15241   return std::make_pair(Lo, Hi);
15242 }
15243 
15244 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
15245     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15246   SDValue In = N->getOperand(0);
15247   EVT InVT = In.getValueType();
15248 
15249   // Common code will handle these just fine.
15250   if (!InVT.isScalableVector() || !InVT.isInteger())
15251     return;
15252 
15253   SDLoc DL(N);
15254   EVT VT = N->getValueType(0);
15255 
15256   // The following checks bail if this is not a halving operation.
15257 
15258   ElementCount ResEC = VT.getVectorElementCount();
15259 
15260   if (InVT.getVectorElementCount() != (ResEC * 2))
15261     return;
15262 
15263   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
15264   if (!CIndex)
15265     return;
15266 
15267   unsigned Index = CIndex->getZExtValue();
15268   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
15269     return;
15270 
15271   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
15272   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
15273 
15274   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
15275   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
15276 }
15277 
15278 // Create an even/odd pair of X registers holding integer value V.
15279 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
15280   SDLoc dl(V.getNode());
15281   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
15282   SDValue VHi = DAG.getAnyExtOrTrunc(
15283       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
15284       dl, MVT::i64);
15285   if (DAG.getDataLayout().isBigEndian())
15286     std::swap (VLo, VHi);
15287   SDValue RegClass =
15288       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
15289   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
15290   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
15291   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
15292   return SDValue(
15293       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
15294 }
15295 
15296 static void ReplaceCMP_SWAP_128Results(SDNode *N,
15297                                        SmallVectorImpl<SDValue> &Results,
15298                                        SelectionDAG &DAG,
15299                                        const AArch64Subtarget *Subtarget) {
15300   assert(N->getValueType(0) == MVT::i128 &&
15301          "AtomicCmpSwap on types less than 128 should be legal");
15302 
15303   if (Subtarget->hasLSE()) {
15304     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
15305     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
15306     SDValue Ops[] = {
15307         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
15308         createGPRPairNode(DAG, N->getOperand(3)), // Store value
15309         N->getOperand(1), // Ptr
15310         N->getOperand(0), // Chain in
15311     };
15312 
15313     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15314 
15315     unsigned Opcode;
15316     switch (MemOp->getOrdering()) {
15317     case AtomicOrdering::Monotonic:
15318       Opcode = AArch64::CASPX;
15319       break;
15320     case AtomicOrdering::Acquire:
15321       Opcode = AArch64::CASPAX;
15322       break;
15323     case AtomicOrdering::Release:
15324       Opcode = AArch64::CASPLX;
15325       break;
15326     case AtomicOrdering::AcquireRelease:
15327     case AtomicOrdering::SequentiallyConsistent:
15328       Opcode = AArch64::CASPALX;
15329       break;
15330     default:
15331       llvm_unreachable("Unexpected ordering!");
15332     }
15333 
15334     MachineSDNode *CmpSwap = DAG.getMachineNode(
15335         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
15336     DAG.setNodeMemRefs(CmpSwap, {MemOp});
15337 
15338     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
15339     if (DAG.getDataLayout().isBigEndian())
15340       std::swap(SubReg1, SubReg2);
15341     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
15342                                             SDValue(CmpSwap, 0));
15343     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
15344                                             SDValue(CmpSwap, 0));
15345     Results.push_back(
15346         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
15347     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
15348     return;
15349   }
15350 
15351   auto Desired = splitInt128(N->getOperand(2), DAG);
15352   auto New = splitInt128(N->getOperand(3), DAG);
15353   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
15354                    New.first,        New.second,    N->getOperand(0)};
15355   SDNode *CmpSwap = DAG.getMachineNode(
15356       AArch64::CMP_SWAP_128, SDLoc(N),
15357       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
15358 
15359   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15360   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
15361 
15362   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15363                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
15364   Results.push_back(SDValue(CmpSwap, 3));
15365 }
15366 
15367 void AArch64TargetLowering::ReplaceNodeResults(
15368     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15369   switch (N->getOpcode()) {
15370   default:
15371     llvm_unreachable("Don't know how to custom expand this");
15372   case ISD::BITCAST:
15373     ReplaceBITCASTResults(N, Results, DAG);
15374     return;
15375   case ISD::VECREDUCE_ADD:
15376   case ISD::VECREDUCE_SMAX:
15377   case ISD::VECREDUCE_SMIN:
15378   case ISD::VECREDUCE_UMAX:
15379   case ISD::VECREDUCE_UMIN:
15380     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
15381     return;
15382 
15383   case ISD::CTPOP:
15384     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
15385     return;
15386   case AArch64ISD::SADDV:
15387     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
15388     return;
15389   case AArch64ISD::UADDV:
15390     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
15391     return;
15392   case AArch64ISD::SMINV:
15393     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
15394     return;
15395   case AArch64ISD::UMINV:
15396     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
15397     return;
15398   case AArch64ISD::SMAXV:
15399     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
15400     return;
15401   case AArch64ISD::UMAXV:
15402     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
15403     return;
15404   case ISD::FP_TO_UINT:
15405   case ISD::FP_TO_SINT:
15406     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
15407     // Let normal code take care of it by not adding anything to Results.
15408     return;
15409   case ISD::ATOMIC_CMP_SWAP:
15410     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
15411     return;
15412   case ISD::LOAD: {
15413     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
15414            "unexpected load's value type");
15415     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
15416     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
15417       // Non-volatile loads are optimized later in AArch64's load/store
15418       // optimizer.
15419       return;
15420     }
15421 
15422     SDValue Result = DAG.getMemIntrinsicNode(
15423         AArch64ISD::LDP, SDLoc(N),
15424         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
15425         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
15426         LoadNode->getMemOperand());
15427 
15428     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15429                                Result.getValue(0), Result.getValue(1));
15430     Results.append({Pair, Result.getValue(2) /* Chain */});
15431     return;
15432   }
15433   case ISD::EXTRACT_SUBVECTOR:
15434     ReplaceExtractSubVectorResults(N, Results, DAG);
15435     return;
15436   case ISD::INTRINSIC_WO_CHAIN: {
15437     EVT VT = N->getValueType(0);
15438     assert((VT == MVT::i8 || VT == MVT::i16) &&
15439            "custom lowering for unexpected type");
15440 
15441     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
15442     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15443     switch (IntID) {
15444     default:
15445       return;
15446     case Intrinsic::aarch64_sve_clasta_n: {
15447       SDLoc DL(N);
15448       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15449       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
15450                            N->getOperand(1), Op2, N->getOperand(3));
15451       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15452       return;
15453     }
15454     case Intrinsic::aarch64_sve_clastb_n: {
15455       SDLoc DL(N);
15456       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15457       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
15458                            N->getOperand(1), Op2, N->getOperand(3));
15459       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15460       return;
15461     }
15462     case Intrinsic::aarch64_sve_lasta: {
15463       SDLoc DL(N);
15464       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
15465                            N->getOperand(1), N->getOperand(2));
15466       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15467       return;
15468     }
15469     case Intrinsic::aarch64_sve_lastb: {
15470       SDLoc DL(N);
15471       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
15472                            N->getOperand(1), N->getOperand(2));
15473       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15474       return;
15475     }
15476     }
15477   }
15478   }
15479 }
15480 
15481 bool AArch64TargetLowering::useLoadStackGuardNode() const {
15482   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
15483     return TargetLowering::useLoadStackGuardNode();
15484   return true;
15485 }
15486 
15487 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
15488   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15489   // reciprocal if there are three or more FDIVs.
15490   return 3;
15491 }
15492 
15493 TargetLoweringBase::LegalizeTypeAction
15494 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
15495   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
15496   // v4i16, v2i32 instead of to promote.
15497   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
15498       VT == MVT::v1f32)
15499     return TypeWidenVector;
15500 
15501   return TargetLoweringBase::getPreferredVectorAction(VT);
15502 }
15503 
15504 // Loads and stores less than 128-bits are already atomic; ones above that
15505 // are doomed anyway, so defer to the default libcall and blame the OS when
15506 // things go wrong.
15507 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15508   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15509   return Size == 128;
15510 }
15511 
15512 // Loads and stores less than 128-bits are already atomic; ones above that
15513 // are doomed anyway, so defer to the default libcall and blame the OS when
15514 // things go wrong.
15515 TargetLowering::AtomicExpansionKind
15516 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15517   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15518   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
15519 }
15520 
15521 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
15522 TargetLowering::AtomicExpansionKind
15523 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15524   if (AI->isFloatingPointOperation())
15525     return AtomicExpansionKind::CmpXChg;
15526 
15527   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15528   if (Size > 128) return AtomicExpansionKind::None;
15529   // Nand not supported in LSE.
15530   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
15531   // Leave 128 bits to LLSC.
15532   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
15533 }
15534 
15535 TargetLowering::AtomicExpansionKind
15536 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
15537     AtomicCmpXchgInst *AI) const {
15538   // If subtarget has LSE, leave cmpxchg intact for codegen.
15539   if (Subtarget->hasLSE())
15540     return AtomicExpansionKind::None;
15541   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15542   // implement cmpxchg without spilling. If the address being exchanged is also
15543   // on the stack and close enough to the spill slot, this can lead to a
15544   // situation where the monitor always gets cleared and the atomic operation
15545   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15546   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
15547     return AtomicExpansionKind::None;
15548   return AtomicExpansionKind::LLSC;
15549 }
15550 
15551 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15552                                              AtomicOrdering Ord) const {
15553   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15554   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15555   bool IsAcquire = isAcquireOrStronger(Ord);
15556 
15557   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
15558   // intrinsic must return {i64, i64} and we have to recombine them into a
15559   // single i128 here.
15560   if (ValTy->getPrimitiveSizeInBits() == 128) {
15561     Intrinsic::ID Int =
15562         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
15563     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
15564 
15565     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15566     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
15567 
15568     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15569     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15570     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15571     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15572     return Builder.CreateOr(
15573         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
15574   }
15575 
15576   Type *Tys[] = { Addr->getType() };
15577   Intrinsic::ID Int =
15578       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
15579   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
15580 
15581   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
15582 
15583   const DataLayout &DL = M->getDataLayout();
15584   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
15585   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
15586 
15587   return Builder.CreateBitCast(Trunc, EltTy);
15588 }
15589 
15590 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15591     IRBuilder<> &Builder) const {
15592   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15593   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
15594 }
15595 
15596 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
15597                                                    Value *Val, Value *Addr,
15598                                                    AtomicOrdering Ord) const {
15599   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15600   bool IsRelease = isReleaseOrStronger(Ord);
15601 
15602   // Since the intrinsics must have legal type, the i128 intrinsics take two
15603   // parameters: "i64, i64". We must marshal Val into the appropriate form
15604   // before the call.
15605   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
15606     Intrinsic::ID Int =
15607         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
15608     Function *Stxr = Intrinsic::getDeclaration(M, Int);
15609     Type *Int64Ty = Type::getInt64Ty(M->getContext());
15610 
15611     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
15612     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
15613     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15614     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
15615   }
15616 
15617   Intrinsic::ID Int =
15618       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
15619   Type *Tys[] = { Addr->getType() };
15620   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
15621 
15622   const DataLayout &DL = M->getDataLayout();
15623   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
15624   Val = Builder.CreateBitCast(Val, IntValTy);
15625 
15626   return Builder.CreateCall(Stxr,
15627                             {Builder.CreateZExtOrBitCast(
15628                                  Val, Stxr->getFunctionType()->getParamType(0)),
15629                              Addr});
15630 }
15631 
15632 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
15633     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15634   if (Ty->isArrayTy())
15635     return true;
15636 
15637   const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
15638   if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
15639     return true;
15640 
15641   return false;
15642 }
15643 
15644 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
15645                                                             EVT) const {
15646   return false;
15647 }
15648 
15649 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
15650   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
15651   Function *ThreadPointerFunc =
15652       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
15653   return IRB.CreatePointerCast(
15654       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
15655                              Offset),
15656       IRB.getInt8PtrTy()->getPointerTo(0));
15657 }
15658 
15659 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
15660   // Android provides a fixed TLS slot for the stack cookie. See the definition
15661   // of TLS_SLOT_STACK_GUARD in
15662   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15663   if (Subtarget->isTargetAndroid())
15664     return UseTlsOffset(IRB, 0x28);
15665 
15666   // Fuchsia is similar.
15667   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
15668   if (Subtarget->isTargetFuchsia())
15669     return UseTlsOffset(IRB, -0x10);
15670 
15671   return TargetLowering::getIRStackGuard(IRB);
15672 }
15673 
15674 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
15675   // MSVC CRT provides functionalities for stack protection.
15676   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
15677     // MSVC CRT has a global variable holding security cookie.
15678     M.getOrInsertGlobal("__security_cookie",
15679                         Type::getInt8PtrTy(M.getContext()));
15680 
15681     // MSVC CRT has a function to validate security cookie.
15682     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15683         "__security_check_cookie", Type::getVoidTy(M.getContext()),
15684         Type::getInt8PtrTy(M.getContext()));
15685     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
15686       F->setCallingConv(CallingConv::Win64);
15687       F->addAttribute(1, Attribute::AttrKind::InReg);
15688     }
15689     return;
15690   }
15691   TargetLowering::insertSSPDeclarations(M);
15692 }
15693 
15694 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
15695   // MSVC CRT has a global variable holding security cookie.
15696   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15697     return M.getGlobalVariable("__security_cookie");
15698   return TargetLowering::getSDagStackGuard(M);
15699 }
15700 
15701 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
15702   // MSVC CRT has a function to validate security cookie.
15703   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15704     return M.getFunction("__security_check_cookie");
15705   return TargetLowering::getSSPStackGuardCheck(M);
15706 }
15707 
15708 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
15709   // Android provides a fixed TLS slot for the SafeStack pointer. See the
15710   // definition of TLS_SLOT_SAFESTACK in
15711   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15712   if (Subtarget->isTargetAndroid())
15713     return UseTlsOffset(IRB, 0x48);
15714 
15715   // Fuchsia is similar.
15716   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
15717   if (Subtarget->isTargetFuchsia())
15718     return UseTlsOffset(IRB, -0x8);
15719 
15720   return TargetLowering::getSafeStackPointerLocation(IRB);
15721 }
15722 
15723 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
15724     const Instruction &AndI) const {
15725   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
15726   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
15727   // may be beneficial to sink in other cases, but we would have to check that
15728   // the cmp would not get folded into the br to form a cbz for these to be
15729   // beneficial.
15730   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
15731   if (!Mask)
15732     return false;
15733   return Mask->getValue().isPowerOf2();
15734 }
15735 
15736 bool AArch64TargetLowering::
15737     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15738         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
15739         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
15740         SelectionDAG &DAG) const {
15741   // Does baseline recommend not to perform the fold by default?
15742   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15743           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
15744     return false;
15745   // Else, if this is a vector shift, prefer 'shl'.
15746   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
15747 }
15748 
15749 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
15750                                               SDNode *N) const {
15751   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15752       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
15753     return false;
15754   return true;
15755 }
15756 
15757 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15758   // Update IsSplitCSR in AArch64unctionInfo.
15759   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
15760   AFI->setIsSplitCSR(true);
15761 }
15762 
15763 void AArch64TargetLowering::insertCopiesSplitCSR(
15764     MachineBasicBlock *Entry,
15765     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15766   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
15767   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15768   if (!IStart)
15769     return;
15770 
15771   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15772   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15773   MachineBasicBlock::iterator MBBI = Entry->begin();
15774   for (const MCPhysReg *I = IStart; *I; ++I) {
15775     const TargetRegisterClass *RC = nullptr;
15776     if (AArch64::GPR64RegClass.contains(*I))
15777       RC = &AArch64::GPR64RegClass;
15778     else if (AArch64::FPR64RegClass.contains(*I))
15779       RC = &AArch64::FPR64RegClass;
15780     else
15781       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15782 
15783     Register NewVR = MRI->createVirtualRegister(RC);
15784     // Create copy from CSR to a virtual register.
15785     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15786     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15787     // nounwind. If we want to generalize this later, we may need to emit
15788     // CFI pseudo-instructions.
15789     assert(Entry->getParent()->getFunction().hasFnAttribute(
15790                Attribute::NoUnwind) &&
15791            "Function should be nounwind in insertCopiesSplitCSR!");
15792     Entry->addLiveIn(*I);
15793     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15794         .addReg(*I);
15795 
15796     // Insert the copy-back instructions right before the terminator.
15797     for (auto *Exit : Exits)
15798       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15799               TII->get(TargetOpcode::COPY), *I)
15800           .addReg(NewVR);
15801   }
15802 }
15803 
15804 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
15805   // Integer division on AArch64 is expensive. However, when aggressively
15806   // optimizing for code size, we prefer to use a div instruction, as it is
15807   // usually smaller than the alternative sequence.
15808   // The exception to this is vector division. Since AArch64 doesn't have vector
15809   // integer division, leaving the division as-is is a loss even in terms of
15810   // size, because it will have to be scalarized, while the alternative code
15811   // sequence can be performed in vector form.
15812   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
15813   return OptSize && !VT.isVector();
15814 }
15815 
15816 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
15817   // We want inc-of-add for scalars and sub-of-not for vectors.
15818   return VT.isScalarInteger();
15819 }
15820 
15821 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
15822   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
15823 }
15824 
15825 unsigned
15826 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
15827   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
15828     return getPointerTy(DL).getSizeInBits();
15829 
15830   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
15831 }
15832 
15833 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
15834   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15835   TargetLoweringBase::finalizeLowering(MF);
15836 }
15837 
15838 // Unlike X86, we let frame lowering assign offsets to all catch objects.
15839 bool AArch64TargetLowering::needsFixedCatchObjects() const {
15840   return false;
15841 }
15842 
15843 bool AArch64TargetLowering::shouldLocalize(
15844     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
15845   switch (MI.getOpcode()) {
15846   case TargetOpcode::G_GLOBAL_VALUE: {
15847     // On Darwin, TLS global vars get selected into function calls, which
15848     // we don't want localized, as they can get moved into the middle of a
15849     // another call sequence.
15850     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
15851     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
15852       return false;
15853     break;
15854   }
15855   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
15856   // localizable.
15857   case AArch64::ADRP:
15858   case AArch64::G_ADD_LOW:
15859     return true;
15860   default:
15861     break;
15862   }
15863   return TargetLoweringBase::shouldLocalize(MI, TTI);
15864 }
15865 
15866 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
15867   if (isa<ScalableVectorType>(Inst.getType()))
15868     return true;
15869 
15870   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
15871     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
15872       return true;
15873 
15874   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
15875     if (isa<ScalableVectorType>(AI->getAllocatedType()))
15876       return true;
15877   }
15878 
15879   return false;
15880 }
15881 
15882 // Return the largest legal scalable vector type that matches VT's element type.
15883 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
15884   assert(VT.isFixedLengthVector() &&
15885          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15886          "Expected legal fixed length vector!");
15887   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15888   default:
15889     llvm_unreachable("unexpected element type for SVE container");
15890   case MVT::i8:
15891     return EVT(MVT::nxv16i8);
15892   case MVT::i16:
15893     return EVT(MVT::nxv8i16);
15894   case MVT::i32:
15895     return EVT(MVT::nxv4i32);
15896   case MVT::i64:
15897     return EVT(MVT::nxv2i64);
15898   case MVT::f16:
15899     return EVT(MVT::nxv8f16);
15900   case MVT::f32:
15901     return EVT(MVT::nxv4f32);
15902   case MVT::f64:
15903     return EVT(MVT::nxv2f64);
15904   }
15905 }
15906 
15907 // Return a PTRUE with active lanes corresponding to the extent of VT.
15908 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
15909                                                 EVT VT) {
15910   assert(VT.isFixedLengthVector() &&
15911          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15912          "Expected legal fixed length vector!");
15913 
15914   int PgPattern;
15915   switch (VT.getVectorNumElements()) {
15916   default:
15917     llvm_unreachable("unexpected element count for SVE predicate");
15918   case 1:
15919     PgPattern = AArch64SVEPredPattern::vl1;
15920     break;
15921   case 2:
15922     PgPattern = AArch64SVEPredPattern::vl2;
15923     break;
15924   case 4:
15925     PgPattern = AArch64SVEPredPattern::vl4;
15926     break;
15927   case 8:
15928     PgPattern = AArch64SVEPredPattern::vl8;
15929     break;
15930   case 16:
15931     PgPattern = AArch64SVEPredPattern::vl16;
15932     break;
15933   case 32:
15934     PgPattern = AArch64SVEPredPattern::vl32;
15935     break;
15936   case 64:
15937     PgPattern = AArch64SVEPredPattern::vl64;
15938     break;
15939   case 128:
15940     PgPattern = AArch64SVEPredPattern::vl128;
15941     break;
15942   case 256:
15943     PgPattern = AArch64SVEPredPattern::vl256;
15944     break;
15945   }
15946 
15947   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
15948   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
15949   // variants of instructions when available.
15950 
15951   MVT MaskVT;
15952   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15953   default:
15954     llvm_unreachable("unexpected element type for SVE predicate");
15955   case MVT::i8:
15956     MaskVT = MVT::nxv16i1;
15957     break;
15958   case MVT::i16:
15959   case MVT::f16:
15960     MaskVT = MVT::nxv8i1;
15961     break;
15962   case MVT::i32:
15963   case MVT::f32:
15964     MaskVT = MVT::nxv4i1;
15965     break;
15966   case MVT::i64:
15967   case MVT::f64:
15968     MaskVT = MVT::nxv2i1;
15969     break;
15970   }
15971 
15972   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15973                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15974 }
15975 
15976 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15977                                              EVT VT) {
15978   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15979          "Expected legal scalable vector!");
15980   auto PredTy = VT.changeVectorElementType(MVT::i1);
15981   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15982 }
15983 
15984 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15985   if (VT.isFixedLengthVector())
15986     return getPredicateForFixedLengthVector(DAG, DL, VT);
15987 
15988   return getPredicateForScalableVector(DAG, DL, VT);
15989 }
15990 
15991 // Grow V to consume an entire SVE register.
15992 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15993   assert(VT.isScalableVector() &&
15994          "Expected to convert into a scalable vector!");
15995   assert(V.getValueType().isFixedLengthVector() &&
15996          "Expected a fixed length vector operand!");
15997   SDLoc DL(V);
15998   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15999   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
16000 }
16001 
16002 // Shrink V so it's just big enough to maintain a VT's worth of data.
16003 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
16004   assert(VT.isFixedLengthVector() &&
16005          "Expected to convert into a fixed length vector!");
16006   assert(V.getValueType().isScalableVector() &&
16007          "Expected a scalable vector operand!");
16008   SDLoc DL(V);
16009   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16010   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
16011 }
16012 
16013 // Convert all fixed length vector loads larger than NEON to masked_loads.
16014 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
16015     SDValue Op, SelectionDAG &DAG) const {
16016   auto Load = cast<LoadSDNode>(Op);
16017 
16018   SDLoc DL(Op);
16019   EVT VT = Op.getValueType();
16020   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16021 
16022   auto NewLoad = DAG.getMaskedLoad(
16023       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
16024       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
16025       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
16026       Load->getExtensionType());
16027 
16028   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
16029   SDValue MergedValues[2] = {Result, Load->getChain()};
16030   return DAG.getMergeValues(MergedValues, DL);
16031 }
16032 
16033 // Convert all fixed length vector stores larger than NEON to masked_stores.
16034 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
16035     SDValue Op, SelectionDAG &DAG) const {
16036   auto Store = cast<StoreSDNode>(Op);
16037 
16038   SDLoc DL(Op);
16039   EVT VT = Store->getValue().getValueType();
16040   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16041 
16042   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
16043   return DAG.getMaskedStore(
16044       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
16045       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
16046       Store->getMemOperand(), Store->getAddressingMode(),
16047       Store->isTruncatingStore());
16048 }
16049 
16050 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
16051     SDValue Op, SelectionDAG &DAG) const {
16052   SDLoc dl(Op);
16053   EVT VT = Op.getValueType();
16054   EVT EltVT = VT.getVectorElementType();
16055 
16056   bool Signed = Op.getOpcode() == ISD::SDIV;
16057   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
16058 
16059   // Scalable vector i32/i64 DIV is supported.
16060   if (EltVT == MVT::i32 || EltVT == MVT::i64)
16061     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
16062 
16063   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
16064   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16065   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
16066   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
16067   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
16068 
16069   // Convert the operands to scalable vectors.
16070   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16071   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16072 
16073   // Extend the scalable operands.
16074   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16075   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
16076   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
16077   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
16078   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
16079   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
16080 
16081   // Convert back to fixed vectors so the DIV can be further lowered.
16082   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
16083   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
16084   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
16085   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
16086   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16087                                  Op0Lo, Op1Lo);
16088   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16089                                  Op0Hi, Op1Hi);
16090 
16091   // Convert again to scalable vectors to truncate.
16092   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
16093   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
16094   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
16095                                        ResultLo, ResultHi);
16096 
16097   return convertFromScalableVector(DAG, VT, ScalableResult);
16098 }
16099 
16100 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
16101     SDValue Op, SelectionDAG &DAG) const {
16102   EVT VT = Op.getValueType();
16103   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16104 
16105   SDLoc DL(Op);
16106   SDValue Val = Op.getOperand(0);
16107   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16108   Val = convertToScalableVector(DAG, ContainerVT, Val);
16109 
16110   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
16111   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16112 
16113   // Repeatedly unpack Val until the result is of the desired element type.
16114   switch (ContainerVT.getSimpleVT().SimpleTy) {
16115   default:
16116     llvm_unreachable("unimplemented container type");
16117   case MVT::nxv16i8:
16118     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
16119     if (VT.getVectorElementType() == MVT::i16)
16120       break;
16121     LLVM_FALLTHROUGH;
16122   case MVT::nxv8i16:
16123     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
16124     if (VT.getVectorElementType() == MVT::i32)
16125       break;
16126     LLVM_FALLTHROUGH;
16127   case MVT::nxv4i32:
16128     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
16129     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
16130     break;
16131   }
16132 
16133   return convertFromScalableVector(DAG, VT, Val);
16134 }
16135 
16136 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
16137     SDValue Op, SelectionDAG &DAG) const {
16138   EVT VT = Op.getValueType();
16139   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16140 
16141   SDLoc DL(Op);
16142   SDValue Val = Op.getOperand(0);
16143   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16144   Val = convertToScalableVector(DAG, ContainerVT, Val);
16145 
16146   // Repeatedly truncate Val until the result is of the desired element type.
16147   switch (ContainerVT.getSimpleVT().SimpleTy) {
16148   default:
16149     llvm_unreachable("unimplemented container type");
16150   case MVT::nxv2i64:
16151     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
16152     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
16153     if (VT.getVectorElementType() == MVT::i32)
16154       break;
16155     LLVM_FALLTHROUGH;
16156   case MVT::nxv4i32:
16157     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
16158     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
16159     if (VT.getVectorElementType() == MVT::i16)
16160       break;
16161     LLVM_FALLTHROUGH;
16162   case MVT::nxv8i16:
16163     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
16164     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
16165     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
16166     break;
16167   }
16168 
16169   return convertFromScalableVector(DAG, VT, Val);
16170 }
16171 
16172 // Convert vector operation 'Op' to an equivalent predicated operation whereby
16173 // the original operation's type is used to construct a suitable predicate.
16174 // NOTE: The results for inactive lanes are undefined.
16175 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
16176                                                    SelectionDAG &DAG,
16177                                                    unsigned NewOp,
16178                                                    bool OverrideNEON) const {
16179   EVT VT = Op.getValueType();
16180   SDLoc DL(Op);
16181   auto Pg = getPredicateForVector(DAG, DL, VT);
16182 
16183   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
16184     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16185 
16186     // Create list of operands by converting existing ones to scalable types.
16187     SmallVector<SDValue, 4> Operands = {Pg};
16188     for (const SDValue &V : Op->op_values()) {
16189       if (isa<CondCodeSDNode>(V)) {
16190         Operands.push_back(V);
16191         continue;
16192       }
16193 
16194       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
16195         EVT VTArg = VTNode->getVT().getVectorElementType();
16196         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
16197         Operands.push_back(DAG.getValueType(NewVTArg));
16198         continue;
16199       }
16200 
16201       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
16202              "Only fixed length vectors are supported!");
16203       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
16204     }
16205 
16206     if (isMergePassthruOpcode(NewOp))
16207       Operands.push_back(DAG.getUNDEF(ContainerVT));
16208 
16209     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
16210     return convertFromScalableVector(DAG, VT, ScalableRes);
16211   }
16212 
16213   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
16214 
16215   SmallVector<SDValue, 4> Operands = {Pg};
16216   for (const SDValue &V : Op->op_values()) {
16217     assert((!V.getValueType().isVector() ||
16218             V.getValueType().isScalableVector()) &&
16219            "Only scalable vectors are supported!");
16220     Operands.push_back(V);
16221   }
16222 
16223   if (isMergePassthruOpcode(NewOp))
16224     Operands.push_back(DAG.getUNDEF(VT));
16225 
16226   return DAG.getNode(NewOp, DL, VT, Operands);
16227 }
16228 
16229 // If a fixed length vector operation has no side effects when applied to
16230 // undefined elements, we can safely use scalable vectors to perform the same
16231 // operation without needing to worry about predication.
16232 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
16233                                                  SelectionDAG &DAG) const {
16234   EVT VT = Op.getValueType();
16235   assert(useSVEForFixedLengthVectorVT(VT) &&
16236          "Only expected to lower fixed length vector operation!");
16237   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16238 
16239   // Create list of operands by converting existing ones to scalable types.
16240   SmallVector<SDValue, 4> Ops;
16241   for (const SDValue &V : Op->op_values()) {
16242     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
16243 
16244     // Pass through non-vector operands.
16245     if (!V.getValueType().isVector()) {
16246       Ops.push_back(V);
16247       continue;
16248     }
16249 
16250     // "cast" fixed length vector to a scalable vector.
16251     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
16252            "Only fixed length vectors are supported!");
16253     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
16254   }
16255 
16256   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
16257   return convertFromScalableVector(DAG, VT, ScalableRes);
16258 }
16259 
16260 SDValue AArch64TargetLowering::LowerFixedLengthReductionToSVE(unsigned Opcode,
16261     SDValue ScalarOp, SelectionDAG &DAG) const {
16262   SDLoc DL(ScalarOp);
16263   SDValue VecOp = ScalarOp.getOperand(0);
16264   EVT SrcVT = VecOp.getValueType();
16265 
16266   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
16267   EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
16268   VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
16269 
16270   // UADDV always returns an i64 result.
16271   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
16272                                                    SrcVT.getVectorElementType();
16273 
16274   SDValue Rdx = DAG.getNode(Opcode, DL, getPackedSVEVectorVT(ResVT), Pg, VecOp);
16275   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
16276                             Rdx, DAG.getConstant(0, DL, MVT::i64));
16277 
16278   // The VEC_REDUCE nodes expect an element size result.
16279   if (ResVT != ScalarOp.getValueType())
16280     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
16281 
16282   return Res;
16283 }
16284 
16285 SDValue
16286 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
16287     SelectionDAG &DAG) const {
16288   EVT VT = Op.getValueType();
16289   SDLoc DL(Op);
16290 
16291   EVT InVT = Op.getOperand(1).getValueType();
16292   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16293   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
16294   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
16295 
16296   // Convert the mask to a predicated (NOTE: We don't need to worry about
16297   // inactive lanes since VSELECT is safe when given undefined elements).
16298   EVT MaskVT = Op.getOperand(0).getValueType();
16299   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
16300   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
16301   Mask = DAG.getNode(ISD::TRUNCATE, DL,
16302                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
16303 
16304   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
16305                                 Mask, Op1, Op2);
16306 
16307   return convertFromScalableVector(DAG, VT, ScalableRes);
16308 }
16309 
16310 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
16311     SDValue Op, SelectionDAG &DAG) const {
16312   SDLoc DL(Op);
16313   EVT InVT = Op.getOperand(0).getValueType();
16314   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16315 
16316   assert(useSVEForFixedLengthVectorVT(InVT) &&
16317          "Only expected to lower fixed length vector operation!");
16318   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
16319          "Expected integer result of the same bit length as the inputs!");
16320 
16321   // Expand floating point vector comparisons.
16322   if (InVT.isFloatingPoint())
16323     return SDValue();
16324 
16325   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16326   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16327   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
16328 
16329   EVT CmpVT = Pg.getValueType();
16330   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
16331                          {Pg, Op1, Op2, Op.getOperand(2)});
16332 
16333   EVT PromoteVT = ContainerVT.changeTypeToInteger();
16334   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
16335   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
16336 }
16337