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   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
3018     SDLoc dl(Op);
3019     SDValue Cv =
3020         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3021                     Op.getOperand(0));
3022     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3023   }
3024 
3025   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
3026     SDLoc dl(Op);
3027     MVT ExtVT =
3028         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3029                          VT.getVectorNumElements());
3030     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3031     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3032   }
3033 
3034   // Type changing conversions are illegal.
3035   return Op;
3036 }
3037 
3038 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3039                                               SelectionDAG &DAG) const {
3040   bool IsStrict = Op->isStrictFPOpcode();
3041   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3042 
3043   if (SrcVal.getValueType().isVector())
3044     return LowerVectorFP_TO_INT(Op, DAG);
3045 
3046   // f16 conversions are promoted to f32 when full fp16 is not supported.
3047   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3048     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3049     SDLoc dl(Op);
3050     return DAG.getNode(
3051         Op.getOpcode(), dl, Op.getValueType(),
3052         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3053   }
3054 
3055   if (SrcVal.getValueType() != MVT::f128) {
3056     // It's legal except when f128 is involved
3057     return Op;
3058   }
3059 
3060   RTLIB::Libcall LC;
3061   if (Op.getOpcode() == ISD::FP_TO_SINT ||
3062       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
3063     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
3064   else
3065     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
3066 
3067   return LowerF128Call(Op, DAG, LC);
3068 }
3069 
3070 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3071                                                     SelectionDAG &DAG) const {
3072   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3073   // Any additional optimization in this function should be recorded
3074   // in the cost tables.
3075   EVT VT = Op.getValueType();
3076   SDLoc dl(Op);
3077   SDValue In = Op.getOperand(0);
3078   EVT InVT = In.getValueType();
3079 
3080   if (VT.isScalableVector()) {
3081     unsigned Opcode = Op.getOpcode() == ISD::UINT_TO_FP
3082                           ? AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU
3083                           : AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU;
3084     return LowerToPredicatedOp(Op, DAG, Opcode);
3085   }
3086 
3087   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
3088     MVT CastVT =
3089         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3090                          InVT.getVectorNumElements());
3091     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
3092     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3093   }
3094 
3095   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
3096     unsigned CastOpc =
3097         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3098     EVT CastVT = VT.changeVectorElementTypeToInteger();
3099     In = DAG.getNode(CastOpc, dl, CastVT, In);
3100     return DAG.getNode(Op.getOpcode(), dl, VT, In);
3101   }
3102 
3103   return Op;
3104 }
3105 
3106 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3107                                             SelectionDAG &DAG) const {
3108   if (Op.getValueType().isVector())
3109     return LowerVectorINT_TO_FP(Op, DAG);
3110 
3111   bool IsStrict = Op->isStrictFPOpcode();
3112   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3113 
3114   // f16 conversions are promoted to f32 when full fp16 is not supported.
3115   if (Op.getValueType() == MVT::f16 &&
3116       !Subtarget->hasFullFP16()) {
3117     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3118     SDLoc dl(Op);
3119     return DAG.getNode(
3120         ISD::FP_ROUND, dl, MVT::f16,
3121         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3122         DAG.getIntPtrConstant(0, dl));
3123   }
3124 
3125   // i128 conversions are libcalls.
3126   if (SrcVal.getValueType() == MVT::i128)
3127     return SDValue();
3128 
3129   // Other conversions are legal, unless it's to the completely software-based
3130   // fp128.
3131   if (Op.getValueType() != MVT::f128)
3132     return Op;
3133 
3134   RTLIB::Libcall LC;
3135   if (Op.getOpcode() == ISD::SINT_TO_FP ||
3136       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
3137     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
3138   else
3139     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
3140 
3141   return LowerF128Call(Op, DAG, LC);
3142 }
3143 
3144 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3145                                             SelectionDAG &DAG) const {
3146   // For iOS, we want to call an alternative entry point: __sincos_stret,
3147   // which returns the values in two S / D registers.
3148   SDLoc dl(Op);
3149   SDValue Arg = Op.getOperand(0);
3150   EVT ArgVT = Arg.getValueType();
3151   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3152 
3153   ArgListTy Args;
3154   ArgListEntry Entry;
3155 
3156   Entry.Node = Arg;
3157   Entry.Ty = ArgTy;
3158   Entry.IsSExt = false;
3159   Entry.IsZExt = false;
3160   Args.push_back(Entry);
3161 
3162   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3163                                         : RTLIB::SINCOS_STRET_F32;
3164   const char *LibcallName = getLibcallName(LC);
3165   SDValue Callee =
3166       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3167 
3168   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3169   TargetLowering::CallLoweringInfo CLI(DAG);
3170   CLI.setDebugLoc(dl)
3171       .setChain(DAG.getEntryNode())
3172       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3173 
3174   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3175   return CallResult.first;
3176 }
3177 
3178 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
3179   EVT OpVT = Op.getValueType();
3180   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3181     return SDValue();
3182 
3183   assert(Op.getOperand(0).getValueType() == MVT::i16);
3184   SDLoc DL(Op);
3185 
3186   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3187   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3188   return SDValue(
3189       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3190                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3191       0);
3192 }
3193 
3194 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3195   if (OrigVT.getSizeInBits() >= 64)
3196     return OrigVT;
3197 
3198   assert(OrigVT.isSimple() && "Expecting a simple value type");
3199 
3200   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3201   switch (OrigSimpleTy) {
3202   default: llvm_unreachable("Unexpected Vector Type");
3203   case MVT::v2i8:
3204   case MVT::v2i16:
3205      return MVT::v2i32;
3206   case MVT::v4i8:
3207     return  MVT::v4i16;
3208   }
3209 }
3210 
3211 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3212                                                  const EVT &OrigTy,
3213                                                  const EVT &ExtTy,
3214                                                  unsigned ExtOpcode) {
3215   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3216   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3217   // 64-bits we need to insert a new extension so that it will be 64-bits.
3218   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3219   if (OrigTy.getSizeInBits() >= 64)
3220     return N;
3221 
3222   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3223   EVT NewVT = getExtensionTo64Bits(OrigTy);
3224 
3225   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3226 }
3227 
3228 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3229                                    bool isSigned) {
3230   EVT VT = N->getValueType(0);
3231 
3232   if (N->getOpcode() != ISD::BUILD_VECTOR)
3233     return false;
3234 
3235   for (const SDValue &Elt : N->op_values()) {
3236     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3237       unsigned EltSize = VT.getScalarSizeInBits();
3238       unsigned HalfSize = EltSize / 2;
3239       if (isSigned) {
3240         if (!isIntN(HalfSize, C->getSExtValue()))
3241           return false;
3242       } else {
3243         if (!isUIntN(HalfSize, C->getZExtValue()))
3244           return false;
3245       }
3246       continue;
3247     }
3248     return false;
3249   }
3250 
3251   return true;
3252 }
3253 
3254 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3255   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
3256     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3257                                              N->getOperand(0)->getValueType(0),
3258                                              N->getValueType(0),
3259                                              N->getOpcode());
3260 
3261   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3262   EVT VT = N->getValueType(0);
3263   SDLoc dl(N);
3264   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3265   unsigned NumElts = VT.getVectorNumElements();
3266   MVT TruncVT = MVT::getIntegerVT(EltSize);
3267   SmallVector<SDValue, 8> Ops;
3268   for (unsigned i = 0; i != NumElts; ++i) {
3269     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3270     const APInt &CInt = C->getAPIntValue();
3271     // Element types smaller than 32 bits are not legal, so use i32 elements.
3272     // The values are implicitly truncated so sext vs. zext doesn't matter.
3273     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3274   }
3275   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3276 }
3277 
3278 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3279   return N->getOpcode() == ISD::SIGN_EXTEND ||
3280          isExtendedBUILD_VECTOR(N, DAG, true);
3281 }
3282 
3283 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3284   return N->getOpcode() == ISD::ZERO_EXTEND ||
3285          isExtendedBUILD_VECTOR(N, DAG, false);
3286 }
3287 
3288 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3289   unsigned Opcode = N->getOpcode();
3290   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3291     SDNode *N0 = N->getOperand(0).getNode();
3292     SDNode *N1 = N->getOperand(1).getNode();
3293     return N0->hasOneUse() && N1->hasOneUse() &&
3294       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3295   }
3296   return false;
3297 }
3298 
3299 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3300   unsigned Opcode = N->getOpcode();
3301   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3302     SDNode *N0 = N->getOperand(0).getNode();
3303     SDNode *N1 = N->getOperand(1).getNode();
3304     return N0->hasOneUse() && N1->hasOneUse() &&
3305       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3306   }
3307   return false;
3308 }
3309 
3310 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3311                                                 SelectionDAG &DAG) const {
3312   // The rounding mode is in bits 23:22 of the FPSCR.
3313   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3314   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3315   // so that the shift + and get folded into a bitfield extract.
3316   SDLoc dl(Op);
3317 
3318   SDValue Chain = Op.getOperand(0);
3319   SDValue FPCR_64 = DAG.getNode(
3320       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3321       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3322   Chain = FPCR_64.getValue(1);
3323   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3324   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3325                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3326   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3327                               DAG.getConstant(22, dl, MVT::i32));
3328   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3329                             DAG.getConstant(3, dl, MVT::i32));
3330   return DAG.getMergeValues({AND, Chain}, dl);
3331 }
3332 
3333 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3334   EVT VT = Op.getValueType();
3335 
3336   // If SVE is available then i64 vector multiplications can also be made legal.
3337   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3338 
3339   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3340     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3341 
3342   // Multiplications are only custom-lowered for 128-bit vectors so that
3343   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3344   assert(VT.is128BitVector() && VT.isInteger() &&
3345          "unexpected type for custom-lowering ISD::MUL");
3346   SDNode *N0 = Op.getOperand(0).getNode();
3347   SDNode *N1 = Op.getOperand(1).getNode();
3348   unsigned NewOpc = 0;
3349   bool isMLA = false;
3350   bool isN0SExt = isSignExtended(N0, DAG);
3351   bool isN1SExt = isSignExtended(N1, DAG);
3352   if (isN0SExt && isN1SExt)
3353     NewOpc = AArch64ISD::SMULL;
3354   else {
3355     bool isN0ZExt = isZeroExtended(N0, DAG);
3356     bool isN1ZExt = isZeroExtended(N1, DAG);
3357     if (isN0ZExt && isN1ZExt)
3358       NewOpc = AArch64ISD::UMULL;
3359     else if (isN1SExt || isN1ZExt) {
3360       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3361       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3362       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3363         NewOpc = AArch64ISD::SMULL;
3364         isMLA = true;
3365       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3366         NewOpc =  AArch64ISD::UMULL;
3367         isMLA = true;
3368       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3369         std::swap(N0, N1);
3370         NewOpc =  AArch64ISD::UMULL;
3371         isMLA = true;
3372       }
3373     }
3374 
3375     if (!NewOpc) {
3376       if (VT == MVT::v2i64)
3377         // Fall through to expand this.  It is not legal.
3378         return SDValue();
3379       else
3380         // Other vector multiplications are legal.
3381         return Op;
3382     }
3383   }
3384 
3385   // Legalize to a S/UMULL instruction
3386   SDLoc DL(Op);
3387   SDValue Op0;
3388   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3389   if (!isMLA) {
3390     Op0 = skipExtensionForVectorMULL(N0, DAG);
3391     assert(Op0.getValueType().is64BitVector() &&
3392            Op1.getValueType().is64BitVector() &&
3393            "unexpected types for extended operands to VMULL");
3394     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3395   }
3396   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3397   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3398   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3399   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3400   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3401   EVT Op1VT = Op1.getValueType();
3402   return DAG.getNode(N0->getOpcode(), DL, VT,
3403                      DAG.getNode(NewOpc, DL, VT,
3404                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3405                      DAG.getNode(NewOpc, DL, VT,
3406                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3407 }
3408 
3409 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3410                                int Pattern) {
3411   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3412                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3413 }
3414 
3415 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3416                                                      SelectionDAG &DAG) const {
3417   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3418   SDLoc dl(Op);
3419   switch (IntNo) {
3420   default: return SDValue();    // Don't custom lower most intrinsics.
3421   case Intrinsic::thread_pointer: {
3422     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3423     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3424   }
3425   case Intrinsic::aarch64_neon_abs: {
3426     EVT Ty = Op.getValueType();
3427     if (Ty == MVT::i64) {
3428       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3429                                    Op.getOperand(1));
3430       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3431       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3432     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3433       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3434     } else {
3435       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3436     }
3437   }
3438   case Intrinsic::aarch64_neon_smax:
3439     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3440                        Op.getOperand(1), Op.getOperand(2));
3441   case Intrinsic::aarch64_neon_umax:
3442     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3443                        Op.getOperand(1), Op.getOperand(2));
3444   case Intrinsic::aarch64_neon_smin:
3445     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3446                        Op.getOperand(1), Op.getOperand(2));
3447   case Intrinsic::aarch64_neon_umin:
3448     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3449                        Op.getOperand(1), Op.getOperand(2));
3450 
3451   case Intrinsic::aarch64_sve_sunpkhi:
3452     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3453                        Op.getOperand(1));
3454   case Intrinsic::aarch64_sve_sunpklo:
3455     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3456                        Op.getOperand(1));
3457   case Intrinsic::aarch64_sve_uunpkhi:
3458     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3459                        Op.getOperand(1));
3460   case Intrinsic::aarch64_sve_uunpklo:
3461     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3462                        Op.getOperand(1));
3463   case Intrinsic::aarch64_sve_clasta_n:
3464     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3465                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3466   case Intrinsic::aarch64_sve_clastb_n:
3467     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3468                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3469   case Intrinsic::aarch64_sve_lasta:
3470     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3471                        Op.getOperand(1), Op.getOperand(2));
3472   case Intrinsic::aarch64_sve_lastb:
3473     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3474                        Op.getOperand(1), Op.getOperand(2));
3475   case Intrinsic::aarch64_sve_rev:
3476     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3477                        Op.getOperand(1));
3478   case Intrinsic::aarch64_sve_tbl:
3479     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3480                        Op.getOperand(1), Op.getOperand(2));
3481   case Intrinsic::aarch64_sve_trn1:
3482     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3483                        Op.getOperand(1), Op.getOperand(2));
3484   case Intrinsic::aarch64_sve_trn2:
3485     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3486                        Op.getOperand(1), Op.getOperand(2));
3487   case Intrinsic::aarch64_sve_uzp1:
3488     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3489                        Op.getOperand(1), Op.getOperand(2));
3490   case Intrinsic::aarch64_sve_uzp2:
3491     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3492                        Op.getOperand(1), Op.getOperand(2));
3493   case Intrinsic::aarch64_sve_zip1:
3494     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3495                        Op.getOperand(1), Op.getOperand(2));
3496   case Intrinsic::aarch64_sve_zip2:
3497     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3498                        Op.getOperand(1), Op.getOperand(2));
3499   case Intrinsic::aarch64_sve_ptrue:
3500     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3501                        Op.getOperand(1));
3502   case Intrinsic::aarch64_sve_dupq_lane:
3503     return LowerDUPQLane(Op, DAG);
3504   case Intrinsic::aarch64_sve_convert_from_svbool:
3505     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3506                        Op.getOperand(1));
3507   case Intrinsic::aarch64_sve_fneg:
3508     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
3509                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3510   case Intrinsic::aarch64_sve_frintp:
3511     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
3512                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3513   case Intrinsic::aarch64_sve_frintm:
3514     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
3515                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3516   case Intrinsic::aarch64_sve_frinti:
3517     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3518                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3519   case Intrinsic::aarch64_sve_frintx:
3520     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3521                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3522   case Intrinsic::aarch64_sve_frinta:
3523     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
3524                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3525   case Intrinsic::aarch64_sve_frintn:
3526     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
3527                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3528   case Intrinsic::aarch64_sve_frintz:
3529     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
3530                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3531   case Intrinsic::aarch64_sve_ucvtf:
3532     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
3533                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3534                        Op.getOperand(1));
3535   case Intrinsic::aarch64_sve_scvtf:
3536     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
3537                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3538                        Op.getOperand(1));
3539   case Intrinsic::aarch64_sve_fcvtzu:
3540     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
3541                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3542                        Op.getOperand(1));
3543   case Intrinsic::aarch64_sve_fcvtzs:
3544     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
3545                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3546                        Op.getOperand(1));
3547   case Intrinsic::aarch64_sve_fsqrt:
3548     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
3549                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3550   case Intrinsic::aarch64_sve_frecpx:
3551     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
3552                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3553   case Intrinsic::aarch64_sve_fabs:
3554     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
3555                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3556   case Intrinsic::aarch64_sve_convert_to_svbool: {
3557     EVT OutVT = Op.getValueType();
3558     EVT InVT = Op.getOperand(1).getValueType();
3559     // Return the operand if the cast isn't changing type,
3560     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3561     if (InVT == OutVT)
3562       return Op.getOperand(1);
3563     // Otherwise, zero the newly introduced lanes.
3564     SDValue Reinterpret =
3565         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3566     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3567     SDValue MaskReinterpret =
3568         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3569     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3570   }
3571 
3572   case Intrinsic::aarch64_sve_insr: {
3573     SDValue Scalar = Op.getOperand(2);
3574     EVT ScalarTy = Scalar.getValueType();
3575     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3576       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3577 
3578     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3579                        Op.getOperand(1), Scalar);
3580   }
3581 
3582   case Intrinsic::aarch64_sve_sxtb:
3583     return DAG.getNode(
3584         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3585         Op.getOperand(2), Op.getOperand(3),
3586         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3587         Op.getOperand(1));
3588   case Intrinsic::aarch64_sve_sxth:
3589     return DAG.getNode(
3590         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3591         Op.getOperand(2), Op.getOperand(3),
3592         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3593         Op.getOperand(1));
3594   case Intrinsic::aarch64_sve_sxtw:
3595     return DAG.getNode(
3596         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3597         Op.getOperand(2), Op.getOperand(3),
3598         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3599         Op.getOperand(1));
3600   case Intrinsic::aarch64_sve_uxtb:
3601     return DAG.getNode(
3602         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3603         Op.getOperand(2), Op.getOperand(3),
3604         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3605         Op.getOperand(1));
3606   case Intrinsic::aarch64_sve_uxth:
3607     return DAG.getNode(
3608         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3609         Op.getOperand(2), Op.getOperand(3),
3610         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3611         Op.getOperand(1));
3612   case Intrinsic::aarch64_sve_uxtw:
3613     return DAG.getNode(
3614         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3615         Op.getOperand(2), Op.getOperand(3),
3616         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3617         Op.getOperand(1));
3618 
3619   case Intrinsic::localaddress: {
3620     const auto &MF = DAG.getMachineFunction();
3621     const auto *RegInfo = Subtarget->getRegisterInfo();
3622     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3623     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3624                               Op.getSimpleValueType());
3625   }
3626 
3627   case Intrinsic::eh_recoverfp: {
3628     // FIXME: This needs to be implemented to correctly handle highly aligned
3629     // stack objects. For now we simply return the incoming FP. Refer D53541
3630     // for more details.
3631     SDValue FnOp = Op.getOperand(1);
3632     SDValue IncomingFPOp = Op.getOperand(2);
3633     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3634     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3635     if (!Fn)
3636       report_fatal_error(
3637           "llvm.eh.recoverfp must take a function as the first argument");
3638     return IncomingFPOp;
3639   }
3640 
3641   case Intrinsic::aarch64_neon_vsri:
3642   case Intrinsic::aarch64_neon_vsli: {
3643     EVT Ty = Op.getValueType();
3644 
3645     if (!Ty.isVector())
3646       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3647 
3648     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3649 
3650     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3651     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3652     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3653                        Op.getOperand(3));
3654   }
3655 
3656   case Intrinsic::aarch64_neon_srhadd:
3657   case Intrinsic::aarch64_neon_urhadd:
3658   case Intrinsic::aarch64_neon_shadd:
3659   case Intrinsic::aarch64_neon_uhadd: {
3660     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3661                         IntNo == Intrinsic::aarch64_neon_shadd);
3662     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3663                           IntNo == Intrinsic::aarch64_neon_urhadd);
3664     unsigned Opcode =
3665         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
3666                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
3667     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3668                        Op.getOperand(2));
3669   }
3670 
3671   case Intrinsic::aarch64_neon_uabd: {
3672     return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(),
3673                        Op.getOperand(1), Op.getOperand(2));
3674   }
3675   case Intrinsic::aarch64_neon_sabd: {
3676     return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(),
3677                        Op.getOperand(1), Op.getOperand(2));
3678   }
3679   }
3680 }
3681 
3682 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3683   return ExtVal.getValueType().isScalableVector();
3684 }
3685 
3686 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3687 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3688                                         EVT VT, EVT MemVT,
3689                                         SelectionDAG &DAG) {
3690   assert(VT.isVector() && "VT should be a vector type");
3691   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3692 
3693   SDValue Value = ST->getValue();
3694 
3695   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3696   // the word lane which represent the v4i8 subvector.  It optimizes the store
3697   // to:
3698   //
3699   //   xtn  v0.8b, v0.8h
3700   //   str  s0, [x0]
3701 
3702   SDValue Undef = DAG.getUNDEF(MVT::i16);
3703   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3704                                         {Undef, Undef, Undef, Undef});
3705 
3706   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3707                                  Value, UndefVec);
3708   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3709 
3710   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3711   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3712                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3713 
3714   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3715                       ST->getBasePtr(), ST->getMemOperand());
3716 }
3717 
3718 // Custom lowering for any store, vector or scalar and/or default or with
3719 // a truncate operations.  Currently only custom lower truncate operation
3720 // from vector v4i16 to v4i8 or volatile stores of i128.
3721 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3722                                           SelectionDAG &DAG) const {
3723   SDLoc Dl(Op);
3724   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3725   assert (StoreNode && "Can only custom lower store nodes");
3726 
3727   SDValue Value = StoreNode->getValue();
3728 
3729   EVT VT = Value.getValueType();
3730   EVT MemVT = StoreNode->getMemoryVT();
3731 
3732   if (VT.isVector()) {
3733     if (useSVEForFixedLengthVectorVT(VT))
3734       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3735 
3736     unsigned AS = StoreNode->getAddressSpace();
3737     Align Alignment = StoreNode->getAlign();
3738     if (Alignment < MemVT.getStoreSize() &&
3739         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3740                                         StoreNode->getMemOperand()->getFlags(),
3741                                         nullptr)) {
3742       return scalarizeVectorStore(StoreNode, DAG);
3743     }
3744 
3745     if (StoreNode->isTruncatingStore()) {
3746       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3747     }
3748     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3749     // the custom lowering, as there are no un-paired non-temporal stores and
3750     // legalization will break up 256 bit inputs.
3751     ElementCount EC = MemVT.getVectorElementCount();
3752     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3753         EC.isKnownEven() &&
3754         ((MemVT.getScalarSizeInBits() == 8u ||
3755           MemVT.getScalarSizeInBits() == 16u ||
3756           MemVT.getScalarSizeInBits() == 32u ||
3757           MemVT.getScalarSizeInBits() == 64u))) {
3758       SDValue Lo =
3759           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3760                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3761                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3762       SDValue Hi =
3763           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3764                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3765                       StoreNode->getValue(),
3766                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
3767       SDValue Result = DAG.getMemIntrinsicNode(
3768           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3769           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3770           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3771       return Result;
3772     }
3773   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3774     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3775     SDValue Lo =
3776         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3777                     DAG.getConstant(0, Dl, MVT::i64));
3778     SDValue Hi =
3779         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3780                     DAG.getConstant(1, Dl, MVT::i64));
3781     SDValue Result = DAG.getMemIntrinsicNode(
3782         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3783         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3784         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3785     return Result;
3786   }
3787 
3788   return SDValue();
3789 }
3790 
3791 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3792                                               SelectionDAG &DAG) const {
3793   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3794   LLVM_DEBUG(Op.dump());
3795 
3796   switch (Op.getOpcode()) {
3797   default:
3798     llvm_unreachable("unimplemented operand");
3799     return SDValue();
3800   case ISD::BITCAST:
3801     return LowerBITCAST(Op, DAG);
3802   case ISD::GlobalAddress:
3803     return LowerGlobalAddress(Op, DAG);
3804   case ISD::GlobalTLSAddress:
3805     return LowerGlobalTLSAddress(Op, DAG);
3806   case ISD::SETCC:
3807   case ISD::STRICT_FSETCC:
3808   case ISD::STRICT_FSETCCS:
3809     return LowerSETCC(Op, DAG);
3810   case ISD::BR_CC:
3811     return LowerBR_CC(Op, DAG);
3812   case ISD::SELECT:
3813     return LowerSELECT(Op, DAG);
3814   case ISD::SELECT_CC:
3815     return LowerSELECT_CC(Op, DAG);
3816   case ISD::JumpTable:
3817     return LowerJumpTable(Op, DAG);
3818   case ISD::BR_JT:
3819     return LowerBR_JT(Op, DAG);
3820   case ISD::ConstantPool:
3821     return LowerConstantPool(Op, DAG);
3822   case ISD::BlockAddress:
3823     return LowerBlockAddress(Op, DAG);
3824   case ISD::VASTART:
3825     return LowerVASTART(Op, DAG);
3826   case ISD::VACOPY:
3827     return LowerVACOPY(Op, DAG);
3828   case ISD::VAARG:
3829     return LowerVAARG(Op, DAG);
3830   case ISD::ADDC:
3831   case ISD::ADDE:
3832   case ISD::SUBC:
3833   case ISD::SUBE:
3834     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3835   case ISD::SADDO:
3836   case ISD::UADDO:
3837   case ISD::SSUBO:
3838   case ISD::USUBO:
3839   case ISD::SMULO:
3840   case ISD::UMULO:
3841     return LowerXALUO(Op, DAG);
3842   case ISD::FADD:
3843     if (Op.getValueType() == MVT::f128)
3844       return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3845     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3846   case ISD::FSUB:
3847     if (Op.getValueType() == MVT::f128)
3848       return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3849     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
3850   case ISD::FMUL:
3851     if (Op.getValueType() == MVT::f128)
3852       return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3853     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
3854   case ISD::FMA:
3855     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3856   case ISD::FDIV:
3857     if (Op.getValueType() == MVT::f128)
3858       return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3859     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
3860   case ISD::FNEG:
3861     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
3862   case ISD::FCEIL:
3863     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
3864   case ISD::FFLOOR:
3865     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
3866   case ISD::FNEARBYINT:
3867     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
3868   case ISD::FRINT:
3869     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
3870   case ISD::FROUND:
3871     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
3872   case ISD::FROUNDEVEN:
3873     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
3874   case ISD::FTRUNC:
3875     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
3876   case ISD::FSQRT:
3877     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
3878   case ISD::FABS:
3879     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
3880   case ISD::FP_ROUND:
3881   case ISD::STRICT_FP_ROUND:
3882     return LowerFP_ROUND(Op, DAG);
3883   case ISD::FP_EXTEND:
3884     return LowerFP_EXTEND(Op, DAG);
3885   case ISD::FRAMEADDR:
3886     return LowerFRAMEADDR(Op, DAG);
3887   case ISD::SPONENTRY:
3888     return LowerSPONENTRY(Op, DAG);
3889   case ISD::RETURNADDR:
3890     return LowerRETURNADDR(Op, DAG);
3891   case ISD::ADDROFRETURNADDR:
3892     return LowerADDROFRETURNADDR(Op, DAG);
3893   case ISD::CONCAT_VECTORS:
3894     return LowerCONCAT_VECTORS(Op, DAG);
3895   case ISD::INSERT_VECTOR_ELT:
3896     return LowerINSERT_VECTOR_ELT(Op, DAG);
3897   case ISD::EXTRACT_VECTOR_ELT:
3898     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3899   case ISD::BUILD_VECTOR:
3900     return LowerBUILD_VECTOR(Op, DAG);
3901   case ISD::VECTOR_SHUFFLE:
3902     return LowerVECTOR_SHUFFLE(Op, DAG);
3903   case ISD::SPLAT_VECTOR:
3904     return LowerSPLAT_VECTOR(Op, DAG);
3905   case ISD::EXTRACT_SUBVECTOR:
3906     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3907   case ISD::INSERT_SUBVECTOR:
3908     return LowerINSERT_SUBVECTOR(Op, DAG);
3909   case ISD::SDIV:
3910   case ISD::UDIV:
3911     return LowerDIV(Op, DAG);
3912   case ISD::SMIN:
3913     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
3914                                /*OverrideNEON=*/true);
3915   case ISD::UMIN:
3916     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
3917                                /*OverrideNEON=*/true);
3918   case ISD::SMAX:
3919     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
3920                                /*OverrideNEON=*/true);
3921   case ISD::UMAX:
3922     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
3923                                /*OverrideNEON=*/true);
3924   case ISD::SRA:
3925   case ISD::SRL:
3926   case ISD::SHL:
3927     return LowerVectorSRA_SRL_SHL(Op, DAG);
3928   case ISD::SHL_PARTS:
3929     return LowerShiftLeftParts(Op, DAG);
3930   case ISD::SRL_PARTS:
3931   case ISD::SRA_PARTS:
3932     return LowerShiftRightParts(Op, DAG);
3933   case ISD::CTPOP:
3934     return LowerCTPOP(Op, DAG);
3935   case ISD::FCOPYSIGN:
3936     return LowerFCOPYSIGN(Op, DAG);
3937   case ISD::OR:
3938     return LowerVectorOR(Op, DAG);
3939   case ISD::XOR:
3940     return LowerXOR(Op, DAG);
3941   case ISD::PREFETCH:
3942     return LowerPREFETCH(Op, DAG);
3943   case ISD::SINT_TO_FP:
3944   case ISD::UINT_TO_FP:
3945   case ISD::STRICT_SINT_TO_FP:
3946   case ISD::STRICT_UINT_TO_FP:
3947     return LowerINT_TO_FP(Op, DAG);
3948   case ISD::FP_TO_SINT:
3949   case ISD::FP_TO_UINT:
3950   case ISD::STRICT_FP_TO_SINT:
3951   case ISD::STRICT_FP_TO_UINT:
3952     return LowerFP_TO_INT(Op, DAG);
3953   case ISD::FSINCOS:
3954     return LowerFSINCOS(Op, DAG);
3955   case ISD::FLT_ROUNDS_:
3956     return LowerFLT_ROUNDS_(Op, DAG);
3957   case ISD::MUL:
3958     return LowerMUL(Op, DAG);
3959   case ISD::INTRINSIC_WO_CHAIN:
3960     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3961   case ISD::STORE:
3962     return LowerSTORE(Op, DAG);
3963   case ISD::VECREDUCE_ADD:
3964   case ISD::VECREDUCE_AND:
3965   case ISD::VECREDUCE_OR:
3966   case ISD::VECREDUCE_XOR:
3967   case ISD::VECREDUCE_SMAX:
3968   case ISD::VECREDUCE_SMIN:
3969   case ISD::VECREDUCE_UMAX:
3970   case ISD::VECREDUCE_UMIN:
3971   case ISD::VECREDUCE_FADD:
3972   case ISD::VECREDUCE_FMAX:
3973   case ISD::VECREDUCE_FMIN:
3974     return LowerVECREDUCE(Op, DAG);
3975   case ISD::ATOMIC_LOAD_SUB:
3976     return LowerATOMIC_LOAD_SUB(Op, DAG);
3977   case ISD::ATOMIC_LOAD_AND:
3978     return LowerATOMIC_LOAD_AND(Op, DAG);
3979   case ISD::DYNAMIC_STACKALLOC:
3980     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3981   case ISD::VSCALE:
3982     return LowerVSCALE(Op, DAG);
3983   case ISD::ANY_EXTEND:
3984   case ISD::SIGN_EXTEND:
3985   case ISD::ZERO_EXTEND:
3986     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
3987   case ISD::SIGN_EXTEND_INREG: {
3988     // Only custom lower when ExtraVT has a legal byte based element type.
3989     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3990     EVT ExtraEltVT = ExtraVT.getVectorElementType();
3991     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
3992         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
3993       return SDValue();
3994 
3995     return LowerToPredicatedOp(Op, DAG,
3996                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
3997   }
3998   case ISD::TRUNCATE:
3999     return LowerTRUNCATE(Op, DAG);
4000   case ISD::LOAD:
4001     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
4002       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
4003     llvm_unreachable("Unexpected request to lower ISD::LOAD");
4004   case ISD::ADD:
4005     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
4006   case ISD::AND:
4007     return LowerToScalableOp(Op, DAG);
4008   case ISD::SUB:
4009     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
4010   case ISD::FMAXNUM:
4011     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
4012   case ISD::FMINNUM:
4013     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
4014   case ISD::VSELECT:
4015     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
4016   }
4017 }
4018 
4019 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
4020   // Prefer NEON unless larger SVE registers are available.
4021   return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
4022 }
4023 
4024 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
4025     EVT VT, bool OverrideNEON) const {
4026   if (!useSVEForFixedLengthVectors())
4027     return false;
4028 
4029   if (!VT.isFixedLengthVector())
4030     return false;
4031 
4032   // Don't use SVE for vectors we cannot scalarize if required.
4033   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
4034   // Fixed length predicates should be promoted to i8.
4035   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
4036   case MVT::i1:
4037   default:
4038     return false;
4039   case MVT::i8:
4040   case MVT::i16:
4041   case MVT::i32:
4042   case MVT::i64:
4043   case MVT::f16:
4044   case MVT::f32:
4045   case MVT::f64:
4046     break;
4047   }
4048 
4049   // All SVE implementations support NEON sized vectors.
4050   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
4051     return true;
4052 
4053   // Ensure NEON MVTs only belong to a single register class.
4054   if (VT.getSizeInBits() <= 128)
4055     return false;
4056 
4057   // Don't use SVE for types that don't fit.
4058   if (VT.getSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
4059     return false;
4060 
4061   // TODO: Perhaps an artificial restriction, but worth having whilst getting
4062   // the base fixed length SVE support in place.
4063   if (!VT.isPow2VectorType())
4064     return false;
4065 
4066   return true;
4067 }
4068 
4069 //===----------------------------------------------------------------------===//
4070 //                      Calling Convention Implementation
4071 //===----------------------------------------------------------------------===//
4072 
4073 /// Selects the correct CCAssignFn for a given CallingConvention value.
4074 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
4075                                                      bool IsVarArg) const {
4076   switch (CC) {
4077   default:
4078     report_fatal_error("Unsupported calling convention.");
4079   case CallingConv::WebKit_JS:
4080     return CC_AArch64_WebKit_JS;
4081   case CallingConv::GHC:
4082     return CC_AArch64_GHC;
4083   case CallingConv::C:
4084   case CallingConv::Fast:
4085   case CallingConv::PreserveMost:
4086   case CallingConv::CXX_FAST_TLS:
4087   case CallingConv::Swift:
4088     if (Subtarget->isTargetWindows() && IsVarArg)
4089       return CC_AArch64_Win64_VarArg;
4090     if (!Subtarget->isTargetDarwin())
4091       return CC_AArch64_AAPCS;
4092     if (!IsVarArg)
4093       return CC_AArch64_DarwinPCS;
4094     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
4095                                       : CC_AArch64_DarwinPCS_VarArg;
4096    case CallingConv::Win64:
4097     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
4098    case CallingConv::CFGuard_Check:
4099      return CC_AArch64_Win64_CFGuard_Check;
4100    case CallingConv::AArch64_VectorCall:
4101    case CallingConv::AArch64_SVE_VectorCall:
4102      return CC_AArch64_AAPCS;
4103   }
4104 }
4105 
4106 CCAssignFn *
4107 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
4108   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
4109                                       : RetCC_AArch64_AAPCS;
4110 }
4111 
4112 SDValue AArch64TargetLowering::LowerFormalArguments(
4113     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4114     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4115     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4116   MachineFunction &MF = DAG.getMachineFunction();
4117   MachineFrameInfo &MFI = MF.getFrameInfo();
4118   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4119 
4120   // Assign locations to all of the incoming arguments.
4121   SmallVector<CCValAssign, 16> ArgLocs;
4122   DenseMap<unsigned, SDValue> CopiedRegs;
4123   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4124                  *DAG.getContext());
4125 
4126   // At this point, Ins[].VT may already be promoted to i32. To correctly
4127   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4128   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4129   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
4130   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
4131   // LocVT.
4132   unsigned NumArgs = Ins.size();
4133   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4134   unsigned CurArgIdx = 0;
4135   for (unsigned i = 0; i != NumArgs; ++i) {
4136     MVT ValVT = Ins[i].VT;
4137     if (Ins[i].isOrigArg()) {
4138       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
4139       CurArgIdx = Ins[i].getOrigArgIndex();
4140 
4141       // Get type of the original argument.
4142       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
4143                                   /*AllowUnknown*/ true);
4144       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
4145       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4146       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4147         ValVT = MVT::i8;
4148       else if (ActualMVT == MVT::i16)
4149         ValVT = MVT::i16;
4150     }
4151     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4152     bool Res =
4153         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
4154     assert(!Res && "Call operand has unhandled type");
4155     (void)Res;
4156   }
4157   assert(ArgLocs.size() == Ins.size());
4158   SmallVector<SDValue, 16> ArgValues;
4159   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4160     CCValAssign &VA = ArgLocs[i];
4161 
4162     if (Ins[i].Flags.isByVal()) {
4163       // Byval is used for HFAs in the PCS, but the system should work in a
4164       // non-compliant manner for larger structs.
4165       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4166       int Size = Ins[i].Flags.getByValSize();
4167       unsigned NumRegs = (Size + 7) / 8;
4168 
4169       // FIXME: This works on big-endian for composite byvals, which are the common
4170       // case. It should also work for fundamental types too.
4171       unsigned FrameIdx =
4172         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
4173       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
4174       InVals.push_back(FrameIdxN);
4175 
4176       continue;
4177     }
4178 
4179     SDValue ArgValue;
4180     if (VA.isRegLoc()) {
4181       // Arguments stored in registers.
4182       EVT RegVT = VA.getLocVT();
4183       const TargetRegisterClass *RC;
4184 
4185       if (RegVT == MVT::i32)
4186         RC = &AArch64::GPR32RegClass;
4187       else if (RegVT == MVT::i64)
4188         RC = &AArch64::GPR64RegClass;
4189       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4190         RC = &AArch64::FPR16RegClass;
4191       else if (RegVT == MVT::f32)
4192         RC = &AArch64::FPR32RegClass;
4193       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
4194         RC = &AArch64::FPR64RegClass;
4195       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
4196         RC = &AArch64::FPR128RegClass;
4197       else if (RegVT.isScalableVector() &&
4198                RegVT.getVectorElementType() == MVT::i1)
4199         RC = &AArch64::PPRRegClass;
4200       else if (RegVT.isScalableVector())
4201         RC = &AArch64::ZPRRegClass;
4202       else
4203         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4204 
4205       // Transform the arguments in physical registers into virtual ones.
4206       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4207       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
4208 
4209       // If this is an 8, 16 or 32-bit value, it is really passed promoted
4210       // to 64 bits.  Insert an assert[sz]ext to capture this, then
4211       // truncate to the right size.
4212       switch (VA.getLocInfo()) {
4213       default:
4214         llvm_unreachable("Unknown loc info!");
4215       case CCValAssign::Full:
4216         break;
4217       case CCValAssign::Indirect:
4218         assert(VA.getValVT().isScalableVector() &&
4219                "Only scalable vectors can be passed indirectly");
4220         break;
4221       case CCValAssign::BCvt:
4222         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
4223         break;
4224       case CCValAssign::AExt:
4225       case CCValAssign::SExt:
4226       case CCValAssign::ZExt:
4227         break;
4228       case CCValAssign::AExtUpper:
4229         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
4230                                DAG.getConstant(32, DL, RegVT));
4231         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
4232         break;
4233       }
4234     } else { // VA.isRegLoc()
4235       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
4236       unsigned ArgOffset = VA.getLocMemOffset();
4237       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
4238                               ? VA.getLocVT().getSizeInBits()
4239                               : VA.getValVT().getSizeInBits()) / 8;
4240 
4241       uint32_t BEAlign = 0;
4242       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
4243           !Ins[i].Flags.isInConsecutiveRegs())
4244         BEAlign = 8 - ArgSize;
4245 
4246       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
4247 
4248       // Create load nodes to retrieve arguments from the stack.
4249       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4250 
4251       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
4252       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4253       MVT MemVT = VA.getValVT();
4254 
4255       switch (VA.getLocInfo()) {
4256       default:
4257         break;
4258       case CCValAssign::Trunc:
4259       case CCValAssign::BCvt:
4260         MemVT = VA.getLocVT();
4261         break;
4262       case CCValAssign::Indirect:
4263         assert(VA.getValVT().isScalableVector() &&
4264                "Only scalable vectors can be passed indirectly");
4265         MemVT = VA.getLocVT();
4266         break;
4267       case CCValAssign::SExt:
4268         ExtType = ISD::SEXTLOAD;
4269         break;
4270       case CCValAssign::ZExt:
4271         ExtType = ISD::ZEXTLOAD;
4272         break;
4273       case CCValAssign::AExt:
4274         ExtType = ISD::EXTLOAD;
4275         break;
4276       }
4277 
4278       ArgValue = DAG.getExtLoad(
4279           ExtType, DL, VA.getLocVT(), Chain, FIN,
4280           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
4281           MemVT);
4282 
4283     }
4284 
4285     if (VA.getLocInfo() == CCValAssign::Indirect) {
4286       assert(VA.getValVT().isScalableVector() &&
4287            "Only scalable vectors can be passed indirectly");
4288       // If value is passed via pointer - do a load.
4289       ArgValue =
4290           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
4291     }
4292 
4293     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
4294       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
4295                              ArgValue, DAG.getValueType(MVT::i32));
4296     InVals.push_back(ArgValue);
4297   }
4298 
4299   // varargs
4300   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4301   if (isVarArg) {
4302     if (!Subtarget->isTargetDarwin() || IsWin64) {
4303       // The AAPCS variadic function ABI is identical to the non-variadic
4304       // one. As a result there may be more arguments in registers and we should
4305       // save them for future reference.
4306       // Win64 variadic functions also pass arguments in registers, but all float
4307       // arguments are passed in integer registers.
4308       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
4309     }
4310 
4311     // This will point to the next argument passed via stack.
4312     unsigned StackOffset = CCInfo.getNextStackOffset();
4313     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
4314     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
4315     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
4316 
4317     if (MFI.hasMustTailInVarArgFunc()) {
4318       SmallVector<MVT, 2> RegParmTypes;
4319       RegParmTypes.push_back(MVT::i64);
4320       RegParmTypes.push_back(MVT::f128);
4321       // Compute the set of forwarded registers. The rest are scratch.
4322       SmallVectorImpl<ForwardedRegister> &Forwards =
4323                                        FuncInfo->getForwardedMustTailRegParms();
4324       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
4325                                                CC_AArch64_AAPCS);
4326 
4327       // Conservatively forward X8, since it might be used for aggregate return.
4328       if (!CCInfo.isAllocated(AArch64::X8)) {
4329         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
4330         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
4331       }
4332     }
4333   }
4334 
4335   // On Windows, InReg pointers must be returned, so record the pointer in a
4336   // virtual register at the start of the function so it can be returned in the
4337   // epilogue.
4338   if (IsWin64) {
4339     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4340       if (Ins[I].Flags.isInReg()) {
4341         assert(!FuncInfo->getSRetReturnReg());
4342 
4343         MVT PtrTy = getPointerTy(DAG.getDataLayout());
4344         Register Reg =
4345             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4346         FuncInfo->setSRetReturnReg(Reg);
4347 
4348         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
4349         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4350         break;
4351       }
4352     }
4353   }
4354 
4355   unsigned StackArgSize = CCInfo.getNextStackOffset();
4356   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4357   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
4358     // This is a non-standard ABI so by fiat I say we're allowed to make full
4359     // use of the stack area to be popped, which must be aligned to 16 bytes in
4360     // any case:
4361     StackArgSize = alignTo(StackArgSize, 16);
4362 
4363     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
4364     // a multiple of 16.
4365     FuncInfo->setArgumentStackToRestore(StackArgSize);
4366 
4367     // This realignment carries over to the available bytes below. Our own
4368     // callers will guarantee the space is free by giving an aligned value to
4369     // CALLSEQ_START.
4370   }
4371   // Even if we're not expected to free up the space, it's useful to know how
4372   // much is there while considering tail calls (because we can reuse it).
4373   FuncInfo->setBytesInStackArgArea(StackArgSize);
4374 
4375   if (Subtarget->hasCustomCallingConv())
4376     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
4377 
4378   return Chain;
4379 }
4380 
4381 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
4382                                                 SelectionDAG &DAG,
4383                                                 const SDLoc &DL,
4384                                                 SDValue &Chain) const {
4385   MachineFunction &MF = DAG.getMachineFunction();
4386   MachineFrameInfo &MFI = MF.getFrameInfo();
4387   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4388   auto PtrVT = getPointerTy(DAG.getDataLayout());
4389   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4390 
4391   SmallVector<SDValue, 8> MemOps;
4392 
4393   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
4394                                           AArch64::X3, AArch64::X4, AArch64::X5,
4395                                           AArch64::X6, AArch64::X7 };
4396   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
4397   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
4398 
4399   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
4400   int GPRIdx = 0;
4401   if (GPRSaveSize != 0) {
4402     if (IsWin64) {
4403       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
4404       if (GPRSaveSize & 15)
4405         // The extra size here, if triggered, will always be 8.
4406         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
4407     } else
4408       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
4409 
4410     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
4411 
4412     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
4413       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
4414       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
4415       SDValue Store = DAG.getStore(
4416           Val.getValue(1), DL, Val, FIN,
4417           IsWin64
4418               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
4419                                                   GPRIdx,
4420                                                   (i - FirstVariadicGPR) * 8)
4421               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
4422       MemOps.push_back(Store);
4423       FIN =
4424           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
4425     }
4426   }
4427   FuncInfo->setVarArgsGPRIndex(GPRIdx);
4428   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4429 
4430   if (Subtarget->hasFPARMv8() && !IsWin64) {
4431     static const MCPhysReg FPRArgRegs[] = {
4432         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4433         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4434     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4435     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4436 
4437     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4438     int FPRIdx = 0;
4439     if (FPRSaveSize != 0) {
4440       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4441 
4442       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4443 
4444       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4445         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4446         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4447 
4448         SDValue Store = DAG.getStore(
4449             Val.getValue(1), DL, Val, FIN,
4450             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4451         MemOps.push_back(Store);
4452         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4453                           DAG.getConstant(16, DL, PtrVT));
4454       }
4455     }
4456     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4457     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4458   }
4459 
4460   if (!MemOps.empty()) {
4461     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4462   }
4463 }
4464 
4465 /// LowerCallResult - Lower the result values of a call into the
4466 /// appropriate copies out of appropriate physical registers.
4467 SDValue AArch64TargetLowering::LowerCallResult(
4468     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4469     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4470     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4471     SDValue ThisVal) const {
4472   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
4473   // Assign locations to each value returned by this call.
4474   SmallVector<CCValAssign, 16> RVLocs;
4475   DenseMap<unsigned, SDValue> CopiedRegs;
4476   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4477                  *DAG.getContext());
4478   CCInfo.AnalyzeCallResult(Ins, RetCC);
4479 
4480   // Copy all of the result registers out of their specified physreg.
4481   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4482     CCValAssign VA = RVLocs[i];
4483 
4484     // Pass 'this' value directly from the argument to return value, to avoid
4485     // reg unit interference
4486     if (i == 0 && isThisReturn) {
4487       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4488              "unexpected return calling convention register assignment");
4489       InVals.push_back(ThisVal);
4490       continue;
4491     }
4492 
4493     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4494     // allows one use of a physreg per block.
4495     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4496     if (!Val) {
4497       Val =
4498           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4499       Chain = Val.getValue(1);
4500       InFlag = Val.getValue(2);
4501       CopiedRegs[VA.getLocReg()] = Val;
4502     }
4503 
4504     switch (VA.getLocInfo()) {
4505     default:
4506       llvm_unreachable("Unknown loc info!");
4507     case CCValAssign::Full:
4508       break;
4509     case CCValAssign::BCvt:
4510       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4511       break;
4512     case CCValAssign::AExtUpper:
4513       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4514                         DAG.getConstant(32, DL, VA.getLocVT()));
4515       LLVM_FALLTHROUGH;
4516     case CCValAssign::AExt:
4517       LLVM_FALLTHROUGH;
4518     case CCValAssign::ZExt:
4519       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4520       break;
4521     }
4522 
4523     InVals.push_back(Val);
4524   }
4525 
4526   return Chain;
4527 }
4528 
4529 /// Return true if the calling convention is one that we can guarantee TCO for.
4530 static bool canGuaranteeTCO(CallingConv::ID CC) {
4531   return CC == CallingConv::Fast;
4532 }
4533 
4534 /// Return true if we might ever do TCO for calls with this calling convention.
4535 static bool mayTailCallThisCC(CallingConv::ID CC) {
4536   switch (CC) {
4537   case CallingConv::C:
4538   case CallingConv::AArch64_SVE_VectorCall:
4539   case CallingConv::PreserveMost:
4540   case CallingConv::Swift:
4541     return true;
4542   default:
4543     return canGuaranteeTCO(CC);
4544   }
4545 }
4546 
4547 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4548     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4549     const SmallVectorImpl<ISD::OutputArg> &Outs,
4550     const SmallVectorImpl<SDValue> &OutVals,
4551     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4552   if (!mayTailCallThisCC(CalleeCC))
4553     return false;
4554 
4555   MachineFunction &MF = DAG.getMachineFunction();
4556   const Function &CallerF = MF.getFunction();
4557   CallingConv::ID CallerCC = CallerF.getCallingConv();
4558 
4559   // If this function uses the C calling convention but has an SVE signature,
4560   // then it preserves more registers and should assume the SVE_VectorCall CC.
4561   // The check for matching callee-saved regs will determine whether it is
4562   // eligible for TCO.
4563   if (CallerCC == CallingConv::C &&
4564       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
4565     CallerCC = CallingConv::AArch64_SVE_VectorCall;
4566 
4567   bool CCMatch = CallerCC == CalleeCC;
4568 
4569   // When using the Windows calling convention on a non-windows OS, we want
4570   // to back up and restore X18 in such functions; we can't do a tail call
4571   // from those functions.
4572   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4573       CalleeCC != CallingConv::Win64)
4574     return false;
4575 
4576   // Byval parameters hand the function a pointer directly into the stack area
4577   // we want to reuse during a tail call. Working around this *is* possible (see
4578   // X86) but less efficient and uglier in LowerCall.
4579   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4580                                     e = CallerF.arg_end();
4581        i != e; ++i) {
4582     if (i->hasByValAttr())
4583       return false;
4584 
4585     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4586     // In this case, it is necessary to save/restore X0 in the callee. Tail
4587     // call opt interferes with this. So we disable tail call opt when the
4588     // caller has an argument with "inreg" attribute.
4589 
4590     // FIXME: Check whether the callee also has an "inreg" argument.
4591     if (i->hasInRegAttr())
4592       return false;
4593   }
4594 
4595   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4596     return canGuaranteeTCO(CalleeCC) && CCMatch;
4597 
4598   // Externally-defined functions with weak linkage should not be
4599   // tail-called on AArch64 when the OS does not support dynamic
4600   // pre-emption of symbols, as the AAELF spec requires normal calls
4601   // to undefined weak functions to be replaced with a NOP or jump to the
4602   // next instruction. The behaviour of branch instructions in this
4603   // situation (as used for tail calls) is implementation-defined, so we
4604   // cannot rely on the linker replacing the tail call with a return.
4605   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4606     const GlobalValue *GV = G->getGlobal();
4607     const Triple &TT = getTargetMachine().getTargetTriple();
4608     if (GV->hasExternalWeakLinkage() &&
4609         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4610       return false;
4611   }
4612 
4613   // Now we search for cases where we can use a tail call without changing the
4614   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4615   // concept.
4616 
4617   // I want anyone implementing a new calling convention to think long and hard
4618   // about this assert.
4619   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4620          "Unexpected variadic calling convention");
4621 
4622   LLVMContext &C = *DAG.getContext();
4623   if (isVarArg && !Outs.empty()) {
4624     // At least two cases here: if caller is fastcc then we can't have any
4625     // memory arguments (we'd be expected to clean up the stack afterwards). If
4626     // caller is C then we could potentially use its argument area.
4627 
4628     // FIXME: for now we take the most conservative of these in both cases:
4629     // disallow all variadic memory operands.
4630     SmallVector<CCValAssign, 16> ArgLocs;
4631     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4632 
4633     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4634     for (const CCValAssign &ArgLoc : ArgLocs)
4635       if (!ArgLoc.isRegLoc())
4636         return false;
4637   }
4638 
4639   // Check that the call results are passed in the same way.
4640   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4641                                   CCAssignFnForCall(CalleeCC, isVarArg),
4642                                   CCAssignFnForCall(CallerCC, isVarArg)))
4643     return false;
4644   // The callee has to preserve all registers the caller needs to preserve.
4645   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4646   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4647   if (!CCMatch) {
4648     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4649     if (Subtarget->hasCustomCallingConv()) {
4650       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4651       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4652     }
4653     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4654       return false;
4655   }
4656 
4657   // Nothing more to check if the callee is taking no arguments
4658   if (Outs.empty())
4659     return true;
4660 
4661   SmallVector<CCValAssign, 16> ArgLocs;
4662   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4663 
4664   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4665 
4666   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4667 
4668   // If any of the arguments is passed indirectly, it must be SVE, so the
4669   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4670   // allocate space on the stack. That is why we determine this explicitly here
4671   // the call cannot be a tailcall.
4672   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4673         assert((A.getLocInfo() != CCValAssign::Indirect ||
4674                 A.getValVT().isScalableVector()) &&
4675                "Expected value to be scalable");
4676         return A.getLocInfo() == CCValAssign::Indirect;
4677       }))
4678     return false;
4679 
4680   // If the stack arguments for this call do not fit into our own save area then
4681   // the call cannot be made tail.
4682   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4683     return false;
4684 
4685   const MachineRegisterInfo &MRI = MF.getRegInfo();
4686   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4687     return false;
4688 
4689   return true;
4690 }
4691 
4692 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4693                                                    SelectionDAG &DAG,
4694                                                    MachineFrameInfo &MFI,
4695                                                    int ClobberedFI) const {
4696   SmallVector<SDValue, 8> ArgChains;
4697   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4698   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4699 
4700   // Include the original chain at the beginning of the list. When this is
4701   // used by target LowerCall hooks, this helps legalize find the
4702   // CALLSEQ_BEGIN node.
4703   ArgChains.push_back(Chain);
4704 
4705   // Add a chain value for each stack argument corresponding
4706   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4707                             UE = DAG.getEntryNode().getNode()->use_end();
4708        U != UE; ++U)
4709     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4710       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4711         if (FI->getIndex() < 0) {
4712           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4713           int64_t InLastByte = InFirstByte;
4714           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4715 
4716           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4717               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4718             ArgChains.push_back(SDValue(L, 1));
4719         }
4720 
4721   // Build a tokenfactor for all the chains.
4722   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4723 }
4724 
4725 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4726                                                    bool TailCallOpt) const {
4727   return CallCC == CallingConv::Fast && TailCallOpt;
4728 }
4729 
4730 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4731 /// and add input and output parameter nodes.
4732 SDValue
4733 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4734                                  SmallVectorImpl<SDValue> &InVals) const {
4735   SelectionDAG &DAG = CLI.DAG;
4736   SDLoc &DL = CLI.DL;
4737   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4738   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4739   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4740   SDValue Chain = CLI.Chain;
4741   SDValue Callee = CLI.Callee;
4742   bool &IsTailCall = CLI.IsTailCall;
4743   CallingConv::ID CallConv = CLI.CallConv;
4744   bool IsVarArg = CLI.IsVarArg;
4745 
4746   MachineFunction &MF = DAG.getMachineFunction();
4747   MachineFunction::CallSiteInfo CSInfo;
4748   bool IsThisReturn = false;
4749 
4750   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4751   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4752   bool IsSibCall = false;
4753 
4754   // Check callee args/returns for SVE registers and set calling convention
4755   // accordingly.
4756   if (CallConv == CallingConv::C) {
4757     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4758       return Out.VT.isScalableVector();
4759     });
4760     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4761       return In.VT.isScalableVector();
4762     });
4763 
4764     if (CalleeInSVE || CalleeOutSVE)
4765       CallConv = CallingConv::AArch64_SVE_VectorCall;
4766   }
4767 
4768   if (IsTailCall) {
4769     // Check if it's really possible to do a tail call.
4770     IsTailCall = isEligibleForTailCallOptimization(
4771         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4772     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4773       report_fatal_error("failed to perform tail call elimination on a call "
4774                          "site marked musttail");
4775 
4776     // A sibling call is one where we're under the usual C ABI and not planning
4777     // to change that but can still do a tail call:
4778     if (!TailCallOpt && IsTailCall)
4779       IsSibCall = true;
4780 
4781     if (IsTailCall)
4782       ++NumTailCalls;
4783   }
4784 
4785   // Analyze operands of the call, assigning locations to each operand.
4786   SmallVector<CCValAssign, 16> ArgLocs;
4787   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4788                  *DAG.getContext());
4789 
4790   if (IsVarArg) {
4791     // Handle fixed and variable vector arguments differently.
4792     // Variable vector arguments always go into memory.
4793     unsigned NumArgs = Outs.size();
4794 
4795     for (unsigned i = 0; i != NumArgs; ++i) {
4796       MVT ArgVT = Outs[i].VT;
4797       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4798       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4799                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4800       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4801       assert(!Res && "Call operand has unhandled type");
4802       (void)Res;
4803     }
4804   } else {
4805     // At this point, Outs[].VT may already be promoted to i32. To correctly
4806     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4807     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4808     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4809     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4810     // LocVT.
4811     unsigned NumArgs = Outs.size();
4812     for (unsigned i = 0; i != NumArgs; ++i) {
4813       MVT ValVT = Outs[i].VT;
4814       // Get type of the original argument.
4815       EVT ActualVT = getValueType(DAG.getDataLayout(),
4816                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4817                                   /*AllowUnknown*/ true);
4818       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4819       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4820       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4821       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4822         ValVT = MVT::i8;
4823       else if (ActualMVT == MVT::i16)
4824         ValVT = MVT::i16;
4825 
4826       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4827       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4828       assert(!Res && "Call operand has unhandled type");
4829       (void)Res;
4830     }
4831   }
4832 
4833   // Get a count of how many bytes are to be pushed on the stack.
4834   unsigned NumBytes = CCInfo.getNextStackOffset();
4835 
4836   if (IsSibCall) {
4837     // Since we're not changing the ABI to make this a tail call, the memory
4838     // operands are already available in the caller's incoming argument space.
4839     NumBytes = 0;
4840   }
4841 
4842   // FPDiff is the byte offset of the call's argument area from the callee's.
4843   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4844   // by this amount for a tail call. In a sibling call it must be 0 because the
4845   // caller will deallocate the entire stack and the callee still expects its
4846   // arguments to begin at SP+0. Completely unused for non-tail calls.
4847   int FPDiff = 0;
4848 
4849   if (IsTailCall && !IsSibCall) {
4850     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4851 
4852     // Since callee will pop argument stack as a tail call, we must keep the
4853     // popped size 16-byte aligned.
4854     NumBytes = alignTo(NumBytes, 16);
4855 
4856     // FPDiff will be negative if this tail call requires more space than we
4857     // would automatically have in our incoming argument space. Positive if we
4858     // can actually shrink the stack.
4859     FPDiff = NumReusableBytes - NumBytes;
4860 
4861     // The stack pointer must be 16-byte aligned at all times it's used for a
4862     // memory operation, which in practice means at *all* times and in
4863     // particular across call boundaries. Therefore our own arguments started at
4864     // a 16-byte aligned SP and the delta applied for the tail call should
4865     // satisfy the same constraint.
4866     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4867   }
4868 
4869   // Adjust the stack pointer for the new arguments...
4870   // These operations are automatically eliminated by the prolog/epilog pass
4871   if (!IsSibCall)
4872     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4873 
4874   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4875                                         getPointerTy(DAG.getDataLayout()));
4876 
4877   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4878   SmallSet<unsigned, 8> RegsUsed;
4879   SmallVector<SDValue, 8> MemOpChains;
4880   auto PtrVT = getPointerTy(DAG.getDataLayout());
4881 
4882   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4883     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4884     for (const auto &F : Forwards) {
4885       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4886        RegsToPass.emplace_back(F.PReg, Val);
4887     }
4888   }
4889 
4890   // Walk the register/memloc assignments, inserting copies/loads.
4891   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4892     CCValAssign &VA = ArgLocs[i];
4893     SDValue Arg = OutVals[i];
4894     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4895 
4896     // Promote the value if needed.
4897     switch (VA.getLocInfo()) {
4898     default:
4899       llvm_unreachable("Unknown loc info!");
4900     case CCValAssign::Full:
4901       break;
4902     case CCValAssign::SExt:
4903       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4904       break;
4905     case CCValAssign::ZExt:
4906       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4907       break;
4908     case CCValAssign::AExt:
4909       if (Outs[i].ArgVT == MVT::i1) {
4910         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4911         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4912         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4913       }
4914       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4915       break;
4916     case CCValAssign::AExtUpper:
4917       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4918       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4919       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4920                         DAG.getConstant(32, DL, VA.getLocVT()));
4921       break;
4922     case CCValAssign::BCvt:
4923       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4924       break;
4925     case CCValAssign::Trunc:
4926       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4927       break;
4928     case CCValAssign::FPExt:
4929       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4930       break;
4931     case CCValAssign::Indirect:
4932       assert(VA.getValVT().isScalableVector() &&
4933              "Only scalable vectors can be passed indirectly");
4934       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4935       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4936       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4937       int FI = MFI.CreateStackObject(
4938           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4939       MFI.setStackID(FI, TargetStackID::SVEVector);
4940 
4941       SDValue SpillSlot = DAG.getFrameIndex(
4942           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4943       Chain = DAG.getStore(
4944           Chain, DL, Arg, SpillSlot,
4945           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4946       Arg = SpillSlot;
4947       break;
4948     }
4949 
4950     if (VA.isRegLoc()) {
4951       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4952           Outs[0].VT == MVT::i64) {
4953         assert(VA.getLocVT() == MVT::i64 &&
4954                "unexpected calling convention register assignment");
4955         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4956                "unexpected use of 'returned'");
4957         IsThisReturn = true;
4958       }
4959       if (RegsUsed.count(VA.getLocReg())) {
4960         // If this register has already been used then we're trying to pack
4961         // parts of an [N x i32] into an X-register. The extension type will
4962         // take care of putting the two halves in the right place but we have to
4963         // combine them.
4964         SDValue &Bits =
4965             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4966                          [=](const std::pair<unsigned, SDValue> &Elt) {
4967                            return Elt.first == VA.getLocReg();
4968                          })
4969                 ->second;
4970         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4971         // Call site info is used for function's parameter entry value
4972         // tracking. For now we track only simple cases when parameter
4973         // is transferred through whole register.
4974         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4975                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4976                                       return ArgReg.Reg == VA.getLocReg();
4977                                     }),
4978                      CSInfo.end());
4979       } else {
4980         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4981         RegsUsed.insert(VA.getLocReg());
4982         const TargetOptions &Options = DAG.getTarget().Options;
4983         if (Options.EmitCallSiteInfo)
4984           CSInfo.emplace_back(VA.getLocReg(), i);
4985       }
4986     } else {
4987       assert(VA.isMemLoc());
4988 
4989       SDValue DstAddr;
4990       MachinePointerInfo DstInfo;
4991 
4992       // FIXME: This works on big-endian for composite byvals, which are the
4993       // common case. It should also work for fundamental types too.
4994       uint32_t BEAlign = 0;
4995       unsigned OpSize;
4996       if (VA.getLocInfo() == CCValAssign::Indirect)
4997         OpSize = VA.getLocVT().getSizeInBits();
4998       else
4999         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
5000                                  : VA.getValVT().getSizeInBits();
5001       OpSize = (OpSize + 7) / 8;
5002       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
5003           !Flags.isInConsecutiveRegs()) {
5004         if (OpSize < 8)
5005           BEAlign = 8 - OpSize;
5006       }
5007       unsigned LocMemOffset = VA.getLocMemOffset();
5008       int32_t Offset = LocMemOffset + BEAlign;
5009       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5010       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5011 
5012       if (IsTailCall) {
5013         Offset = Offset + FPDiff;
5014         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5015 
5016         DstAddr = DAG.getFrameIndex(FI, PtrVT);
5017         DstInfo =
5018             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
5019 
5020         // Make sure any stack arguments overlapping with where we're storing
5021         // are loaded before this eventual operation. Otherwise they'll be
5022         // clobbered.
5023         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
5024       } else {
5025         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5026 
5027         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5028         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
5029                                                LocMemOffset);
5030       }
5031 
5032       if (Outs[i].Flags.isByVal()) {
5033         SDValue SizeNode =
5034             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
5035         SDValue Cpy = DAG.getMemcpy(
5036             Chain, DL, DstAddr, Arg, SizeNode,
5037             Outs[i].Flags.getNonZeroByValAlign(),
5038             /*isVol = */ false, /*AlwaysInline = */ false,
5039             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
5040 
5041         MemOpChains.push_back(Cpy);
5042       } else {
5043         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
5044         // promoted to a legal register type i32, we should truncate Arg back to
5045         // i1/i8/i16.
5046         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
5047             VA.getValVT() == MVT::i16)
5048           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
5049 
5050         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
5051         MemOpChains.push_back(Store);
5052       }
5053     }
5054   }
5055 
5056   if (!MemOpChains.empty())
5057     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
5058 
5059   // Build a sequence of copy-to-reg nodes chained together with token chain
5060   // and flag operands which copy the outgoing args into the appropriate regs.
5061   SDValue InFlag;
5062   for (auto &RegToPass : RegsToPass) {
5063     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
5064                              RegToPass.second, InFlag);
5065     InFlag = Chain.getValue(1);
5066   }
5067 
5068   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
5069   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
5070   // node so that legalize doesn't hack it.
5071   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5072     auto GV = G->getGlobal();
5073     unsigned OpFlags =
5074         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
5075     if (OpFlags & AArch64II::MO_GOT) {
5076       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
5077       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5078     } else {
5079       const GlobalValue *GV = G->getGlobal();
5080       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
5081     }
5082   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5083     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5084         Subtarget->isTargetMachO()) {
5085       const char *Sym = S->getSymbol();
5086       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
5087       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5088     } else {
5089       const char *Sym = S->getSymbol();
5090       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
5091     }
5092   }
5093 
5094   // We don't usually want to end the call-sequence here because we would tidy
5095   // the frame up *after* the call, however in the ABI-changing tail-call case
5096   // we've carefully laid out the parameters so that when sp is reset they'll be
5097   // in the correct location.
5098   if (IsTailCall && !IsSibCall) {
5099     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5100                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
5101     InFlag = Chain.getValue(1);
5102   }
5103 
5104   std::vector<SDValue> Ops;
5105   Ops.push_back(Chain);
5106   Ops.push_back(Callee);
5107 
5108   if (IsTailCall) {
5109     // Each tail call may have to adjust the stack by a different amount, so
5110     // this information must travel along with the operation for eventual
5111     // consumption by emitEpilogue.
5112     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
5113   }
5114 
5115   // Add argument registers to the end of the list so that they are known live
5116   // into the call.
5117   for (auto &RegToPass : RegsToPass)
5118     Ops.push_back(DAG.getRegister(RegToPass.first,
5119                                   RegToPass.second.getValueType()));
5120 
5121   // Add a register mask operand representing the call-preserved registers.
5122   const uint32_t *Mask;
5123   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5124   if (IsThisReturn) {
5125     // For 'this' returns, use the X0-preserving mask if applicable
5126     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
5127     if (!Mask) {
5128       IsThisReturn = false;
5129       Mask = TRI->getCallPreservedMask(MF, CallConv);
5130     }
5131   } else
5132     Mask = TRI->getCallPreservedMask(MF, CallConv);
5133 
5134   if (Subtarget->hasCustomCallingConv())
5135     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
5136 
5137   if (TRI->isAnyArgRegReserved(MF))
5138     TRI->emitReservedArgRegCallError(MF);
5139 
5140   assert(Mask && "Missing call preserved mask for calling convention");
5141   Ops.push_back(DAG.getRegisterMask(Mask));
5142 
5143   if (InFlag.getNode())
5144     Ops.push_back(InFlag);
5145 
5146   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5147 
5148   // If we're doing a tall call, use a TC_RETURN here rather than an
5149   // actual call instruction.
5150   if (IsTailCall) {
5151     MF.getFrameInfo().setHasTailCall();
5152     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
5153     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
5154     return Ret;
5155   }
5156 
5157   // Returns a chain and a flag for retval copy to use.
5158   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
5159   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5160   InFlag = Chain.getValue(1);
5161   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
5162 
5163   uint64_t CalleePopBytes =
5164       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
5165 
5166   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5167                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
5168                              InFlag, DL);
5169   if (!Ins.empty())
5170     InFlag = Chain.getValue(1);
5171 
5172   // Handle result values, copying them out of physregs into vregs that we
5173   // return.
5174   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
5175                          InVals, IsThisReturn,
5176                          IsThisReturn ? OutVals[0] : SDValue());
5177 }
5178 
5179 bool AArch64TargetLowering::CanLowerReturn(
5180     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
5181     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
5182   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5183   SmallVector<CCValAssign, 16> RVLocs;
5184   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5185   return CCInfo.CheckReturn(Outs, RetCC);
5186 }
5187 
5188 SDValue
5189 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5190                                    bool isVarArg,
5191                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
5192                                    const SmallVectorImpl<SDValue> &OutVals,
5193                                    const SDLoc &DL, SelectionDAG &DAG) const {
5194   auto &MF = DAG.getMachineFunction();
5195   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5196 
5197   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5198   SmallVector<CCValAssign, 16> RVLocs;
5199   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5200                  *DAG.getContext());
5201   CCInfo.AnalyzeReturn(Outs, RetCC);
5202 
5203   // Copy the result values into the output registers.
5204   SDValue Flag;
5205   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
5206   SmallSet<unsigned, 4> RegsUsed;
5207   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
5208        ++i, ++realRVLocIdx) {
5209     CCValAssign &VA = RVLocs[i];
5210     assert(VA.isRegLoc() && "Can only return in registers!");
5211     SDValue Arg = OutVals[realRVLocIdx];
5212 
5213     switch (VA.getLocInfo()) {
5214     default:
5215       llvm_unreachable("Unknown loc info!");
5216     case CCValAssign::Full:
5217       if (Outs[i].ArgVT == MVT::i1) {
5218         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
5219         // value. This is strictly redundant on Darwin (which uses "zeroext
5220         // i1"), but will be optimised out before ISel.
5221         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5222         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5223       }
5224       break;
5225     case CCValAssign::BCvt:
5226       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
5227       break;
5228     case CCValAssign::AExt:
5229     case CCValAssign::ZExt:
5230       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5231       break;
5232     case CCValAssign::AExtUpper:
5233       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5234       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5235       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5236                         DAG.getConstant(32, DL, VA.getLocVT()));
5237       break;
5238     }
5239 
5240     if (RegsUsed.count(VA.getLocReg())) {
5241       SDValue &Bits =
5242           std::find_if(RetVals.begin(), RetVals.end(),
5243                        [=](const std::pair<unsigned, SDValue> &Elt) {
5244                          return Elt.first == VA.getLocReg();
5245                        })
5246               ->second;
5247       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5248     } else {
5249       RetVals.emplace_back(VA.getLocReg(), Arg);
5250       RegsUsed.insert(VA.getLocReg());
5251     }
5252   }
5253 
5254   SmallVector<SDValue, 4> RetOps(1, Chain);
5255   for (auto &RetVal : RetVals) {
5256     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
5257     Flag = Chain.getValue(1);
5258     RetOps.push_back(
5259         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
5260   }
5261 
5262   // Windows AArch64 ABIs require that for returning structs by value we copy
5263   // the sret argument into X0 for the return.
5264   // We saved the argument into a virtual register in the entry block,
5265   // so now we copy the value out and into X0.
5266   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
5267     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
5268                                      getPointerTy(MF.getDataLayout()));
5269 
5270     unsigned RetValReg = AArch64::X0;
5271     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
5272     Flag = Chain.getValue(1);
5273 
5274     RetOps.push_back(
5275       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
5276   }
5277 
5278   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5279   const MCPhysReg *I =
5280       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5281   if (I) {
5282     for (; *I; ++I) {
5283       if (AArch64::GPR64RegClass.contains(*I))
5284         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5285       else if (AArch64::FPR64RegClass.contains(*I))
5286         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5287       else
5288         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5289     }
5290   }
5291 
5292   RetOps[0] = Chain; // Update chain.
5293 
5294   // Add the flag if we have it.
5295   if (Flag.getNode())
5296     RetOps.push_back(Flag);
5297 
5298   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
5299 }
5300 
5301 //===----------------------------------------------------------------------===//
5302 //  Other Lowering Code
5303 //===----------------------------------------------------------------------===//
5304 
5305 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
5306                                              SelectionDAG &DAG,
5307                                              unsigned Flag) const {
5308   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
5309                                     N->getOffset(), Flag);
5310 }
5311 
5312 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
5313                                              SelectionDAG &DAG,
5314                                              unsigned Flag) const {
5315   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
5316 }
5317 
5318 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
5319                                              SelectionDAG &DAG,
5320                                              unsigned Flag) const {
5321   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
5322                                    N->getOffset(), Flag);
5323 }
5324 
5325 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
5326                                              SelectionDAG &DAG,
5327                                              unsigned Flag) const {
5328   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
5329 }
5330 
5331 // (loadGOT sym)
5332 template <class NodeTy>
5333 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
5334                                       unsigned Flags) const {
5335   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
5336   SDLoc DL(N);
5337   EVT Ty = getPointerTy(DAG.getDataLayout());
5338   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
5339   // FIXME: Once remat is capable of dealing with instructions with register
5340   // operands, expand this into two nodes instead of using a wrapper node.
5341   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
5342 }
5343 
5344 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
5345 template <class NodeTy>
5346 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
5347                                             unsigned Flags) const {
5348   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
5349   SDLoc DL(N);
5350   EVT Ty = getPointerTy(DAG.getDataLayout());
5351   const unsigned char MO_NC = AArch64II::MO_NC;
5352   return DAG.getNode(
5353       AArch64ISD::WrapperLarge, DL, Ty,
5354       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
5355       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
5356       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
5357       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
5358 }
5359 
5360 // (addlow (adrp %hi(sym)) %lo(sym))
5361 template <class NodeTy>
5362 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
5363                                        unsigned Flags) const {
5364   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
5365   SDLoc DL(N);
5366   EVT Ty = getPointerTy(DAG.getDataLayout());
5367   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
5368   SDValue Lo = getTargetNode(N, Ty, DAG,
5369                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
5370   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
5371   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
5372 }
5373 
5374 // (adr sym)
5375 template <class NodeTy>
5376 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
5377                                            unsigned Flags) const {
5378   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
5379   SDLoc DL(N);
5380   EVT Ty = getPointerTy(DAG.getDataLayout());
5381   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
5382   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
5383 }
5384 
5385 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
5386                                                   SelectionDAG &DAG) const {
5387   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
5388   const GlobalValue *GV = GN->getGlobal();
5389   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5390 
5391   if (OpFlags != AArch64II::MO_NO_FLAG)
5392     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
5393            "unexpected offset in global node");
5394 
5395   // This also catches the large code model case for Darwin, and tiny code
5396   // model with got relocations.
5397   if ((OpFlags & AArch64II::MO_GOT) != 0) {
5398     return getGOT(GN, DAG, OpFlags);
5399   }
5400 
5401   SDValue Result;
5402   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5403     Result = getAddrLarge(GN, DAG, OpFlags);
5404   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5405     Result = getAddrTiny(GN, DAG, OpFlags);
5406   } else {
5407     Result = getAddr(GN, DAG, OpFlags);
5408   }
5409   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5410   SDLoc DL(GN);
5411   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
5412     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
5413                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
5414   return Result;
5415 }
5416 
5417 /// Convert a TLS address reference into the correct sequence of loads
5418 /// and calls to compute the variable's address (for Darwin, currently) and
5419 /// return an SDValue containing the final node.
5420 
5421 /// Darwin only has one TLS scheme which must be capable of dealing with the
5422 /// fully general situation, in the worst case. This means:
5423 ///     + "extern __thread" declaration.
5424 ///     + Defined in a possibly unknown dynamic library.
5425 ///
5426 /// The general system is that each __thread variable has a [3 x i64] descriptor
5427 /// which contains information used by the runtime to calculate the address. The
5428 /// only part of this the compiler needs to know about is the first xword, which
5429 /// contains a function pointer that must be called with the address of the
5430 /// entire descriptor in "x0".
5431 ///
5432 /// Since this descriptor may be in a different unit, in general even the
5433 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5434 /// is:
5435 ///     adrp x0, _var@TLVPPAGE
5436 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5437 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5438 ///                                      ; the function pointer
5439 ///     blr x1                           ; Uses descriptor address in x0
5440 ///     ; Address of _var is now in x0.
5441 ///
5442 /// If the address of _var's descriptor *is* known to the linker, then it can
5443 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5444 /// a slight efficiency gain.
5445 SDValue
5446 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5447                                                    SelectionDAG &DAG) const {
5448   assert(Subtarget->isTargetDarwin() &&
5449          "This function expects a Darwin target");
5450 
5451   SDLoc DL(Op);
5452   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5453   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5454   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5455 
5456   SDValue TLVPAddr =
5457       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5458   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5459 
5460   // The first entry in the descriptor is a function pointer that we must call
5461   // to obtain the address of the variable.
5462   SDValue Chain = DAG.getEntryNode();
5463   SDValue FuncTLVGet = DAG.getLoad(
5464       PtrMemVT, DL, Chain, DescAddr,
5465       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5466       Align(PtrMemVT.getSizeInBits() / 8),
5467       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5468   Chain = FuncTLVGet.getValue(1);
5469 
5470   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5471   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5472 
5473   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5474   MFI.setAdjustsStack(true);
5475 
5476   // TLS calls preserve all registers except those that absolutely must be
5477   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5478   // silly).
5479   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5480   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5481   if (Subtarget->hasCustomCallingConv())
5482     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5483 
5484   // Finally, we can make the call. This is just a degenerate version of a
5485   // normal AArch64 call node: x0 takes the address of the descriptor, and
5486   // returns the address of the variable in this thread.
5487   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5488   Chain =
5489       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5490                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5491                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5492   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5493 }
5494 
5495 /// Convert a thread-local variable reference into a sequence of instructions to
5496 /// compute the variable's address for the local exec TLS model of ELF targets.
5497 /// The sequence depends on the maximum TLS area size.
5498 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5499                                                     SDValue ThreadBase,
5500                                                     const SDLoc &DL,
5501                                                     SelectionDAG &DAG) const {
5502   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5503   SDValue TPOff, Addr;
5504 
5505   switch (DAG.getTarget().Options.TLSSize) {
5506   default:
5507     llvm_unreachable("Unexpected TLS size");
5508 
5509   case 12: {
5510     // mrs   x0, TPIDR_EL0
5511     // add   x0, x0, :tprel_lo12:a
5512     SDValue Var = DAG.getTargetGlobalAddress(
5513         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5514     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5515                                       Var,
5516                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5517                    0);
5518   }
5519 
5520   case 24: {
5521     // mrs   x0, TPIDR_EL0
5522     // add   x0, x0, :tprel_hi12:a
5523     // add   x0, x0, :tprel_lo12_nc:a
5524     SDValue HiVar = DAG.getTargetGlobalAddress(
5525         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5526     SDValue LoVar = DAG.getTargetGlobalAddress(
5527         GV, DL, PtrVT, 0,
5528         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5529     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5530                                       HiVar,
5531                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5532                    0);
5533     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5534                                       LoVar,
5535                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5536                    0);
5537   }
5538 
5539   case 32: {
5540     // mrs   x1, TPIDR_EL0
5541     // movz  x0, #:tprel_g1:a
5542     // movk  x0, #:tprel_g0_nc:a
5543     // add   x0, x1, x0
5544     SDValue HiVar = DAG.getTargetGlobalAddress(
5545         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5546     SDValue LoVar = DAG.getTargetGlobalAddress(
5547         GV, DL, PtrVT, 0,
5548         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5549     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5550                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5551                     0);
5552     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5553                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5554                     0);
5555     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5556   }
5557 
5558   case 48: {
5559     // mrs   x1, TPIDR_EL0
5560     // movz  x0, #:tprel_g2:a
5561     // movk  x0, #:tprel_g1_nc:a
5562     // movk  x0, #:tprel_g0_nc:a
5563     // add   x0, x1, x0
5564     SDValue HiVar = DAG.getTargetGlobalAddress(
5565         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5566     SDValue MiVar = DAG.getTargetGlobalAddress(
5567         GV, DL, PtrVT, 0,
5568         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5569     SDValue LoVar = DAG.getTargetGlobalAddress(
5570         GV, DL, PtrVT, 0,
5571         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5572     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5573                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5574                     0);
5575     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5576                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5577                     0);
5578     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5579                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5580                     0);
5581     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5582   }
5583   }
5584 }
5585 
5586 /// When accessing thread-local variables under either the general-dynamic or
5587 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5588 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5589 /// is a function pointer to carry out the resolution.
5590 ///
5591 /// The sequence is:
5592 ///    adrp  x0, :tlsdesc:var
5593 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5594 ///    add   x0, x0, #:tlsdesc_lo12:var
5595 ///    .tlsdesccall var
5596 ///    blr   x1
5597 ///    (TPIDR_EL0 offset now in x0)
5598 ///
5599 ///  The above sequence must be produced unscheduled, to enable the linker to
5600 ///  optimize/relax this sequence.
5601 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5602 ///  above sequence, and expanded really late in the compilation flow, to ensure
5603 ///  the sequence is produced as per above.
5604 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5605                                                       const SDLoc &DL,
5606                                                       SelectionDAG &DAG) const {
5607   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5608 
5609   SDValue Chain = DAG.getEntryNode();
5610   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5611 
5612   Chain =
5613       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5614   SDValue Glue = Chain.getValue(1);
5615 
5616   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5617 }
5618 
5619 SDValue
5620 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5621                                                 SelectionDAG &DAG) const {
5622   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5623 
5624   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5625 
5626   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5627 
5628   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5629     if (Model == TLSModel::LocalDynamic)
5630       Model = TLSModel::GeneralDynamic;
5631   }
5632 
5633   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5634       Model != TLSModel::LocalExec)
5635     report_fatal_error("ELF TLS only supported in small memory model or "
5636                        "in local exec TLS model");
5637   // Different choices can be made for the maximum size of the TLS area for a
5638   // module. For the small address model, the default TLS size is 16MiB and the
5639   // maximum TLS size is 4GiB.
5640   // FIXME: add tiny and large code model support for TLS access models other
5641   // than local exec. We currently generate the same code as small for tiny,
5642   // which may be larger than needed.
5643 
5644   SDValue TPOff;
5645   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5646   SDLoc DL(Op);
5647   const GlobalValue *GV = GA->getGlobal();
5648 
5649   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5650 
5651   if (Model == TLSModel::LocalExec) {
5652     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5653   } else if (Model == TLSModel::InitialExec) {
5654     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5655     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5656   } else if (Model == TLSModel::LocalDynamic) {
5657     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5658     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5659     // the beginning of the module's TLS region, followed by a DTPREL offset
5660     // calculation.
5661 
5662     // These accesses will need deduplicating if there's more than one.
5663     AArch64FunctionInfo *MFI =
5664         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5665     MFI->incNumLocalDynamicTLSAccesses();
5666 
5667     // The call needs a relocation too for linker relaxation. It doesn't make
5668     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5669     // the address.
5670     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5671                                                   AArch64II::MO_TLS);
5672 
5673     // Now we can calculate the offset from TPIDR_EL0 to this module's
5674     // thread-local area.
5675     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5676 
5677     // Now use :dtprel_whatever: operations to calculate this variable's offset
5678     // in its thread-storage area.
5679     SDValue HiVar = DAG.getTargetGlobalAddress(
5680         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5681     SDValue LoVar = DAG.getTargetGlobalAddress(
5682         GV, DL, MVT::i64, 0,
5683         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5684 
5685     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5686                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5687                     0);
5688     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5689                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5690                     0);
5691   } else if (Model == TLSModel::GeneralDynamic) {
5692     // The call needs a relocation too for linker relaxation. It doesn't make
5693     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5694     // the address.
5695     SDValue SymAddr =
5696         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5697 
5698     // Finally we can make a call to calculate the offset from tpidr_el0.
5699     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5700   } else
5701     llvm_unreachable("Unsupported ELF TLS access model");
5702 
5703   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5704 }
5705 
5706 SDValue
5707 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5708                                                     SelectionDAG &DAG) const {
5709   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5710 
5711   SDValue Chain = DAG.getEntryNode();
5712   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5713   SDLoc DL(Op);
5714 
5715   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5716 
5717   // Load the ThreadLocalStoragePointer from the TEB
5718   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5719   SDValue TLSArray =
5720       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5721   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5722   Chain = TLSArray.getValue(1);
5723 
5724   // Load the TLS index from the C runtime;
5725   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5726   // This also does the same as LOADgot, but using a generic i32 load,
5727   // while LOADgot only loads i64.
5728   SDValue TLSIndexHi =
5729       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5730   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5731       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5732   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5733   SDValue TLSIndex =
5734       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5735   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5736   Chain = TLSIndex.getValue(1);
5737 
5738   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5739   // offset into the TLSArray.
5740   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5741   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5742                              DAG.getConstant(3, DL, PtrVT));
5743   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5744                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5745                             MachinePointerInfo());
5746   Chain = TLS.getValue(1);
5747 
5748   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5749   const GlobalValue *GV = GA->getGlobal();
5750   SDValue TGAHi = DAG.getTargetGlobalAddress(
5751       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5752   SDValue TGALo = DAG.getTargetGlobalAddress(
5753       GV, DL, PtrVT, 0,
5754       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5755 
5756   // Add the offset from the start of the .tls section (section base).
5757   SDValue Addr =
5758       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5759                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5760               0);
5761   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5762   return Addr;
5763 }
5764 
5765 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5766                                                      SelectionDAG &DAG) const {
5767   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5768   if (DAG.getTarget().useEmulatedTLS())
5769     return LowerToTLSEmulatedModel(GA, DAG);
5770 
5771   if (Subtarget->isTargetDarwin())
5772     return LowerDarwinGlobalTLSAddress(Op, DAG);
5773   if (Subtarget->isTargetELF())
5774     return LowerELFGlobalTLSAddress(Op, DAG);
5775   if (Subtarget->isTargetWindows())
5776     return LowerWindowsGlobalTLSAddress(Op, DAG);
5777 
5778   llvm_unreachable("Unexpected platform trying to use TLS");
5779 }
5780 
5781 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5782   SDValue Chain = Op.getOperand(0);
5783   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5784   SDValue LHS = Op.getOperand(2);
5785   SDValue RHS = Op.getOperand(3);
5786   SDValue Dest = Op.getOperand(4);
5787   SDLoc dl(Op);
5788 
5789   MachineFunction &MF = DAG.getMachineFunction();
5790   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5791   // will not be produced, as they are conditional branch instructions that do
5792   // not set flags.
5793   bool ProduceNonFlagSettingCondBr =
5794       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5795 
5796   // Handle f128 first, since lowering it will result in comparing the return
5797   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5798   // is expecting to deal with.
5799   if (LHS.getValueType() == MVT::f128) {
5800     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5801 
5802     // If softenSetCCOperands returned a scalar, we need to compare the result
5803     // against zero to select between true and false values.
5804     if (!RHS.getNode()) {
5805       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5806       CC = ISD::SETNE;
5807     }
5808   }
5809 
5810   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5811   // instruction.
5812   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5813       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5814     // Only lower legal XALUO ops.
5815     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5816       return SDValue();
5817 
5818     // The actual operation with overflow check.
5819     AArch64CC::CondCode OFCC;
5820     SDValue Value, Overflow;
5821     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5822 
5823     if (CC == ISD::SETNE)
5824       OFCC = getInvertedCondCode(OFCC);
5825     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5826 
5827     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5828                        Overflow);
5829   }
5830 
5831   if (LHS.getValueType().isInteger()) {
5832     assert((LHS.getValueType() == RHS.getValueType()) &&
5833            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5834 
5835     // If the RHS of the comparison is zero, we can potentially fold this
5836     // to a specialized branch.
5837     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5838     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5839       if (CC == ISD::SETEQ) {
5840         // See if we can use a TBZ to fold in an AND as well.
5841         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5842         // out of bounds, a late MI-layer pass rewrites branches.
5843         // 403.gcc is an example that hits this case.
5844         if (LHS.getOpcode() == ISD::AND &&
5845             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5846             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5847           SDValue Test = LHS.getOperand(0);
5848           uint64_t Mask = LHS.getConstantOperandVal(1);
5849           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5850                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5851                              Dest);
5852         }
5853 
5854         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5855       } else if (CC == ISD::SETNE) {
5856         // See if we can use a TBZ to fold in an AND as well.
5857         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5858         // out of bounds, a late MI-layer pass rewrites branches.
5859         // 403.gcc is an example that hits this case.
5860         if (LHS.getOpcode() == ISD::AND &&
5861             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5862             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5863           SDValue Test = LHS.getOperand(0);
5864           uint64_t Mask = LHS.getConstantOperandVal(1);
5865           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5866                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5867                              Dest);
5868         }
5869 
5870         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5871       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5872         // Don't combine AND since emitComparison converts the AND to an ANDS
5873         // (a.k.a. TST) and the test in the test bit and branch instruction
5874         // becomes redundant.  This would also increase register pressure.
5875         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5876         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5877                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5878       }
5879     }
5880     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5881         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5882       // Don't combine AND since emitComparison converts the AND to an ANDS
5883       // (a.k.a. TST) and the test in the test bit and branch instruction
5884       // becomes redundant.  This would also increase register pressure.
5885       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5886       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5887                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5888     }
5889 
5890     SDValue CCVal;
5891     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5892     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5893                        Cmp);
5894   }
5895 
5896   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5897          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5898 
5899   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5900   // clean.  Some of them require two branches to implement.
5901   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5902   AArch64CC::CondCode CC1, CC2;
5903   changeFPCCToAArch64CC(CC, CC1, CC2);
5904   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5905   SDValue BR1 =
5906       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5907   if (CC2 != AArch64CC::AL) {
5908     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5909     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5910                        Cmp);
5911   }
5912 
5913   return BR1;
5914 }
5915 
5916 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5917                                               SelectionDAG &DAG) const {
5918   EVT VT = Op.getValueType();
5919   SDLoc DL(Op);
5920 
5921   SDValue In1 = Op.getOperand(0);
5922   SDValue In2 = Op.getOperand(1);
5923   EVT SrcVT = In2.getValueType();
5924 
5925   if (SrcVT.bitsLT(VT))
5926     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5927   else if (SrcVT.bitsGT(VT))
5928     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5929 
5930   EVT VecVT;
5931   uint64_t EltMask;
5932   SDValue VecVal1, VecVal2;
5933 
5934   auto setVecVal = [&] (int Idx) {
5935     if (!VT.isVector()) {
5936       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5937                                           DAG.getUNDEF(VecVT), In1);
5938       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5939                                           DAG.getUNDEF(VecVT), In2);
5940     } else {
5941       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5942       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5943     }
5944   };
5945 
5946   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5947     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5948     EltMask = 0x80000000ULL;
5949     setVecVal(AArch64::ssub);
5950   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5951     VecVT = MVT::v2i64;
5952 
5953     // We want to materialize a mask with the high bit set, but the AdvSIMD
5954     // immediate moves cannot materialize that in a single instruction for
5955     // 64-bit elements. Instead, materialize zero and then negate it.
5956     EltMask = 0;
5957 
5958     setVecVal(AArch64::dsub);
5959   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5960     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5961     EltMask = 0x8000ULL;
5962     setVecVal(AArch64::hsub);
5963   } else {
5964     llvm_unreachable("Invalid type for copysign!");
5965   }
5966 
5967   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5968 
5969   // If we couldn't materialize the mask above, then the mask vector will be
5970   // the zero vector, and we need to negate it here.
5971   if (VT == MVT::f64 || VT == MVT::v2f64) {
5972     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5973     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5974     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5975   }
5976 
5977   SDValue Sel =
5978       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5979 
5980   if (VT == MVT::f16)
5981     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5982   if (VT == MVT::f32)
5983     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5984   else if (VT == MVT::f64)
5985     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5986   else
5987     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5988 }
5989 
5990 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5991   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5992           Attribute::NoImplicitFloat))
5993     return SDValue();
5994 
5995   if (!Subtarget->hasNEON())
5996     return SDValue();
5997 
5998   // While there is no integer popcount instruction, it can
5999   // be more efficiently lowered to the following sequence that uses
6000   // AdvSIMD registers/instructions as long as the copies to/from
6001   // the AdvSIMD registers are cheap.
6002   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
6003   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
6004   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
6005   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
6006   SDValue Val = Op.getOperand(0);
6007   SDLoc DL(Op);
6008   EVT VT = Op.getValueType();
6009 
6010   if (VT == MVT::i32 || VT == MVT::i64) {
6011     if (VT == MVT::i32)
6012       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
6013     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
6014 
6015     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
6016     SDValue UaddLV = DAG.getNode(
6017         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6018         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6019 
6020     if (VT == MVT::i64)
6021       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
6022     return UaddLV;
6023   } else if (VT == MVT::i128) {
6024     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
6025 
6026     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
6027     SDValue UaddLV = DAG.getNode(
6028         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6029         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6030 
6031     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
6032   }
6033 
6034   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6035           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6036          "Unexpected type for custom ctpop lowering");
6037 
6038   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6039   Val = DAG.getBitcast(VT8Bit, Val);
6040   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
6041 
6042   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6043   unsigned EltSize = 8;
6044   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6045   while (EltSize != VT.getScalarSizeInBits()) {
6046     EltSize *= 2;
6047     NumElts /= 2;
6048     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6049     Val = DAG.getNode(
6050         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
6051         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
6052   }
6053 
6054   return Val;
6055 }
6056 
6057 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6058 
6059   if (Op.getValueType().isVector())
6060     return LowerVSETCC(Op, DAG);
6061 
6062   bool IsStrict = Op->isStrictFPOpcode();
6063   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
6064   unsigned OpNo = IsStrict ? 1 : 0;
6065   SDValue Chain;
6066   if (IsStrict)
6067     Chain = Op.getOperand(0);
6068   SDValue LHS = Op.getOperand(OpNo + 0);
6069   SDValue RHS = Op.getOperand(OpNo + 1);
6070   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
6071   SDLoc dl(Op);
6072 
6073   // We chose ZeroOrOneBooleanContents, so use zero and one.
6074   EVT VT = Op.getValueType();
6075   SDValue TVal = DAG.getConstant(1, dl, VT);
6076   SDValue FVal = DAG.getConstant(0, dl, VT);
6077 
6078   // Handle f128 first, since one possible outcome is a normal integer
6079   // comparison which gets picked up by the next if statement.
6080   if (LHS.getValueType() == MVT::f128) {
6081     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
6082                         IsSignaling);
6083 
6084     // If softenSetCCOperands returned a scalar, use it.
6085     if (!RHS.getNode()) {
6086       assert(LHS.getValueType() == Op.getValueType() &&
6087              "Unexpected setcc expansion!");
6088       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
6089     }
6090   }
6091 
6092   if (LHS.getValueType().isInteger()) {
6093     SDValue CCVal;
6094     SDValue Cmp = getAArch64Cmp(
6095         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
6096 
6097     // Note that we inverted the condition above, so we reverse the order of
6098     // the true and false operands here.  This will allow the setcc to be
6099     // matched to a single CSINC instruction.
6100     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
6101     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
6102   }
6103 
6104   // Now we know we're dealing with FP values.
6105   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6106          LHS.getValueType() == MVT::f64);
6107 
6108   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
6109   // and do the comparison.
6110   SDValue Cmp;
6111   if (IsStrict)
6112     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
6113   else
6114     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6115 
6116   AArch64CC::CondCode CC1, CC2;
6117   changeFPCCToAArch64CC(CC, CC1, CC2);
6118   SDValue Res;
6119   if (CC2 == AArch64CC::AL) {
6120     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
6121                           CC2);
6122     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6123 
6124     // Note that we inverted the condition above, so we reverse the order of
6125     // the true and false operands here.  This will allow the setcc to be
6126     // matched to a single CSINC instruction.
6127     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
6128   } else {
6129     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
6130     // totally clean.  Some of them require two CSELs to implement.  As is in
6131     // this case, we emit the first CSEL and then emit a second using the output
6132     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
6133 
6134     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
6135     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6136     SDValue CS1 =
6137         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6138 
6139     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6140     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6141   }
6142   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
6143 }
6144 
6145 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
6146                                               SDValue RHS, SDValue TVal,
6147                                               SDValue FVal, const SDLoc &dl,
6148                                               SelectionDAG &DAG) const {
6149   // Handle f128 first, because it will result in a comparison of some RTLIB
6150   // call result against zero.
6151   if (LHS.getValueType() == MVT::f128) {
6152     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6153 
6154     // If softenSetCCOperands returned a scalar, we need to compare the result
6155     // against zero to select between true and false values.
6156     if (!RHS.getNode()) {
6157       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6158       CC = ISD::SETNE;
6159     }
6160   }
6161 
6162   // Also handle f16, for which we need to do a f32 comparison.
6163   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
6164     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
6165     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
6166   }
6167 
6168   // Next, handle integers.
6169   if (LHS.getValueType().isInteger()) {
6170     assert((LHS.getValueType() == RHS.getValueType()) &&
6171            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
6172 
6173     unsigned Opcode = AArch64ISD::CSEL;
6174 
6175     // If both the TVal and the FVal are constants, see if we can swap them in
6176     // order to for a CSINV or CSINC out of them.
6177     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
6178     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
6179 
6180     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
6181       std::swap(TVal, FVal);
6182       std::swap(CTVal, CFVal);
6183       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6184     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
6185       std::swap(TVal, FVal);
6186       std::swap(CTVal, CFVal);
6187       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6188     } else if (TVal.getOpcode() == ISD::XOR) {
6189       // If TVal is a NOT we want to swap TVal and FVal so that we can match
6190       // with a CSINV rather than a CSEL.
6191       if (isAllOnesConstant(TVal.getOperand(1))) {
6192         std::swap(TVal, FVal);
6193         std::swap(CTVal, CFVal);
6194         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6195       }
6196     } else if (TVal.getOpcode() == ISD::SUB) {
6197       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
6198       // that we can match with a CSNEG rather than a CSEL.
6199       if (isNullConstant(TVal.getOperand(0))) {
6200         std::swap(TVal, FVal);
6201         std::swap(CTVal, CFVal);
6202         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6203       }
6204     } else if (CTVal && CFVal) {
6205       const int64_t TrueVal = CTVal->getSExtValue();
6206       const int64_t FalseVal = CFVal->getSExtValue();
6207       bool Swap = false;
6208 
6209       // If both TVal and FVal are constants, see if FVal is the
6210       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
6211       // instead of a CSEL in that case.
6212       if (TrueVal == ~FalseVal) {
6213         Opcode = AArch64ISD::CSINV;
6214       } else if (TrueVal == -FalseVal) {
6215         Opcode = AArch64ISD::CSNEG;
6216       } else if (TVal.getValueType() == MVT::i32) {
6217         // If our operands are only 32-bit wide, make sure we use 32-bit
6218         // arithmetic for the check whether we can use CSINC. This ensures that
6219         // the addition in the check will wrap around properly in case there is
6220         // an overflow (which would not be the case if we do the check with
6221         // 64-bit arithmetic).
6222         const uint32_t TrueVal32 = CTVal->getZExtValue();
6223         const uint32_t FalseVal32 = CFVal->getZExtValue();
6224 
6225         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
6226           Opcode = AArch64ISD::CSINC;
6227 
6228           if (TrueVal32 > FalseVal32) {
6229             Swap = true;
6230           }
6231         }
6232         // 64-bit check whether we can use CSINC.
6233       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
6234         Opcode = AArch64ISD::CSINC;
6235 
6236         if (TrueVal > FalseVal) {
6237           Swap = true;
6238         }
6239       }
6240 
6241       // Swap TVal and FVal if necessary.
6242       if (Swap) {
6243         std::swap(TVal, FVal);
6244         std::swap(CTVal, CFVal);
6245         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6246       }
6247 
6248       if (Opcode != AArch64ISD::CSEL) {
6249         // Drop FVal since we can get its value by simply inverting/negating
6250         // TVal.
6251         FVal = TVal;
6252       }
6253     }
6254 
6255     // Avoid materializing a constant when possible by reusing a known value in
6256     // a register.  However, don't perform this optimization if the known value
6257     // is one, zero or negative one in the case of a CSEL.  We can always
6258     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
6259     // FVal, respectively.
6260     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
6261     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
6262         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
6263       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6264       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
6265       // "a != C ? x : a" to avoid materializing C.
6266       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
6267         TVal = LHS;
6268       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
6269         FVal = LHS;
6270     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
6271       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
6272       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
6273       // avoid materializing C.
6274       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6275       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
6276         Opcode = AArch64ISD::CSINV;
6277         TVal = LHS;
6278         FVal = DAG.getConstant(0, dl, FVal.getValueType());
6279       }
6280     }
6281 
6282     SDValue CCVal;
6283     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6284     EVT VT = TVal.getValueType();
6285     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
6286   }
6287 
6288   // Now we know we're dealing with FP values.
6289   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6290          LHS.getValueType() == MVT::f64);
6291   assert(LHS.getValueType() == RHS.getValueType());
6292   EVT VT = TVal.getValueType();
6293   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6294 
6295   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6296   // clean.  Some of them require two CSELs to implement.
6297   AArch64CC::CondCode CC1, CC2;
6298   changeFPCCToAArch64CC(CC, CC1, CC2);
6299 
6300   if (DAG.getTarget().Options.UnsafeFPMath) {
6301     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
6302     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
6303     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
6304     if (RHSVal && RHSVal->isZero()) {
6305       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
6306       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
6307 
6308       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
6309           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
6310         TVal = LHS;
6311       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
6312                CFVal && CFVal->isZero() &&
6313                FVal.getValueType() == LHS.getValueType())
6314         FVal = LHS;
6315     }
6316   }
6317 
6318   // Emit first, and possibly only, CSEL.
6319   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6320   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6321 
6322   // If we need a second CSEL, emit it, using the output of the first as the
6323   // RHS.  We're effectively OR'ing the two CC's together.
6324   if (CC2 != AArch64CC::AL) {
6325     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6326     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6327   }
6328 
6329   // Otherwise, return the output of the first CSEL.
6330   return CS1;
6331 }
6332 
6333 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
6334                                               SelectionDAG &DAG) const {
6335   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6336   SDValue LHS = Op.getOperand(0);
6337   SDValue RHS = Op.getOperand(1);
6338   SDValue TVal = Op.getOperand(2);
6339   SDValue FVal = Op.getOperand(3);
6340   SDLoc DL(Op);
6341   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6342 }
6343 
6344 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
6345                                            SelectionDAG &DAG) const {
6346   SDValue CCVal = Op->getOperand(0);
6347   SDValue TVal = Op->getOperand(1);
6348   SDValue FVal = Op->getOperand(2);
6349   SDLoc DL(Op);
6350 
6351   EVT Ty = Op.getValueType();
6352   if (Ty.isScalableVector()) {
6353     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
6354     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
6355     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
6356     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
6357   }
6358 
6359   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
6360   // instruction.
6361   if (ISD::isOverflowIntrOpRes(CCVal)) {
6362     // Only lower legal XALUO ops.
6363     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
6364       return SDValue();
6365 
6366     AArch64CC::CondCode OFCC;
6367     SDValue Value, Overflow;
6368     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
6369     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
6370 
6371     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
6372                        CCVal, Overflow);
6373   }
6374 
6375   // Lower it the same way as we would lower a SELECT_CC node.
6376   ISD::CondCode CC;
6377   SDValue LHS, RHS;
6378   if (CCVal.getOpcode() == ISD::SETCC) {
6379     LHS = CCVal.getOperand(0);
6380     RHS = CCVal.getOperand(1);
6381     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
6382   } else {
6383     LHS = CCVal;
6384     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
6385     CC = ISD::SETNE;
6386   }
6387   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6388 }
6389 
6390 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
6391                                               SelectionDAG &DAG) const {
6392   // Jump table entries as PC relative offsets. No additional tweaking
6393   // is necessary here. Just get the address of the jump table.
6394   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6395 
6396   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6397       !Subtarget->isTargetMachO()) {
6398     return getAddrLarge(JT, DAG);
6399   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6400     return getAddrTiny(JT, DAG);
6401   }
6402   return getAddr(JT, DAG);
6403 }
6404 
6405 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
6406                                           SelectionDAG &DAG) const {
6407   // Jump table entries as PC relative offsets. No additional tweaking
6408   // is necessary here. Just get the address of the jump table.
6409   SDLoc DL(Op);
6410   SDValue JT = Op.getOperand(1);
6411   SDValue Entry = Op.getOperand(2);
6412   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
6413 
6414   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6415   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
6416 
6417   SDNode *Dest =
6418       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
6419                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
6420   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
6421                      SDValue(Dest, 0));
6422 }
6423 
6424 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6425                                                  SelectionDAG &DAG) const {
6426   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6427 
6428   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6429     // Use the GOT for the large code model on iOS.
6430     if (Subtarget->isTargetMachO()) {
6431       return getGOT(CP, DAG);
6432     }
6433     return getAddrLarge(CP, DAG);
6434   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6435     return getAddrTiny(CP, DAG);
6436   } else {
6437     return getAddr(CP, DAG);
6438   }
6439 }
6440 
6441 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6442                                                SelectionDAG &DAG) const {
6443   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6444   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6445       !Subtarget->isTargetMachO()) {
6446     return getAddrLarge(BA, DAG);
6447   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6448     return getAddrTiny(BA, DAG);
6449   }
6450   return getAddr(BA, DAG);
6451 }
6452 
6453 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6454                                                  SelectionDAG &DAG) const {
6455   AArch64FunctionInfo *FuncInfo =
6456       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6457 
6458   SDLoc DL(Op);
6459   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6460                                  getPointerTy(DAG.getDataLayout()));
6461   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6462   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6463   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6464                       MachinePointerInfo(SV));
6465 }
6466 
6467 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6468                                                   SelectionDAG &DAG) const {
6469   AArch64FunctionInfo *FuncInfo =
6470       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6471 
6472   SDLoc DL(Op);
6473   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6474                                      ? FuncInfo->getVarArgsGPRIndex()
6475                                      : FuncInfo->getVarArgsStackIndex(),
6476                                  getPointerTy(DAG.getDataLayout()));
6477   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6478   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6479                       MachinePointerInfo(SV));
6480 }
6481 
6482 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6483                                                 SelectionDAG &DAG) const {
6484   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6485   // Standard, section B.3.
6486   MachineFunction &MF = DAG.getMachineFunction();
6487   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6488   auto PtrVT = getPointerTy(DAG.getDataLayout());
6489   SDLoc DL(Op);
6490 
6491   SDValue Chain = Op.getOperand(0);
6492   SDValue VAList = Op.getOperand(1);
6493   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6494   SmallVector<SDValue, 4> MemOps;
6495 
6496   // void *__stack at offset 0
6497   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6498   MemOps.push_back(
6499       DAG.getStore(Chain, DL, Stack, VAList, MachinePointerInfo(SV), Align(8)));
6500 
6501   // void *__gr_top at offset 8
6502   int GPRSize = FuncInfo->getVarArgsGPRSize();
6503   if (GPRSize > 0) {
6504     SDValue GRTop, GRTopAddr;
6505 
6506     GRTopAddr =
6507         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6508 
6509     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6510     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6511                         DAG.getConstant(GPRSize, DL, PtrVT));
6512 
6513     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6514                                   MachinePointerInfo(SV, 8), Align(8)));
6515   }
6516 
6517   // void *__vr_top at offset 16
6518   int FPRSize = FuncInfo->getVarArgsFPRSize();
6519   if (FPRSize > 0) {
6520     SDValue VRTop, VRTopAddr;
6521     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6522                             DAG.getConstant(16, DL, PtrVT));
6523 
6524     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6525     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6526                         DAG.getConstant(FPRSize, DL, PtrVT));
6527 
6528     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6529                                   MachinePointerInfo(SV, 16), Align(8)));
6530   }
6531 
6532   // int __gr_offs at offset 24
6533   SDValue GROffsAddr =
6534       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6535   MemOps.push_back(
6536       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
6537                    GROffsAddr, MachinePointerInfo(SV, 24), Align(4)));
6538 
6539   // int __vr_offs at offset 28
6540   SDValue VROffsAddr =
6541       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6542   MemOps.push_back(
6543       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
6544                    VROffsAddr, MachinePointerInfo(SV, 28), Align(4)));
6545 
6546   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6547 }
6548 
6549 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6550                                             SelectionDAG &DAG) const {
6551   MachineFunction &MF = DAG.getMachineFunction();
6552 
6553   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6554     return LowerWin64_VASTART(Op, DAG);
6555   else if (Subtarget->isTargetDarwin())
6556     return LowerDarwin_VASTART(Op, DAG);
6557   else
6558     return LowerAAPCS_VASTART(Op, DAG);
6559 }
6560 
6561 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6562                                            SelectionDAG &DAG) const {
6563   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6564   // pointer.
6565   SDLoc DL(Op);
6566   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6567   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6568                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6569   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6570   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6571 
6572   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6573                        DAG.getConstant(VaListSize, DL, MVT::i32),
6574                        Align(PtrSize), false, false, false,
6575                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6576 }
6577 
6578 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6579   assert(Subtarget->isTargetDarwin() &&
6580          "automatic va_arg instruction only works on Darwin");
6581 
6582   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6583   EVT VT = Op.getValueType();
6584   SDLoc DL(Op);
6585   SDValue Chain = Op.getOperand(0);
6586   SDValue Addr = Op.getOperand(1);
6587   MaybeAlign Align(Op.getConstantOperandVal(3));
6588   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6589   auto PtrVT = getPointerTy(DAG.getDataLayout());
6590   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6591   SDValue VAList =
6592       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6593   Chain = VAList.getValue(1);
6594   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6595 
6596   if (Align && *Align > MinSlotSize) {
6597     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6598                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6599     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6600                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6601   }
6602 
6603   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6604   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6605 
6606   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6607   // up to 64 bits.  At the very least, we have to increase the striding of the
6608   // vaargs list to match this, and for FP values we need to introduce
6609   // FP_ROUND nodes as well.
6610   if (VT.isInteger() && !VT.isVector())
6611     ArgSize = std::max(ArgSize, MinSlotSize);
6612   bool NeedFPTrunc = false;
6613   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6614     ArgSize = 8;
6615     NeedFPTrunc = true;
6616   }
6617 
6618   // Increment the pointer, VAList, to the next vaarg
6619   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6620                                DAG.getConstant(ArgSize, DL, PtrVT));
6621   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6622 
6623   // Store the incremented VAList to the legalized pointer
6624   SDValue APStore =
6625       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6626 
6627   // Load the actual argument out of the pointer VAList
6628   if (NeedFPTrunc) {
6629     // Load the value as an f64.
6630     SDValue WideFP =
6631         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6632     // Round the value down to an f32.
6633     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6634                                    DAG.getIntPtrConstant(1, DL));
6635     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6636     // Merge the rounded value with the chain output of the load.
6637     return DAG.getMergeValues(Ops, DL);
6638   }
6639 
6640   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6641 }
6642 
6643 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6644                                               SelectionDAG &DAG) const {
6645   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6646   MFI.setFrameAddressIsTaken(true);
6647 
6648   EVT VT = Op.getValueType();
6649   SDLoc DL(Op);
6650   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6651   SDValue FrameAddr =
6652       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6653   while (Depth--)
6654     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6655                             MachinePointerInfo());
6656 
6657   if (Subtarget->isTargetILP32())
6658     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6659                             DAG.getValueType(VT));
6660 
6661   return FrameAddr;
6662 }
6663 
6664 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6665                                               SelectionDAG &DAG) const {
6666   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6667 
6668   EVT VT = getPointerTy(DAG.getDataLayout());
6669   SDLoc DL(Op);
6670   int FI = MFI.CreateFixedObject(4, 0, false);
6671   return DAG.getFrameIndex(FI, VT);
6672 }
6673 
6674 #define GET_REGISTER_MATCHER
6675 #include "AArch64GenAsmMatcher.inc"
6676 
6677 // FIXME? Maybe this could be a TableGen attribute on some registers and
6678 // this table could be generated automatically from RegInfo.
6679 Register AArch64TargetLowering::
6680 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6681   Register Reg = MatchRegisterName(RegName);
6682   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6683     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6684     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6685     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6686       Reg = 0;
6687   }
6688   if (Reg)
6689     return Reg;
6690   report_fatal_error(Twine("Invalid register name \""
6691                               + StringRef(RegName)  + "\"."));
6692 }
6693 
6694 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6695                                                      SelectionDAG &DAG) const {
6696   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6697 
6698   EVT VT = Op.getValueType();
6699   SDLoc DL(Op);
6700 
6701   SDValue FrameAddr =
6702       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6703   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6704 
6705   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6706 }
6707 
6708 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6709                                                SelectionDAG &DAG) const {
6710   MachineFunction &MF = DAG.getMachineFunction();
6711   MachineFrameInfo &MFI = MF.getFrameInfo();
6712   MFI.setReturnAddressIsTaken(true);
6713 
6714   EVT VT = Op.getValueType();
6715   SDLoc DL(Op);
6716   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6717   SDValue ReturnAddress;
6718   if (Depth) {
6719     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6720     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6721     ReturnAddress = DAG.getLoad(
6722         VT, DL, DAG.getEntryNode(),
6723         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
6724   } else {
6725     // Return LR, which contains the return address. Mark it an implicit
6726     // live-in.
6727     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6728     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6729   }
6730 
6731   // The XPACLRI instruction assembles to a hint-space instruction before
6732   // Armv8.3-A therefore this instruction can be safely used for any pre
6733   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
6734   // that instead.
6735   SDNode *St;
6736   if (Subtarget->hasV8_3aOps()) {
6737     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
6738   } else {
6739     // XPACLRI operates on LR therefore we must move the operand accordingly.
6740     SDValue Chain =
6741         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
6742     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
6743   }
6744   return SDValue(St, 0);
6745 }
6746 
6747 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6748 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6749 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6750                                                     SelectionDAG &DAG) const {
6751   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6752   EVT VT = Op.getValueType();
6753   unsigned VTBits = VT.getSizeInBits();
6754   SDLoc dl(Op);
6755   SDValue ShOpLo = Op.getOperand(0);
6756   SDValue ShOpHi = Op.getOperand(1);
6757   SDValue ShAmt = Op.getOperand(2);
6758   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6759 
6760   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6761 
6762   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6763                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6764   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6765 
6766   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6767   // is "undef". We wanted 0, so CSEL it directly.
6768   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6769                                ISD::SETEQ, dl, DAG);
6770   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6771   HiBitsForLo =
6772       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6773                   HiBitsForLo, CCVal, Cmp);
6774 
6775   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6776                                    DAG.getConstant(VTBits, dl, MVT::i64));
6777 
6778   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6779   SDValue LoForNormalShift =
6780       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6781 
6782   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6783                        dl, DAG);
6784   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6785   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6786   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6787                            LoForNormalShift, CCVal, Cmp);
6788 
6789   // AArch64 shifts larger than the register width are wrapped rather than
6790   // clamped, so we can't just emit "hi >> x".
6791   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6792   SDValue HiForBigShift =
6793       Opc == ISD::SRA
6794           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6795                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6796           : DAG.getConstant(0, dl, VT);
6797   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6798                            HiForNormalShift, CCVal, Cmp);
6799 
6800   SDValue Ops[2] = { Lo, Hi };
6801   return DAG.getMergeValues(Ops, dl);
6802 }
6803 
6804 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6805 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6806 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6807                                                    SelectionDAG &DAG) const {
6808   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6809   EVT VT = Op.getValueType();
6810   unsigned VTBits = VT.getSizeInBits();
6811   SDLoc dl(Op);
6812   SDValue ShOpLo = Op.getOperand(0);
6813   SDValue ShOpHi = Op.getOperand(1);
6814   SDValue ShAmt = Op.getOperand(2);
6815 
6816   assert(Op.getOpcode() == ISD::SHL_PARTS);
6817   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6818                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6819   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6820 
6821   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6822   // is "undef". We wanted 0, so CSEL it directly.
6823   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6824                                ISD::SETEQ, dl, DAG);
6825   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6826   LoBitsForHi =
6827       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6828                   LoBitsForHi, CCVal, Cmp);
6829 
6830   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6831                                    DAG.getConstant(VTBits, dl, MVT::i64));
6832   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6833   SDValue HiForNormalShift =
6834       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6835 
6836   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6837 
6838   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6839                        dl, DAG);
6840   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6841   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6842                            HiForNormalShift, CCVal, Cmp);
6843 
6844   // AArch64 shifts of larger than register sizes are wrapped rather than
6845   // clamped, so we can't just emit "lo << a" if a is too big.
6846   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6847   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6848   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6849                            LoForNormalShift, CCVal, Cmp);
6850 
6851   SDValue Ops[2] = { Lo, Hi };
6852   return DAG.getMergeValues(Ops, dl);
6853 }
6854 
6855 bool AArch64TargetLowering::isOffsetFoldingLegal(
6856     const GlobalAddressSDNode *GA) const {
6857   // Offsets are folded in the DAG combine rather than here so that we can
6858   // intelligently choose an offset based on the uses.
6859   return false;
6860 }
6861 
6862 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6863                                          bool OptForSize) const {
6864   bool IsLegal = false;
6865   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6866   // 16-bit case when target has full fp16 support.
6867   // FIXME: We should be able to handle f128 as well with a clever lowering.
6868   const APInt ImmInt = Imm.bitcastToAPInt();
6869   if (VT == MVT::f64)
6870     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6871   else if (VT == MVT::f32)
6872     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6873   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6874     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6875   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6876   //       generate that fmov.
6877 
6878   // If we can not materialize in immediate field for fmov, check if the
6879   // value can be encoded as the immediate operand of a logical instruction.
6880   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6881   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6882     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6883     // however the mov+fmov sequence is always better because of the reduced
6884     // cache pressure. The timings are still the same if you consider
6885     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6886     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6887     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6888     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6889 			      Insn);
6890     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6891     IsLegal = Insn.size() <= Limit;
6892   }
6893 
6894   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6895                     << " imm value: "; Imm.dump(););
6896   return IsLegal;
6897 }
6898 
6899 //===----------------------------------------------------------------------===//
6900 //                          AArch64 Optimization Hooks
6901 //===----------------------------------------------------------------------===//
6902 
6903 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6904                            SDValue Operand, SelectionDAG &DAG,
6905                            int &ExtraSteps) {
6906   EVT VT = Operand.getValueType();
6907   if (ST->hasNEON() &&
6908       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6909        VT == MVT::f32 || VT == MVT::v1f32 ||
6910        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6911     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6912       // For the reciprocal estimates, convergence is quadratic, so the number
6913       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6914       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6915       // the result for float (23 mantissa bits) is 2 and for double (52
6916       // mantissa bits) is 3.
6917       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6918 
6919     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6920   }
6921 
6922   return SDValue();
6923 }
6924 
6925 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6926                                                SelectionDAG &DAG, int Enabled,
6927                                                int &ExtraSteps,
6928                                                bool &UseOneConst,
6929                                                bool Reciprocal) const {
6930   if (Enabled == ReciprocalEstimate::Enabled ||
6931       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6932     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6933                                        DAG, ExtraSteps)) {
6934       SDLoc DL(Operand);
6935       EVT VT = Operand.getValueType();
6936 
6937       SDNodeFlags Flags;
6938       Flags.setAllowReassociation(true);
6939 
6940       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6941       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6942       for (int i = ExtraSteps; i > 0; --i) {
6943         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6944                                    Flags);
6945         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6946         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6947       }
6948       if (!Reciprocal) {
6949         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6950                                       VT);
6951         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6952         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6953 
6954         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6955         // Correct the result if the operand is 0.0.
6956         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6957                                VT, Eq, Operand, Estimate);
6958       }
6959 
6960       ExtraSteps = 0;
6961       return Estimate;
6962     }
6963 
6964   return SDValue();
6965 }
6966 
6967 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6968                                                 SelectionDAG &DAG, int Enabled,
6969                                                 int &ExtraSteps) const {
6970   if (Enabled == ReciprocalEstimate::Enabled)
6971     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6972                                        DAG, ExtraSteps)) {
6973       SDLoc DL(Operand);
6974       EVT VT = Operand.getValueType();
6975 
6976       SDNodeFlags Flags;
6977       Flags.setAllowReassociation(true);
6978 
6979       // Newton reciprocal iteration: E * (2 - X * E)
6980       // AArch64 reciprocal iteration instruction: (2 - M * N)
6981       for (int i = ExtraSteps; i > 0; --i) {
6982         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6983                                    Estimate, Flags);
6984         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6985       }
6986 
6987       ExtraSteps = 0;
6988       return Estimate;
6989     }
6990 
6991   return SDValue();
6992 }
6993 
6994 //===----------------------------------------------------------------------===//
6995 //                          AArch64 Inline Assembly Support
6996 //===----------------------------------------------------------------------===//
6997 
6998 // Table of Constraints
6999 // TODO: This is the current set of constraints supported by ARM for the
7000 // compiler, not all of them may make sense.
7001 //
7002 // r - A general register
7003 // w - An FP/SIMD register of some size in the range v0-v31
7004 // x - An FP/SIMD register of some size in the range v0-v15
7005 // I - Constant that can be used with an ADD instruction
7006 // J - Constant that can be used with a SUB instruction
7007 // K - Constant that can be used with a 32-bit logical instruction
7008 // L - Constant that can be used with a 64-bit logical instruction
7009 // M - Constant that can be used as a 32-bit MOV immediate
7010 // N - Constant that can be used as a 64-bit MOV immediate
7011 // Q - A memory reference with base register and no offset
7012 // S - A symbolic address
7013 // Y - Floating point constant zero
7014 // Z - Integer constant zero
7015 //
7016 //   Note that general register operands will be output using their 64-bit x
7017 // register name, whatever the size of the variable, unless the asm operand
7018 // is prefixed by the %w modifier. Floating-point and SIMD register operands
7019 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
7020 // %q modifier.
7021 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
7022   // At this point, we have to lower this constraint to something else, so we
7023   // lower it to an "r" or "w". However, by doing this we will force the result
7024   // to be in register, while the X constraint is much more permissive.
7025   //
7026   // Although we are correct (we are free to emit anything, without
7027   // constraints), we might break use cases that would expect us to be more
7028   // efficient and emit something else.
7029   if (!Subtarget->hasFPARMv8())
7030     return "r";
7031 
7032   if (ConstraintVT.isFloatingPoint())
7033     return "w";
7034 
7035   if (ConstraintVT.isVector() &&
7036      (ConstraintVT.getSizeInBits() == 64 ||
7037       ConstraintVT.getSizeInBits() == 128))
7038     return "w";
7039 
7040   return "r";
7041 }
7042 
7043 enum PredicateConstraint {
7044   Upl,
7045   Upa,
7046   Invalid
7047 };
7048 
7049 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
7050   PredicateConstraint P = PredicateConstraint::Invalid;
7051   if (Constraint == "Upa")
7052     P = PredicateConstraint::Upa;
7053   if (Constraint == "Upl")
7054     P = PredicateConstraint::Upl;
7055   return P;
7056 }
7057 
7058 /// getConstraintType - Given a constraint letter, return the type of
7059 /// constraint it is for this target.
7060 AArch64TargetLowering::ConstraintType
7061 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
7062   if (Constraint.size() == 1) {
7063     switch (Constraint[0]) {
7064     default:
7065       break;
7066     case 'x':
7067     case 'w':
7068     case 'y':
7069       return C_RegisterClass;
7070     // An address with a single base register. Due to the way we
7071     // currently handle addresses it is the same as 'r'.
7072     case 'Q':
7073       return C_Memory;
7074     case 'I':
7075     case 'J':
7076     case 'K':
7077     case 'L':
7078     case 'M':
7079     case 'N':
7080     case 'Y':
7081     case 'Z':
7082       return C_Immediate;
7083     case 'z':
7084     case 'S': // A symbolic address
7085       return C_Other;
7086     }
7087   } else if (parsePredicateConstraint(Constraint) !=
7088              PredicateConstraint::Invalid)
7089       return C_RegisterClass;
7090   return TargetLowering::getConstraintType(Constraint);
7091 }
7092 
7093 /// Examine constraint type and operand type and determine a weight value.
7094 /// This object must already have been set up with the operand type
7095 /// and the current alternative constraint selected.
7096 TargetLowering::ConstraintWeight
7097 AArch64TargetLowering::getSingleConstraintMatchWeight(
7098     AsmOperandInfo &info, const char *constraint) const {
7099   ConstraintWeight weight = CW_Invalid;
7100   Value *CallOperandVal = info.CallOperandVal;
7101   // If we don't have a value, we can't do a match,
7102   // but allow it at the lowest weight.
7103   if (!CallOperandVal)
7104     return CW_Default;
7105   Type *type = CallOperandVal->getType();
7106   // Look at the constraint type.
7107   switch (*constraint) {
7108   default:
7109     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7110     break;
7111   case 'x':
7112   case 'w':
7113   case 'y':
7114     if (type->isFloatingPointTy() || type->isVectorTy())
7115       weight = CW_Register;
7116     break;
7117   case 'z':
7118     weight = CW_Constant;
7119     break;
7120   case 'U':
7121     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
7122       weight = CW_Register;
7123     break;
7124   }
7125   return weight;
7126 }
7127 
7128 std::pair<unsigned, const TargetRegisterClass *>
7129 AArch64TargetLowering::getRegForInlineAsmConstraint(
7130     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
7131   if (Constraint.size() == 1) {
7132     switch (Constraint[0]) {
7133     case 'r':
7134       if (VT.getSizeInBits() == 64)
7135         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
7136       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
7137     case 'w':
7138       if (!Subtarget->hasFPARMv8())
7139         break;
7140       if (VT.isScalableVector())
7141         return std::make_pair(0U, &AArch64::ZPRRegClass);
7142       if (VT.getSizeInBits() == 16)
7143         return std::make_pair(0U, &AArch64::FPR16RegClass);
7144       if (VT.getSizeInBits() == 32)
7145         return std::make_pair(0U, &AArch64::FPR32RegClass);
7146       if (VT.getSizeInBits() == 64)
7147         return std::make_pair(0U, &AArch64::FPR64RegClass);
7148       if (VT.getSizeInBits() == 128)
7149         return std::make_pair(0U, &AArch64::FPR128RegClass);
7150       break;
7151     // The instructions that this constraint is designed for can
7152     // only take 128-bit registers so just use that regclass.
7153     case 'x':
7154       if (!Subtarget->hasFPARMv8())
7155         break;
7156       if (VT.isScalableVector())
7157         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
7158       if (VT.getSizeInBits() == 128)
7159         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
7160       break;
7161     case 'y':
7162       if (!Subtarget->hasFPARMv8())
7163         break;
7164       if (VT.isScalableVector())
7165         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
7166       break;
7167     }
7168   } else {
7169     PredicateConstraint PC = parsePredicateConstraint(Constraint);
7170     if (PC != PredicateConstraint::Invalid) {
7171       assert(VT.isScalableVector());
7172       bool restricted = (PC == PredicateConstraint::Upl);
7173       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
7174                           : std::make_pair(0U, &AArch64::PPRRegClass);
7175     }
7176   }
7177   if (StringRef("{cc}").equals_lower(Constraint))
7178     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
7179 
7180   // Use the default implementation in TargetLowering to convert the register
7181   // constraint into a member of a register class.
7182   std::pair<unsigned, const TargetRegisterClass *> Res;
7183   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7184 
7185   // Not found as a standard register?
7186   if (!Res.second) {
7187     unsigned Size = Constraint.size();
7188     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
7189         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
7190       int RegNo;
7191       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
7192       if (!Failed && RegNo >= 0 && RegNo <= 31) {
7193         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
7194         // By default we'll emit v0-v31 for this unless there's a modifier where
7195         // we'll emit the correct register as well.
7196         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
7197           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
7198           Res.second = &AArch64::FPR64RegClass;
7199         } else {
7200           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
7201           Res.second = &AArch64::FPR128RegClass;
7202         }
7203       }
7204     }
7205   }
7206 
7207   if (Res.second && !Subtarget->hasFPARMv8() &&
7208       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
7209       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
7210     return std::make_pair(0U, nullptr);
7211 
7212   return Res;
7213 }
7214 
7215 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7216 /// vector.  If it is invalid, don't add anything to Ops.
7217 void AArch64TargetLowering::LowerAsmOperandForConstraint(
7218     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
7219     SelectionDAG &DAG) const {
7220   SDValue Result;
7221 
7222   // Currently only support length 1 constraints.
7223   if (Constraint.length() != 1)
7224     return;
7225 
7226   char ConstraintLetter = Constraint[0];
7227   switch (ConstraintLetter) {
7228   default:
7229     break;
7230 
7231   // This set of constraints deal with valid constants for various instructions.
7232   // Validate and return a target constant for them if we can.
7233   case 'z': {
7234     // 'z' maps to xzr or wzr so it needs an input of 0.
7235     if (!isNullConstant(Op))
7236       return;
7237 
7238     if (Op.getValueType() == MVT::i64)
7239       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
7240     else
7241       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
7242     break;
7243   }
7244   case 'S': {
7245     // An absolute symbolic address or label reference.
7246     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
7247       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
7248                                           GA->getValueType(0));
7249     } else if (const BlockAddressSDNode *BA =
7250                    dyn_cast<BlockAddressSDNode>(Op)) {
7251       Result =
7252           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
7253     } else if (const ExternalSymbolSDNode *ES =
7254                    dyn_cast<ExternalSymbolSDNode>(Op)) {
7255       Result =
7256           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
7257     } else
7258       return;
7259     break;
7260   }
7261 
7262   case 'I':
7263   case 'J':
7264   case 'K':
7265   case 'L':
7266   case 'M':
7267   case 'N':
7268     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7269     if (!C)
7270       return;
7271 
7272     // Grab the value and do some validation.
7273     uint64_t CVal = C->getZExtValue();
7274     switch (ConstraintLetter) {
7275     // The I constraint applies only to simple ADD or SUB immediate operands:
7276     // i.e. 0 to 4095 with optional shift by 12
7277     // The J constraint applies only to ADD or SUB immediates that would be
7278     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
7279     // instruction [or vice versa], in other words -1 to -4095 with optional
7280     // left shift by 12.
7281     case 'I':
7282       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
7283         break;
7284       return;
7285     case 'J': {
7286       uint64_t NVal = -C->getSExtValue();
7287       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
7288         CVal = C->getSExtValue();
7289         break;
7290       }
7291       return;
7292     }
7293     // The K and L constraints apply *only* to logical immediates, including
7294     // what used to be the MOVI alias for ORR (though the MOVI alias has now
7295     // been removed and MOV should be used). So these constraints have to
7296     // distinguish between bit patterns that are valid 32-bit or 64-bit
7297     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
7298     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
7299     // versa.
7300     case 'K':
7301       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7302         break;
7303       return;
7304     case 'L':
7305       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7306         break;
7307       return;
7308     // The M and N constraints are a superset of K and L respectively, for use
7309     // with the MOV (immediate) alias. As well as the logical immediates they
7310     // also match 32 or 64-bit immediates that can be loaded either using a
7311     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
7312     // (M) or 64-bit 0x1234000000000000 (N) etc.
7313     // As a note some of this code is liberally stolen from the asm parser.
7314     case 'M': {
7315       if (!isUInt<32>(CVal))
7316         return;
7317       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7318         break;
7319       if ((CVal & 0xFFFF) == CVal)
7320         break;
7321       if ((CVal & 0xFFFF0000ULL) == CVal)
7322         break;
7323       uint64_t NCVal = ~(uint32_t)CVal;
7324       if ((NCVal & 0xFFFFULL) == NCVal)
7325         break;
7326       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7327         break;
7328       return;
7329     }
7330     case 'N': {
7331       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7332         break;
7333       if ((CVal & 0xFFFFULL) == CVal)
7334         break;
7335       if ((CVal & 0xFFFF0000ULL) == CVal)
7336         break;
7337       if ((CVal & 0xFFFF00000000ULL) == CVal)
7338         break;
7339       if ((CVal & 0xFFFF000000000000ULL) == CVal)
7340         break;
7341       uint64_t NCVal = ~CVal;
7342       if ((NCVal & 0xFFFFULL) == NCVal)
7343         break;
7344       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7345         break;
7346       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
7347         break;
7348       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
7349         break;
7350       return;
7351     }
7352     default:
7353       return;
7354     }
7355 
7356     // All assembler immediates are 64-bit integers.
7357     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
7358     break;
7359   }
7360 
7361   if (Result.getNode()) {
7362     Ops.push_back(Result);
7363     return;
7364   }
7365 
7366   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7367 }
7368 
7369 //===----------------------------------------------------------------------===//
7370 //                     AArch64 Advanced SIMD Support
7371 //===----------------------------------------------------------------------===//
7372 
7373 /// WidenVector - Given a value in the V64 register class, produce the
7374 /// equivalent value in the V128 register class.
7375 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
7376   EVT VT = V64Reg.getValueType();
7377   unsigned NarrowSize = VT.getVectorNumElements();
7378   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7379   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
7380   SDLoc DL(V64Reg);
7381 
7382   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
7383                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
7384 }
7385 
7386 /// getExtFactor - Determine the adjustment factor for the position when
7387 /// generating an "extract from vector registers" instruction.
7388 static unsigned getExtFactor(SDValue &V) {
7389   EVT EltType = V.getValueType().getVectorElementType();
7390   return EltType.getSizeInBits() / 8;
7391 }
7392 
7393 /// NarrowVector - Given a value in the V128 register class, produce the
7394 /// equivalent value in the V64 register class.
7395 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
7396   EVT VT = V128Reg.getValueType();
7397   unsigned WideSize = VT.getVectorNumElements();
7398   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7399   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
7400   SDLoc DL(V128Reg);
7401 
7402   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
7403 }
7404 
7405 // Gather data to see if the operation can be modelled as a
7406 // shuffle in combination with VEXTs.
7407 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
7408                                                   SelectionDAG &DAG) const {
7409   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7410   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
7411   SDLoc dl(Op);
7412   EVT VT = Op.getValueType();
7413   unsigned NumElts = VT.getVectorNumElements();
7414 
7415   struct ShuffleSourceInfo {
7416     SDValue Vec;
7417     unsigned MinElt;
7418     unsigned MaxElt;
7419 
7420     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7421     // be compatible with the shuffle we intend to construct. As a result
7422     // ShuffleVec will be some sliding window into the original Vec.
7423     SDValue ShuffleVec;
7424 
7425     // Code should guarantee that element i in Vec starts at element "WindowBase
7426     // + i * WindowScale in ShuffleVec".
7427     int WindowBase;
7428     int WindowScale;
7429 
7430     ShuffleSourceInfo(SDValue Vec)
7431       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
7432           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
7433 
7434     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7435   };
7436 
7437   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7438   // node.
7439   SmallVector<ShuffleSourceInfo, 2> Sources;
7440   for (unsigned i = 0; i < NumElts; ++i) {
7441     SDValue V = Op.getOperand(i);
7442     if (V.isUndef())
7443       continue;
7444     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7445              !isa<ConstantSDNode>(V.getOperand(1))) {
7446       LLVM_DEBUG(
7447           dbgs() << "Reshuffle failed: "
7448                     "a shuffle can only come from building a vector from "
7449                     "various elements of other vectors, provided their "
7450                     "indices are constant\n");
7451       return SDValue();
7452     }
7453 
7454     // Add this element source to the list if it's not already there.
7455     SDValue SourceVec = V.getOperand(0);
7456     auto Source = find(Sources, SourceVec);
7457     if (Source == Sources.end())
7458       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7459 
7460     // Update the minimum and maximum lane number seen.
7461     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7462     Source->MinElt = std::min(Source->MinElt, EltNo);
7463     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7464   }
7465 
7466   if (Sources.size() > 2) {
7467     LLVM_DEBUG(
7468         dbgs() << "Reshuffle failed: currently only do something sane when at "
7469                   "most two source vectors are involved\n");
7470     return SDValue();
7471   }
7472 
7473   // Find out the smallest element size among result and two sources, and use
7474   // it as element size to build the shuffle_vector.
7475   EVT SmallestEltTy = VT.getVectorElementType();
7476   for (auto &Source : Sources) {
7477     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7478     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7479       SmallestEltTy = SrcEltTy;
7480     }
7481   }
7482   unsigned ResMultiplier =
7483       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7484   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7485   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7486 
7487   // If the source vector is too wide or too narrow, we may nevertheless be able
7488   // to construct a compatible shuffle either by concatenating it with UNDEF or
7489   // extracting a suitable range of elements.
7490   for (auto &Src : Sources) {
7491     EVT SrcVT = Src.ShuffleVec.getValueType();
7492 
7493     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7494       continue;
7495 
7496     // This stage of the search produces a source with the same element type as
7497     // the original, but with a total width matching the BUILD_VECTOR output.
7498     EVT EltVT = SrcVT.getVectorElementType();
7499     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7500     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7501 
7502     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7503       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
7504       // We can pad out the smaller vector for free, so if it's part of a
7505       // shuffle...
7506       Src.ShuffleVec =
7507           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7508                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7509       continue;
7510     }
7511 
7512     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits()) {
7513       LLVM_DEBUG(
7514           dbgs() << "Reshuffle failed: result vector too small to extract\n");
7515       return SDValue();
7516     }
7517 
7518     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7519       LLVM_DEBUG(
7520           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7521       return SDValue();
7522     }
7523 
7524     if (Src.MinElt >= NumSrcElts) {
7525       // The extraction can just take the second half
7526       Src.ShuffleVec =
7527           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7528                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7529       Src.WindowBase = -NumSrcElts;
7530     } else if (Src.MaxElt < NumSrcElts) {
7531       // The extraction can just take the first half
7532       Src.ShuffleVec =
7533           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7534                       DAG.getConstant(0, dl, MVT::i64));
7535     } else {
7536       // An actual VEXT is needed
7537       SDValue VEXTSrc1 =
7538           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7539                       DAG.getConstant(0, dl, MVT::i64));
7540       SDValue VEXTSrc2 =
7541           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7542                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7543       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7544 
7545       if (!SrcVT.is64BitVector()) {
7546         LLVM_DEBUG(
7547           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
7548                     "for SVE vectors.");
7549         return SDValue();
7550       }
7551 
7552       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7553                                    VEXTSrc2,
7554                                    DAG.getConstant(Imm, dl, MVT::i32));
7555       Src.WindowBase = -Src.MinElt;
7556     }
7557   }
7558 
7559   // Another possible incompatibility occurs from the vector element types. We
7560   // can fix this by bitcasting the source vectors to the same type we intend
7561   // for the shuffle.
7562   for (auto &Src : Sources) {
7563     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7564     if (SrcEltTy == SmallestEltTy)
7565       continue;
7566     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7567     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7568     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7569     Src.WindowBase *= Src.WindowScale;
7570   }
7571 
7572   // Final sanity check before we try to actually produce a shuffle.
7573   LLVM_DEBUG(for (auto Src
7574                   : Sources)
7575                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7576 
7577   // The stars all align, our next step is to produce the mask for the shuffle.
7578   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7579   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7580   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7581     SDValue Entry = Op.getOperand(i);
7582     if (Entry.isUndef())
7583       continue;
7584 
7585     auto Src = find(Sources, Entry.getOperand(0));
7586     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7587 
7588     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7589     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7590     // segment.
7591     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7592     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7593                                VT.getScalarSizeInBits());
7594     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7595 
7596     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7597     // starting at the appropriate offset.
7598     int *LaneMask = &Mask[i * ResMultiplier];
7599 
7600     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7601     ExtractBase += NumElts * (Src - Sources.begin());
7602     for (int j = 0; j < LanesDefined; ++j)
7603       LaneMask[j] = ExtractBase + j;
7604   }
7605 
7606   // Final check before we try to produce nonsense...
7607   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7608     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7609     return SDValue();
7610   }
7611 
7612   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7613   for (unsigned i = 0; i < Sources.size(); ++i)
7614     ShuffleOps[i] = Sources[i].ShuffleVec;
7615 
7616   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7617                                          ShuffleOps[1], Mask);
7618   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7619 
7620   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7621              dbgs() << "Reshuffle, creating node: "; V.dump(););
7622 
7623   return V;
7624 }
7625 
7626 // check if an EXT instruction can handle the shuffle mask when the
7627 // vector sources of the shuffle are the same.
7628 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7629   unsigned NumElts = VT.getVectorNumElements();
7630 
7631   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7632   if (M[0] < 0)
7633     return false;
7634 
7635   Imm = M[0];
7636 
7637   // If this is a VEXT shuffle, the immediate value is the index of the first
7638   // element.  The other shuffle indices must be the successive elements after
7639   // the first one.
7640   unsigned ExpectedElt = Imm;
7641   for (unsigned i = 1; i < NumElts; ++i) {
7642     // Increment the expected index.  If it wraps around, just follow it
7643     // back to index zero and keep going.
7644     ++ExpectedElt;
7645     if (ExpectedElt == NumElts)
7646       ExpectedElt = 0;
7647 
7648     if (M[i] < 0)
7649       continue; // ignore UNDEF indices
7650     if (ExpectedElt != static_cast<unsigned>(M[i]))
7651       return false;
7652   }
7653 
7654   return true;
7655 }
7656 
7657 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
7658 /// element width than the vector lane type. If that is the case the function
7659 /// returns true and writes the value of the DUP instruction lane operand into
7660 /// DupLaneOp
7661 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
7662                           unsigned &DupLaneOp) {
7663   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7664          "Only possible block sizes for wide DUP are: 16, 32, 64");
7665 
7666   if (BlockSize <= VT.getScalarSizeInBits())
7667     return false;
7668   if (BlockSize % VT.getScalarSizeInBits() != 0)
7669     return false;
7670   if (VT.getSizeInBits() % BlockSize != 0)
7671     return false;
7672 
7673   size_t SingleVecNumElements = VT.getVectorNumElements();
7674   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
7675   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
7676 
7677   // We are looking for masks like
7678   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
7679   // might be replaced by 'undefined'. BlockIndices will eventually contain
7680   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
7681   // for the above examples)
7682   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
7683   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
7684     for (size_t I = 0; I < NumEltsPerBlock; I++) {
7685       int Elt = M[BlockIndex * NumEltsPerBlock + I];
7686       if (Elt < 0)
7687         continue;
7688       // For now we don't support shuffles that use the second operand
7689       if ((unsigned)Elt >= SingleVecNumElements)
7690         return false;
7691       if (BlockElts[I] < 0)
7692         BlockElts[I] = Elt;
7693       else if (BlockElts[I] != Elt)
7694         return false;
7695     }
7696 
7697   // We found a candidate block (possibly with some undefs). It must be a
7698   // sequence of consecutive integers starting with a value divisible by
7699   // NumEltsPerBlock with some values possibly replaced by undef-s.
7700 
7701   // Find first non-undef element
7702   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
7703   assert(FirstRealEltIter != BlockElts.end() &&
7704          "Shuffle with all-undefs must have been caught by previous cases, "
7705          "e.g. isSplat()");
7706   if (FirstRealEltIter == BlockElts.end()) {
7707     DupLaneOp = 0;
7708     return true;
7709   }
7710 
7711   // Index of FirstRealElt in BlockElts
7712   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
7713 
7714   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
7715     return false;
7716   // BlockElts[0] must have the following value if it isn't undef:
7717   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
7718 
7719   // Check the first element
7720   if (Elt0 % NumEltsPerBlock != 0)
7721     return false;
7722   // Check that the sequence indeed consists of consecutive integers (modulo
7723   // undefs)
7724   for (size_t I = 0; I < NumEltsPerBlock; I++)
7725     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
7726       return false;
7727 
7728   DupLaneOp = Elt0 / NumEltsPerBlock;
7729   return true;
7730 }
7731 
7732 // check if an EXT instruction can handle the shuffle mask when the
7733 // vector sources of the shuffle are different.
7734 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7735                       unsigned &Imm) {
7736   // Look for the first non-undef element.
7737   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7738 
7739   // Benefit form APInt to handle overflow when calculating expected element.
7740   unsigned NumElts = VT.getVectorNumElements();
7741   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7742   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7743   // The following shuffle indices must be the successive elements after the
7744   // first real element.
7745   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7746       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7747   if (FirstWrongElt != M.end())
7748     return false;
7749 
7750   // The index of an EXT is the first element if it is not UNDEF.
7751   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7752   // value of the first element.  E.g.
7753   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7754   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7755   // ExpectedElt is the last mask index plus 1.
7756   Imm = ExpectedElt.getZExtValue();
7757 
7758   // There are two difference cases requiring to reverse input vectors.
7759   // For example, for vector <4 x i32> we have the following cases,
7760   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7761   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7762   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7763   // to reverse two input vectors.
7764   if (Imm < NumElts)
7765     ReverseEXT = true;
7766   else
7767     Imm -= NumElts;
7768 
7769   return true;
7770 }
7771 
7772 /// isREVMask - Check if a vector shuffle corresponds to a REV
7773 /// instruction with the specified blocksize.  (The order of the elements
7774 /// within each block of the vector is reversed.)
7775 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7776   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7777          "Only possible block sizes for REV are: 16, 32, 64");
7778 
7779   unsigned EltSz = VT.getScalarSizeInBits();
7780   if (EltSz == 64)
7781     return false;
7782 
7783   unsigned NumElts = VT.getVectorNumElements();
7784   unsigned BlockElts = M[0] + 1;
7785   // If the first shuffle index is UNDEF, be optimistic.
7786   if (M[0] < 0)
7787     BlockElts = BlockSize / EltSz;
7788 
7789   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7790     return false;
7791 
7792   for (unsigned i = 0; i < NumElts; ++i) {
7793     if (M[i] < 0)
7794       continue; // ignore UNDEF indices
7795     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7796       return false;
7797   }
7798 
7799   return true;
7800 }
7801 
7802 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7803   unsigned NumElts = VT.getVectorNumElements();
7804   if (NumElts % 2 != 0)
7805     return false;
7806   WhichResult = (M[0] == 0 ? 0 : 1);
7807   unsigned Idx = WhichResult * NumElts / 2;
7808   for (unsigned i = 0; i != NumElts; i += 2) {
7809     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7810         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7811       return false;
7812     Idx += 1;
7813   }
7814 
7815   return true;
7816 }
7817 
7818 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7819   unsigned NumElts = VT.getVectorNumElements();
7820   WhichResult = (M[0] == 0 ? 0 : 1);
7821   for (unsigned i = 0; i != NumElts; ++i) {
7822     if (M[i] < 0)
7823       continue; // ignore UNDEF indices
7824     if ((unsigned)M[i] != 2 * i + WhichResult)
7825       return false;
7826   }
7827 
7828   return true;
7829 }
7830 
7831 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7832   unsigned NumElts = VT.getVectorNumElements();
7833   if (NumElts % 2 != 0)
7834     return false;
7835   WhichResult = (M[0] == 0 ? 0 : 1);
7836   for (unsigned i = 0; i < NumElts; i += 2) {
7837     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7838         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7839       return false;
7840   }
7841   return true;
7842 }
7843 
7844 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7845 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7846 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7847 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7848   unsigned NumElts = VT.getVectorNumElements();
7849   if (NumElts % 2 != 0)
7850     return false;
7851   WhichResult = (M[0] == 0 ? 0 : 1);
7852   unsigned Idx = WhichResult * NumElts / 2;
7853   for (unsigned i = 0; i != NumElts; i += 2) {
7854     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7855         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7856       return false;
7857     Idx += 1;
7858   }
7859 
7860   return true;
7861 }
7862 
7863 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7864 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7865 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7866 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7867   unsigned Half = VT.getVectorNumElements() / 2;
7868   WhichResult = (M[0] == 0 ? 0 : 1);
7869   for (unsigned j = 0; j != 2; ++j) {
7870     unsigned Idx = WhichResult;
7871     for (unsigned i = 0; i != Half; ++i) {
7872       int MIdx = M[i + j * Half];
7873       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7874         return false;
7875       Idx += 2;
7876     }
7877   }
7878 
7879   return true;
7880 }
7881 
7882 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7883 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7884 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7885 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7886   unsigned NumElts = VT.getVectorNumElements();
7887   if (NumElts % 2 != 0)
7888     return false;
7889   WhichResult = (M[0] == 0 ? 0 : 1);
7890   for (unsigned i = 0; i < NumElts; i += 2) {
7891     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7892         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7893       return false;
7894   }
7895   return true;
7896 }
7897 
7898 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7899                       bool &DstIsLeft, int &Anomaly) {
7900   if (M.size() != static_cast<size_t>(NumInputElements))
7901     return false;
7902 
7903   int NumLHSMatch = 0, NumRHSMatch = 0;
7904   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7905 
7906   for (int i = 0; i < NumInputElements; ++i) {
7907     if (M[i] == -1) {
7908       ++NumLHSMatch;
7909       ++NumRHSMatch;
7910       continue;
7911     }
7912 
7913     if (M[i] == i)
7914       ++NumLHSMatch;
7915     else
7916       LastLHSMismatch = i;
7917 
7918     if (M[i] == i + NumInputElements)
7919       ++NumRHSMatch;
7920     else
7921       LastRHSMismatch = i;
7922   }
7923 
7924   if (NumLHSMatch == NumInputElements - 1) {
7925     DstIsLeft = true;
7926     Anomaly = LastLHSMismatch;
7927     return true;
7928   } else if (NumRHSMatch == NumInputElements - 1) {
7929     DstIsLeft = false;
7930     Anomaly = LastRHSMismatch;
7931     return true;
7932   }
7933 
7934   return false;
7935 }
7936 
7937 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7938   if (VT.getSizeInBits() != 128)
7939     return false;
7940 
7941   unsigned NumElts = VT.getVectorNumElements();
7942 
7943   for (int I = 0, E = NumElts / 2; I != E; I++) {
7944     if (Mask[I] != I)
7945       return false;
7946   }
7947 
7948   int Offset = NumElts / 2;
7949   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7950     if (Mask[I] != I + SplitLHS * Offset)
7951       return false;
7952   }
7953 
7954   return true;
7955 }
7956 
7957 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7958   SDLoc DL(Op);
7959   EVT VT = Op.getValueType();
7960   SDValue V0 = Op.getOperand(0);
7961   SDValue V1 = Op.getOperand(1);
7962   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7963 
7964   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7965       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7966     return SDValue();
7967 
7968   bool SplitV0 = V0.getValueSizeInBits() == 128;
7969 
7970   if (!isConcatMask(Mask, VT, SplitV0))
7971     return SDValue();
7972 
7973   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7974   if (SplitV0) {
7975     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7976                      DAG.getConstant(0, DL, MVT::i64));
7977   }
7978   if (V1.getValueSizeInBits() == 128) {
7979     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7980                      DAG.getConstant(0, DL, MVT::i64));
7981   }
7982   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7983 }
7984 
7985 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7986 /// the specified operations to build the shuffle.
7987 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7988                                       SDValue RHS, SelectionDAG &DAG,
7989                                       const SDLoc &dl) {
7990   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7991   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7992   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7993 
7994   enum {
7995     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7996     OP_VREV,
7997     OP_VDUP0,
7998     OP_VDUP1,
7999     OP_VDUP2,
8000     OP_VDUP3,
8001     OP_VEXT1,
8002     OP_VEXT2,
8003     OP_VEXT3,
8004     OP_VUZPL, // VUZP, left result
8005     OP_VUZPR, // VUZP, right result
8006     OP_VZIPL, // VZIP, left result
8007     OP_VZIPR, // VZIP, right result
8008     OP_VTRNL, // VTRN, left result
8009     OP_VTRNR  // VTRN, right result
8010   };
8011 
8012   if (OpNum == OP_COPY) {
8013     if (LHSID == (1 * 9 + 2) * 9 + 3)
8014       return LHS;
8015     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
8016     return RHS;
8017   }
8018 
8019   SDValue OpLHS, OpRHS;
8020   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8021   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8022   EVT VT = OpLHS.getValueType();
8023 
8024   switch (OpNum) {
8025   default:
8026     llvm_unreachable("Unknown shuffle opcode!");
8027   case OP_VREV:
8028     // VREV divides the vector in half and swaps within the half.
8029     if (VT.getVectorElementType() == MVT::i32 ||
8030         VT.getVectorElementType() == MVT::f32)
8031       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
8032     // vrev <4 x i16> -> REV32
8033     if (VT.getVectorElementType() == MVT::i16 ||
8034         VT.getVectorElementType() == MVT::f16 ||
8035         VT.getVectorElementType() == MVT::bf16)
8036       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
8037     // vrev <4 x i8> -> REV16
8038     assert(VT.getVectorElementType() == MVT::i8);
8039     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
8040   case OP_VDUP0:
8041   case OP_VDUP1:
8042   case OP_VDUP2:
8043   case OP_VDUP3: {
8044     EVT EltTy = VT.getVectorElementType();
8045     unsigned Opcode;
8046     if (EltTy == MVT::i8)
8047       Opcode = AArch64ISD::DUPLANE8;
8048     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
8049       Opcode = AArch64ISD::DUPLANE16;
8050     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
8051       Opcode = AArch64ISD::DUPLANE32;
8052     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
8053       Opcode = AArch64ISD::DUPLANE64;
8054     else
8055       llvm_unreachable("Invalid vector element type?");
8056 
8057     if (VT.getSizeInBits() == 64)
8058       OpLHS = WidenVector(OpLHS, DAG);
8059     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
8060     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
8061   }
8062   case OP_VEXT1:
8063   case OP_VEXT2:
8064   case OP_VEXT3: {
8065     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
8066     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
8067                        DAG.getConstant(Imm, dl, MVT::i32));
8068   }
8069   case OP_VUZPL:
8070     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
8071                        OpRHS);
8072   case OP_VUZPR:
8073     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
8074                        OpRHS);
8075   case OP_VZIPL:
8076     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
8077                        OpRHS);
8078   case OP_VZIPR:
8079     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
8080                        OpRHS);
8081   case OP_VTRNL:
8082     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
8083                        OpRHS);
8084   case OP_VTRNR:
8085     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
8086                        OpRHS);
8087   }
8088 }
8089 
8090 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
8091                            SelectionDAG &DAG) {
8092   // Check to see if we can use the TBL instruction.
8093   SDValue V1 = Op.getOperand(0);
8094   SDValue V2 = Op.getOperand(1);
8095   SDLoc DL(Op);
8096 
8097   EVT EltVT = Op.getValueType().getVectorElementType();
8098   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
8099 
8100   SmallVector<SDValue, 8> TBLMask;
8101   for (int Val : ShuffleMask) {
8102     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
8103       unsigned Offset = Byte + Val * BytesPerElt;
8104       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
8105     }
8106   }
8107 
8108   MVT IndexVT = MVT::v8i8;
8109   unsigned IndexLen = 8;
8110   if (Op.getValueSizeInBits() == 128) {
8111     IndexVT = MVT::v16i8;
8112     IndexLen = 16;
8113   }
8114 
8115   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
8116   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
8117 
8118   SDValue Shuffle;
8119   if (V2.getNode()->isUndef()) {
8120     if (IndexLen == 8)
8121       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
8122     Shuffle = DAG.getNode(
8123         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8124         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8125         DAG.getBuildVector(IndexVT, DL,
8126                            makeArrayRef(TBLMask.data(), IndexLen)));
8127   } else {
8128     if (IndexLen == 8) {
8129       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
8130       Shuffle = DAG.getNode(
8131           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8132           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8133           DAG.getBuildVector(IndexVT, DL,
8134                              makeArrayRef(TBLMask.data(), IndexLen)));
8135     } else {
8136       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
8137       // cannot currently represent the register constraints on the input
8138       // table registers.
8139       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
8140       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
8141       //                   IndexLen));
8142       Shuffle = DAG.getNode(
8143           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8144           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
8145           V2Cst, DAG.getBuildVector(IndexVT, DL,
8146                                     makeArrayRef(TBLMask.data(), IndexLen)));
8147     }
8148   }
8149   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
8150 }
8151 
8152 static unsigned getDUPLANEOp(EVT EltType) {
8153   if (EltType == MVT::i8)
8154     return AArch64ISD::DUPLANE8;
8155   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
8156     return AArch64ISD::DUPLANE16;
8157   if (EltType == MVT::i32 || EltType == MVT::f32)
8158     return AArch64ISD::DUPLANE32;
8159   if (EltType == MVT::i64 || EltType == MVT::f64)
8160     return AArch64ISD::DUPLANE64;
8161 
8162   llvm_unreachable("Invalid vector element type?");
8163 }
8164 
8165 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
8166                             unsigned Opcode, SelectionDAG &DAG) {
8167   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
8168   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
8169     // Match: dup (bitcast (extract_subv X, C)), LaneC
8170     if (BitCast.getOpcode() != ISD::BITCAST ||
8171         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
8172       return false;
8173 
8174     // The extract index must align in the destination type. That may not
8175     // happen if the bitcast is from narrow to wide type.
8176     SDValue Extract = BitCast.getOperand(0);
8177     unsigned ExtIdx = Extract.getConstantOperandVal(1);
8178     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
8179     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
8180     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
8181     if (ExtIdxInBits % CastedEltBitWidth != 0)
8182       return false;
8183 
8184     // Update the lane value by offsetting with the scaled extract index.
8185     LaneC += ExtIdxInBits / CastedEltBitWidth;
8186 
8187     // Determine the casted vector type of the wide vector input.
8188     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
8189     // Examples:
8190     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
8191     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
8192     unsigned SrcVecNumElts =
8193         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
8194     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
8195                               SrcVecNumElts);
8196     return true;
8197   };
8198   MVT CastVT;
8199   if (getScaledOffsetDup(V, Lane, CastVT)) {
8200     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
8201   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8202     // The lane is incremented by the index of the extract.
8203     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
8204     Lane += V.getConstantOperandVal(1);
8205     V = V.getOperand(0);
8206   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
8207     // The lane is decremented if we are splatting from the 2nd operand.
8208     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
8209     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
8210     Lane -= Idx * VT.getVectorNumElements() / 2;
8211     V = WidenVector(V.getOperand(Idx), DAG);
8212   } else if (VT.getSizeInBits() == 64) {
8213     // Widen the operand to 128-bit register with undef.
8214     V = WidenVector(V, DAG);
8215   }
8216   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
8217 }
8218 
8219 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8220                                                    SelectionDAG &DAG) const {
8221   SDLoc dl(Op);
8222   EVT VT = Op.getValueType();
8223 
8224   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8225 
8226   // Convert shuffles that are directly supported on NEON to target-specific
8227   // DAG nodes, instead of keeping them as shuffles and matching them again
8228   // during code selection.  This is more efficient and avoids the possibility
8229   // of inconsistencies between legalization and selection.
8230   ArrayRef<int> ShuffleMask = SVN->getMask();
8231 
8232   SDValue V1 = Op.getOperand(0);
8233   SDValue V2 = Op.getOperand(1);
8234 
8235   if (SVN->isSplat()) {
8236     int Lane = SVN->getSplatIndex();
8237     // If this is undef splat, generate it via "just" vdup, if possible.
8238     if (Lane == -1)
8239       Lane = 0;
8240 
8241     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
8242       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
8243                          V1.getOperand(0));
8244     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
8245     // constant. If so, we can just reference the lane's definition directly.
8246     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
8247         !isa<ConstantSDNode>(V1.getOperand(Lane)))
8248       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
8249 
8250     // Otherwise, duplicate from the lane of the input vector.
8251     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
8252     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
8253   }
8254 
8255   // Check if the mask matches a DUP for a wider element
8256   for (unsigned LaneSize : {64U, 32U, 16U}) {
8257     unsigned Lane = 0;
8258     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
8259       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
8260                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
8261                                                         : AArch64ISD::DUPLANE16;
8262       // Cast V1 to an integer vector with required lane size
8263       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
8264       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
8265       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
8266       V1 = DAG.getBitcast(NewVecTy, V1);
8267       // Constuct the DUP instruction
8268       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
8269       // Cast back to the original type
8270       return DAG.getBitcast(VT, V1);
8271     }
8272   }
8273 
8274   if (isREVMask(ShuffleMask, VT, 64))
8275     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
8276   if (isREVMask(ShuffleMask, VT, 32))
8277     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
8278   if (isREVMask(ShuffleMask, VT, 16))
8279     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
8280 
8281   bool ReverseEXT = false;
8282   unsigned Imm;
8283   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
8284     if (ReverseEXT)
8285       std::swap(V1, V2);
8286     Imm *= getExtFactor(V1);
8287     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
8288                        DAG.getConstant(Imm, dl, MVT::i32));
8289   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
8290     Imm *= getExtFactor(V1);
8291     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
8292                        DAG.getConstant(Imm, dl, MVT::i32));
8293   }
8294 
8295   unsigned WhichResult;
8296   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
8297     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8298     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8299   }
8300   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
8301     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8302     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8303   }
8304   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
8305     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8306     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8307   }
8308 
8309   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8310     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8311     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8312   }
8313   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8314     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8315     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8316   }
8317   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8318     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8319     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8320   }
8321 
8322   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
8323     return Concat;
8324 
8325   bool DstIsLeft;
8326   int Anomaly;
8327   int NumInputElements = V1.getValueType().getVectorNumElements();
8328   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
8329     SDValue DstVec = DstIsLeft ? V1 : V2;
8330     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
8331 
8332     SDValue SrcVec = V1;
8333     int SrcLane = ShuffleMask[Anomaly];
8334     if (SrcLane >= NumInputElements) {
8335       SrcVec = V2;
8336       SrcLane -= VT.getVectorNumElements();
8337     }
8338     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
8339 
8340     EVT ScalarVT = VT.getVectorElementType();
8341 
8342     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
8343       ScalarVT = MVT::i32;
8344 
8345     return DAG.getNode(
8346         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8347         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
8348         DstLaneV);
8349   }
8350 
8351   // If the shuffle is not directly supported and it has 4 elements, use
8352   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8353   unsigned NumElts = VT.getVectorNumElements();
8354   if (NumElts == 4) {
8355     unsigned PFIndexes[4];
8356     for (unsigned i = 0; i != 4; ++i) {
8357       if (ShuffleMask[i] < 0)
8358         PFIndexes[i] = 8;
8359       else
8360         PFIndexes[i] = ShuffleMask[i];
8361     }
8362 
8363     // Compute the index in the perfect shuffle table.
8364     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8365                             PFIndexes[2] * 9 + PFIndexes[3];
8366     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8367     unsigned Cost = (PFEntry >> 30);
8368 
8369     if (Cost <= 4)
8370       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8371   }
8372 
8373   return GenerateTBL(Op, ShuffleMask, DAG);
8374 }
8375 
8376 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
8377                                                  SelectionDAG &DAG) const {
8378   SDLoc dl(Op);
8379   EVT VT = Op.getValueType();
8380   EVT ElemVT = VT.getScalarType();
8381   SDValue SplatVal = Op.getOperand(0);
8382 
8383   if (useSVEForFixedLengthVectorVT(VT))
8384     return LowerToScalableOp(Op, DAG);
8385 
8386   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
8387   // FPRs don't have this restriction.
8388   switch (ElemVT.getSimpleVT().SimpleTy) {
8389   case MVT::i1: {
8390     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
8391     // lowering code.
8392     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
8393       if (ConstVal->isOne())
8394         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
8395       // TODO: Add special case for constant false
8396     }
8397     // The general case of i1.  There isn't any natural way to do this,
8398     // so we use some trickery with whilelo.
8399     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8400     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
8401                            DAG.getValueType(MVT::i1));
8402     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
8403                                        MVT::i64);
8404     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
8405                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
8406   }
8407   case MVT::i8:
8408   case MVT::i16:
8409   case MVT::i32:
8410     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
8411     break;
8412   case MVT::i64:
8413     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8414     break;
8415   case MVT::f16:
8416   case MVT::bf16:
8417   case MVT::f32:
8418   case MVT::f64:
8419     // Fine as is
8420     break;
8421   default:
8422     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
8423   }
8424 
8425   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
8426 }
8427 
8428 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
8429                                              SelectionDAG &DAG) const {
8430   SDLoc DL(Op);
8431 
8432   EVT VT = Op.getValueType();
8433   if (!isTypeLegal(VT) || !VT.isScalableVector())
8434     return SDValue();
8435 
8436   // Current lowering only supports the SVE-ACLE types.
8437   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
8438     return SDValue();
8439 
8440   // The DUPQ operation is indepedent of element type so normalise to i64s.
8441   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
8442   SDValue Idx128 = Op.getOperand(2);
8443 
8444   // DUPQ can be used when idx is in range.
8445   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
8446   if (CIdx && (CIdx->getZExtValue() <= 3)) {
8447     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
8448     SDNode *DUPQ =
8449         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
8450     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
8451   }
8452 
8453   // The ACLE says this must produce the same result as:
8454   //   svtbl(data, svadd_x(svptrue_b64(),
8455   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
8456   //                       index * 2))
8457   SDValue One = DAG.getConstant(1, DL, MVT::i64);
8458   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
8459 
8460   // create the vector 0,1,0,1,...
8461   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
8462   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
8463                            DL, MVT::nxv2i64, Zero, One);
8464   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
8465 
8466   // create the vector idx64,idx64+1,idx64,idx64+1,...
8467   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
8468   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
8469   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
8470 
8471   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
8472   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
8473   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
8474 }
8475 
8476 
8477 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
8478                                APInt &UndefBits) {
8479   EVT VT = BVN->getValueType(0);
8480   APInt SplatBits, SplatUndef;
8481   unsigned SplatBitSize;
8482   bool HasAnyUndefs;
8483   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8484     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
8485 
8486     for (unsigned i = 0; i < NumSplats; ++i) {
8487       CnstBits <<= SplatBitSize;
8488       UndefBits <<= SplatBitSize;
8489       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
8490       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
8491     }
8492 
8493     return true;
8494   }
8495 
8496   return false;
8497 }
8498 
8499 // Try 64-bit splatted SIMD immediate.
8500 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8501                                  const APInt &Bits) {
8502   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8503     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8504     EVT VT = Op.getValueType();
8505     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
8506 
8507     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
8508       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
8509 
8510       SDLoc dl(Op);
8511       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8512                                 DAG.getConstant(Value, dl, MVT::i32));
8513       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8514     }
8515   }
8516 
8517   return SDValue();
8518 }
8519 
8520 // Try 32-bit splatted SIMD immediate.
8521 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8522                                   const APInt &Bits,
8523                                   const SDValue *LHS = nullptr) {
8524   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8525     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8526     EVT VT = Op.getValueType();
8527     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8528     bool isAdvSIMDModImm = false;
8529     uint64_t Shift;
8530 
8531     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
8532       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
8533       Shift = 0;
8534     }
8535     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
8536       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
8537       Shift = 8;
8538     }
8539     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
8540       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
8541       Shift = 16;
8542     }
8543     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
8544       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
8545       Shift = 24;
8546     }
8547 
8548     if (isAdvSIMDModImm) {
8549       SDLoc dl(Op);
8550       SDValue Mov;
8551 
8552       if (LHS)
8553         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8554                           DAG.getConstant(Value, dl, MVT::i32),
8555                           DAG.getConstant(Shift, dl, MVT::i32));
8556       else
8557         Mov = DAG.getNode(NewOp, dl, MovTy,
8558                           DAG.getConstant(Value, dl, MVT::i32),
8559                           DAG.getConstant(Shift, dl, MVT::i32));
8560 
8561       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8562     }
8563   }
8564 
8565   return SDValue();
8566 }
8567 
8568 // Try 16-bit splatted SIMD immediate.
8569 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8570                                   const APInt &Bits,
8571                                   const SDValue *LHS = nullptr) {
8572   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8573     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8574     EVT VT = Op.getValueType();
8575     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8576     bool isAdvSIMDModImm = false;
8577     uint64_t Shift;
8578 
8579     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8580       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8581       Shift = 0;
8582     }
8583     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8584       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8585       Shift = 8;
8586     }
8587 
8588     if (isAdvSIMDModImm) {
8589       SDLoc dl(Op);
8590       SDValue Mov;
8591 
8592       if (LHS)
8593         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8594                           DAG.getConstant(Value, dl, MVT::i32),
8595                           DAG.getConstant(Shift, dl, MVT::i32));
8596       else
8597         Mov = DAG.getNode(NewOp, dl, MovTy,
8598                           DAG.getConstant(Value, dl, MVT::i32),
8599                           DAG.getConstant(Shift, dl, MVT::i32));
8600 
8601       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8602     }
8603   }
8604 
8605   return SDValue();
8606 }
8607 
8608 // Try 32-bit splatted SIMD immediate with shifted ones.
8609 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8610                                     SelectionDAG &DAG, const APInt &Bits) {
8611   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8612     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8613     EVT VT = Op.getValueType();
8614     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8615     bool isAdvSIMDModImm = false;
8616     uint64_t Shift;
8617 
8618     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8619       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8620       Shift = 264;
8621     }
8622     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8623       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8624       Shift = 272;
8625     }
8626 
8627     if (isAdvSIMDModImm) {
8628       SDLoc dl(Op);
8629       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8630                                 DAG.getConstant(Value, dl, MVT::i32),
8631                                 DAG.getConstant(Shift, dl, MVT::i32));
8632       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8633     }
8634   }
8635 
8636   return SDValue();
8637 }
8638 
8639 // Try 8-bit splatted SIMD immediate.
8640 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8641                                  const APInt &Bits) {
8642   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8643     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8644     EVT VT = Op.getValueType();
8645     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8646 
8647     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8648       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8649 
8650       SDLoc dl(Op);
8651       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8652                                 DAG.getConstant(Value, dl, MVT::i32));
8653       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8654     }
8655   }
8656 
8657   return SDValue();
8658 }
8659 
8660 // Try FP splatted SIMD immediate.
8661 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8662                                   const APInt &Bits) {
8663   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8664     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8665     EVT VT = Op.getValueType();
8666     bool isWide = (VT.getSizeInBits() == 128);
8667     MVT MovTy;
8668     bool isAdvSIMDModImm = false;
8669 
8670     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8671       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8672       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8673     }
8674     else if (isWide &&
8675              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8676       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8677       MovTy = MVT::v2f64;
8678     }
8679 
8680     if (isAdvSIMDModImm) {
8681       SDLoc dl(Op);
8682       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8683                                 DAG.getConstant(Value, dl, MVT::i32));
8684       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8685     }
8686   }
8687 
8688   return SDValue();
8689 }
8690 
8691 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8692 // consists of only the same constant int value, returned in reference arg
8693 // ConstVal
8694 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8695                                      uint64_t &ConstVal) {
8696   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8697   if (!Bvec)
8698     return false;
8699   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8700   if (!FirstElt)
8701     return false;
8702   EVT VT = Bvec->getValueType(0);
8703   unsigned NumElts = VT.getVectorNumElements();
8704   for (unsigned i = 1; i < NumElts; ++i)
8705     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8706       return false;
8707   ConstVal = FirstElt->getZExtValue();
8708   return true;
8709 }
8710 
8711 static unsigned getIntrinsicID(const SDNode *N) {
8712   unsigned Opcode = N->getOpcode();
8713   switch (Opcode) {
8714   default:
8715     return Intrinsic::not_intrinsic;
8716   case ISD::INTRINSIC_WO_CHAIN: {
8717     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8718     if (IID < Intrinsic::num_intrinsics)
8719       return IID;
8720     return Intrinsic::not_intrinsic;
8721   }
8722   }
8723 }
8724 
8725 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8726 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8727 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8728 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8729 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8730 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8731 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8732   EVT VT = N->getValueType(0);
8733 
8734   if (!VT.isVector())
8735     return SDValue();
8736 
8737   SDLoc DL(N);
8738 
8739   SDValue And;
8740   SDValue Shift;
8741 
8742   SDValue FirstOp = N->getOperand(0);
8743   unsigned FirstOpc = FirstOp.getOpcode();
8744   SDValue SecondOp = N->getOperand(1);
8745   unsigned SecondOpc = SecondOp.getOpcode();
8746 
8747   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8748   // a BICi in order to use an immediate instead of a register.
8749   // Is the other operand an shl or lshr? This will have been turned into:
8750   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8751   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8752       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8753     And = FirstOp;
8754     Shift = SecondOp;
8755 
8756   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8757              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8758     And = SecondOp;
8759     Shift = FirstOp;
8760   } else
8761     return SDValue();
8762 
8763   bool IsAnd = And.getOpcode() == ISD::AND;
8764   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8765 
8766   // Is the shift amount constant?
8767   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8768   if (!C2node)
8769     return SDValue();
8770 
8771   uint64_t C1;
8772   if (IsAnd) {
8773     // Is the and mask vector all constant?
8774     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8775       return SDValue();
8776   } else {
8777     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8778     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8779     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8780     assert(C1nodeImm && C1nodeShift);
8781     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8782   }
8783 
8784   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8785   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8786   // how much one can shift elements of a particular size?
8787   uint64_t C2 = C2node->getZExtValue();
8788   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8789   if (C2 > ElemSizeInBits)
8790     return SDValue();
8791 
8792   APInt C1AsAPInt(ElemSizeInBits, C1);
8793   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8794                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8795   if (C1AsAPInt != RequiredC1)
8796     return SDValue();
8797 
8798   SDValue X = And.getOperand(0);
8799   SDValue Y = Shift.getOperand(0);
8800 
8801   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8802   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8803 
8804   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8805   LLVM_DEBUG(N->dump(&DAG));
8806   LLVM_DEBUG(dbgs() << "into: \n");
8807   LLVM_DEBUG(ResultSLI->dump(&DAG));
8808 
8809   ++NumShiftInserts;
8810   return ResultSLI;
8811 }
8812 
8813 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8814                                              SelectionDAG &DAG) const {
8815   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
8816     return LowerToScalableOp(Op, DAG);
8817 
8818   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8819   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8820     return Res;
8821 
8822   EVT VT = Op.getValueType();
8823 
8824   SDValue LHS = Op.getOperand(0);
8825   BuildVectorSDNode *BVN =
8826       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8827   if (!BVN) {
8828     // OR commutes, so try swapping the operands.
8829     LHS = Op.getOperand(1);
8830     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8831   }
8832   if (!BVN)
8833     return Op;
8834 
8835   APInt DefBits(VT.getSizeInBits(), 0);
8836   APInt UndefBits(VT.getSizeInBits(), 0);
8837   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8838     SDValue NewOp;
8839 
8840     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8841                                     DefBits, &LHS)) ||
8842         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8843                                     DefBits, &LHS)))
8844       return NewOp;
8845 
8846     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8847                                     UndefBits, &LHS)) ||
8848         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8849                                     UndefBits, &LHS)))
8850       return NewOp;
8851   }
8852 
8853   // We can always fall back to a non-immediate OR.
8854   return Op;
8855 }
8856 
8857 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8858 // be truncated to fit element width.
8859 static SDValue NormalizeBuildVector(SDValue Op,
8860                                     SelectionDAG &DAG) {
8861   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8862   SDLoc dl(Op);
8863   EVT VT = Op.getValueType();
8864   EVT EltTy= VT.getVectorElementType();
8865 
8866   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8867     return Op;
8868 
8869   SmallVector<SDValue, 16> Ops;
8870   for (SDValue Lane : Op->ops()) {
8871     // For integer vectors, type legalization would have promoted the
8872     // operands already. Otherwise, if Op is a floating-point splat
8873     // (with operands cast to integers), then the only possibilities
8874     // are constants and UNDEFs.
8875     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8876       APInt LowBits(EltTy.getSizeInBits(),
8877                     CstLane->getZExtValue());
8878       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8879     } else if (Lane.getNode()->isUndef()) {
8880       Lane = DAG.getUNDEF(MVT::i32);
8881     } else {
8882       assert(Lane.getValueType() == MVT::i32 &&
8883              "Unexpected BUILD_VECTOR operand type");
8884     }
8885     Ops.push_back(Lane);
8886   }
8887   return DAG.getBuildVector(VT, dl, Ops);
8888 }
8889 
8890 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8891   EVT VT = Op.getValueType();
8892 
8893   APInt DefBits(VT.getSizeInBits(), 0);
8894   APInt UndefBits(VT.getSizeInBits(), 0);
8895   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8896   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8897     SDValue NewOp;
8898     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8899         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8900         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8901         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8902         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8903         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8904       return NewOp;
8905 
8906     DefBits = ~DefBits;
8907     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8908         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8909         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8910       return NewOp;
8911 
8912     DefBits = UndefBits;
8913     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8914         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8915         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8916         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8917         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8918         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8919       return NewOp;
8920 
8921     DefBits = ~UndefBits;
8922     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8923         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8924         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8925       return NewOp;
8926   }
8927 
8928   return SDValue();
8929 }
8930 
8931 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8932                                                  SelectionDAG &DAG) const {
8933   EVT VT = Op.getValueType();
8934 
8935   // Try to build a simple constant vector.
8936   Op = NormalizeBuildVector(Op, DAG);
8937   if (VT.isInteger()) {
8938     // Certain vector constants, used to express things like logical NOT and
8939     // arithmetic NEG, are passed through unmodified.  This allows special
8940     // patterns for these operations to match, which will lower these constants
8941     // to whatever is proven necessary.
8942     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8943     if (BVN->isConstant())
8944       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8945         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8946         APInt Val(BitSize,
8947                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8948         if (Val.isNullValue() || Val.isAllOnesValue())
8949           return Op;
8950       }
8951   }
8952 
8953   if (SDValue V = ConstantBuildVector(Op, DAG))
8954     return V;
8955 
8956   // Scan through the operands to find some interesting properties we can
8957   // exploit:
8958   //   1) If only one value is used, we can use a DUP, or
8959   //   2) if only the low element is not undef, we can just insert that, or
8960   //   3) if only one constant value is used (w/ some non-constant lanes),
8961   //      we can splat the constant value into the whole vector then fill
8962   //      in the non-constant lanes.
8963   //   4) FIXME: If different constant values are used, but we can intelligently
8964   //             select the values we'll be overwriting for the non-constant
8965   //             lanes such that we can directly materialize the vector
8966   //             some other way (MOVI, e.g.), we can be sneaky.
8967   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8968   SDLoc dl(Op);
8969   unsigned NumElts = VT.getVectorNumElements();
8970   bool isOnlyLowElement = true;
8971   bool usesOnlyOneValue = true;
8972   bool usesOnlyOneConstantValue = true;
8973   bool isConstant = true;
8974   bool AllLanesExtractElt = true;
8975   unsigned NumConstantLanes = 0;
8976   SDValue Value;
8977   SDValue ConstantValue;
8978   for (unsigned i = 0; i < NumElts; ++i) {
8979     SDValue V = Op.getOperand(i);
8980     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8981       AllLanesExtractElt = false;
8982     if (V.isUndef())
8983       continue;
8984     if (i > 0)
8985       isOnlyLowElement = false;
8986     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8987       isConstant = false;
8988 
8989     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8990       ++NumConstantLanes;
8991       if (!ConstantValue.getNode())
8992         ConstantValue = V;
8993       else if (ConstantValue != V)
8994         usesOnlyOneConstantValue = false;
8995     }
8996 
8997     if (!Value.getNode())
8998       Value = V;
8999     else if (V != Value)
9000       usesOnlyOneValue = false;
9001   }
9002 
9003   if (!Value.getNode()) {
9004     LLVM_DEBUG(
9005         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
9006     return DAG.getUNDEF(VT);
9007   }
9008 
9009   // Convert BUILD_VECTOR where all elements but the lowest are undef into
9010   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
9011   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
9012   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
9013     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
9014                          "SCALAR_TO_VECTOR node\n");
9015     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
9016   }
9017 
9018   if (AllLanesExtractElt) {
9019     SDNode *Vector = nullptr;
9020     bool Even = false;
9021     bool Odd = false;
9022     // Check whether the extract elements match the Even pattern <0,2,4,...> or
9023     // the Odd pattern <1,3,5,...>.
9024     for (unsigned i = 0; i < NumElts; ++i) {
9025       SDValue V = Op.getOperand(i);
9026       const SDNode *N = V.getNode();
9027       if (!isa<ConstantSDNode>(N->getOperand(1)))
9028         break;
9029       SDValue N0 = N->getOperand(0);
9030 
9031       // All elements are extracted from the same vector.
9032       if (!Vector) {
9033         Vector = N0.getNode();
9034         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
9035         // BUILD_VECTOR.
9036         if (VT.getVectorElementType() !=
9037             N0.getValueType().getVectorElementType())
9038           break;
9039       } else if (Vector != N0.getNode()) {
9040         Odd = false;
9041         Even = false;
9042         break;
9043       }
9044 
9045       // Extracted values are either at Even indices <0,2,4,...> or at Odd
9046       // indices <1,3,5,...>.
9047       uint64_t Val = N->getConstantOperandVal(1);
9048       if (Val == 2 * i) {
9049         Even = true;
9050         continue;
9051       }
9052       if (Val - 1 == 2 * i) {
9053         Odd = true;
9054         continue;
9055       }
9056 
9057       // Something does not match: abort.
9058       Odd = false;
9059       Even = false;
9060       break;
9061     }
9062     if (Even || Odd) {
9063       SDValue LHS =
9064           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9065                       DAG.getConstant(0, dl, MVT::i64));
9066       SDValue RHS =
9067           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9068                       DAG.getConstant(NumElts, dl, MVT::i64));
9069 
9070       if (Even && !Odd)
9071         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
9072                            RHS);
9073       if (Odd && !Even)
9074         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
9075                            RHS);
9076     }
9077   }
9078 
9079   // Use DUP for non-constant splats. For f32 constant splats, reduce to
9080   // i32 and try again.
9081   if (usesOnlyOneValue) {
9082     if (!isConstant) {
9083       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9084           Value.getValueType() != VT) {
9085         LLVM_DEBUG(
9086             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
9087         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
9088       }
9089 
9090       // This is actually a DUPLANExx operation, which keeps everything vectory.
9091 
9092       SDValue Lane = Value.getOperand(1);
9093       Value = Value.getOperand(0);
9094       if (Value.getValueSizeInBits() == 64) {
9095         LLVM_DEBUG(
9096             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
9097                       "widening it\n");
9098         Value = WidenVector(Value, DAG);
9099       }
9100 
9101       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
9102       return DAG.getNode(Opcode, dl, VT, Value, Lane);
9103     }
9104 
9105     if (VT.getVectorElementType().isFloatingPoint()) {
9106       SmallVector<SDValue, 8> Ops;
9107       EVT EltTy = VT.getVectorElementType();
9108       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
9109                EltTy == MVT::f64) && "Unsupported floating-point vector type");
9110       LLVM_DEBUG(
9111           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
9112                     "BITCASTS, and try again\n");
9113       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
9114       for (unsigned i = 0; i < NumElts; ++i)
9115         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
9116       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
9117       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
9118       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
9119                  Val.dump(););
9120       Val = LowerBUILD_VECTOR(Val, DAG);
9121       if (Val.getNode())
9122         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9123     }
9124   }
9125 
9126   // If there was only one constant value used and for more than one lane,
9127   // start by splatting that value, then replace the non-constant lanes. This
9128   // is better than the default, which will perform a separate initialization
9129   // for each lane.
9130   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
9131     // Firstly, try to materialize the splat constant.
9132     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
9133             Val = ConstantBuildVector(Vec, DAG);
9134     if (!Val) {
9135       // Otherwise, materialize the constant and splat it.
9136       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
9137       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
9138     }
9139 
9140     // Now insert the non-constant lanes.
9141     for (unsigned i = 0; i < NumElts; ++i) {
9142       SDValue V = Op.getOperand(i);
9143       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9144       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
9145         // Note that type legalization likely mucked about with the VT of the
9146         // source operand, so we may have to convert it here before inserting.
9147         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
9148     }
9149     return Val;
9150   }
9151 
9152   // This will generate a load from the constant pool.
9153   if (isConstant) {
9154     LLVM_DEBUG(
9155         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
9156                   "expansion\n");
9157     return SDValue();
9158   }
9159 
9160   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
9161   if (NumElts >= 4) {
9162     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
9163       return shuffle;
9164   }
9165 
9166   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
9167   // know the default expansion would otherwise fall back on something even
9168   // worse. For a vector with one or two non-undef values, that's
9169   // scalar_to_vector for the elements followed by a shuffle (provided the
9170   // shuffle is valid for the target) and materialization element by element
9171   // on the stack followed by a load for everything else.
9172   if (!isConstant && !usesOnlyOneValue) {
9173     LLVM_DEBUG(
9174         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
9175                   "of INSERT_VECTOR_ELT\n");
9176 
9177     SDValue Vec = DAG.getUNDEF(VT);
9178     SDValue Op0 = Op.getOperand(0);
9179     unsigned i = 0;
9180 
9181     // Use SCALAR_TO_VECTOR for lane zero to
9182     // a) Avoid a RMW dependency on the full vector register, and
9183     // b) Allow the register coalescer to fold away the copy if the
9184     //    value is already in an S or D register, and we're forced to emit an
9185     //    INSERT_SUBREG that we can't fold anywhere.
9186     //
9187     // We also allow types like i8 and i16 which are illegal scalar but legal
9188     // vector element types. After type-legalization the inserted value is
9189     // extended (i32) and it is safe to cast them to the vector type by ignoring
9190     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
9191     if (!Op0.isUndef()) {
9192       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
9193       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
9194       ++i;
9195     }
9196     LLVM_DEBUG(if (i < NumElts) dbgs()
9197                    << "Creating nodes for the other vector elements:\n";);
9198     for (; i < NumElts; ++i) {
9199       SDValue V = Op.getOperand(i);
9200       if (V.isUndef())
9201         continue;
9202       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9203       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
9204     }
9205     return Vec;
9206   }
9207 
9208   LLVM_DEBUG(
9209       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
9210                 "better alternative\n");
9211   return SDValue();
9212 }
9213 
9214 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
9215                                                    SelectionDAG &DAG) const {
9216   assert(Op.getValueType().isScalableVector() &&
9217          isTypeLegal(Op.getValueType()) &&
9218          "Expected legal scalable vector type!");
9219 
9220   if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2)
9221     return Op;
9222 
9223   return SDValue();
9224 }
9225 
9226 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9227                                                       SelectionDAG &DAG) const {
9228   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
9229 
9230   // Check for non-constant or out of range lane.
9231   EVT VT = Op.getOperand(0).getValueType();
9232   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9233   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9234     return SDValue();
9235 
9236 
9237   // Insertion/extraction are legal for V128 types.
9238   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9239       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9240       VT == MVT::v8f16 || VT == MVT::v8bf16)
9241     return Op;
9242 
9243   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9244       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9245       VT != MVT::v4bf16)
9246     return SDValue();
9247 
9248   // For V64 types, we perform insertion by expanding the value
9249   // to a V128 type and perform the insertion on that.
9250   SDLoc DL(Op);
9251   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9252   EVT WideTy = WideVec.getValueType();
9253 
9254   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
9255                              Op.getOperand(1), Op.getOperand(2));
9256   // Re-narrow the resultant vector.
9257   return NarrowVector(Node, DAG);
9258 }
9259 
9260 SDValue
9261 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9262                                                SelectionDAG &DAG) const {
9263   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
9264 
9265   // Check for non-constant or out of range lane.
9266   EVT VT = Op.getOperand(0).getValueType();
9267   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9268   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9269     return SDValue();
9270 
9271 
9272   // Insertion/extraction are legal for V128 types.
9273   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9274       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9275       VT == MVT::v8f16 || VT == MVT::v8bf16)
9276     return Op;
9277 
9278   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9279       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9280       VT != MVT::v4bf16)
9281     return SDValue();
9282 
9283   // For V64 types, we perform extraction by expanding the value
9284   // to a V128 type and perform the extraction on that.
9285   SDLoc DL(Op);
9286   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9287   EVT WideTy = WideVec.getValueType();
9288 
9289   EVT ExtrTy = WideTy.getVectorElementType();
9290   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
9291     ExtrTy = MVT::i32;
9292 
9293   // For extractions, we just return the result directly.
9294   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
9295                      Op.getOperand(1));
9296 }
9297 
9298 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
9299                                                       SelectionDAG &DAG) const {
9300   assert(Op.getValueType().isFixedLengthVector() &&
9301          "Only cases that extract a fixed length vector are supported!");
9302 
9303   EVT InVT = Op.getOperand(0).getValueType();
9304   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9305   unsigned Size = Op.getValueSizeInBits();
9306 
9307   if (InVT.isScalableVector()) {
9308     // This will be matched by custom code during ISelDAGToDAG.
9309     if (Idx == 0 && isPackedVectorType(InVT, DAG))
9310       return Op;
9311 
9312     return SDValue();
9313   }
9314 
9315   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
9316   if (Idx == 0 && InVT.getSizeInBits() <= 128)
9317     return Op;
9318 
9319   // If this is extracting the upper 64-bits of a 128-bit vector, we match
9320   // that directly.
9321   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
9322       InVT.getSizeInBits() == 128)
9323     return Op;
9324 
9325   return SDValue();
9326 }
9327 
9328 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
9329                                                      SelectionDAG &DAG) const {
9330   assert(Op.getValueType().isScalableVector() &&
9331          "Only expect to lower inserts into scalable vectors!");
9332 
9333   EVT InVT = Op.getOperand(1).getValueType();
9334   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9335 
9336   if (InVT.isScalableVector()) {
9337     SDLoc DL(Op);
9338     EVT VT = Op.getValueType();
9339 
9340     if (!isTypeLegal(VT) || !VT.isInteger())
9341       return SDValue();
9342 
9343     SDValue Vec0 = Op.getOperand(0);
9344     SDValue Vec1 = Op.getOperand(1);
9345 
9346     // Ensure the subvector is half the size of the main vector.
9347     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
9348       return SDValue();
9349 
9350     // Extend elements of smaller vector...
9351     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
9352     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
9353 
9354     if (Idx == 0) {
9355       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
9356       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
9357     } else if (Idx == InVT.getVectorMinNumElements()) {
9358       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
9359       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
9360     }
9361 
9362     return SDValue();
9363   }
9364 
9365   // This will be matched by custom code during ISelDAGToDAG.
9366   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
9367     return Op;
9368 
9369   return SDValue();
9370 }
9371 
9372 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
9373   EVT VT = Op.getValueType();
9374 
9375   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
9376     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
9377 
9378   assert(VT.isScalableVector() && "Expected a scalable vector.");
9379 
9380   bool Signed = Op.getOpcode() == ISD::SDIV;
9381   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
9382 
9383   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
9384     return LowerToPredicatedOp(Op, DAG, PredOpcode);
9385 
9386   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
9387   // operations, and truncate the result.
9388   EVT WidenedVT;
9389   if (VT == MVT::nxv16i8)
9390     WidenedVT = MVT::nxv8i16;
9391   else if (VT == MVT::nxv8i16)
9392     WidenedVT = MVT::nxv4i32;
9393   else
9394     llvm_unreachable("Unexpected Custom DIV operation");
9395 
9396   SDLoc dl(Op);
9397   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
9398   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
9399   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
9400   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
9401   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
9402   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
9403   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
9404   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
9405   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
9406 }
9407 
9408 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
9409   // Currently no fixed length shuffles that require SVE are legal.
9410   if (useSVEForFixedLengthVectorVT(VT))
9411     return false;
9412 
9413   if (VT.getVectorNumElements() == 4 &&
9414       (VT.is128BitVector() || VT.is64BitVector())) {
9415     unsigned PFIndexes[4];
9416     for (unsigned i = 0; i != 4; ++i) {
9417       if (M[i] < 0)
9418         PFIndexes[i] = 8;
9419       else
9420         PFIndexes[i] = M[i];
9421     }
9422 
9423     // Compute the index in the perfect shuffle table.
9424     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
9425                             PFIndexes[2] * 9 + PFIndexes[3];
9426     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9427     unsigned Cost = (PFEntry >> 30);
9428 
9429     if (Cost <= 4)
9430       return true;
9431   }
9432 
9433   bool DummyBool;
9434   int DummyInt;
9435   unsigned DummyUnsigned;
9436 
9437   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
9438           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
9439           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
9440           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
9441           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
9442           isZIPMask(M, VT, DummyUnsigned) ||
9443           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
9444           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
9445           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
9446           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
9447           isConcatMask(M, VT, VT.getSizeInBits() == 128));
9448 }
9449 
9450 /// getVShiftImm - Check if this is a valid build_vector for the immediate
9451 /// operand of a vector shift operation, where all the elements of the
9452 /// build_vector must have the same constant integer value.
9453 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9454   // Ignore bit_converts.
9455   while (Op.getOpcode() == ISD::BITCAST)
9456     Op = Op.getOperand(0);
9457   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9458   APInt SplatBits, SplatUndef;
9459   unsigned SplatBitSize;
9460   bool HasAnyUndefs;
9461   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9462                                     HasAnyUndefs, ElementBits) ||
9463       SplatBitSize > ElementBits)
9464     return false;
9465   Cnt = SplatBits.getSExtValue();
9466   return true;
9467 }
9468 
9469 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9470 /// operand of a vector shift left operation.  That value must be in the range:
9471 ///   0 <= Value < ElementBits for a left shift; or
9472 ///   0 <= Value <= ElementBits for a long left shift.
9473 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9474   assert(VT.isVector() && "vector shift count is not a vector type");
9475   int64_t ElementBits = VT.getScalarSizeInBits();
9476   if (!getVShiftImm(Op, ElementBits, Cnt))
9477     return false;
9478   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
9479 }
9480 
9481 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9482 /// operand of a vector shift right operation. The value must be in the range:
9483 ///   1 <= Value <= ElementBits for a right shift; or
9484 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
9485   assert(VT.isVector() && "vector shift count is not a vector type");
9486   int64_t ElementBits = VT.getScalarSizeInBits();
9487   if (!getVShiftImm(Op, ElementBits, Cnt))
9488     return false;
9489   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
9490 }
9491 
9492 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
9493                                              SelectionDAG &DAG) const {
9494   EVT VT = Op.getValueType();
9495 
9496   if (VT.getScalarType() == MVT::i1) {
9497     // Lower i1 truncate to `(x & 1) != 0`.
9498     SDLoc dl(Op);
9499     EVT OpVT = Op.getOperand(0).getValueType();
9500     SDValue Zero = DAG.getConstant(0, dl, OpVT);
9501     SDValue One = DAG.getConstant(1, dl, OpVT);
9502     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
9503     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
9504   }
9505 
9506   if (!VT.isVector() || VT.isScalableVector())
9507     return SDValue();
9508 
9509   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9510     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
9511 
9512   return SDValue();
9513 }
9514 
9515 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
9516                                                       SelectionDAG &DAG) const {
9517   EVT VT = Op.getValueType();
9518   SDLoc DL(Op);
9519   int64_t Cnt;
9520 
9521   if (!Op.getOperand(1).getValueType().isVector())
9522     return Op;
9523   unsigned EltSize = VT.getScalarSizeInBits();
9524 
9525   switch (Op.getOpcode()) {
9526   default:
9527     llvm_unreachable("unexpected shift opcode");
9528 
9529   case ISD::SHL:
9530     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
9531       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
9532 
9533     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
9534       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
9535                          DAG.getConstant(Cnt, DL, MVT::i32));
9536     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9537                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
9538                                        MVT::i32),
9539                        Op.getOperand(0), Op.getOperand(1));
9540   case ISD::SRA:
9541   case ISD::SRL:
9542     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
9543       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
9544                                                 : AArch64ISD::SRL_PRED;
9545       return LowerToPredicatedOp(Op, DAG, Opc);
9546     }
9547 
9548     // Right shift immediate
9549     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
9550       unsigned Opc =
9551           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
9552       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
9553                          DAG.getConstant(Cnt, DL, MVT::i32));
9554     }
9555 
9556     // Right shift register.  Note, there is not a shift right register
9557     // instruction, but the shift left register instruction takes a signed
9558     // value, where negative numbers specify a right shift.
9559     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
9560                                                 : Intrinsic::aarch64_neon_ushl;
9561     // negate the shift amount
9562     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
9563     SDValue NegShiftLeft =
9564         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9565                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
9566                     NegShift);
9567     return NegShiftLeft;
9568   }
9569 
9570   return SDValue();
9571 }
9572 
9573 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
9574                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
9575                                     const SDLoc &dl, SelectionDAG &DAG) {
9576   EVT SrcVT = LHS.getValueType();
9577   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9578          "function only supposed to emit natural comparisons");
9579 
9580   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9581   APInt CnstBits(VT.getSizeInBits(), 0);
9582   APInt UndefBits(VT.getSizeInBits(), 0);
9583   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9584   bool IsZero = IsCnst && (CnstBits == 0);
9585 
9586   if (SrcVT.getVectorElementType().isFloatingPoint()) {
9587     switch (CC) {
9588     default:
9589       return SDValue();
9590     case AArch64CC::NE: {
9591       SDValue Fcmeq;
9592       if (IsZero)
9593         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9594       else
9595         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9596       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9597     }
9598     case AArch64CC::EQ:
9599       if (IsZero)
9600         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9601       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9602     case AArch64CC::GE:
9603       if (IsZero)
9604         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9605       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9606     case AArch64CC::GT:
9607       if (IsZero)
9608         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9609       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9610     case AArch64CC::LS:
9611       if (IsZero)
9612         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9613       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9614     case AArch64CC::LT:
9615       if (!NoNans)
9616         return SDValue();
9617       // If we ignore NaNs then we can use to the MI implementation.
9618       LLVM_FALLTHROUGH;
9619     case AArch64CC::MI:
9620       if (IsZero)
9621         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9622       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9623     }
9624   }
9625 
9626   switch (CC) {
9627   default:
9628     return SDValue();
9629   case AArch64CC::NE: {
9630     SDValue Cmeq;
9631     if (IsZero)
9632       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9633     else
9634       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9635     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9636   }
9637   case AArch64CC::EQ:
9638     if (IsZero)
9639       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9640     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9641   case AArch64CC::GE:
9642     if (IsZero)
9643       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9644     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9645   case AArch64CC::GT:
9646     if (IsZero)
9647       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9648     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9649   case AArch64CC::LE:
9650     if (IsZero)
9651       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9652     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9653   case AArch64CC::LS:
9654     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9655   case AArch64CC::LO:
9656     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9657   case AArch64CC::LT:
9658     if (IsZero)
9659       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9660     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9661   case AArch64CC::HI:
9662     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9663   case AArch64CC::HS:
9664     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9665   }
9666 }
9667 
9668 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9669                                            SelectionDAG &DAG) const {
9670   if (Op.getValueType().isScalableVector()) {
9671     if (Op.getOperand(0).getValueType().isFloatingPoint())
9672       return Op;
9673     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9674   }
9675 
9676   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9677     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
9678 
9679   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9680   SDValue LHS = Op.getOperand(0);
9681   SDValue RHS = Op.getOperand(1);
9682   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9683   SDLoc dl(Op);
9684 
9685   if (LHS.getValueType().getVectorElementType().isInteger()) {
9686     assert(LHS.getValueType() == RHS.getValueType());
9687     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9688     SDValue Cmp =
9689         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9690     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9691   }
9692 
9693   const bool FullFP16 =
9694     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9695 
9696   // Make v4f16 (only) fcmp operations utilise vector instructions
9697   // v8f16 support will be a litle more complicated
9698   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9699     if (LHS.getValueType().getVectorNumElements() == 4) {
9700       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9701       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9702       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9703       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9704       CmpVT = MVT::v4i32;
9705     } else
9706       return SDValue();
9707   }
9708 
9709   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9710           LHS.getValueType().getVectorElementType() != MVT::f128);
9711 
9712   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9713   // clean.  Some of them require two branches to implement.
9714   AArch64CC::CondCode CC1, CC2;
9715   bool ShouldInvert;
9716   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9717 
9718   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9719   SDValue Cmp =
9720       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9721   if (!Cmp.getNode())
9722     return SDValue();
9723 
9724   if (CC2 != AArch64CC::AL) {
9725     SDValue Cmp2 =
9726         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9727     if (!Cmp2.getNode())
9728       return SDValue();
9729 
9730     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9731   }
9732 
9733   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9734 
9735   if (ShouldInvert)
9736     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9737 
9738   return Cmp;
9739 }
9740 
9741 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9742                                   SelectionDAG &DAG) {
9743   SDValue VecOp = ScalarOp.getOperand(0);
9744   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9745   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9746                      DAG.getConstant(0, DL, MVT::i64));
9747 }
9748 
9749 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9750                                               SelectionDAG &DAG) const {
9751   SDValue Src = Op.getOperand(0);
9752 
9753   // Try to lower fixed length reductions to SVE.
9754   EVT SrcVT = Src.getValueType();
9755   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
9756                       Op.getOpcode() == ISD::VECREDUCE_OR ||
9757                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
9758                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
9759                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
9760                        SrcVT.getVectorElementType() == MVT::i64);
9761   if (useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
9762     switch (Op.getOpcode()) {
9763     case ISD::VECREDUCE_ADD:
9764       return LowerFixedLengthReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
9765     case ISD::VECREDUCE_AND:
9766       return LowerFixedLengthReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
9767     case ISD::VECREDUCE_OR:
9768       return LowerFixedLengthReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
9769     case ISD::VECREDUCE_SMAX:
9770       return LowerFixedLengthReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
9771     case ISD::VECREDUCE_SMIN:
9772       return LowerFixedLengthReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
9773     case ISD::VECREDUCE_UMAX:
9774       return LowerFixedLengthReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
9775     case ISD::VECREDUCE_UMIN:
9776       return LowerFixedLengthReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
9777     case ISD::VECREDUCE_XOR:
9778       return LowerFixedLengthReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
9779     case ISD::VECREDUCE_FADD:
9780       return LowerFixedLengthReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
9781     case ISD::VECREDUCE_FMAX:
9782       return LowerFixedLengthReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
9783     case ISD::VECREDUCE_FMIN:
9784       return LowerFixedLengthReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
9785     default:
9786       llvm_unreachable("Unhandled fixed length reduction");
9787     }
9788   }
9789 
9790   // Lower NEON reductions.
9791   SDLoc dl(Op);
9792   switch (Op.getOpcode()) {
9793   case ISD::VECREDUCE_ADD:
9794     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9795   case ISD::VECREDUCE_SMAX:
9796     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9797   case ISD::VECREDUCE_SMIN:
9798     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9799   case ISD::VECREDUCE_UMAX:
9800     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9801   case ISD::VECREDUCE_UMIN:
9802     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9803   case ISD::VECREDUCE_FMAX: {
9804     return DAG.getNode(
9805         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9806         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9807         Src);
9808   }
9809   case ISD::VECREDUCE_FMIN: {
9810     return DAG.getNode(
9811         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9812         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9813         Src);
9814   }
9815   default:
9816     llvm_unreachable("Unhandled reduction");
9817   }
9818 }
9819 
9820 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9821                                                     SelectionDAG &DAG) const {
9822   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9823   if (!Subtarget.hasLSE())
9824     return SDValue();
9825 
9826   // LSE has an atomic load-add instruction, but not a load-sub.
9827   SDLoc dl(Op);
9828   MVT VT = Op.getSimpleValueType();
9829   SDValue RHS = Op.getOperand(2);
9830   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9831   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9832   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9833                        Op.getOperand(0), Op.getOperand(1), RHS,
9834                        AN->getMemOperand());
9835 }
9836 
9837 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9838                                                     SelectionDAG &DAG) const {
9839   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9840   if (!Subtarget.hasLSE())
9841     return SDValue();
9842 
9843   // LSE has an atomic load-clear instruction, but not a load-and.
9844   SDLoc dl(Op);
9845   MVT VT = Op.getSimpleValueType();
9846   SDValue RHS = Op.getOperand(2);
9847   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9848   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9849   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9850                        Op.getOperand(0), Op.getOperand(1), RHS,
9851                        AN->getMemOperand());
9852 }
9853 
9854 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9855     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9856   SDLoc dl(Op);
9857   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9858   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9859 
9860   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9861   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9862   if (Subtarget->hasCustomCallingConv())
9863     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9864 
9865   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9866                      DAG.getConstant(4, dl, MVT::i64));
9867   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9868   Chain =
9869       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9870                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9871                   DAG.getRegisterMask(Mask), Chain.getValue(1));
9872   // To match the actual intent better, we should read the output from X15 here
9873   // again (instead of potentially spilling it to the stack), but rereading Size
9874   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9875   // here.
9876 
9877   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9878                      DAG.getConstant(4, dl, MVT::i64));
9879   return Chain;
9880 }
9881 
9882 SDValue
9883 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9884                                                SelectionDAG &DAG) const {
9885   assert(Subtarget->isTargetWindows() &&
9886          "Only Windows alloca probing supported");
9887   SDLoc dl(Op);
9888   // Get the inputs.
9889   SDNode *Node = Op.getNode();
9890   SDValue Chain = Op.getOperand(0);
9891   SDValue Size = Op.getOperand(1);
9892   MaybeAlign Align =
9893       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9894   EVT VT = Node->getValueType(0);
9895 
9896   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9897           "no-stack-arg-probe")) {
9898     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9899     Chain = SP.getValue(1);
9900     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9901     if (Align)
9902       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9903                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9904     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9905     SDValue Ops[2] = {SP, Chain};
9906     return DAG.getMergeValues(Ops, dl);
9907   }
9908 
9909   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9910 
9911   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9912 
9913   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9914   Chain = SP.getValue(1);
9915   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9916   if (Align)
9917     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9918                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9919   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9920 
9921   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9922                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9923 
9924   SDValue Ops[2] = {SP, Chain};
9925   return DAG.getMergeValues(Ops, dl);
9926 }
9927 
9928 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9929                                            SelectionDAG &DAG) const {
9930   EVT VT = Op.getValueType();
9931   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9932 
9933   SDLoc DL(Op);
9934   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9935   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9936                             DL, VT);
9937 }
9938 
9939 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9940 template <unsigned NumVecs>
9941 static bool
9942 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
9943               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
9944   Info.opc = ISD::INTRINSIC_VOID;
9945   // Retrieve EC from first vector argument.
9946   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
9947   ElementCount EC = VT.getVectorElementCount();
9948 #ifndef NDEBUG
9949   // Check the assumption that all input vectors are the same type.
9950   for (unsigned I = 0; I < NumVecs; ++I)
9951     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
9952            "Invalid type.");
9953 #endif
9954   // memVT is `NumVecs * VT`.
9955   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9956                                 EC * NumVecs);
9957   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9958   Info.offset = 0;
9959   Info.align.reset();
9960   Info.flags = MachineMemOperand::MOStore;
9961   return true;
9962 }
9963 
9964 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9965 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9966 /// specified in the intrinsic calls.
9967 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9968                                                const CallInst &I,
9969                                                MachineFunction &MF,
9970                                                unsigned Intrinsic) const {
9971   auto &DL = I.getModule()->getDataLayout();
9972   switch (Intrinsic) {
9973   case Intrinsic::aarch64_sve_st2:
9974     return setInfoSVEStN<2>(*this, DL, Info, I);
9975   case Intrinsic::aarch64_sve_st3:
9976     return setInfoSVEStN<3>(*this, DL, Info, I);
9977   case Intrinsic::aarch64_sve_st4:
9978     return setInfoSVEStN<4>(*this, DL, Info, I);
9979   case Intrinsic::aarch64_neon_ld2:
9980   case Intrinsic::aarch64_neon_ld3:
9981   case Intrinsic::aarch64_neon_ld4:
9982   case Intrinsic::aarch64_neon_ld1x2:
9983   case Intrinsic::aarch64_neon_ld1x3:
9984   case Intrinsic::aarch64_neon_ld1x4:
9985   case Intrinsic::aarch64_neon_ld2lane:
9986   case Intrinsic::aarch64_neon_ld3lane:
9987   case Intrinsic::aarch64_neon_ld4lane:
9988   case Intrinsic::aarch64_neon_ld2r:
9989   case Intrinsic::aarch64_neon_ld3r:
9990   case Intrinsic::aarch64_neon_ld4r: {
9991     Info.opc = ISD::INTRINSIC_W_CHAIN;
9992     // Conservatively set memVT to the entire set of vectors loaded.
9993     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
9994     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9995     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9996     Info.offset = 0;
9997     Info.align.reset();
9998     // volatile loads with NEON intrinsics not supported
9999     Info.flags = MachineMemOperand::MOLoad;
10000     return true;
10001   }
10002   case Intrinsic::aarch64_neon_st2:
10003   case Intrinsic::aarch64_neon_st3:
10004   case Intrinsic::aarch64_neon_st4:
10005   case Intrinsic::aarch64_neon_st1x2:
10006   case Intrinsic::aarch64_neon_st1x3:
10007   case Intrinsic::aarch64_neon_st1x4:
10008   case Intrinsic::aarch64_neon_st2lane:
10009   case Intrinsic::aarch64_neon_st3lane:
10010   case Intrinsic::aarch64_neon_st4lane: {
10011     Info.opc = ISD::INTRINSIC_VOID;
10012     // Conservatively set memVT to the entire set of vectors stored.
10013     unsigned NumElts = 0;
10014     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10015       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10016       if (!ArgTy->isVectorTy())
10017         break;
10018       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
10019     }
10020     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10021     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10022     Info.offset = 0;
10023     Info.align.reset();
10024     // volatile stores with NEON intrinsics not supported
10025     Info.flags = MachineMemOperand::MOStore;
10026     return true;
10027   }
10028   case Intrinsic::aarch64_ldaxr:
10029   case Intrinsic::aarch64_ldxr: {
10030     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10031     Info.opc = ISD::INTRINSIC_W_CHAIN;
10032     Info.memVT = MVT::getVT(PtrTy->getElementType());
10033     Info.ptrVal = I.getArgOperand(0);
10034     Info.offset = 0;
10035     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10036     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10037     return true;
10038   }
10039   case Intrinsic::aarch64_stlxr:
10040   case Intrinsic::aarch64_stxr: {
10041     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10042     Info.opc = ISD::INTRINSIC_W_CHAIN;
10043     Info.memVT = MVT::getVT(PtrTy->getElementType());
10044     Info.ptrVal = I.getArgOperand(1);
10045     Info.offset = 0;
10046     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10047     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10048     return true;
10049   }
10050   case Intrinsic::aarch64_ldaxp:
10051   case Intrinsic::aarch64_ldxp:
10052     Info.opc = ISD::INTRINSIC_W_CHAIN;
10053     Info.memVT = MVT::i128;
10054     Info.ptrVal = I.getArgOperand(0);
10055     Info.offset = 0;
10056     Info.align = Align(16);
10057     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10058     return true;
10059   case Intrinsic::aarch64_stlxp:
10060   case Intrinsic::aarch64_stxp:
10061     Info.opc = ISD::INTRINSIC_W_CHAIN;
10062     Info.memVT = MVT::i128;
10063     Info.ptrVal = I.getArgOperand(2);
10064     Info.offset = 0;
10065     Info.align = Align(16);
10066     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10067     return true;
10068   case Intrinsic::aarch64_sve_ldnt1: {
10069     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10070     Info.opc = ISD::INTRINSIC_W_CHAIN;
10071     Info.memVT = MVT::getVT(I.getType());
10072     Info.ptrVal = I.getArgOperand(1);
10073     Info.offset = 0;
10074     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10075     Info.flags = MachineMemOperand::MOLoad;
10076     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
10077       Info.flags |= MachineMemOperand::MONonTemporal;
10078     return true;
10079   }
10080   case Intrinsic::aarch64_sve_stnt1: {
10081     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
10082     Info.opc = ISD::INTRINSIC_W_CHAIN;
10083     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
10084     Info.ptrVal = I.getArgOperand(2);
10085     Info.offset = 0;
10086     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10087     Info.flags = MachineMemOperand::MOStore;
10088     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
10089       Info.flags |= MachineMemOperand::MONonTemporal;
10090     return true;
10091   }
10092   default:
10093     break;
10094   }
10095 
10096   return false;
10097 }
10098 
10099 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
10100                                                   ISD::LoadExtType ExtTy,
10101                                                   EVT NewVT) const {
10102   // TODO: This may be worth removing. Check regression tests for diffs.
10103   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
10104     return false;
10105 
10106   // If we're reducing the load width in order to avoid having to use an extra
10107   // instruction to do extension then it's probably a good idea.
10108   if (ExtTy != ISD::NON_EXTLOAD)
10109     return true;
10110   // Don't reduce load width if it would prevent us from combining a shift into
10111   // the offset.
10112   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
10113   assert(Mem);
10114   const SDValue &Base = Mem->getBasePtr();
10115   if (Base.getOpcode() == ISD::ADD &&
10116       Base.getOperand(1).getOpcode() == ISD::SHL &&
10117       Base.getOperand(1).hasOneUse() &&
10118       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
10119     // The shift can be combined if it matches the size of the value being
10120     // loaded (and so reducing the width would make it not match).
10121     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
10122     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
10123     if (ShiftAmount == Log2_32(LoadBytes))
10124       return false;
10125   }
10126   // We have no reason to disallow reducing the load width, so allow it.
10127   return true;
10128 }
10129 
10130 // Truncations from 64-bit GPR to 32-bit GPR is free.
10131 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10132   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10133     return false;
10134   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10135   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10136   return NumBits1 > NumBits2;
10137 }
10138 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10139   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10140     return false;
10141   unsigned NumBits1 = VT1.getSizeInBits();
10142   unsigned NumBits2 = VT2.getSizeInBits();
10143   return NumBits1 > NumBits2;
10144 }
10145 
10146 /// Check if it is profitable to hoist instruction in then/else to if.
10147 /// Not profitable if I and it's user can form a FMA instruction
10148 /// because we prefer FMSUB/FMADD.
10149 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
10150   if (I->getOpcode() != Instruction::FMul)
10151     return true;
10152 
10153   if (!I->hasOneUse())
10154     return true;
10155 
10156   Instruction *User = I->user_back();
10157 
10158   if (User &&
10159       !(User->getOpcode() == Instruction::FSub ||
10160         User->getOpcode() == Instruction::FAdd))
10161     return true;
10162 
10163   const TargetOptions &Options = getTargetMachine().Options;
10164   const Function *F = I->getFunction();
10165   const DataLayout &DL = F->getParent()->getDataLayout();
10166   Type *Ty = User->getOperand(0)->getType();
10167 
10168   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
10169            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
10170            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
10171             Options.UnsafeFPMath));
10172 }
10173 
10174 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
10175 // 64-bit GPR.
10176 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10177   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10178     return false;
10179   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10180   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10181   return NumBits1 == 32 && NumBits2 == 64;
10182 }
10183 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10184   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10185     return false;
10186   unsigned NumBits1 = VT1.getSizeInBits();
10187   unsigned NumBits2 = VT2.getSizeInBits();
10188   return NumBits1 == 32 && NumBits2 == 64;
10189 }
10190 
10191 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10192   EVT VT1 = Val.getValueType();
10193   if (isZExtFree(VT1, VT2)) {
10194     return true;
10195   }
10196 
10197   if (Val.getOpcode() != ISD::LOAD)
10198     return false;
10199 
10200   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
10201   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
10202           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
10203           VT1.getSizeInBits() <= 32);
10204 }
10205 
10206 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
10207   if (isa<FPExtInst>(Ext))
10208     return false;
10209 
10210   // Vector types are not free.
10211   if (Ext->getType()->isVectorTy())
10212     return false;
10213 
10214   for (const Use &U : Ext->uses()) {
10215     // The extension is free if we can fold it with a left shift in an
10216     // addressing mode or an arithmetic operation: add, sub, and cmp.
10217 
10218     // Is there a shift?
10219     const Instruction *Instr = cast<Instruction>(U.getUser());
10220 
10221     // Is this a constant shift?
10222     switch (Instr->getOpcode()) {
10223     case Instruction::Shl:
10224       if (!isa<ConstantInt>(Instr->getOperand(1)))
10225         return false;
10226       break;
10227     case Instruction::GetElementPtr: {
10228       gep_type_iterator GTI = gep_type_begin(Instr);
10229       auto &DL = Ext->getModule()->getDataLayout();
10230       std::advance(GTI, U.getOperandNo()-1);
10231       Type *IdxTy = GTI.getIndexedType();
10232       // This extension will end up with a shift because of the scaling factor.
10233       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
10234       // Get the shift amount based on the scaling factor:
10235       // log2(sizeof(IdxTy)) - log2(8).
10236       uint64_t ShiftAmt =
10237         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
10238       // Is the constant foldable in the shift of the addressing mode?
10239       // I.e., shift amount is between 1 and 4 inclusive.
10240       if (ShiftAmt == 0 || ShiftAmt > 4)
10241         return false;
10242       break;
10243     }
10244     case Instruction::Trunc:
10245       // Check if this is a noop.
10246       // trunc(sext ty1 to ty2) to ty1.
10247       if (Instr->getType() == Ext->getOperand(0)->getType())
10248         continue;
10249       LLVM_FALLTHROUGH;
10250     default:
10251       return false;
10252     }
10253 
10254     // At this point we can use the bfm family, so this extension is free
10255     // for that use.
10256   }
10257   return true;
10258 }
10259 
10260 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
10261 /// or upper half of the vector elements.
10262 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
10263   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
10264     auto *FullTy = FullV->getType();
10265     auto *HalfTy = HalfV->getType();
10266     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
10267            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
10268   };
10269 
10270   auto extractHalf = [](Value *FullV, Value *HalfV) {
10271     auto *FullVT = cast<FixedVectorType>(FullV->getType());
10272     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
10273     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
10274   };
10275 
10276   ArrayRef<int> M1, M2;
10277   Value *S1Op1, *S2Op1;
10278   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
10279       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
10280     return false;
10281 
10282   // Check that the operands are half as wide as the result and we extract
10283   // half of the elements of the input vectors.
10284   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
10285       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
10286     return false;
10287 
10288   // Check the mask extracts either the lower or upper half of vector
10289   // elements.
10290   int M1Start = -1;
10291   int M2Start = -1;
10292   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
10293   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
10294       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
10295       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
10296     return false;
10297 
10298   return true;
10299 }
10300 
10301 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
10302 /// of the vector elements.
10303 static bool areExtractExts(Value *Ext1, Value *Ext2) {
10304   auto areExtDoubled = [](Instruction *Ext) {
10305     return Ext->getType()->getScalarSizeInBits() ==
10306            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
10307   };
10308 
10309   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
10310       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
10311       !areExtDoubled(cast<Instruction>(Ext1)) ||
10312       !areExtDoubled(cast<Instruction>(Ext2)))
10313     return false;
10314 
10315   return true;
10316 }
10317 
10318 /// Check if Op could be used with vmull_high_p64 intrinsic.
10319 static bool isOperandOfVmullHighP64(Value *Op) {
10320   Value *VectorOperand = nullptr;
10321   ConstantInt *ElementIndex = nullptr;
10322   return match(Op, m_ExtractElt(m_Value(VectorOperand),
10323                                 m_ConstantInt(ElementIndex))) &&
10324          ElementIndex->getValue() == 1 &&
10325          isa<FixedVectorType>(VectorOperand->getType()) &&
10326          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
10327 }
10328 
10329 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
10330 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
10331   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
10332 }
10333 
10334 /// Check if sinking \p I's operands to I's basic block is profitable, because
10335 /// the operands can be folded into a target instruction, e.g.
10336 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
10337 bool AArch64TargetLowering::shouldSinkOperands(
10338     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
10339   if (!I->getType()->isVectorTy())
10340     return false;
10341 
10342   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
10343     switch (II->getIntrinsicID()) {
10344     case Intrinsic::aarch64_neon_umull:
10345       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
10346         return false;
10347       Ops.push_back(&II->getOperandUse(0));
10348       Ops.push_back(&II->getOperandUse(1));
10349       return true;
10350 
10351     case Intrinsic::aarch64_neon_pmull64:
10352       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
10353                                      II->getArgOperand(1)))
10354         return false;
10355       Ops.push_back(&II->getArgOperandUse(0));
10356       Ops.push_back(&II->getArgOperandUse(1));
10357       return true;
10358 
10359     default:
10360       return false;
10361     }
10362   }
10363 
10364   switch (I->getOpcode()) {
10365   case Instruction::Sub:
10366   case Instruction::Add: {
10367     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
10368       return false;
10369 
10370     // If the exts' operands extract either the lower or upper elements, we
10371     // can sink them too.
10372     auto Ext1 = cast<Instruction>(I->getOperand(0));
10373     auto Ext2 = cast<Instruction>(I->getOperand(1));
10374     if (areExtractShuffleVectors(Ext1, Ext2)) {
10375       Ops.push_back(&Ext1->getOperandUse(0));
10376       Ops.push_back(&Ext2->getOperandUse(0));
10377     }
10378 
10379     Ops.push_back(&I->getOperandUse(0));
10380     Ops.push_back(&I->getOperandUse(1));
10381 
10382     return true;
10383   }
10384   default:
10385     return false;
10386   }
10387   return false;
10388 }
10389 
10390 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
10391                                           Align &RequiredAligment) const {
10392   if (!LoadedType.isSimple() ||
10393       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
10394     return false;
10395   // Cyclone supports unaligned accesses.
10396   RequiredAligment = Align(1);
10397   unsigned NumBits = LoadedType.getSizeInBits();
10398   return NumBits == 32 || NumBits == 64;
10399 }
10400 
10401 /// A helper function for determining the number of interleaved accesses we
10402 /// will generate when lowering accesses of the given type.
10403 unsigned
10404 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
10405                                                  const DataLayout &DL) const {
10406   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
10407 }
10408 
10409 MachineMemOperand::Flags
10410 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
10411   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
10412       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
10413     return MOStridedAccess;
10414   return MachineMemOperand::MONone;
10415 }
10416 
10417 bool AArch64TargetLowering::isLegalInterleavedAccessType(
10418     VectorType *VecTy, const DataLayout &DL) const {
10419 
10420   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
10421   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
10422 
10423   // Ensure the number of vector elements is greater than 1.
10424   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
10425     return false;
10426 
10427   // Ensure the element type is legal.
10428   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
10429     return false;
10430 
10431   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
10432   // 128 will be split into multiple interleaved accesses.
10433   return VecSize == 64 || VecSize % 128 == 0;
10434 }
10435 
10436 /// Lower an interleaved load into a ldN intrinsic.
10437 ///
10438 /// E.g. Lower an interleaved load (Factor = 2):
10439 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
10440 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
10441 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
10442 ///
10443 ///      Into:
10444 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
10445 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
10446 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
10447 bool AArch64TargetLowering::lowerInterleavedLoad(
10448     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
10449     ArrayRef<unsigned> Indices, unsigned Factor) const {
10450   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10451          "Invalid interleave factor");
10452   assert(!Shuffles.empty() && "Empty shufflevector input");
10453   assert(Shuffles.size() == Indices.size() &&
10454          "Unmatched number of shufflevectors and indices");
10455 
10456   const DataLayout &DL = LI->getModule()->getDataLayout();
10457 
10458   VectorType *VTy = Shuffles[0]->getType();
10459 
10460   // Skip if we do not have NEON and skip illegal vector types. We can
10461   // "legalize" wide vector types into multiple interleaved accesses as long as
10462   // the vector types are divisible by 128.
10463   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
10464     return false;
10465 
10466   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
10467 
10468   auto *FVTy = cast<FixedVectorType>(VTy);
10469 
10470   // A pointer vector can not be the return type of the ldN intrinsics. Need to
10471   // load integer vectors first and then convert to pointer vectors.
10472   Type *EltTy = FVTy->getElementType();
10473   if (EltTy->isPointerTy())
10474     FVTy =
10475         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
10476 
10477   IRBuilder<> Builder(LI);
10478 
10479   // The base address of the load.
10480   Value *BaseAddr = LI->getPointerOperand();
10481 
10482   if (NumLoads > 1) {
10483     // If we're going to generate more than one load, reset the sub-vector type
10484     // to something legal.
10485     FVTy = FixedVectorType::get(FVTy->getElementType(),
10486                                 FVTy->getNumElements() / NumLoads);
10487 
10488     // We will compute the pointer operand of each load from the original base
10489     // address using GEPs. Cast the base address to a pointer to the scalar
10490     // element type.
10491     BaseAddr = Builder.CreateBitCast(
10492         BaseAddr,
10493         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
10494   }
10495 
10496   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
10497   Type *Tys[2] = {FVTy, PtrTy};
10498   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
10499                                             Intrinsic::aarch64_neon_ld3,
10500                                             Intrinsic::aarch64_neon_ld4};
10501   Function *LdNFunc =
10502       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
10503 
10504   // Holds sub-vectors extracted from the load intrinsic return values. The
10505   // sub-vectors are associated with the shufflevector instructions they will
10506   // replace.
10507   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
10508 
10509   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
10510 
10511     // If we're generating more than one load, compute the base address of
10512     // subsequent loads as an offset from the previous.
10513     if (LoadCount > 0)
10514       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
10515                                             FVTy->getNumElements() * Factor);
10516 
10517     CallInst *LdN = Builder.CreateCall(
10518         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
10519 
10520     // Extract and store the sub-vectors returned by the load intrinsic.
10521     for (unsigned i = 0; i < Shuffles.size(); i++) {
10522       ShuffleVectorInst *SVI = Shuffles[i];
10523       unsigned Index = Indices[i];
10524 
10525       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
10526 
10527       // Convert the integer vector to pointer vector if the element is pointer.
10528       if (EltTy->isPointerTy())
10529         SubVec = Builder.CreateIntToPtr(
10530             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
10531                                          FVTy->getNumElements()));
10532       SubVecs[SVI].push_back(SubVec);
10533     }
10534   }
10535 
10536   // Replace uses of the shufflevector instructions with the sub-vectors
10537   // returned by the load intrinsic. If a shufflevector instruction is
10538   // associated with more than one sub-vector, those sub-vectors will be
10539   // concatenated into a single wide vector.
10540   for (ShuffleVectorInst *SVI : Shuffles) {
10541     auto &SubVec = SubVecs[SVI];
10542     auto *WideVec =
10543         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
10544     SVI->replaceAllUsesWith(WideVec);
10545   }
10546 
10547   return true;
10548 }
10549 
10550 /// Lower an interleaved store into a stN intrinsic.
10551 ///
10552 /// E.g. Lower an interleaved store (Factor = 3):
10553 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
10554 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
10555 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10556 ///
10557 ///      Into:
10558 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
10559 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
10560 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
10561 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10562 ///
10563 /// Note that the new shufflevectors will be removed and we'll only generate one
10564 /// st3 instruction in CodeGen.
10565 ///
10566 /// Example for a more general valid mask (Factor 3). Lower:
10567 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
10568 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
10569 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10570 ///
10571 ///      Into:
10572 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
10573 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
10574 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
10575 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10576 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
10577                                                   ShuffleVectorInst *SVI,
10578                                                   unsigned Factor) const {
10579   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10580          "Invalid interleave factor");
10581 
10582   auto *VecTy = cast<FixedVectorType>(SVI->getType());
10583   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
10584 
10585   unsigned LaneLen = VecTy->getNumElements() / Factor;
10586   Type *EltTy = VecTy->getElementType();
10587   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
10588 
10589   const DataLayout &DL = SI->getModule()->getDataLayout();
10590 
10591   // Skip if we do not have NEON and skip illegal vector types. We can
10592   // "legalize" wide vector types into multiple interleaved accesses as long as
10593   // the vector types are divisible by 128.
10594   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
10595     return false;
10596 
10597   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
10598 
10599   Value *Op0 = SVI->getOperand(0);
10600   Value *Op1 = SVI->getOperand(1);
10601   IRBuilder<> Builder(SI);
10602 
10603   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
10604   // vectors to integer vectors.
10605   if (EltTy->isPointerTy()) {
10606     Type *IntTy = DL.getIntPtrType(EltTy);
10607     unsigned NumOpElts =
10608         cast<FixedVectorType>(Op0->getType())->getNumElements();
10609 
10610     // Convert to the corresponding integer vector.
10611     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
10612     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
10613     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
10614 
10615     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
10616   }
10617 
10618   // The base address of the store.
10619   Value *BaseAddr = SI->getPointerOperand();
10620 
10621   if (NumStores > 1) {
10622     // If we're going to generate more than one store, reset the lane length
10623     // and sub-vector type to something legal.
10624     LaneLen /= NumStores;
10625     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10626 
10627     // We will compute the pointer operand of each store from the original base
10628     // address using GEPs. Cast the base address to a pointer to the scalar
10629     // element type.
10630     BaseAddr = Builder.CreateBitCast(
10631         BaseAddr,
10632         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10633   }
10634 
10635   auto Mask = SVI->getShuffleMask();
10636 
10637   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10638   Type *Tys[2] = {SubVecTy, PtrTy};
10639   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10640                                              Intrinsic::aarch64_neon_st3,
10641                                              Intrinsic::aarch64_neon_st4};
10642   Function *StNFunc =
10643       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10644 
10645   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10646 
10647     SmallVector<Value *, 5> Ops;
10648 
10649     // Split the shufflevector operands into sub vectors for the new stN call.
10650     for (unsigned i = 0; i < Factor; i++) {
10651       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10652       if (Mask[IdxI] >= 0) {
10653         Ops.push_back(Builder.CreateShuffleVector(
10654             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10655       } else {
10656         unsigned StartMask = 0;
10657         for (unsigned j = 1; j < LaneLen; j++) {
10658           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10659           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10660             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10661             break;
10662           }
10663         }
10664         // Note: Filling undef gaps with random elements is ok, since
10665         // those elements were being written anyway (with undefs).
10666         // In the case of all undefs we're defaulting to using elems from 0
10667         // Note: StartMask cannot be negative, it's checked in
10668         // isReInterleaveMask
10669         Ops.push_back(Builder.CreateShuffleVector(
10670             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10671       }
10672     }
10673 
10674     // If we generating more than one store, we compute the base address of
10675     // subsequent stores as an offset from the previous.
10676     if (StoreCount > 0)
10677       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10678                                             BaseAddr, LaneLen * Factor);
10679 
10680     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10681     Builder.CreateCall(StNFunc, Ops);
10682   }
10683   return true;
10684 }
10685 
10686 // Lower an SVE structured load intrinsic returning a tuple type to target
10687 // specific intrinsic taking the same input but returning a multi-result value
10688 // of the split tuple type.
10689 //
10690 // E.g. Lowering an LD3:
10691 //
10692 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10693 //                                                    <vscale x 4 x i1> %pred,
10694 //                                                    <vscale x 4 x i32>* %addr)
10695 //
10696 //  Output DAG:
10697 //
10698 //    t0: ch = EntryToken
10699 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10700 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10701 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10702 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10703 //
10704 // This is called pre-legalization to avoid widening/splitting issues with
10705 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10706 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10707                                                   ArrayRef<SDValue> LoadOps,
10708                                                   EVT VT, SelectionDAG &DAG,
10709                                                   const SDLoc &DL) const {
10710   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10711 
10712   unsigned N, Opcode;
10713   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10714       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10715       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10716       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10717 
10718   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10719   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
10720          "invalid tuple vector type!");
10721 
10722   EVT SplitVT =
10723       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10724                        VT.getVectorElementCount().divideCoefficientBy(N));
10725   assert(isTypeLegal(SplitVT));
10726 
10727   SmallVector<EVT, 5> VTs(N, SplitVT);
10728   VTs.push_back(MVT::Other); // Chain
10729   SDVTList NodeTys = DAG.getVTList(VTs);
10730 
10731   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10732   SmallVector<SDValue, 4> PseudoLoadOps;
10733   for (unsigned I = 0; I < N; ++I)
10734     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10735   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10736 }
10737 
10738 EVT AArch64TargetLowering::getOptimalMemOpType(
10739     const MemOp &Op, const AttributeList &FuncAttributes) const {
10740   bool CanImplicitFloat =
10741       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10742   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10743   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10744   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10745   // taken one instruction to materialize the v2i64 zero and one store (with
10746   // restrictive addressing mode). Just do i64 stores.
10747   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10748   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10749     if (Op.isAligned(AlignCheck))
10750       return true;
10751     bool Fast;
10752     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10753                                           &Fast) &&
10754            Fast;
10755   };
10756 
10757   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10758       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10759     return MVT::v2i64;
10760   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10761     return MVT::f128;
10762   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10763     return MVT::i64;
10764   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10765     return MVT::i32;
10766   return MVT::Other;
10767 }
10768 
10769 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10770     const MemOp &Op, const AttributeList &FuncAttributes) const {
10771   bool CanImplicitFloat =
10772       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10773   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10774   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10775   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10776   // taken one instruction to materialize the v2i64 zero and one store (with
10777   // restrictive addressing mode). Just do i64 stores.
10778   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10779   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10780     if (Op.isAligned(AlignCheck))
10781       return true;
10782     bool Fast;
10783     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10784                                           &Fast) &&
10785            Fast;
10786   };
10787 
10788   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10789       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10790     return LLT::vector(2, 64);
10791   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10792     return LLT::scalar(128);
10793   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10794     return LLT::scalar(64);
10795   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10796     return LLT::scalar(32);
10797   return LLT();
10798 }
10799 
10800 // 12-bit optionally shifted immediates are legal for adds.
10801 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10802   if (Immed == std::numeric_limits<int64_t>::min()) {
10803     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10804                       << ": avoid UB for INT64_MIN\n");
10805     return false;
10806   }
10807   // Same encoding for add/sub, just flip the sign.
10808   Immed = std::abs(Immed);
10809   bool IsLegal = ((Immed >> 12) == 0 ||
10810                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10811   LLVM_DEBUG(dbgs() << "Is " << Immed
10812                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10813   return IsLegal;
10814 }
10815 
10816 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10817 // immediates is the same as for an add or a sub.
10818 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10819   return isLegalAddImmediate(Immed);
10820 }
10821 
10822 /// isLegalAddressingMode - Return true if the addressing mode represented
10823 /// by AM is legal for this target, for a load/store of the specified type.
10824 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10825                                                   const AddrMode &AM, Type *Ty,
10826                                                   unsigned AS, Instruction *I) const {
10827   // AArch64 has five basic addressing modes:
10828   //  reg
10829   //  reg + 9-bit signed offset
10830   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
10831   //  reg1 + reg2
10832   //  reg + SIZE_IN_BYTES * reg
10833 
10834   // No global is ever allowed as a base.
10835   if (AM.BaseGV)
10836     return false;
10837 
10838   // No reg+reg+imm addressing.
10839   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10840     return false;
10841 
10842   // FIXME: Update this method to support scalable addressing modes.
10843   if (isa<ScalableVectorType>(Ty))
10844     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10845 
10846   // check reg + imm case:
10847   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10848   uint64_t NumBytes = 0;
10849   if (Ty->isSized()) {
10850     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10851     NumBytes = NumBits / 8;
10852     if (!isPowerOf2_64(NumBits))
10853       NumBytes = 0;
10854   }
10855 
10856   if (!AM.Scale) {
10857     int64_t Offset = AM.BaseOffs;
10858 
10859     // 9-bit signed offset
10860     if (isInt<9>(Offset))
10861       return true;
10862 
10863     // 12-bit unsigned offset
10864     unsigned shift = Log2_64(NumBytes);
10865     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10866         // Must be a multiple of NumBytes (NumBytes is a power of 2)
10867         (Offset >> shift) << shift == Offset)
10868       return true;
10869     return false;
10870   }
10871 
10872   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10873 
10874   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10875 }
10876 
10877 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10878   // Consider splitting large offset of struct or array.
10879   return true;
10880 }
10881 
10882 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10883                                                 const AddrMode &AM, Type *Ty,
10884                                                 unsigned AS) const {
10885   // Scaling factors are not free at all.
10886   // Operands                     | Rt Latency
10887   // -------------------------------------------
10888   // Rt, [Xn, Xm]                 | 4
10889   // -------------------------------------------
10890   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
10891   // Rt, [Xn, Wm, <extend> #imm]  |
10892   if (isLegalAddressingMode(DL, AM, Ty, AS))
10893     // Scale represents reg2 * scale, thus account for 1 if
10894     // it is not equal to 0 or 1.
10895     return AM.Scale != 0 && AM.Scale != 1;
10896   return -1;
10897 }
10898 
10899 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10900     const MachineFunction &MF, EVT VT) const {
10901   VT = VT.getScalarType();
10902 
10903   if (!VT.isSimple())
10904     return false;
10905 
10906   switch (VT.getSimpleVT().SimpleTy) {
10907   case MVT::f32:
10908   case MVT::f64:
10909     return true;
10910   default:
10911     break;
10912   }
10913 
10914   return false;
10915 }
10916 
10917 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10918                                                        Type *Ty) const {
10919   switch (Ty->getScalarType()->getTypeID()) {
10920   case Type::FloatTyID:
10921   case Type::DoubleTyID:
10922     return true;
10923   default:
10924     return false;
10925   }
10926 }
10927 
10928 const MCPhysReg *
10929 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10930   // LR is a callee-save register, but we must treat it as clobbered by any call
10931   // site. Hence we include LR in the scratch registers, which are in turn added
10932   // as implicit-defs for stackmaps and patchpoints.
10933   static const MCPhysReg ScratchRegs[] = {
10934     AArch64::X16, AArch64::X17, AArch64::LR, 0
10935   };
10936   return ScratchRegs;
10937 }
10938 
10939 bool
10940 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10941                                                      CombineLevel Level) const {
10942   N = N->getOperand(0).getNode();
10943   EVT VT = N->getValueType(0);
10944     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10945     // it with shift to let it be lowered to UBFX.
10946   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10947       isa<ConstantSDNode>(N->getOperand(1))) {
10948     uint64_t TruncMask = N->getConstantOperandVal(1);
10949     if (isMask_64(TruncMask) &&
10950       N->getOperand(0).getOpcode() == ISD::SRL &&
10951       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10952       return false;
10953   }
10954   return true;
10955 }
10956 
10957 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10958                                                               Type *Ty) const {
10959   assert(Ty->isIntegerTy());
10960 
10961   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10962   if (BitSize == 0)
10963     return false;
10964 
10965   int64_t Val = Imm.getSExtValue();
10966   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10967     return true;
10968 
10969   if ((int64_t)Val < 0)
10970     Val = ~Val;
10971   if (BitSize == 32)
10972     Val &= (1LL << 32) - 1;
10973 
10974   unsigned LZ = countLeadingZeros((uint64_t)Val);
10975   unsigned Shift = (63 - LZ) / 16;
10976   // MOVZ is free so return true for one or fewer MOVK.
10977   return Shift < 3;
10978 }
10979 
10980 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10981                                                     unsigned Index) const {
10982   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10983     return false;
10984 
10985   return (Index == 0 || Index == ResVT.getVectorNumElements());
10986 }
10987 
10988 /// Turn vector tests of the signbit in the form of:
10989 ///   xor (sra X, elt_size(X)-1), -1
10990 /// into:
10991 ///   cmge X, X, #0
10992 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
10993                                          const AArch64Subtarget *Subtarget) {
10994   EVT VT = N->getValueType(0);
10995   if (!Subtarget->hasNEON() || !VT.isVector())
10996     return SDValue();
10997 
10998   // There must be a shift right algebraic before the xor, and the xor must be a
10999   // 'not' operation.
11000   SDValue Shift = N->getOperand(0);
11001   SDValue Ones = N->getOperand(1);
11002   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
11003       !ISD::isBuildVectorAllOnes(Ones.getNode()))
11004     return SDValue();
11005 
11006   // The shift should be smearing the sign bit across each vector element.
11007   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
11008   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
11009   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
11010     return SDValue();
11011 
11012   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
11013 }
11014 
11015 // Generate SUBS and CSEL for integer abs.
11016 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
11017   EVT VT = N->getValueType(0);
11018 
11019   SDValue N0 = N->getOperand(0);
11020   SDValue N1 = N->getOperand(1);
11021   SDLoc DL(N);
11022 
11023   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
11024   // and change it to SUB and CSEL.
11025   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
11026       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
11027       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
11028     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
11029       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
11030         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
11031                                   N0.getOperand(0));
11032         // Generate SUBS & CSEL.
11033         SDValue Cmp =
11034             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
11035                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
11036         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
11037                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
11038                            SDValue(Cmp.getNode(), 1));
11039       }
11040   return SDValue();
11041 }
11042 
11043 // VECREDUCE_ADD( EXTEND(v16i8_type) ) to
11044 // VECREDUCE_ADD( DOTv16i8(v16i8_type) )
11045 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
11046                                           const AArch64Subtarget *ST) {
11047   SDValue Op0 = N->getOperand(0);
11048   if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32)
11049     return SDValue();
11050 
11051   if (Op0.getValueType().getVectorElementType() != MVT::i32)
11052     return SDValue();
11053 
11054   unsigned ExtOpcode = Op0.getOpcode();
11055   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
11056     return SDValue();
11057 
11058   EVT Op0VT = Op0.getOperand(0).getValueType();
11059   if (Op0VT != MVT::v16i8)
11060     return SDValue();
11061 
11062   SDLoc DL(Op0);
11063   SDValue Ones = DAG.getConstant(1, DL, Op0VT);
11064   SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
11065   auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND)
11066                          ? Intrinsic::aarch64_neon_udot
11067                          : Intrinsic::aarch64_neon_sdot;
11068   SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(),
11069                             DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros,
11070                             Ones, Op0.getOperand(0));
11071   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
11072 }
11073 
11074 // Given a ABS node, detect the following pattern:
11075 // (ABS (SUB (EXTEND a), (EXTEND b))).
11076 // Generates UABD/SABD instruction.
11077 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG,
11078                                  TargetLowering::DAGCombinerInfo &DCI,
11079                                  const AArch64Subtarget *Subtarget) {
11080   SDValue AbsOp1 = N->getOperand(0);
11081   SDValue Op0, Op1;
11082 
11083   if (AbsOp1.getOpcode() != ISD::SUB)
11084     return SDValue();
11085 
11086   Op0 = AbsOp1.getOperand(0);
11087   Op1 = AbsOp1.getOperand(1);
11088 
11089   unsigned Opc0 = Op0.getOpcode();
11090   // Check if the operands of the sub are (zero|sign)-extended.
11091   if (Opc0 != Op1.getOpcode() ||
11092       (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
11093     return SDValue();
11094 
11095   EVT VectorT1 = Op0.getOperand(0).getValueType();
11096   EVT VectorT2 = Op1.getOperand(0).getValueType();
11097   // Check if vectors are of same type and valid size.
11098   uint64_t Size = VectorT1.getFixedSizeInBits();
11099   if (VectorT1 != VectorT2 || (Size != 64 && Size != 128))
11100     return SDValue();
11101 
11102   // Check if vector element types are valid.
11103   EVT VT1 = VectorT1.getVectorElementType();
11104   if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32)
11105     return SDValue();
11106 
11107   Op0 = Op0.getOperand(0);
11108   Op1 = Op1.getOperand(0);
11109   unsigned ABDOpcode =
11110       (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD;
11111   SDValue ABD =
11112       DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
11113   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
11114 }
11115 
11116 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
11117                                  TargetLowering::DAGCombinerInfo &DCI,
11118                                  const AArch64Subtarget *Subtarget) {
11119   if (DCI.isBeforeLegalizeOps())
11120     return SDValue();
11121 
11122   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
11123     return Cmp;
11124 
11125   return performIntegerAbsCombine(N, DAG);
11126 }
11127 
11128 SDValue
11129 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11130                                      SelectionDAG &DAG,
11131                                      SmallVectorImpl<SDNode *> &Created) const {
11132   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11133   if (isIntDivCheap(N->getValueType(0), Attr))
11134     return SDValue(N,0); // Lower SDIV as SDIV
11135 
11136   // fold (sdiv X, pow2)
11137   EVT VT = N->getValueType(0);
11138   if ((VT != MVT::i32 && VT != MVT::i64) ||
11139       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11140     return SDValue();
11141 
11142   SDLoc DL(N);
11143   SDValue N0 = N->getOperand(0);
11144   unsigned Lg2 = Divisor.countTrailingZeros();
11145   SDValue Zero = DAG.getConstant(0, DL, VT);
11146   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11147 
11148   // Add (N0 < 0) ? Pow2 - 1 : 0;
11149   SDValue CCVal;
11150   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
11151   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11152   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
11153 
11154   Created.push_back(Cmp.getNode());
11155   Created.push_back(Add.getNode());
11156   Created.push_back(CSel.getNode());
11157 
11158   // Divide by pow2.
11159   SDValue SRA =
11160       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
11161 
11162   // If we're dividing by a positive value, we're done.  Otherwise, we must
11163   // negate the result.
11164   if (Divisor.isNonNegative())
11165     return SRA;
11166 
11167   Created.push_back(SRA.getNode());
11168   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11169 }
11170 
11171 static bool IsSVECntIntrinsic(SDValue S) {
11172   switch(getIntrinsicID(S.getNode())) {
11173   default:
11174     break;
11175   case Intrinsic::aarch64_sve_cntb:
11176   case Intrinsic::aarch64_sve_cnth:
11177   case Intrinsic::aarch64_sve_cntw:
11178   case Intrinsic::aarch64_sve_cntd:
11179     return true;
11180   }
11181   return false;
11182 }
11183 
11184 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
11185                                  TargetLowering::DAGCombinerInfo &DCI,
11186                                  const AArch64Subtarget *Subtarget) {
11187   if (DCI.isBeforeLegalizeOps())
11188     return SDValue();
11189 
11190   // The below optimizations require a constant RHS.
11191   if (!isa<ConstantSDNode>(N->getOperand(1)))
11192     return SDValue();
11193 
11194   SDValue N0 = N->getOperand(0);
11195   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
11196   const APInt &ConstValue = C->getAPIntValue();
11197 
11198   // Allow the scaling to be folded into the `cnt` instruction by preventing
11199   // the scaling to be obscured here. This makes it easier to pattern match.
11200   if (IsSVECntIntrinsic(N0) ||
11201      (N0->getOpcode() == ISD::TRUNCATE &&
11202       (IsSVECntIntrinsic(N0->getOperand(0)))))
11203        if (ConstValue.sge(1) && ConstValue.sle(16))
11204          return SDValue();
11205 
11206   // Multiplication of a power of two plus/minus one can be done more
11207   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
11208   // future CPUs have a cheaper MADD instruction, this may need to be
11209   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
11210   // 64-bit is 5 cycles, so this is always a win.
11211   // More aggressively, some multiplications N0 * C can be lowered to
11212   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
11213   // e.g. 6=3*2=(2+1)*2.
11214   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
11215   // which equals to (1+2)*16-(1+2).
11216   // TrailingZeroes is used to test if the mul can be lowered to
11217   // shift+add+shift.
11218   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
11219   if (TrailingZeroes) {
11220     // Conservatively do not lower to shift+add+shift if the mul might be
11221     // folded into smul or umul.
11222     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
11223                             isZeroExtended(N0.getNode(), DAG)))
11224       return SDValue();
11225     // Conservatively do not lower to shift+add+shift if the mul might be
11226     // folded into madd or msub.
11227     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
11228                            N->use_begin()->getOpcode() == ISD::SUB))
11229       return SDValue();
11230   }
11231   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
11232   // and shift+add+shift.
11233   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
11234 
11235   unsigned ShiftAmt, AddSubOpc;
11236   // Is the shifted value the LHS operand of the add/sub?
11237   bool ShiftValUseIsN0 = true;
11238   // Do we need to negate the result?
11239   bool NegateResult = false;
11240 
11241   if (ConstValue.isNonNegative()) {
11242     // (mul x, 2^N + 1) => (add (shl x, N), x)
11243     // (mul x, 2^N - 1) => (sub (shl x, N), x)
11244     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
11245     APInt SCVMinus1 = ShiftedConstValue - 1;
11246     APInt CVPlus1 = ConstValue + 1;
11247     if (SCVMinus1.isPowerOf2()) {
11248       ShiftAmt = SCVMinus1.logBase2();
11249       AddSubOpc = ISD::ADD;
11250     } else if (CVPlus1.isPowerOf2()) {
11251       ShiftAmt = CVPlus1.logBase2();
11252       AddSubOpc = ISD::SUB;
11253     } else
11254       return SDValue();
11255   } else {
11256     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11257     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11258     APInt CVNegPlus1 = -ConstValue + 1;
11259     APInt CVNegMinus1 = -ConstValue - 1;
11260     if (CVNegPlus1.isPowerOf2()) {
11261       ShiftAmt = CVNegPlus1.logBase2();
11262       AddSubOpc = ISD::SUB;
11263       ShiftValUseIsN0 = false;
11264     } else if (CVNegMinus1.isPowerOf2()) {
11265       ShiftAmt = CVNegMinus1.logBase2();
11266       AddSubOpc = ISD::ADD;
11267       NegateResult = true;
11268     } else
11269       return SDValue();
11270   }
11271 
11272   SDLoc DL(N);
11273   EVT VT = N->getValueType(0);
11274   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
11275                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
11276 
11277   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
11278   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
11279   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
11280   assert(!(NegateResult && TrailingZeroes) &&
11281          "NegateResult and TrailingZeroes cannot both be true for now.");
11282   // Negate the result.
11283   if (NegateResult)
11284     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
11285   // Shift the result.
11286   if (TrailingZeroes)
11287     return DAG.getNode(ISD::SHL, DL, VT, Res,
11288                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
11289   return Res;
11290 }
11291 
11292 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
11293                                                          SelectionDAG &DAG) {
11294   // Take advantage of vector comparisons producing 0 or -1 in each lane to
11295   // optimize away operation when it's from a constant.
11296   //
11297   // The general transformation is:
11298   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
11299   //       AND(VECTOR_CMP(x,y), constant2)
11300   //    constant2 = UNARYOP(constant)
11301 
11302   // Early exit if this isn't a vector operation, the operand of the
11303   // unary operation isn't a bitwise AND, or if the sizes of the operations
11304   // aren't the same.
11305   EVT VT = N->getValueType(0);
11306   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
11307       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
11308       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
11309     return SDValue();
11310 
11311   // Now check that the other operand of the AND is a constant. We could
11312   // make the transformation for non-constant splats as well, but it's unclear
11313   // that would be a benefit as it would not eliminate any operations, just
11314   // perform one more step in scalar code before moving to the vector unit.
11315   if (BuildVectorSDNode *BV =
11316           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
11317     // Bail out if the vector isn't a constant.
11318     if (!BV->isConstant())
11319       return SDValue();
11320 
11321     // Everything checks out. Build up the new and improved node.
11322     SDLoc DL(N);
11323     EVT IntVT = BV->getValueType(0);
11324     // Create a new constant of the appropriate type for the transformed
11325     // DAG.
11326     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
11327     // The AND node needs bitcasts to/from an integer vector type around it.
11328     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
11329     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
11330                                  N->getOperand(0)->getOperand(0), MaskConst);
11331     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
11332     return Res;
11333   }
11334 
11335   return SDValue();
11336 }
11337 
11338 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
11339                                      const AArch64Subtarget *Subtarget) {
11340   // First try to optimize away the conversion when it's conditionally from
11341   // a constant. Vectors only.
11342   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
11343     return Res;
11344 
11345   EVT VT = N->getValueType(0);
11346   if (VT != MVT::f32 && VT != MVT::f64)
11347     return SDValue();
11348 
11349   // Only optimize when the source and destination types have the same width.
11350   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
11351     return SDValue();
11352 
11353   // If the result of an integer load is only used by an integer-to-float
11354   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
11355   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
11356   SDValue N0 = N->getOperand(0);
11357   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11358       // Do not change the width of a volatile load.
11359       !cast<LoadSDNode>(N0)->isVolatile()) {
11360     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11361     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
11362                                LN0->getPointerInfo(), LN0->getAlignment(),
11363                                LN0->getMemOperand()->getFlags());
11364 
11365     // Make sure successors of the original load stay after it by updating them
11366     // to use the new Chain.
11367     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
11368 
11369     unsigned Opcode =
11370         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
11371     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
11372   }
11373 
11374   return SDValue();
11375 }
11376 
11377 /// Fold a floating-point multiply by power of two into floating-point to
11378 /// fixed-point conversion.
11379 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
11380                                      TargetLowering::DAGCombinerInfo &DCI,
11381                                      const AArch64Subtarget *Subtarget) {
11382   if (!Subtarget->hasNEON())
11383     return SDValue();
11384 
11385   if (!N->getValueType(0).isSimple())
11386     return SDValue();
11387 
11388   SDValue Op = N->getOperand(0);
11389   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11390       Op.getOpcode() != ISD::FMUL)
11391     return SDValue();
11392 
11393   SDValue ConstVec = Op->getOperand(1);
11394   if (!isa<BuildVectorSDNode>(ConstVec))
11395     return SDValue();
11396 
11397   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11398   uint32_t FloatBits = FloatTy.getSizeInBits();
11399   if (FloatBits != 32 && FloatBits != 64)
11400     return SDValue();
11401 
11402   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11403   uint32_t IntBits = IntTy.getSizeInBits();
11404   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11405     return SDValue();
11406 
11407   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
11408   if (IntBits > FloatBits)
11409     return SDValue();
11410 
11411   BitVector UndefElements;
11412   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11413   int32_t Bits = IntBits == 64 ? 64 : 32;
11414   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
11415   if (C == -1 || C == 0 || C > Bits)
11416     return SDValue();
11417 
11418   MVT ResTy;
11419   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11420   switch (NumLanes) {
11421   default:
11422     return SDValue();
11423   case 2:
11424     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11425     break;
11426   case 4:
11427     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11428     break;
11429   }
11430 
11431   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11432     return SDValue();
11433 
11434   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
11435          "Illegal vector type after legalization");
11436 
11437   SDLoc DL(N);
11438   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11439   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
11440                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
11441   SDValue FixConv =
11442       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
11443                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
11444                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
11445   // We can handle smaller integers by generating an extra trunc.
11446   if (IntBits < FloatBits)
11447     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
11448 
11449   return FixConv;
11450 }
11451 
11452 /// Fold a floating-point divide by power of two into fixed-point to
11453 /// floating-point conversion.
11454 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
11455                                   TargetLowering::DAGCombinerInfo &DCI,
11456                                   const AArch64Subtarget *Subtarget) {
11457   if (!Subtarget->hasNEON())
11458     return SDValue();
11459 
11460   SDValue Op = N->getOperand(0);
11461   unsigned Opc = Op->getOpcode();
11462   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11463       !Op.getOperand(0).getValueType().isSimple() ||
11464       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
11465     return SDValue();
11466 
11467   SDValue ConstVec = N->getOperand(1);
11468   if (!isa<BuildVectorSDNode>(ConstVec))
11469     return SDValue();
11470 
11471   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11472   int32_t IntBits = IntTy.getSizeInBits();
11473   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11474     return SDValue();
11475 
11476   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11477   int32_t FloatBits = FloatTy.getSizeInBits();
11478   if (FloatBits != 32 && FloatBits != 64)
11479     return SDValue();
11480 
11481   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
11482   if (IntBits > FloatBits)
11483     return SDValue();
11484 
11485   BitVector UndefElements;
11486   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11487   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
11488   if (C == -1 || C == 0 || C > FloatBits)
11489     return SDValue();
11490 
11491   MVT ResTy;
11492   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11493   switch (NumLanes) {
11494   default:
11495     return SDValue();
11496   case 2:
11497     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11498     break;
11499   case 4:
11500     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11501     break;
11502   }
11503 
11504   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11505     return SDValue();
11506 
11507   SDLoc DL(N);
11508   SDValue ConvInput = Op.getOperand(0);
11509   bool IsSigned = Opc == ISD::SINT_TO_FP;
11510   if (IntBits < FloatBits)
11511     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
11512                             ResTy, ConvInput);
11513 
11514   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
11515                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
11516   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
11517                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
11518                      DAG.getConstant(C, DL, MVT::i32));
11519 }
11520 
11521 /// An EXTR instruction is made up of two shifts, ORed together. This helper
11522 /// searches for and classifies those shifts.
11523 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
11524                          bool &FromHi) {
11525   if (N.getOpcode() == ISD::SHL)
11526     FromHi = false;
11527   else if (N.getOpcode() == ISD::SRL)
11528     FromHi = true;
11529   else
11530     return false;
11531 
11532   if (!isa<ConstantSDNode>(N.getOperand(1)))
11533     return false;
11534 
11535   ShiftAmount = N->getConstantOperandVal(1);
11536   Src = N->getOperand(0);
11537   return true;
11538 }
11539 
11540 /// EXTR instruction extracts a contiguous chunk of bits from two existing
11541 /// registers viewed as a high/low pair. This function looks for the pattern:
11542 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
11543 /// with an EXTR. Can't quite be done in TableGen because the two immediates
11544 /// aren't independent.
11545 static SDValue tryCombineToEXTR(SDNode *N,
11546                                 TargetLowering::DAGCombinerInfo &DCI) {
11547   SelectionDAG &DAG = DCI.DAG;
11548   SDLoc DL(N);
11549   EVT VT = N->getValueType(0);
11550 
11551   assert(N->getOpcode() == ISD::OR && "Unexpected root");
11552 
11553   if (VT != MVT::i32 && VT != MVT::i64)
11554     return SDValue();
11555 
11556   SDValue LHS;
11557   uint32_t ShiftLHS = 0;
11558   bool LHSFromHi = false;
11559   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
11560     return SDValue();
11561 
11562   SDValue RHS;
11563   uint32_t ShiftRHS = 0;
11564   bool RHSFromHi = false;
11565   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
11566     return SDValue();
11567 
11568   // If they're both trying to come from the high part of the register, they're
11569   // not really an EXTR.
11570   if (LHSFromHi == RHSFromHi)
11571     return SDValue();
11572 
11573   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
11574     return SDValue();
11575 
11576   if (LHSFromHi) {
11577     std::swap(LHS, RHS);
11578     std::swap(ShiftLHS, ShiftRHS);
11579   }
11580 
11581   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
11582                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
11583 }
11584 
11585 static SDValue tryCombineToBSL(SDNode *N,
11586                                 TargetLowering::DAGCombinerInfo &DCI) {
11587   EVT VT = N->getValueType(0);
11588   SelectionDAG &DAG = DCI.DAG;
11589   SDLoc DL(N);
11590 
11591   if (!VT.isVector())
11592     return SDValue();
11593 
11594   SDValue N0 = N->getOperand(0);
11595   if (N0.getOpcode() != ISD::AND)
11596     return SDValue();
11597 
11598   SDValue N1 = N->getOperand(1);
11599   if (N1.getOpcode() != ISD::AND)
11600     return SDValue();
11601 
11602   // We only have to look for constant vectors here since the general, variable
11603   // case can be handled in TableGen.
11604   unsigned Bits = VT.getScalarSizeInBits();
11605   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
11606   for (int i = 1; i >= 0; --i)
11607     for (int j = 1; j >= 0; --j) {
11608       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
11609       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
11610       if (!BVN0 || !BVN1)
11611         continue;
11612 
11613       bool FoundMatch = true;
11614       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
11615         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
11616         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
11617         if (!CN0 || !CN1 ||
11618             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
11619           FoundMatch = false;
11620           break;
11621         }
11622       }
11623 
11624       if (FoundMatch)
11625         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
11626                            N0->getOperand(1 - i), N1->getOperand(1 - j));
11627     }
11628 
11629   return SDValue();
11630 }
11631 
11632 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11633                                 const AArch64Subtarget *Subtarget) {
11634   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
11635   SelectionDAG &DAG = DCI.DAG;
11636   EVT VT = N->getValueType(0);
11637 
11638   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11639     return SDValue();
11640 
11641   if (SDValue Res = tryCombineToEXTR(N, DCI))
11642     return Res;
11643 
11644   if (SDValue Res = tryCombineToBSL(N, DCI))
11645     return Res;
11646 
11647   return SDValue();
11648 }
11649 
11650 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
11651   if (!MemVT.getVectorElementType().isSimple())
11652     return false;
11653 
11654   uint64_t MaskForTy = 0ull;
11655   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
11656   case MVT::i8:
11657     MaskForTy = 0xffull;
11658     break;
11659   case MVT::i16:
11660     MaskForTy = 0xffffull;
11661     break;
11662   case MVT::i32:
11663     MaskForTy = 0xffffffffull;
11664     break;
11665   default:
11666     return false;
11667     break;
11668   }
11669 
11670   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
11671     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
11672       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
11673 
11674   return false;
11675 }
11676 
11677 static SDValue performSVEAndCombine(SDNode *N,
11678                                     TargetLowering::DAGCombinerInfo &DCI) {
11679   if (DCI.isBeforeLegalizeOps())
11680     return SDValue();
11681 
11682   SelectionDAG &DAG = DCI.DAG;
11683   SDValue Src = N->getOperand(0);
11684   unsigned Opc = Src->getOpcode();
11685 
11686   // Zero/any extend of an unsigned unpack
11687   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
11688     SDValue UnpkOp = Src->getOperand(0);
11689     SDValue Dup = N->getOperand(1);
11690 
11691     if (Dup.getOpcode() != AArch64ISD::DUP)
11692       return SDValue();
11693 
11694     SDLoc DL(N);
11695     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11696     uint64_t ExtVal = C->getZExtValue();
11697 
11698     // If the mask is fully covered by the unpack, we don't need to push
11699     // a new AND onto the operand
11700     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11701     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11702         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11703         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11704       return Src;
11705 
11706     // Truncate to prevent a DUP with an over wide constant
11707     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11708 
11709     // Otherwise, make sure we propagate the AND to the operand
11710     // of the unpack
11711     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11712                       UnpkOp->getValueType(0),
11713                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11714 
11715     SDValue And = DAG.getNode(ISD::AND, DL,
11716                               UnpkOp->getValueType(0), UnpkOp, Dup);
11717 
11718     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11719   }
11720 
11721   SDValue Mask = N->getOperand(1);
11722 
11723   if (!Src.hasOneUse())
11724     return SDValue();
11725 
11726   EVT MemVT;
11727 
11728   // SVE load instructions perform an implicit zero-extend, which makes them
11729   // perfect candidates for combining.
11730   switch (Opc) {
11731   case AArch64ISD::LD1_MERGE_ZERO:
11732   case AArch64ISD::LDNF1_MERGE_ZERO:
11733   case AArch64ISD::LDFF1_MERGE_ZERO:
11734     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11735     break;
11736   case AArch64ISD::GLD1_MERGE_ZERO:
11737   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11738   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11739   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11740   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11741   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11742   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11743   case AArch64ISD::GLDFF1_MERGE_ZERO:
11744   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11745   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11746   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11747   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11748   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11749   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11750   case AArch64ISD::GLDNT1_MERGE_ZERO:
11751     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11752     break;
11753   default:
11754     return SDValue();
11755   }
11756 
11757   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11758     return Src;
11759 
11760   return SDValue();
11761 }
11762 
11763 static SDValue performANDCombine(SDNode *N,
11764                                  TargetLowering::DAGCombinerInfo &DCI) {
11765   SelectionDAG &DAG = DCI.DAG;
11766   SDValue LHS = N->getOperand(0);
11767   EVT VT = N->getValueType(0);
11768   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11769     return SDValue();
11770 
11771   if (VT.isScalableVector())
11772     return performSVEAndCombine(N, DCI);
11773 
11774   // The combining code below works only for NEON vectors. In particular, it
11775   // does not work for SVE when dealing with vectors wider than 128 bits.
11776   if (!(VT.is64BitVector() || VT.is128BitVector()))
11777     return SDValue();
11778 
11779   BuildVectorSDNode *BVN =
11780       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11781   if (!BVN)
11782     return SDValue();
11783 
11784   // AND does not accept an immediate, so check if we can use a BIC immediate
11785   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11786   // pattern in isel, because some immediates may be lowered to the preferred
11787   // (and x, (movi imm)) form, even though an mvni representation also exists.
11788   APInt DefBits(VT.getSizeInBits(), 0);
11789   APInt UndefBits(VT.getSizeInBits(), 0);
11790   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11791     SDValue NewOp;
11792 
11793     DefBits = ~DefBits;
11794     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11795                                     DefBits, &LHS)) ||
11796         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11797                                     DefBits, &LHS)))
11798       return NewOp;
11799 
11800     UndefBits = ~UndefBits;
11801     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11802                                     UndefBits, &LHS)) ||
11803         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11804                                     UndefBits, &LHS)))
11805       return NewOp;
11806   }
11807 
11808   return SDValue();
11809 }
11810 
11811 static SDValue performSRLCombine(SDNode *N,
11812                                  TargetLowering::DAGCombinerInfo &DCI) {
11813   SelectionDAG &DAG = DCI.DAG;
11814   EVT VT = N->getValueType(0);
11815   if (VT != MVT::i32 && VT != MVT::i64)
11816     return SDValue();
11817 
11818   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11819   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11820   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11821   SDValue N0 = N->getOperand(0);
11822   if (N0.getOpcode() == ISD::BSWAP) {
11823     SDLoc DL(N);
11824     SDValue N1 = N->getOperand(1);
11825     SDValue N00 = N0.getOperand(0);
11826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11827       uint64_t ShiftAmt = C->getZExtValue();
11828       if (VT == MVT::i32 && ShiftAmt == 16 &&
11829           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11830         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11831       if (VT == MVT::i64 && ShiftAmt == 32 &&
11832           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11833         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11834     }
11835   }
11836   return SDValue();
11837 }
11838 
11839 // Attempt to form urhadd(OpA, OpB) from
11840 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
11841 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
11842 // The original form of the first expression is
11843 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
11844 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
11845 // Before this function is called the srl will have been lowered to
11846 // AArch64ISD::VLSHR.
11847 // This pass can also recognize signed variants of the patterns that use sign
11848 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
11849 // shadd(OpA, OpB) from them.
11850 static SDValue
11851 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11852                              SelectionDAG &DAG) {
11853   EVT VT = N->getValueType(0);
11854 
11855   // Since we are looking for a right shift by a constant value of 1 and we are
11856   // operating on types at least 16 bits in length (sign/zero extended OpA and
11857   // OpB, which are at least 8 bits), it follows that the truncate will always
11858   // discard the shifted-in bit and therefore the right shift will be logical
11859   // regardless of the signedness of OpA and OpB.
11860   SDValue Shift = N->getOperand(0);
11861   if (Shift.getOpcode() != AArch64ISD::VLSHR)
11862     return SDValue();
11863 
11864   // Is the right shift using an immediate value of 1?
11865   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
11866   if (ShiftAmount != 1)
11867     return SDValue();
11868 
11869   SDValue ExtendOpA, ExtendOpB;
11870   SDValue ShiftOp0 = Shift.getOperand(0);
11871   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
11872   if (ShiftOp0Opc == ISD::SUB) {
11873 
11874     SDValue Xor = ShiftOp0.getOperand(1);
11875     if (Xor.getOpcode() != ISD::XOR)
11876       return SDValue();
11877 
11878     // Is the XOR using a constant amount of all ones in the right hand side?
11879     uint64_t C;
11880     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
11881       return SDValue();
11882 
11883     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
11884     APInt CAsAPInt(ElemSizeInBits, C);
11885     if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
11886       return SDValue();
11887 
11888     ExtendOpA = Xor.getOperand(0);
11889     ExtendOpB = ShiftOp0.getOperand(0);
11890   } else if (ShiftOp0Opc == ISD::ADD) {
11891     ExtendOpA = ShiftOp0.getOperand(0);
11892     ExtendOpB = ShiftOp0.getOperand(1);
11893   } else
11894     return SDValue();
11895 
11896   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
11897   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
11898   if (!(ExtendOpAOpc == ExtendOpBOpc &&
11899         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
11900     return SDValue();
11901 
11902   // Is the result of the right shift being truncated to the same value type as
11903   // the original operands, OpA and OpB?
11904   SDValue OpA = ExtendOpA.getOperand(0);
11905   SDValue OpB = ExtendOpB.getOperand(0);
11906   EVT OpAVT = OpA.getValueType();
11907   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
11908   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
11909     return SDValue();
11910 
11911   SDLoc DL(N);
11912   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
11913   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
11914   unsigned HADDOpc = IsSignExtend
11915                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
11916                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
11917   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
11918 
11919   return ResultHADD;
11920 }
11921 
11922 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
11923   switch (Opcode) {
11924   case ISD::FADD:
11925     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
11926   case ISD::ADD:
11927     return VT == MVT::i64;
11928   default:
11929     return false;
11930   }
11931 }
11932 
11933 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
11934   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11935   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
11936 
11937   EVT VT = N->getValueType(0);
11938   const bool FullFP16 =
11939       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
11940 
11941   // Rewrite for pairwise fadd pattern
11942   //   (f32 (extract_vector_elt
11943   //           (fadd (vXf32 Other)
11944   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
11945   // ->
11946   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
11947   //              (extract_vector_elt (vXf32 Other) 1))
11948   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
11949       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
11950     SDLoc DL(N0);
11951     SDValue N00 = N0->getOperand(0);
11952     SDValue N01 = N0->getOperand(1);
11953 
11954     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
11955     SDValue Other = N00;
11956 
11957     // And handle the commutative case.
11958     if (!Shuffle) {
11959       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
11960       Other = N01;
11961     }
11962 
11963     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
11964         Other == Shuffle->getOperand(0)) {
11965       return DAG.getNode(N0->getOpcode(), DL, VT,
11966                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
11967                                      DAG.getConstant(0, DL, MVT::i64)),
11968                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
11969                                      DAG.getConstant(1, DL, MVT::i64)));
11970     }
11971   }
11972 
11973   return SDValue();
11974 }
11975 
11976 static SDValue performConcatVectorsCombine(SDNode *N,
11977                                            TargetLowering::DAGCombinerInfo &DCI,
11978                                            SelectionDAG &DAG) {
11979   SDLoc dl(N);
11980   EVT VT = N->getValueType(0);
11981   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11982   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11983 
11984   // Optimize concat_vectors of truncated vectors, where the intermediate
11985   // type is illegal, to avoid said illegality,  e.g.,
11986   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11987   //                          (v2i16 (truncate (v2i64)))))
11988   // ->
11989   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11990   //                                    (v4i32 (bitcast (v2i64))),
11991   //                                    <0, 2, 4, 6>)))
11992   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
11993   // on both input and result type, so we might generate worse code.
11994   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
11995   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
11996       N1Opc == ISD::TRUNCATE) {
11997     SDValue N00 = N0->getOperand(0);
11998     SDValue N10 = N1->getOperand(0);
11999     EVT N00VT = N00.getValueType();
12000 
12001     if (N00VT == N10.getValueType() &&
12002         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
12003         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
12004       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
12005       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
12006       for (size_t i = 0; i < Mask.size(); ++i)
12007         Mask[i] = i * 2;
12008       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12009                          DAG.getVectorShuffle(
12010                              MidVT, dl,
12011                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
12012                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
12013     }
12014   }
12015 
12016   // Wait 'til after everything is legalized to try this. That way we have
12017   // legal vector types and such.
12018   if (DCI.isBeforeLegalizeOps())
12019     return SDValue();
12020 
12021   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
12022   // subvectors from the same original vectors. Combine these into a single
12023   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
12024   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
12025   //                                        extract_subvector (v16i8 OpB,
12026   //                                        <0>))),
12027   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
12028   //                                        extract_subvector (v16i8 OpB,
12029   //                                        <8>)))))
12030   // ->
12031   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
12032   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
12033       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
12034        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
12035     SDValue N00 = N0->getOperand(0);
12036     SDValue N01 = N0->getOperand(1);
12037     SDValue N10 = N1->getOperand(0);
12038     SDValue N11 = N1->getOperand(1);
12039 
12040     EVT N00VT = N00.getValueType();
12041     EVT N10VT = N10.getValueType();
12042 
12043     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12044         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12045         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12046         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
12047       SDValue N00Source = N00->getOperand(0);
12048       SDValue N01Source = N01->getOperand(0);
12049       SDValue N10Source = N10->getOperand(0);
12050       SDValue N11Source = N11->getOperand(0);
12051 
12052       if (N00Source == N10Source && N01Source == N11Source &&
12053           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
12054         assert(N0.getValueType() == N1.getValueType());
12055 
12056         uint64_t N00Index = N00.getConstantOperandVal(1);
12057         uint64_t N01Index = N01.getConstantOperandVal(1);
12058         uint64_t N10Index = N10.getConstantOperandVal(1);
12059         uint64_t N11Index = N11.getConstantOperandVal(1);
12060 
12061         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
12062             N10Index == N00VT.getVectorNumElements())
12063           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
12064       }
12065     }
12066   }
12067 
12068   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
12069   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
12070   // canonicalise to that.
12071   if (N0 == N1 && VT.getVectorNumElements() == 2) {
12072     assert(VT.getScalarSizeInBits() == 64);
12073     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
12074                        DAG.getConstant(0, dl, MVT::i64));
12075   }
12076 
12077   // Canonicalise concat_vectors so that the right-hand vector has as few
12078   // bit-casts as possible before its real operation. The primary matching
12079   // destination for these operations will be the narrowing "2" instructions,
12080   // which depend on the operation being performed on this right-hand vector.
12081   // For example,
12082   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
12083   // becomes
12084   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
12085 
12086   if (N1Opc != ISD::BITCAST)
12087     return SDValue();
12088   SDValue RHS = N1->getOperand(0);
12089   MVT RHSTy = RHS.getValueType().getSimpleVT();
12090   // If the RHS is not a vector, this is not the pattern we're looking for.
12091   if (!RHSTy.isVector())
12092     return SDValue();
12093 
12094   LLVM_DEBUG(
12095       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
12096 
12097   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
12098                                   RHSTy.getVectorNumElements() * 2);
12099   return DAG.getNode(ISD::BITCAST, dl, VT,
12100                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
12101                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
12102                                  RHS));
12103 }
12104 
12105 static SDValue tryCombineFixedPointConvert(SDNode *N,
12106                                            TargetLowering::DAGCombinerInfo &DCI,
12107                                            SelectionDAG &DAG) {
12108   // Wait until after everything is legalized to try this. That way we have
12109   // legal vector types and such.
12110   if (DCI.isBeforeLegalizeOps())
12111     return SDValue();
12112   // Transform a scalar conversion of a value from a lane extract into a
12113   // lane extract of a vector conversion. E.g., from foo1 to foo2:
12114   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
12115   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
12116   //
12117   // The second form interacts better with instruction selection and the
12118   // register allocator to avoid cross-class register copies that aren't
12119   // coalescable due to a lane reference.
12120 
12121   // Check the operand and see if it originates from a lane extract.
12122   SDValue Op1 = N->getOperand(1);
12123   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12124     // Yep, no additional predication needed. Perform the transform.
12125     SDValue IID = N->getOperand(0);
12126     SDValue Shift = N->getOperand(2);
12127     SDValue Vec = Op1.getOperand(0);
12128     SDValue Lane = Op1.getOperand(1);
12129     EVT ResTy = N->getValueType(0);
12130     EVT VecResTy;
12131     SDLoc DL(N);
12132 
12133     // The vector width should be 128 bits by the time we get here, even
12134     // if it started as 64 bits (the extract_vector handling will have
12135     // done so).
12136     assert(Vec.getValueSizeInBits() == 128 &&
12137            "unexpected vector size on extract_vector_elt!");
12138     if (Vec.getValueType() == MVT::v4i32)
12139       VecResTy = MVT::v4f32;
12140     else if (Vec.getValueType() == MVT::v2i64)
12141       VecResTy = MVT::v2f64;
12142     else
12143       llvm_unreachable("unexpected vector type!");
12144 
12145     SDValue Convert =
12146         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
12147     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
12148   }
12149   return SDValue();
12150 }
12151 
12152 // AArch64 high-vector "long" operations are formed by performing the non-high
12153 // version on an extract_subvector of each operand which gets the high half:
12154 //
12155 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
12156 //
12157 // However, there are cases which don't have an extract_high explicitly, but
12158 // have another operation that can be made compatible with one for free. For
12159 // example:
12160 //
12161 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
12162 //
12163 // This routine does the actual conversion of such DUPs, once outer routines
12164 // have determined that everything else is in order.
12165 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
12166 // similarly here.
12167 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
12168   switch (N.getOpcode()) {
12169   case AArch64ISD::DUP:
12170   case AArch64ISD::DUPLANE8:
12171   case AArch64ISD::DUPLANE16:
12172   case AArch64ISD::DUPLANE32:
12173   case AArch64ISD::DUPLANE64:
12174   case AArch64ISD::MOVI:
12175   case AArch64ISD::MOVIshift:
12176   case AArch64ISD::MOVIedit:
12177   case AArch64ISD::MOVImsl:
12178   case AArch64ISD::MVNIshift:
12179   case AArch64ISD::MVNImsl:
12180     break;
12181   default:
12182     // FMOV could be supported, but isn't very useful, as it would only occur
12183     // if you passed a bitcast' floating point immediate to an eligible long
12184     // integer op (addl, smull, ...).
12185     return SDValue();
12186   }
12187 
12188   MVT NarrowTy = N.getSimpleValueType();
12189   if (!NarrowTy.is64BitVector())
12190     return SDValue();
12191 
12192   MVT ElementTy = NarrowTy.getVectorElementType();
12193   unsigned NumElems = NarrowTy.getVectorNumElements();
12194   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
12195 
12196   SDLoc dl(N);
12197   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
12198                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
12199                      DAG.getConstant(NumElems, dl, MVT::i64));
12200 }
12201 
12202 static bool isEssentiallyExtractHighSubvector(SDValue N) {
12203   if (N.getOpcode() == ISD::BITCAST)
12204     N = N.getOperand(0);
12205   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12206     return false;
12207   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
12208          N.getOperand(0).getValueType().getVectorNumElements() / 2;
12209 }
12210 
12211 /// Helper structure to keep track of ISD::SET_CC operands.
12212 struct GenericSetCCInfo {
12213   const SDValue *Opnd0;
12214   const SDValue *Opnd1;
12215   ISD::CondCode CC;
12216 };
12217 
12218 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
12219 struct AArch64SetCCInfo {
12220   const SDValue *Cmp;
12221   AArch64CC::CondCode CC;
12222 };
12223 
12224 /// Helper structure to keep track of SetCC information.
12225 union SetCCInfo {
12226   GenericSetCCInfo Generic;
12227   AArch64SetCCInfo AArch64;
12228 };
12229 
12230 /// Helper structure to be able to read SetCC information.  If set to
12231 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
12232 /// GenericSetCCInfo.
12233 struct SetCCInfoAndKind {
12234   SetCCInfo Info;
12235   bool IsAArch64;
12236 };
12237 
12238 /// Check whether or not \p Op is a SET_CC operation, either a generic or
12239 /// an
12240 /// AArch64 lowered one.
12241 /// \p SetCCInfo is filled accordingly.
12242 /// \post SetCCInfo is meanginfull only when this function returns true.
12243 /// \return True when Op is a kind of SET_CC operation.
12244 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
12245   // If this is a setcc, this is straight forward.
12246   if (Op.getOpcode() == ISD::SETCC) {
12247     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
12248     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
12249     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12250     SetCCInfo.IsAArch64 = false;
12251     return true;
12252   }
12253   // Otherwise, check if this is a matching csel instruction.
12254   // In other words:
12255   // - csel 1, 0, cc
12256   // - csel 0, 1, !cc
12257   if (Op.getOpcode() != AArch64ISD::CSEL)
12258     return false;
12259   // Set the information about the operands.
12260   // TODO: we want the operands of the Cmp not the csel
12261   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
12262   SetCCInfo.IsAArch64 = true;
12263   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
12264       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12265 
12266   // Check that the operands matches the constraints:
12267   // (1) Both operands must be constants.
12268   // (2) One must be 1 and the other must be 0.
12269   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
12270   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12271 
12272   // Check (1).
12273   if (!TValue || !FValue)
12274     return false;
12275 
12276   // Check (2).
12277   if (!TValue->isOne()) {
12278     // Update the comparison when we are interested in !cc.
12279     std::swap(TValue, FValue);
12280     SetCCInfo.Info.AArch64.CC =
12281         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
12282   }
12283   return TValue->isOne() && FValue->isNullValue();
12284 }
12285 
12286 // Returns true if Op is setcc or zext of setcc.
12287 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
12288   if (isSetCC(Op, Info))
12289     return true;
12290   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
12291     isSetCC(Op->getOperand(0), Info));
12292 }
12293 
12294 // The folding we want to perform is:
12295 // (add x, [zext] (setcc cc ...) )
12296 //   -->
12297 // (csel x, (add x, 1), !cc ...)
12298 //
12299 // The latter will get matched to a CSINC instruction.
12300 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
12301   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
12302   SDValue LHS = Op->getOperand(0);
12303   SDValue RHS = Op->getOperand(1);
12304   SetCCInfoAndKind InfoAndKind;
12305 
12306   // If neither operand is a SET_CC, give up.
12307   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
12308     std::swap(LHS, RHS);
12309     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
12310       return SDValue();
12311   }
12312 
12313   // FIXME: This could be generatized to work for FP comparisons.
12314   EVT CmpVT = InfoAndKind.IsAArch64
12315                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
12316                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
12317   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
12318     return SDValue();
12319 
12320   SDValue CCVal;
12321   SDValue Cmp;
12322   SDLoc dl(Op);
12323   if (InfoAndKind.IsAArch64) {
12324     CCVal = DAG.getConstant(
12325         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
12326         MVT::i32);
12327     Cmp = *InfoAndKind.Info.AArch64.Cmp;
12328   } else
12329     Cmp = getAArch64Cmp(
12330         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
12331         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
12332         dl);
12333 
12334   EVT VT = Op->getValueType(0);
12335   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
12336   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
12337 }
12338 
12339 // The basic add/sub long vector instructions have variants with "2" on the end
12340 // which act on the high-half of their inputs. They are normally matched by
12341 // patterns like:
12342 //
12343 // (add (zeroext (extract_high LHS)),
12344 //      (zeroext (extract_high RHS)))
12345 // -> uaddl2 vD, vN, vM
12346 //
12347 // However, if one of the extracts is something like a duplicate, this
12348 // instruction can still be used profitably. This function puts the DAG into a
12349 // more appropriate form for those patterns to trigger.
12350 static SDValue performAddSubLongCombine(SDNode *N,
12351                                         TargetLowering::DAGCombinerInfo &DCI,
12352                                         SelectionDAG &DAG) {
12353   if (DCI.isBeforeLegalizeOps())
12354     return SDValue();
12355 
12356   MVT VT = N->getSimpleValueType(0);
12357   if (!VT.is128BitVector()) {
12358     if (N->getOpcode() == ISD::ADD)
12359       return performSetccAddFolding(N, DAG);
12360     return SDValue();
12361   }
12362 
12363   // Make sure both branches are extended in the same way.
12364   SDValue LHS = N->getOperand(0);
12365   SDValue RHS = N->getOperand(1);
12366   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
12367        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
12368       LHS.getOpcode() != RHS.getOpcode())
12369     return SDValue();
12370 
12371   unsigned ExtType = LHS.getOpcode();
12372 
12373   // It's not worth doing if at least one of the inputs isn't already an
12374   // extract, but we don't know which it'll be so we have to try both.
12375   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
12376     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
12377     if (!RHS.getNode())
12378       return SDValue();
12379 
12380     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
12381   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
12382     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
12383     if (!LHS.getNode())
12384       return SDValue();
12385 
12386     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
12387   }
12388 
12389   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
12390 }
12391 
12392 // Massage DAGs which we can use the high-half "long" operations on into
12393 // something isel will recognize better. E.g.
12394 //
12395 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
12396 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
12397 //                     (extract_high (v2i64 (dup128 scalar)))))
12398 //
12399 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
12400                                        TargetLowering::DAGCombinerInfo &DCI,
12401                                        SelectionDAG &DAG) {
12402   if (DCI.isBeforeLegalizeOps())
12403     return SDValue();
12404 
12405   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
12406   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
12407   assert(LHS.getValueType().is64BitVector() &&
12408          RHS.getValueType().is64BitVector() &&
12409          "unexpected shape for long operation");
12410 
12411   // Either node could be a DUP, but it's not worth doing both of them (you'd
12412   // just as well use the non-high version) so look for a corresponding extract
12413   // operation on the other "wing".
12414   if (isEssentiallyExtractHighSubvector(LHS)) {
12415     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
12416     if (!RHS.getNode())
12417       return SDValue();
12418   } else if (isEssentiallyExtractHighSubvector(RHS)) {
12419     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
12420     if (!LHS.getNode())
12421       return SDValue();
12422   }
12423 
12424   if (IID == Intrinsic::not_intrinsic)
12425     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
12426 
12427   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
12428                      N->getOperand(0), LHS, RHS);
12429 }
12430 
12431 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
12432   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
12433   unsigned ElemBits = ElemTy.getSizeInBits();
12434 
12435   int64_t ShiftAmount;
12436   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
12437     APInt SplatValue, SplatUndef;
12438     unsigned SplatBitSize;
12439     bool HasAnyUndefs;
12440     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12441                               HasAnyUndefs, ElemBits) ||
12442         SplatBitSize != ElemBits)
12443       return SDValue();
12444 
12445     ShiftAmount = SplatValue.getSExtValue();
12446   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
12447     ShiftAmount = CVN->getSExtValue();
12448   } else
12449     return SDValue();
12450 
12451   unsigned Opcode;
12452   bool IsRightShift;
12453   switch (IID) {
12454   default:
12455     llvm_unreachable("Unknown shift intrinsic");
12456   case Intrinsic::aarch64_neon_sqshl:
12457     Opcode = AArch64ISD::SQSHL_I;
12458     IsRightShift = false;
12459     break;
12460   case Intrinsic::aarch64_neon_uqshl:
12461     Opcode = AArch64ISD::UQSHL_I;
12462     IsRightShift = false;
12463     break;
12464   case Intrinsic::aarch64_neon_srshl:
12465     Opcode = AArch64ISD::SRSHR_I;
12466     IsRightShift = true;
12467     break;
12468   case Intrinsic::aarch64_neon_urshl:
12469     Opcode = AArch64ISD::URSHR_I;
12470     IsRightShift = true;
12471     break;
12472   case Intrinsic::aarch64_neon_sqshlu:
12473     Opcode = AArch64ISD::SQSHLU_I;
12474     IsRightShift = false;
12475     break;
12476   case Intrinsic::aarch64_neon_sshl:
12477   case Intrinsic::aarch64_neon_ushl:
12478     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
12479     // left shift for positive shift amounts. Below, we only replace the current
12480     // node with VSHL, if this condition is met.
12481     Opcode = AArch64ISD::VSHL;
12482     IsRightShift = false;
12483     break;
12484   }
12485 
12486   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
12487     SDLoc dl(N);
12488     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12489                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
12490   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
12491     SDLoc dl(N);
12492     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12493                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
12494   }
12495 
12496   return SDValue();
12497 }
12498 
12499 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
12500 // the intrinsics must be legal and take an i32, this means there's almost
12501 // certainly going to be a zext in the DAG which we can eliminate.
12502 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
12503   SDValue AndN = N->getOperand(2);
12504   if (AndN.getOpcode() != ISD::AND)
12505     return SDValue();
12506 
12507   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
12508   if (!CMask || CMask->getZExtValue() != Mask)
12509     return SDValue();
12510 
12511   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
12512                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
12513 }
12514 
12515 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
12516                                            SelectionDAG &DAG) {
12517   SDLoc dl(N);
12518   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
12519                      DAG.getNode(Opc, dl,
12520                                  N->getOperand(1).getSimpleValueType(),
12521                                  N->getOperand(1)),
12522                      DAG.getConstant(0, dl, MVT::i64));
12523 }
12524 
12525 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
12526   SDLoc DL(N);
12527   SDValue Op1 = N->getOperand(1);
12528   SDValue Op2 = N->getOperand(2);
12529   EVT ScalarTy = Op1.getValueType();
12530 
12531   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
12532     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
12533     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
12534   }
12535 
12536   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
12537                      Op1, Op2);
12538 }
12539 
12540 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
12541   SDLoc dl(N);
12542   SDValue Scalar = N->getOperand(3);
12543   EVT ScalarTy = Scalar.getValueType();
12544 
12545   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
12546     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
12547 
12548   SDValue Passthru = N->getOperand(1);
12549   SDValue Pred = N->getOperand(2);
12550   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
12551                      Pred, Scalar, Passthru);
12552 }
12553 
12554 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
12555   SDLoc dl(N);
12556   LLVMContext &Ctx = *DAG.getContext();
12557   EVT VT = N->getValueType(0);
12558 
12559   assert(VT.isScalableVector() && "Expected a scalable vector.");
12560 
12561   // Current lowering only supports the SVE-ACLE types.
12562   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
12563     return SDValue();
12564 
12565   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
12566   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
12567   EVT ByteVT =
12568       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
12569 
12570   // Convert everything to the domain of EXT (i.e bytes).
12571   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
12572   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
12573   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
12574                             DAG.getConstant(ElemSize, dl, MVT::i32));
12575 
12576   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
12577   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
12578 }
12579 
12580 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
12581                                         TargetLowering::DAGCombinerInfo &DCI,
12582                                         SelectionDAG &DAG) {
12583   if (DCI.isBeforeLegalize())
12584     return SDValue();
12585 
12586   SDValue Comparator = N->getOperand(3);
12587   if (Comparator.getOpcode() == AArch64ISD::DUP ||
12588       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
12589     unsigned IID = getIntrinsicID(N);
12590     EVT VT = N->getValueType(0);
12591     EVT CmpVT = N->getOperand(2).getValueType();
12592     SDValue Pred = N->getOperand(1);
12593     SDValue Imm;
12594     SDLoc DL(N);
12595 
12596     switch (IID) {
12597     default:
12598       llvm_unreachable("Called with wrong intrinsic!");
12599       break;
12600 
12601     // Signed comparisons
12602     case Intrinsic::aarch64_sve_cmpeq_wide:
12603     case Intrinsic::aarch64_sve_cmpne_wide:
12604     case Intrinsic::aarch64_sve_cmpge_wide:
12605     case Intrinsic::aarch64_sve_cmpgt_wide:
12606     case Intrinsic::aarch64_sve_cmplt_wide:
12607     case Intrinsic::aarch64_sve_cmple_wide: {
12608       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12609         int64_t ImmVal = CN->getSExtValue();
12610         if (ImmVal >= -16 && ImmVal <= 15)
12611           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12612         else
12613           return SDValue();
12614       }
12615       break;
12616     }
12617     // Unsigned comparisons
12618     case Intrinsic::aarch64_sve_cmphs_wide:
12619     case Intrinsic::aarch64_sve_cmphi_wide:
12620     case Intrinsic::aarch64_sve_cmplo_wide:
12621     case Intrinsic::aarch64_sve_cmpls_wide:  {
12622       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12623         uint64_t ImmVal = CN->getZExtValue();
12624         if (ImmVal <= 127)
12625           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12626         else
12627           return SDValue();
12628       }
12629       break;
12630     }
12631     }
12632 
12633     if (!Imm)
12634       return SDValue();
12635 
12636     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
12637     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
12638                        N->getOperand(2), Splat, DAG.getCondCode(CC));
12639   }
12640 
12641   return SDValue();
12642 }
12643 
12644 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
12645                         AArch64CC::CondCode Cond) {
12646   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12647 
12648   SDLoc DL(Op);
12649   assert(Op.getValueType().isScalableVector() &&
12650          TLI.isTypeLegal(Op.getValueType()) &&
12651          "Expected legal scalable vector type!");
12652 
12653   // Ensure target specific opcodes are using legal type.
12654   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12655   SDValue TVal = DAG.getConstant(1, DL, OutVT);
12656   SDValue FVal = DAG.getConstant(0, DL, OutVT);
12657 
12658   // Set condition code (CC) flags.
12659   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
12660 
12661   // Convert CC to integer based on requested condition.
12662   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
12663   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
12664   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
12665   return DAG.getZExtOrTrunc(Res, DL, VT);
12666 }
12667 
12668 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
12669                                       SelectionDAG &DAG) {
12670   SDLoc DL(N);
12671 
12672   SDValue Pred = N->getOperand(1);
12673   SDValue VecToReduce = N->getOperand(2);
12674 
12675   // NOTE: The integer reduction's result type is not always linked to the
12676   // operand's element type so we construct it from the intrinsic's result type.
12677   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
12678   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12679 
12680   // SVE reductions set the whole vector register with the first element
12681   // containing the reduction result, which we'll now extract.
12682   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12683   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12684                      Zero);
12685 }
12686 
12687 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
12688                                      SelectionDAG &DAG) {
12689   SDLoc DL(N);
12690 
12691   SDValue Pred = N->getOperand(1);
12692   SDValue VecToReduce = N->getOperand(2);
12693 
12694   EVT ReduceVT = VecToReduce.getValueType();
12695   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12696 
12697   // SVE reductions set the whole vector register with the first element
12698   // containing the reduction result, which we'll now extract.
12699   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12700   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12701                      Zero);
12702 }
12703 
12704 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
12705                                             SelectionDAG &DAG) {
12706   SDLoc DL(N);
12707 
12708   SDValue Pred = N->getOperand(1);
12709   SDValue InitVal = N->getOperand(2);
12710   SDValue VecToReduce = N->getOperand(3);
12711   EVT ReduceVT = VecToReduce.getValueType();
12712 
12713   // Ordered reductions use the first lane of the result vector as the
12714   // reduction's initial value.
12715   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12716   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
12717                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
12718 
12719   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
12720 
12721   // SVE reductions set the whole vector register with the first element
12722   // containing the reduction result, which we'll now extract.
12723   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12724                      Zero);
12725 }
12726 
12727 // If a merged operation has no inactive lanes we can relax it to a predicated
12728 // or unpredicated operation, which potentially allows better isel (perhaps
12729 // using immediate forms) or relaxing register reuse requirements.
12730 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
12731                                        SelectionDAG &DAG) {
12732   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
12733   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
12734   SDValue Pg = N->getOperand(1);
12735 
12736   // ISD way to specify an all active predicate.
12737   if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
12738       (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
12739     return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
12740                        N->getOperand(2), N->getOperand(3));
12741 
12742   // FUTURE: SplatVector(true)
12743   return SDValue();
12744 }
12745 
12746 static SDValue performIntrinsicCombine(SDNode *N,
12747                                        TargetLowering::DAGCombinerInfo &DCI,
12748                                        const AArch64Subtarget *Subtarget) {
12749   SelectionDAG &DAG = DCI.DAG;
12750   unsigned IID = getIntrinsicID(N);
12751   switch (IID) {
12752   default:
12753     break;
12754   case Intrinsic::aarch64_neon_vcvtfxs2fp:
12755   case Intrinsic::aarch64_neon_vcvtfxu2fp:
12756     return tryCombineFixedPointConvert(N, DCI, DAG);
12757   case Intrinsic::aarch64_neon_saddv:
12758     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
12759   case Intrinsic::aarch64_neon_uaddv:
12760     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
12761   case Intrinsic::aarch64_neon_sminv:
12762     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
12763   case Intrinsic::aarch64_neon_uminv:
12764     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
12765   case Intrinsic::aarch64_neon_smaxv:
12766     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
12767   case Intrinsic::aarch64_neon_umaxv:
12768     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
12769   case Intrinsic::aarch64_neon_fmax:
12770     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
12771                        N->getOperand(1), N->getOperand(2));
12772   case Intrinsic::aarch64_neon_fmin:
12773     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
12774                        N->getOperand(1), N->getOperand(2));
12775   case Intrinsic::aarch64_neon_fmaxnm:
12776     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
12777                        N->getOperand(1), N->getOperand(2));
12778   case Intrinsic::aarch64_neon_fminnm:
12779     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
12780                        N->getOperand(1), N->getOperand(2));
12781   case Intrinsic::aarch64_neon_smull:
12782   case Intrinsic::aarch64_neon_umull:
12783   case Intrinsic::aarch64_neon_pmull:
12784   case Intrinsic::aarch64_neon_sqdmull:
12785     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
12786   case Intrinsic::aarch64_neon_sqshl:
12787   case Intrinsic::aarch64_neon_uqshl:
12788   case Intrinsic::aarch64_neon_sqshlu:
12789   case Intrinsic::aarch64_neon_srshl:
12790   case Intrinsic::aarch64_neon_urshl:
12791   case Intrinsic::aarch64_neon_sshl:
12792   case Intrinsic::aarch64_neon_ushl:
12793     return tryCombineShiftImm(IID, N, DAG);
12794   case Intrinsic::aarch64_crc32b:
12795   case Intrinsic::aarch64_crc32cb:
12796     return tryCombineCRC32(0xff, N, DAG);
12797   case Intrinsic::aarch64_crc32h:
12798   case Intrinsic::aarch64_crc32ch:
12799     return tryCombineCRC32(0xffff, N, DAG);
12800   case Intrinsic::aarch64_sve_saddv:
12801     // There is no i64 version of SADDV because the sign is irrelevant.
12802     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
12803       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
12804     else
12805       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
12806   case Intrinsic::aarch64_sve_uaddv:
12807     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
12808   case Intrinsic::aarch64_sve_smaxv:
12809     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
12810   case Intrinsic::aarch64_sve_umaxv:
12811     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
12812   case Intrinsic::aarch64_sve_sminv:
12813     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
12814   case Intrinsic::aarch64_sve_uminv:
12815     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
12816   case Intrinsic::aarch64_sve_orv:
12817     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
12818   case Intrinsic::aarch64_sve_eorv:
12819     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
12820   case Intrinsic::aarch64_sve_andv:
12821     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
12822   case Intrinsic::aarch64_sve_index:
12823     return LowerSVEIntrinsicIndex(N, DAG);
12824   case Intrinsic::aarch64_sve_dup:
12825     return LowerSVEIntrinsicDUP(N, DAG);
12826   case Intrinsic::aarch64_sve_dup_x:
12827     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
12828                        N->getOperand(1));
12829   case Intrinsic::aarch64_sve_ext:
12830     return LowerSVEIntrinsicEXT(N, DAG);
12831   case Intrinsic::aarch64_sve_smin:
12832     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
12833   case Intrinsic::aarch64_sve_umin:
12834     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
12835   case Intrinsic::aarch64_sve_smax:
12836     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
12837   case Intrinsic::aarch64_sve_umax:
12838     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
12839   case Intrinsic::aarch64_sve_lsl:
12840     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
12841   case Intrinsic::aarch64_sve_lsr:
12842     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
12843   case Intrinsic::aarch64_sve_asr:
12844     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
12845   case Intrinsic::aarch64_sve_cmphs:
12846     if (!N->getOperand(2).getValueType().isFloatingPoint())
12847       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12848                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12849                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
12850     break;
12851   case Intrinsic::aarch64_sve_cmphi:
12852     if (!N->getOperand(2).getValueType().isFloatingPoint())
12853       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12854                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12855                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
12856     break;
12857   case Intrinsic::aarch64_sve_cmpge:
12858     if (!N->getOperand(2).getValueType().isFloatingPoint())
12859       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12860                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12861                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
12862     break;
12863   case Intrinsic::aarch64_sve_cmpgt:
12864     if (!N->getOperand(2).getValueType().isFloatingPoint())
12865       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12866                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12867                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12868     break;
12869   case Intrinsic::aarch64_sve_cmpeq:
12870     if (!N->getOperand(2).getValueType().isFloatingPoint())
12871       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12872                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12873                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12874     break;
12875   case Intrinsic::aarch64_sve_cmpne:
12876     if (!N->getOperand(2).getValueType().isFloatingPoint())
12877       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12878                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12879                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12880     break;
12881   case Intrinsic::aarch64_sve_fadda:
12882     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12883   case Intrinsic::aarch64_sve_faddv:
12884     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12885   case Intrinsic::aarch64_sve_fmaxnmv:
12886     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12887   case Intrinsic::aarch64_sve_fmaxv:
12888     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12889   case Intrinsic::aarch64_sve_fminnmv:
12890     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12891   case Intrinsic::aarch64_sve_fminv:
12892     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12893   case Intrinsic::aarch64_sve_sel:
12894     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12895                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12896   case Intrinsic::aarch64_sve_cmpeq_wide:
12897     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12898   case Intrinsic::aarch64_sve_cmpne_wide:
12899     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12900   case Intrinsic::aarch64_sve_cmpge_wide:
12901     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12902   case Intrinsic::aarch64_sve_cmpgt_wide:
12903     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12904   case Intrinsic::aarch64_sve_cmplt_wide:
12905     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12906   case Intrinsic::aarch64_sve_cmple_wide:
12907     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12908   case Intrinsic::aarch64_sve_cmphs_wide:
12909     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12910   case Intrinsic::aarch64_sve_cmphi_wide:
12911     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12912   case Intrinsic::aarch64_sve_cmplo_wide:
12913     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12914   case Intrinsic::aarch64_sve_cmpls_wide:
12915     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12916   case Intrinsic::aarch64_sve_ptest_any:
12917     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12918                     AArch64CC::ANY_ACTIVE);
12919   case Intrinsic::aarch64_sve_ptest_first:
12920     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12921                     AArch64CC::FIRST_ACTIVE);
12922   case Intrinsic::aarch64_sve_ptest_last:
12923     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12924                     AArch64CC::LAST_ACTIVE);
12925   }
12926   return SDValue();
12927 }
12928 
12929 static SDValue performExtendCombine(SDNode *N,
12930                                     TargetLowering::DAGCombinerInfo &DCI,
12931                                     SelectionDAG &DAG) {
12932   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12933   // we can convert that DUP into another extract_high (of a bigger DUP), which
12934   // helps the backend to decide that an sabdl2 would be useful, saving a real
12935   // extract_high operation.
12936   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12937       (N->getOperand(0).getOpcode() == AArch64ISD::UABD ||
12938        N->getOperand(0).getOpcode() == AArch64ISD::SABD)) {
12939     SDNode *ABDNode = N->getOperand(0).getNode();
12940     SDValue NewABD =
12941         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
12942     if (!NewABD.getNode())
12943       return SDValue();
12944 
12945     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
12946   }
12947 
12948   // This is effectively a custom type legalization for AArch64.
12949   //
12950   // Type legalization will split an extend of a small, legal, type to a larger
12951   // illegal type by first splitting the destination type, often creating
12952   // illegal source types, which then get legalized in isel-confusing ways,
12953   // leading to really terrible codegen. E.g.,
12954   //   %result = v8i32 sext v8i8 %value
12955   // becomes
12956   //   %losrc = extract_subreg %value, ...
12957   //   %hisrc = extract_subreg %value, ...
12958   //   %lo = v4i32 sext v4i8 %losrc
12959   //   %hi = v4i32 sext v4i8 %hisrc
12960   // Things go rapidly downhill from there.
12961   //
12962   // For AArch64, the [sz]ext vector instructions can only go up one element
12963   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
12964   // take two instructions.
12965   //
12966   // This implies that the most efficient way to do the extend from v8i8
12967   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
12968   // the normal splitting to happen for the v8i16->v8i32.
12969 
12970   // This is pre-legalization to catch some cases where the default
12971   // type legalization will create ill-tempered code.
12972   if (!DCI.isBeforeLegalizeOps())
12973     return SDValue();
12974 
12975   // We're only interested in cleaning things up for non-legal vector types
12976   // here. If both the source and destination are legal, things will just
12977   // work naturally without any fiddling.
12978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12979   EVT ResVT = N->getValueType(0);
12980   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
12981     return SDValue();
12982   // If the vector type isn't a simple VT, it's beyond the scope of what
12983   // we're  worried about here. Let legalization do its thing and hope for
12984   // the best.
12985   SDValue Src = N->getOperand(0);
12986   EVT SrcVT = Src->getValueType(0);
12987   if (!ResVT.isSimple() || !SrcVT.isSimple())
12988     return SDValue();
12989 
12990   // If the source VT is a 64-bit fixed or scalable vector, we can play games
12991   // and get the better results we want.
12992   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
12993     return SDValue();
12994 
12995   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
12996   ElementCount SrcEC = SrcVT.getVectorElementCount();
12997   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
12998   SDLoc DL(N);
12999   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
13000 
13001   // Now split the rest of the operation into two halves, each with a 64
13002   // bit source.
13003   EVT LoVT, HiVT;
13004   SDValue Lo, Hi;
13005   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
13006 
13007   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
13008                                LoVT.getVectorElementCount());
13009   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13010                    DAG.getConstant(0, DL, MVT::i64));
13011   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13012                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
13013   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
13014   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
13015 
13016   // Now combine the parts back together so we still have a single result
13017   // like the combiner expects.
13018   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
13019 }
13020 
13021 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
13022                                SDValue SplatVal, unsigned NumVecElts) {
13023   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
13024   unsigned OrigAlignment = St.getAlignment();
13025   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
13026 
13027   // Create scalar stores. This is at least as good as the code sequence for a
13028   // split unaligned store which is a dup.s, ext.b, and two stores.
13029   // Most of the time the three stores should be replaced by store pair
13030   // instructions (stp).
13031   SDLoc DL(&St);
13032   SDValue BasePtr = St.getBasePtr();
13033   uint64_t BaseOffset = 0;
13034 
13035   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
13036   SDValue NewST1 =
13037       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
13038                    OrigAlignment, St.getMemOperand()->getFlags());
13039 
13040   // As this in ISel, we will not merge this add which may degrade results.
13041   if (BasePtr->getOpcode() == ISD::ADD &&
13042       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
13043     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
13044     BasePtr = BasePtr->getOperand(0);
13045   }
13046 
13047   unsigned Offset = EltOffset;
13048   while (--NumVecElts) {
13049     unsigned Alignment = MinAlign(OrigAlignment, Offset);
13050     SDValue OffsetPtr =
13051         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13052                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
13053     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
13054                           PtrInfo.getWithOffset(Offset), Alignment,
13055                           St.getMemOperand()->getFlags());
13056     Offset += EltOffset;
13057   }
13058   return NewST1;
13059 }
13060 
13061 // Returns an SVE type that ContentTy can be trivially sign or zero extended
13062 // into.
13063 static MVT getSVEContainerType(EVT ContentTy) {
13064   assert(ContentTy.isSimple() && "No SVE containers for extended types");
13065 
13066   switch (ContentTy.getSimpleVT().SimpleTy) {
13067   default:
13068     llvm_unreachable("No known SVE container for this MVT type");
13069   case MVT::nxv2i8:
13070   case MVT::nxv2i16:
13071   case MVT::nxv2i32:
13072   case MVT::nxv2i64:
13073   case MVT::nxv2f32:
13074   case MVT::nxv2f64:
13075     return MVT::nxv2i64;
13076   case MVT::nxv4i8:
13077   case MVT::nxv4i16:
13078   case MVT::nxv4i32:
13079   case MVT::nxv4f32:
13080     return MVT::nxv4i32;
13081   case MVT::nxv8i8:
13082   case MVT::nxv8i16:
13083   case MVT::nxv8f16:
13084   case MVT::nxv8bf16:
13085     return MVT::nxv8i16;
13086   case MVT::nxv16i8:
13087     return MVT::nxv16i8;
13088   }
13089 }
13090 
13091 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
13092   SDLoc DL(N);
13093   EVT VT = N->getValueType(0);
13094 
13095   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13096     return SDValue();
13097 
13098   EVT ContainerVT = VT;
13099   if (ContainerVT.isInteger())
13100     ContainerVT = getSVEContainerType(ContainerVT);
13101 
13102   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
13103   SDValue Ops[] = { N->getOperand(0), // Chain
13104                     N->getOperand(2), // Pg
13105                     N->getOperand(3), // Base
13106                     DAG.getValueType(VT) };
13107 
13108   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
13109   SDValue LoadChain = SDValue(Load.getNode(), 1);
13110 
13111   if (ContainerVT.isInteger() && (VT != ContainerVT))
13112     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
13113 
13114   return DAG.getMergeValues({ Load, LoadChain }, DL);
13115 }
13116 
13117 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
13118   SDLoc DL(N);
13119   EVT VT = N->getValueType(0);
13120   EVT PtrTy = N->getOperand(3).getValueType();
13121 
13122   if (VT == MVT::nxv8bf16 &&
13123       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13124     return SDValue();
13125 
13126   EVT LoadVT = VT;
13127   if (VT.isFloatingPoint())
13128     LoadVT = VT.changeTypeToInteger();
13129 
13130   auto *MINode = cast<MemIntrinsicSDNode>(N);
13131   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
13132   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
13133                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
13134                                 MINode->getOperand(2), PassThru,
13135                                 MINode->getMemoryVT(), MINode->getMemOperand(),
13136                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
13137 
13138    if (VT.isFloatingPoint()) {
13139      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
13140      return DAG.getMergeValues(Ops, DL);
13141    }
13142 
13143   return L;
13144 }
13145 
13146 template <unsigned Opcode>
13147 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
13148   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
13149                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
13150                 "Unsupported opcode.");
13151   SDLoc DL(N);
13152   EVT VT = N->getValueType(0);
13153   if (VT == MVT::nxv8bf16 &&
13154       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13155     return SDValue();
13156 
13157   EVT LoadVT = VT;
13158   if (VT.isFloatingPoint())
13159     LoadVT = VT.changeTypeToInteger();
13160 
13161   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
13162   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
13163   SDValue LoadChain = SDValue(Load.getNode(), 1);
13164 
13165   if (VT.isFloatingPoint())
13166     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
13167 
13168   return DAG.getMergeValues({Load, LoadChain}, DL);
13169 }
13170 
13171 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
13172   SDLoc DL(N);
13173   SDValue Data = N->getOperand(2);
13174   EVT DataVT = Data.getValueType();
13175   EVT HwSrcVt = getSVEContainerType(DataVT);
13176   SDValue InputVT = DAG.getValueType(DataVT);
13177 
13178   if (DataVT == MVT::nxv8bf16 &&
13179       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13180     return SDValue();
13181 
13182   if (DataVT.isFloatingPoint())
13183     InputVT = DAG.getValueType(HwSrcVt);
13184 
13185   SDValue SrcNew;
13186   if (Data.getValueType().isFloatingPoint())
13187     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
13188   else
13189     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
13190 
13191   SDValue Ops[] = { N->getOperand(0), // Chain
13192                     SrcNew,
13193                     N->getOperand(4), // Base
13194                     N->getOperand(3), // Pg
13195                     InputVT
13196                   };
13197 
13198   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
13199 }
13200 
13201 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
13202   SDLoc DL(N);
13203 
13204   SDValue Data = N->getOperand(2);
13205   EVT DataVT = Data.getValueType();
13206   EVT PtrTy = N->getOperand(4).getValueType();
13207 
13208   if (DataVT == MVT::nxv8bf16 &&
13209       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13210     return SDValue();
13211 
13212   if (DataVT.isFloatingPoint())
13213     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
13214 
13215   auto *MINode = cast<MemIntrinsicSDNode>(N);
13216   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
13217                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
13218                             MINode->getMemoryVT(), MINode->getMemOperand(),
13219                             ISD::UNINDEXED, false, false);
13220 }
13221 
13222 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
13223 /// load store optimizer pass will merge them to store pair stores.  This should
13224 /// be better than a movi to create the vector zero followed by a vector store
13225 /// if the zero constant is not re-used, since one instructions and one register
13226 /// live range will be removed.
13227 ///
13228 /// For example, the final generated code should be:
13229 ///
13230 ///   stp xzr, xzr, [x0]
13231 ///
13232 /// instead of:
13233 ///
13234 ///   movi v0.2d, #0
13235 ///   str q0, [x0]
13236 ///
13237 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13238   SDValue StVal = St.getValue();
13239   EVT VT = StVal.getValueType();
13240 
13241   // Avoid scalarizing zero splat stores for scalable vectors.
13242   if (VT.isScalableVector())
13243     return SDValue();
13244 
13245   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
13246   // 2, 3 or 4 i32 elements.
13247   int NumVecElts = VT.getVectorNumElements();
13248   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
13249          VT.getVectorElementType().getSizeInBits() == 64) ||
13250         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
13251          VT.getVectorElementType().getSizeInBits() == 32)))
13252     return SDValue();
13253 
13254   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
13255     return SDValue();
13256 
13257   // If the zero constant has more than one use then the vector store could be
13258   // better since the constant mov will be amortized and stp q instructions
13259   // should be able to be formed.
13260   if (!StVal.hasOneUse())
13261     return SDValue();
13262 
13263   // If the store is truncating then it's going down to i16 or smaller, which
13264   // means it can be implemented in a single store anyway.
13265   if (St.isTruncatingStore())
13266     return SDValue();
13267 
13268   // If the immediate offset of the address operand is too large for the stp
13269   // instruction, then bail out.
13270   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
13271     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
13272     if (Offset < -512 || Offset > 504)
13273       return SDValue();
13274   }
13275 
13276   for (int I = 0; I < NumVecElts; ++I) {
13277     SDValue EltVal = StVal.getOperand(I);
13278     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
13279       return SDValue();
13280   }
13281 
13282   // Use a CopyFromReg WZR/XZR here to prevent
13283   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
13284   SDLoc DL(&St);
13285   unsigned ZeroReg;
13286   EVT ZeroVT;
13287   if (VT.getVectorElementType().getSizeInBits() == 32) {
13288     ZeroReg = AArch64::WZR;
13289     ZeroVT = MVT::i32;
13290   } else {
13291     ZeroReg = AArch64::XZR;
13292     ZeroVT = MVT::i64;
13293   }
13294   SDValue SplatVal =
13295       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
13296   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13297 }
13298 
13299 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
13300 /// value. The load store optimizer pass will merge them to store pair stores.
13301 /// This has better performance than a splat of the scalar followed by a split
13302 /// vector store. Even if the stores are not merged it is four stores vs a dup,
13303 /// followed by an ext.b and two stores.
13304 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13305   SDValue StVal = St.getValue();
13306   EVT VT = StVal.getValueType();
13307 
13308   // Don't replace floating point stores, they possibly won't be transformed to
13309   // stp because of the store pair suppress pass.
13310   if (VT.isFloatingPoint())
13311     return SDValue();
13312 
13313   // We can express a splat as store pair(s) for 2 or 4 elements.
13314   unsigned NumVecElts = VT.getVectorNumElements();
13315   if (NumVecElts != 4 && NumVecElts != 2)
13316     return SDValue();
13317 
13318   // If the store is truncating then it's going down to i16 or smaller, which
13319   // means it can be implemented in a single store anyway.
13320   if (St.isTruncatingStore())
13321     return SDValue();
13322 
13323   // Check that this is a splat.
13324   // Make sure that each of the relevant vector element locations are inserted
13325   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
13326   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
13327   SDValue SplatVal;
13328   for (unsigned I = 0; I < NumVecElts; ++I) {
13329     // Check for insert vector elements.
13330     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
13331       return SDValue();
13332 
13333     // Check that same value is inserted at each vector element.
13334     if (I == 0)
13335       SplatVal = StVal.getOperand(1);
13336     else if (StVal.getOperand(1) != SplatVal)
13337       return SDValue();
13338 
13339     // Check insert element index.
13340     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
13341     if (!CIndex)
13342       return SDValue();
13343     uint64_t IndexVal = CIndex->getZExtValue();
13344     if (IndexVal >= NumVecElts)
13345       return SDValue();
13346     IndexNotInserted.reset(IndexVal);
13347 
13348     StVal = StVal.getOperand(0);
13349   }
13350   // Check that all vector element locations were inserted to.
13351   if (IndexNotInserted.any())
13352       return SDValue();
13353 
13354   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13355 }
13356 
13357 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13358                            SelectionDAG &DAG,
13359                            const AArch64Subtarget *Subtarget) {
13360 
13361   StoreSDNode *S = cast<StoreSDNode>(N);
13362   if (S->isVolatile() || S->isIndexed())
13363     return SDValue();
13364 
13365   SDValue StVal = S->getValue();
13366   EVT VT = StVal.getValueType();
13367 
13368   if (!VT.isFixedLengthVector())
13369     return SDValue();
13370 
13371   // If we get a splat of zeros, convert this vector store to a store of
13372   // scalars. They will be merged into store pairs of xzr thereby removing one
13373   // instruction and one register.
13374   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
13375     return ReplacedZeroSplat;
13376 
13377   // FIXME: The logic for deciding if an unaligned store should be split should
13378   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
13379   // a call to that function here.
13380 
13381   if (!Subtarget->isMisaligned128StoreSlow())
13382     return SDValue();
13383 
13384   // Don't split at -Oz.
13385   if (DAG.getMachineFunction().getFunction().hasMinSize())
13386     return SDValue();
13387 
13388   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
13389   // those up regresses performance on micro-benchmarks and olden/bh.
13390   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
13391     return SDValue();
13392 
13393   // Split unaligned 16B stores. They are terrible for performance.
13394   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
13395   // extensions can use this to mark that it does not want splitting to happen
13396   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
13397   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
13398   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
13399       S->getAlignment() <= 2)
13400     return SDValue();
13401 
13402   // If we get a splat of a scalar convert this vector store to a store of
13403   // scalars. They will be merged into store pairs thereby removing two
13404   // instructions.
13405   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
13406     return ReplacedSplat;
13407 
13408   SDLoc DL(S);
13409 
13410   // Split VT into two.
13411   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13412   unsigned NumElts = HalfVT.getVectorNumElements();
13413   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13414                                    DAG.getConstant(0, DL, MVT::i64));
13415   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13416                                    DAG.getConstant(NumElts, DL, MVT::i64));
13417   SDValue BasePtr = S->getBasePtr();
13418   SDValue NewST1 =
13419       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
13420                    S->getAlignment(), S->getMemOperand()->getFlags());
13421   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13422                                   DAG.getConstant(8, DL, MVT::i64));
13423   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
13424                       S->getPointerInfo(), S->getAlignment(),
13425                       S->getMemOperand()->getFlags());
13426 }
13427 
13428 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
13429   SDLoc DL(N);
13430   SDValue Op0 = N->getOperand(0);
13431   SDValue Op1 = N->getOperand(1);
13432   EVT ResVT = N->getValueType(0);
13433 
13434   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
13435   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
13436     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13437       SDValue X = Op0.getOperand(0).getOperand(0);
13438       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
13439     }
13440   }
13441 
13442   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
13443   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
13444     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13445       SDValue Z = Op1.getOperand(0).getOperand(1);
13446       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
13447     }
13448   }
13449 
13450   return SDValue();
13451 }
13452 
13453 /// Target-specific DAG combine function for post-increment LD1 (lane) and
13454 /// post-increment LD1R.
13455 static SDValue performPostLD1Combine(SDNode *N,
13456                                      TargetLowering::DAGCombinerInfo &DCI,
13457                                      bool IsLaneOp) {
13458   if (DCI.isBeforeLegalizeOps())
13459     return SDValue();
13460 
13461   SelectionDAG &DAG = DCI.DAG;
13462   EVT VT = N->getValueType(0);
13463 
13464   if (VT.isScalableVector())
13465     return SDValue();
13466 
13467   unsigned LoadIdx = IsLaneOp ? 1 : 0;
13468   SDNode *LD = N->getOperand(LoadIdx).getNode();
13469   // If it is not LOAD, can not do such combine.
13470   if (LD->getOpcode() != ISD::LOAD)
13471     return SDValue();
13472 
13473   // The vector lane must be a constant in the LD1LANE opcode.
13474   SDValue Lane;
13475   if (IsLaneOp) {
13476     Lane = N->getOperand(2);
13477     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
13478     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
13479       return SDValue();
13480   }
13481 
13482   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
13483   EVT MemVT = LoadSDN->getMemoryVT();
13484   // Check if memory operand is the same type as the vector element.
13485   if (MemVT != VT.getVectorElementType())
13486     return SDValue();
13487 
13488   // Check if there are other uses. If so, do not combine as it will introduce
13489   // an extra load.
13490   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
13491        ++UI) {
13492     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
13493       continue;
13494     if (*UI != N)
13495       return SDValue();
13496   }
13497 
13498   SDValue Addr = LD->getOperand(1);
13499   SDValue Vector = N->getOperand(0);
13500   // Search for a use of the address operand that is an increment.
13501   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
13502        Addr.getNode()->use_end(); UI != UE; ++UI) {
13503     SDNode *User = *UI;
13504     if (User->getOpcode() != ISD::ADD
13505         || UI.getUse().getResNo() != Addr.getResNo())
13506       continue;
13507 
13508     // If the increment is a constant, it must match the memory ref size.
13509     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13510     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13511       uint32_t IncVal = CInc->getZExtValue();
13512       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
13513       if (IncVal != NumBytes)
13514         continue;
13515       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13516     }
13517 
13518     // To avoid cycle construction make sure that neither the load nor the add
13519     // are predecessors to each other or the Vector.
13520     SmallPtrSet<const SDNode *, 32> Visited;
13521     SmallVector<const SDNode *, 16> Worklist;
13522     Visited.insert(Addr.getNode());
13523     Worklist.push_back(User);
13524     Worklist.push_back(LD);
13525     Worklist.push_back(Vector.getNode());
13526     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
13527         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13528       continue;
13529 
13530     SmallVector<SDValue, 8> Ops;
13531     Ops.push_back(LD->getOperand(0));  // Chain
13532     if (IsLaneOp) {
13533       Ops.push_back(Vector);           // The vector to be inserted
13534       Ops.push_back(Lane);             // The lane to be inserted in the vector
13535     }
13536     Ops.push_back(Addr);
13537     Ops.push_back(Inc);
13538 
13539     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
13540     SDVTList SDTys = DAG.getVTList(Tys);
13541     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
13542     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
13543                                            MemVT,
13544                                            LoadSDN->getMemOperand());
13545 
13546     // Update the uses.
13547     SDValue NewResults[] = {
13548         SDValue(LD, 0),            // The result of load
13549         SDValue(UpdN.getNode(), 2) // Chain
13550     };
13551     DCI.CombineTo(LD, NewResults);
13552     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
13553     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
13554 
13555     break;
13556   }
13557   return SDValue();
13558 }
13559 
13560 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
13561 /// address translation.
13562 static bool performTBISimplification(SDValue Addr,
13563                                      TargetLowering::DAGCombinerInfo &DCI,
13564                                      SelectionDAG &DAG) {
13565   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
13566   KnownBits Known;
13567   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13568                                         !DCI.isBeforeLegalizeOps());
13569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13570   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
13571     DCI.CommitTargetLoweringOpt(TLO);
13572     return true;
13573   }
13574   return false;
13575 }
13576 
13577 static SDValue performSTORECombine(SDNode *N,
13578                                    TargetLowering::DAGCombinerInfo &DCI,
13579                                    SelectionDAG &DAG,
13580                                    const AArch64Subtarget *Subtarget) {
13581   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
13582     return Split;
13583 
13584   if (Subtarget->supportsAddressTopByteIgnored() &&
13585       performTBISimplification(N->getOperand(2), DCI, DAG))
13586     return SDValue(N, 0);
13587 
13588   return SDValue();
13589 }
13590 
13591 
13592 /// Target-specific DAG combine function for NEON load/store intrinsics
13593 /// to merge base address updates.
13594 static SDValue performNEONPostLDSTCombine(SDNode *N,
13595                                           TargetLowering::DAGCombinerInfo &DCI,
13596                                           SelectionDAG &DAG) {
13597   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13598     return SDValue();
13599 
13600   unsigned AddrOpIdx = N->getNumOperands() - 1;
13601   SDValue Addr = N->getOperand(AddrOpIdx);
13602 
13603   // Search for a use of the address operand that is an increment.
13604   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13605        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13606     SDNode *User = *UI;
13607     if (User->getOpcode() != ISD::ADD ||
13608         UI.getUse().getResNo() != Addr.getResNo())
13609       continue;
13610 
13611     // Check that the add is independent of the load/store.  Otherwise, folding
13612     // it would create a cycle.
13613     SmallPtrSet<const SDNode *, 32> Visited;
13614     SmallVector<const SDNode *, 16> Worklist;
13615     Visited.insert(Addr.getNode());
13616     Worklist.push_back(N);
13617     Worklist.push_back(User);
13618     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13619         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13620       continue;
13621 
13622     // Find the new opcode for the updating load/store.
13623     bool IsStore = false;
13624     bool IsLaneOp = false;
13625     bool IsDupOp = false;
13626     unsigned NewOpc = 0;
13627     unsigned NumVecs = 0;
13628     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13629     switch (IntNo) {
13630     default: llvm_unreachable("unexpected intrinsic for Neon base update");
13631     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
13632       NumVecs = 2; break;
13633     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
13634       NumVecs = 3; break;
13635     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
13636       NumVecs = 4; break;
13637     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
13638       NumVecs = 2; IsStore = true; break;
13639     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
13640       NumVecs = 3; IsStore = true; break;
13641     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
13642       NumVecs = 4; IsStore = true; break;
13643     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
13644       NumVecs = 2; break;
13645     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
13646       NumVecs = 3; break;
13647     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
13648       NumVecs = 4; break;
13649     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
13650       NumVecs = 2; IsStore = true; break;
13651     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
13652       NumVecs = 3; IsStore = true; break;
13653     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
13654       NumVecs = 4; IsStore = true; break;
13655     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
13656       NumVecs = 2; IsDupOp = true; break;
13657     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
13658       NumVecs = 3; IsDupOp = true; break;
13659     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
13660       NumVecs = 4; IsDupOp = true; break;
13661     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
13662       NumVecs = 2; IsLaneOp = true; break;
13663     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
13664       NumVecs = 3; IsLaneOp = true; break;
13665     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
13666       NumVecs = 4; IsLaneOp = true; break;
13667     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
13668       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
13669     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
13670       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
13671     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
13672       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
13673     }
13674 
13675     EVT VecTy;
13676     if (IsStore)
13677       VecTy = N->getOperand(2).getValueType();
13678     else
13679       VecTy = N->getValueType(0);
13680 
13681     // If the increment is a constant, it must match the memory ref size.
13682     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13683     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13684       uint32_t IncVal = CInc->getZExtValue();
13685       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13686       if (IsLaneOp || IsDupOp)
13687         NumBytes /= VecTy.getVectorNumElements();
13688       if (IncVal != NumBytes)
13689         continue;
13690       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13691     }
13692     SmallVector<SDValue, 8> Ops;
13693     Ops.push_back(N->getOperand(0)); // Incoming chain
13694     // Load lane and store have vector list as input.
13695     if (IsLaneOp || IsStore)
13696       for (unsigned i = 2; i < AddrOpIdx; ++i)
13697         Ops.push_back(N->getOperand(i));
13698     Ops.push_back(Addr); // Base register
13699     Ops.push_back(Inc);
13700 
13701     // Return Types.
13702     EVT Tys[6];
13703     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
13704     unsigned n;
13705     for (n = 0; n < NumResultVecs; ++n)
13706       Tys[n] = VecTy;
13707     Tys[n++] = MVT::i64;  // Type of write back register
13708     Tys[n] = MVT::Other;  // Type of the chain
13709     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13710 
13711     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
13712     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
13713                                            MemInt->getMemoryVT(),
13714                                            MemInt->getMemOperand());
13715 
13716     // Update the uses.
13717     std::vector<SDValue> NewResults;
13718     for (unsigned i = 0; i < NumResultVecs; ++i) {
13719       NewResults.push_back(SDValue(UpdN.getNode(), i));
13720     }
13721     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
13722     DCI.CombineTo(N, NewResults);
13723     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13724 
13725     break;
13726   }
13727   return SDValue();
13728 }
13729 
13730 // Checks to see if the value is the prescribed width and returns information
13731 // about its extension mode.
13732 static
13733 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
13734   ExtType = ISD::NON_EXTLOAD;
13735   switch(V.getNode()->getOpcode()) {
13736   default:
13737     return false;
13738   case ISD::LOAD: {
13739     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
13740     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
13741        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
13742       ExtType = LoadNode->getExtensionType();
13743       return true;
13744     }
13745     return false;
13746   }
13747   case ISD::AssertSext: {
13748     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13749     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13750        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13751       ExtType = ISD::SEXTLOAD;
13752       return true;
13753     }
13754     return false;
13755   }
13756   case ISD::AssertZext: {
13757     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13758     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13759        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13760       ExtType = ISD::ZEXTLOAD;
13761       return true;
13762     }
13763     return false;
13764   }
13765   case ISD::Constant:
13766   case ISD::TargetConstant: {
13767     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
13768            1LL << (width - 1);
13769   }
13770   }
13771 
13772   return true;
13773 }
13774 
13775 // This function does a whole lot of voodoo to determine if the tests are
13776 // equivalent without and with a mask. Essentially what happens is that given a
13777 // DAG resembling:
13778 //
13779 //  +-------------+ +-------------+ +-------------+ +-------------+
13780 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
13781 //  +-------------+ +-------------+ +-------------+ +-------------+
13782 //           |           |           |               |
13783 //           V           V           |    +----------+
13784 //          +-------------+  +----+  |    |
13785 //          |     ADD     |  |0xff|  |    |
13786 //          +-------------+  +----+  |    |
13787 //                  |           |    |    |
13788 //                  V           V    |    |
13789 //                 +-------------+   |    |
13790 //                 |     AND     |   |    |
13791 //                 +-------------+   |    |
13792 //                      |            |    |
13793 //                      +-----+      |    |
13794 //                            |      |    |
13795 //                            V      V    V
13796 //                           +-------------+
13797 //                           |     CMP     |
13798 //                           +-------------+
13799 //
13800 // The AND node may be safely removed for some combinations of inputs. In
13801 // particular we need to take into account the extension type of the Input,
13802 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
13803 // width of the input (this can work for any width inputs, the above graph is
13804 // specific to 8 bits.
13805 //
13806 // The specific equations were worked out by generating output tables for each
13807 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
13808 // problem was simplified by working with 4 bit inputs, which means we only
13809 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
13810 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
13811 // patterns present in both extensions (0,7). For every distinct set of
13812 // AddConstant and CompConstants bit patterns we can consider the masked and
13813 // unmasked versions to be equivalent if the result of this function is true for
13814 // all 16 distinct bit patterns of for the current extension type of Input (w0).
13815 //
13816 //   sub      w8, w0, w1
13817 //   and      w10, w8, #0x0f
13818 //   cmp      w8, w2
13819 //   cset     w9, AArch64CC
13820 //   cmp      w10, w2
13821 //   cset     w11, AArch64CC
13822 //   cmp      w9, w11
13823 //   cset     w0, eq
13824 //   ret
13825 //
13826 // Since the above function shows when the outputs are equivalent it defines
13827 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
13828 // would be expensive to run during compiles. The equations below were written
13829 // in a test harness that confirmed they gave equivalent outputs to the above
13830 // for all inputs function, so they can be used determine if the removal is
13831 // legal instead.
13832 //
13833 // isEquivalentMaskless() is the code for testing if the AND can be removed
13834 // factored out of the DAG recognition as the DAG can take several forms.
13835 
13836 static bool isEquivalentMaskless(unsigned CC, unsigned width,
13837                                  ISD::LoadExtType ExtType, int AddConstant,
13838                                  int CompConstant) {
13839   // By being careful about our equations and only writing the in term
13840   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
13841   // make them generally applicable to all bit widths.
13842   int MaxUInt = (1 << width);
13843 
13844   // For the purposes of these comparisons sign extending the type is
13845   // equivalent to zero extending the add and displacing it by half the integer
13846   // width. Provided we are careful and make sure our equations are valid over
13847   // the whole range we can just adjust the input and avoid writing equations
13848   // for sign extended inputs.
13849   if (ExtType == ISD::SEXTLOAD)
13850     AddConstant -= (1 << (width-1));
13851 
13852   switch(CC) {
13853   case AArch64CC::LE:
13854   case AArch64CC::GT:
13855     if ((AddConstant == 0) ||
13856         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
13857         (AddConstant >= 0 && CompConstant < 0) ||
13858         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
13859       return true;
13860     break;
13861   case AArch64CC::LT:
13862   case AArch64CC::GE:
13863     if ((AddConstant == 0) ||
13864         (AddConstant >= 0 && CompConstant <= 0) ||
13865         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
13866       return true;
13867     break;
13868   case AArch64CC::HI:
13869   case AArch64CC::LS:
13870     if ((AddConstant >= 0 && CompConstant < 0) ||
13871        (AddConstant <= 0 && CompConstant >= -1 &&
13872         CompConstant < AddConstant + MaxUInt))
13873       return true;
13874    break;
13875   case AArch64CC::PL:
13876   case AArch64CC::MI:
13877     if ((AddConstant == 0) ||
13878         (AddConstant > 0 && CompConstant <= 0) ||
13879         (AddConstant < 0 && CompConstant <= AddConstant))
13880       return true;
13881     break;
13882   case AArch64CC::LO:
13883   case AArch64CC::HS:
13884     if ((AddConstant >= 0 && CompConstant <= 0) ||
13885         (AddConstant <= 0 && CompConstant >= 0 &&
13886          CompConstant <= AddConstant + MaxUInt))
13887       return true;
13888     break;
13889   case AArch64CC::EQ:
13890   case AArch64CC::NE:
13891     if ((AddConstant > 0 && CompConstant < 0) ||
13892         (AddConstant < 0 && CompConstant >= 0 &&
13893          CompConstant < AddConstant + MaxUInt) ||
13894         (AddConstant >= 0 && CompConstant >= 0 &&
13895          CompConstant >= AddConstant) ||
13896         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13897       return true;
13898     break;
13899   case AArch64CC::VS:
13900   case AArch64CC::VC:
13901   case AArch64CC::AL:
13902   case AArch64CC::NV:
13903     return true;
13904   case AArch64CC::Invalid:
13905     break;
13906   }
13907 
13908   return false;
13909 }
13910 
13911 static
13912 SDValue performCONDCombine(SDNode *N,
13913                            TargetLowering::DAGCombinerInfo &DCI,
13914                            SelectionDAG &DAG, unsigned CCIndex,
13915                            unsigned CmpIndex) {
13916   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13917   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13918   unsigned CondOpcode = SubsNode->getOpcode();
13919 
13920   if (CondOpcode != AArch64ISD::SUBS)
13921     return SDValue();
13922 
13923   // There is a SUBS feeding this condition. Is it fed by a mask we can
13924   // use?
13925 
13926   SDNode *AndNode = SubsNode->getOperand(0).getNode();
13927   unsigned MaskBits = 0;
13928 
13929   if (AndNode->getOpcode() != ISD::AND)
13930     return SDValue();
13931 
13932   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13933     uint32_t CNV = CN->getZExtValue();
13934     if (CNV == 255)
13935       MaskBits = 8;
13936     else if (CNV == 65535)
13937       MaskBits = 16;
13938   }
13939 
13940   if (!MaskBits)
13941     return SDValue();
13942 
13943   SDValue AddValue = AndNode->getOperand(0);
13944 
13945   if (AddValue.getOpcode() != ISD::ADD)
13946     return SDValue();
13947 
13948   // The basic dag structure is correct, grab the inputs and validate them.
13949 
13950   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
13951   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
13952   SDValue SubsInputValue = SubsNode->getOperand(1);
13953 
13954   // The mask is present and the provenance of all the values is a smaller type,
13955   // lets see if the mask is superfluous.
13956 
13957   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
13958       !isa<ConstantSDNode>(SubsInputValue.getNode()))
13959     return SDValue();
13960 
13961   ISD::LoadExtType ExtType;
13962 
13963   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
13964       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
13965       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
13966     return SDValue();
13967 
13968   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
13969                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
13970                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
13971     return SDValue();
13972 
13973   // The AND is not necessary, remove it.
13974 
13975   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
13976                                SubsNode->getValueType(1));
13977   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
13978 
13979   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
13980   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
13981 
13982   return SDValue(N, 0);
13983 }
13984 
13985 // Optimize compare with zero and branch.
13986 static SDValue performBRCONDCombine(SDNode *N,
13987                                     TargetLowering::DAGCombinerInfo &DCI,
13988                                     SelectionDAG &DAG) {
13989   MachineFunction &MF = DAG.getMachineFunction();
13990   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
13991   // will not be produced, as they are conditional branch instructions that do
13992   // not set flags.
13993   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
13994     return SDValue();
13995 
13996   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
13997     N = NV.getNode();
13998   SDValue Chain = N->getOperand(0);
13999   SDValue Dest = N->getOperand(1);
14000   SDValue CCVal = N->getOperand(2);
14001   SDValue Cmp = N->getOperand(3);
14002 
14003   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
14004   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
14005   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
14006     return SDValue();
14007 
14008   unsigned CmpOpc = Cmp.getOpcode();
14009   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
14010     return SDValue();
14011 
14012   // Only attempt folding if there is only one use of the flag and no use of the
14013   // value.
14014   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
14015     return SDValue();
14016 
14017   SDValue LHS = Cmp.getOperand(0);
14018   SDValue RHS = Cmp.getOperand(1);
14019 
14020   assert(LHS.getValueType() == RHS.getValueType() &&
14021          "Expected the value type to be the same for both operands!");
14022   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
14023     return SDValue();
14024 
14025   if (isNullConstant(LHS))
14026     std::swap(LHS, RHS);
14027 
14028   if (!isNullConstant(RHS))
14029     return SDValue();
14030 
14031   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
14032       LHS.getOpcode() == ISD::SRL)
14033     return SDValue();
14034 
14035   // Fold the compare into the branch instruction.
14036   SDValue BR;
14037   if (CC == AArch64CC::EQ)
14038     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14039   else
14040     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14041 
14042   // Do not add new nodes to DAG combiner worklist.
14043   DCI.CombineTo(N, BR, false);
14044 
14045   return SDValue();
14046 }
14047 
14048 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
14049 // as well as whether the test should be inverted.  This code is required to
14050 // catch these cases (as opposed to standard dag combines) because
14051 // AArch64ISD::TBZ is matched during legalization.
14052 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
14053                                  SelectionDAG &DAG) {
14054 
14055   if (!Op->hasOneUse())
14056     return Op;
14057 
14058   // We don't handle undef/constant-fold cases below, as they should have
14059   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
14060   // etc.)
14061 
14062   // (tbz (trunc x), b) -> (tbz x, b)
14063   // This case is just here to enable more of the below cases to be caught.
14064   if (Op->getOpcode() == ISD::TRUNCATE &&
14065       Bit < Op->getValueType(0).getSizeInBits()) {
14066     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14067   }
14068 
14069   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
14070   if (Op->getOpcode() == ISD::ANY_EXTEND &&
14071       Bit < Op->getOperand(0).getValueSizeInBits()) {
14072     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14073   }
14074 
14075   if (Op->getNumOperands() != 2)
14076     return Op;
14077 
14078   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14079   if (!C)
14080     return Op;
14081 
14082   switch (Op->getOpcode()) {
14083   default:
14084     return Op;
14085 
14086   // (tbz (and x, m), b) -> (tbz x, b)
14087   case ISD::AND:
14088     if ((C->getZExtValue() >> Bit) & 1)
14089       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14090     return Op;
14091 
14092   // (tbz (shl x, c), b) -> (tbz x, b-c)
14093   case ISD::SHL:
14094     if (C->getZExtValue() <= Bit &&
14095         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14096       Bit = Bit - C->getZExtValue();
14097       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14098     }
14099     return Op;
14100 
14101   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
14102   case ISD::SRA:
14103     Bit = Bit + C->getZExtValue();
14104     if (Bit >= Op->getValueType(0).getSizeInBits())
14105       Bit = Op->getValueType(0).getSizeInBits() - 1;
14106     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14107 
14108   // (tbz (srl x, c), b) -> (tbz x, b+c)
14109   case ISD::SRL:
14110     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14111       Bit = Bit + C->getZExtValue();
14112       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14113     }
14114     return Op;
14115 
14116   // (tbz (xor x, -1), b) -> (tbnz x, b)
14117   case ISD::XOR:
14118     if ((C->getZExtValue() >> Bit) & 1)
14119       Invert = !Invert;
14120     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14121   }
14122 }
14123 
14124 // Optimize test single bit zero/non-zero and branch.
14125 static SDValue performTBZCombine(SDNode *N,
14126                                  TargetLowering::DAGCombinerInfo &DCI,
14127                                  SelectionDAG &DAG) {
14128   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14129   bool Invert = false;
14130   SDValue TestSrc = N->getOperand(1);
14131   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
14132 
14133   if (TestSrc == NewTestSrc)
14134     return SDValue();
14135 
14136   unsigned NewOpc = N->getOpcode();
14137   if (Invert) {
14138     if (NewOpc == AArch64ISD::TBZ)
14139       NewOpc = AArch64ISD::TBNZ;
14140     else {
14141       assert(NewOpc == AArch64ISD::TBNZ);
14142       NewOpc = AArch64ISD::TBZ;
14143     }
14144   }
14145 
14146   SDLoc DL(N);
14147   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
14148                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
14149 }
14150 
14151 // vselect (v1i1 setcc) ->
14152 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
14153 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
14154 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
14155 // such VSELECT.
14156 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
14157   SDValue N0 = N->getOperand(0);
14158   EVT CCVT = N0.getValueType();
14159 
14160   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
14161       CCVT.getVectorElementType() != MVT::i1)
14162     return SDValue();
14163 
14164   EVT ResVT = N->getValueType(0);
14165   EVT CmpVT = N0.getOperand(0).getValueType();
14166   // Only combine when the result type is of the same size as the compared
14167   // operands.
14168   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
14169     return SDValue();
14170 
14171   SDValue IfTrue = N->getOperand(1);
14172   SDValue IfFalse = N->getOperand(2);
14173   SDValue SetCC =
14174       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
14175                    N0.getOperand(0), N0.getOperand(1),
14176                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
14177   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
14178                      IfTrue, IfFalse);
14179 }
14180 
14181 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
14182 /// the compare-mask instructions rather than going via NZCV, even if LHS and
14183 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
14184 /// with a vector one followed by a DUP shuffle on the result.
14185 static SDValue performSelectCombine(SDNode *N,
14186                                     TargetLowering::DAGCombinerInfo &DCI) {
14187   SelectionDAG &DAG = DCI.DAG;
14188   SDValue N0 = N->getOperand(0);
14189   EVT ResVT = N->getValueType(0);
14190 
14191   if (N0.getOpcode() != ISD::SETCC)
14192     return SDValue();
14193 
14194   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
14195   // scalar SetCCResultType. We also don't expect vectors, because we assume
14196   // that selects fed by vector SETCCs are canonicalized to VSELECT.
14197   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
14198          "Scalar-SETCC feeding SELECT has unexpected result type!");
14199 
14200   // If NumMaskElts == 0, the comparison is larger than select result. The
14201   // largest real NEON comparison is 64-bits per lane, which means the result is
14202   // at most 32-bits and an illegal vector. Just bail out for now.
14203   EVT SrcVT = N0.getOperand(0).getValueType();
14204 
14205   // Don't try to do this optimization when the setcc itself has i1 operands.
14206   // There are no legal vectors of i1, so this would be pointless.
14207   if (SrcVT == MVT::i1)
14208     return SDValue();
14209 
14210   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
14211   if (!ResVT.isVector() || NumMaskElts == 0)
14212     return SDValue();
14213 
14214   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
14215   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
14216 
14217   // Also bail out if the vector CCVT isn't the same size as ResVT.
14218   // This can happen if the SETCC operand size doesn't divide the ResVT size
14219   // (e.g., f64 vs v3f32).
14220   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
14221     return SDValue();
14222 
14223   // Make sure we didn't create illegal types, if we're not supposed to.
14224   assert(DCI.isBeforeLegalize() ||
14225          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
14226 
14227   // First perform a vector comparison, where lane 0 is the one we're interested
14228   // in.
14229   SDLoc DL(N0);
14230   SDValue LHS =
14231       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
14232   SDValue RHS =
14233       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
14234   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
14235 
14236   // Now duplicate the comparison mask we want across all other lanes.
14237   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
14238   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
14239   Mask = DAG.getNode(ISD::BITCAST, DL,
14240                      ResVT.changeVectorElementTypeToInteger(), Mask);
14241 
14242   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
14243 }
14244 
14245 /// Get rid of unnecessary NVCASTs (that don't change the type).
14246 static SDValue performNVCASTCombine(SDNode *N) {
14247   if (N->getValueType(0) == N->getOperand(0).getValueType())
14248     return N->getOperand(0);
14249 
14250   return SDValue();
14251 }
14252 
14253 // If all users of the globaladdr are of the form (globaladdr + constant), find
14254 // the smallest constant, fold it into the globaladdr's offset and rewrite the
14255 // globaladdr as (globaladdr + constant) - constant.
14256 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
14257                                            const AArch64Subtarget *Subtarget,
14258                                            const TargetMachine &TM) {
14259   auto *GN = cast<GlobalAddressSDNode>(N);
14260   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
14261       AArch64II::MO_NO_FLAG)
14262     return SDValue();
14263 
14264   uint64_t MinOffset = -1ull;
14265   for (SDNode *N : GN->uses()) {
14266     if (N->getOpcode() != ISD::ADD)
14267       return SDValue();
14268     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
14269     if (!C)
14270       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14271     if (!C)
14272       return SDValue();
14273     MinOffset = std::min(MinOffset, C->getZExtValue());
14274   }
14275   uint64_t Offset = MinOffset + GN->getOffset();
14276 
14277   // Require that the new offset is larger than the existing one. Otherwise, we
14278   // can end up oscillating between two possible DAGs, for example,
14279   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
14280   if (Offset <= uint64_t(GN->getOffset()))
14281     return SDValue();
14282 
14283   // Check whether folding this offset is legal. It must not go out of bounds of
14284   // the referenced object to avoid violating the code model, and must be
14285   // smaller than 2^21 because this is the largest offset expressible in all
14286   // object formats.
14287   //
14288   // This check also prevents us from folding negative offsets, which will end
14289   // up being treated in the same way as large positive ones. They could also
14290   // cause code model violations, and aren't really common enough to matter.
14291   if (Offset >= (1 << 21))
14292     return SDValue();
14293 
14294   const GlobalValue *GV = GN->getGlobal();
14295   Type *T = GV->getValueType();
14296   if (!T->isSized() ||
14297       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
14298     return SDValue();
14299 
14300   SDLoc DL(GN);
14301   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
14302   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
14303                      DAG.getConstant(MinOffset, DL, MVT::i64));
14304 }
14305 
14306 // Turns the vector of indices into a vector of byte offstes by scaling Offset
14307 // by (BitWidth / 8).
14308 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
14309                                           SDLoc DL, unsigned BitWidth) {
14310   assert(Offset.getValueType().isScalableVector() &&
14311          "This method is only for scalable vectors of offsets");
14312 
14313   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
14314   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
14315 
14316   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
14317 }
14318 
14319 /// Check if the value of \p OffsetInBytes can be used as an immediate for
14320 /// the gather load/prefetch and scatter store instructions with vector base and
14321 /// immediate offset addressing mode:
14322 ///
14323 ///      [<Zn>.[S|D]{, #<imm>}]
14324 ///
14325 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
14326 
14327 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
14328                                                   unsigned ScalarSizeInBytes) {
14329   // The immediate is not a multiple of the scalar size.
14330   if (OffsetInBytes % ScalarSizeInBytes)
14331     return false;
14332 
14333   // The immediate is out of range.
14334   if (OffsetInBytes / ScalarSizeInBytes > 31)
14335     return false;
14336 
14337   return true;
14338 }
14339 
14340 /// Check if the value of \p Offset represents a valid immediate for the SVE
14341 /// gather load/prefetch and scatter store instructiona with vector base and
14342 /// immediate offset addressing mode:
14343 ///
14344 ///      [<Zn>.[S|D]{, #<imm>}]
14345 ///
14346 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
14347 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
14348                                            unsigned ScalarSizeInBytes) {
14349   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
14350   return OffsetConst && isValidImmForSVEVecImmAddrMode(
14351                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
14352 }
14353 
14354 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
14355                                           unsigned Opcode,
14356                                           bool OnlyPackedOffsets = true) {
14357   const SDValue Src = N->getOperand(2);
14358   const EVT SrcVT = Src->getValueType(0);
14359   assert(SrcVT.isScalableVector() &&
14360          "Scatter stores are only possible for SVE vectors");
14361 
14362   SDLoc DL(N);
14363   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
14364 
14365   // Make sure that source data will fit into an SVE register
14366   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14367     return SDValue();
14368 
14369   // For FPs, ACLE only supports _packed_ single and double precision types.
14370   if (SrcElVT.isFloatingPoint())
14371     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
14372       return SDValue();
14373 
14374   // Depending on the addressing mode, this is either a pointer or a vector of
14375   // pointers (that fits into one register)
14376   SDValue Base = N->getOperand(4);
14377   // Depending on the addressing mode, this is either a single offset or a
14378   // vector of offsets  (that fits into one register)
14379   SDValue Offset = N->getOperand(5);
14380 
14381   // For "scalar + vector of indices", just scale the indices. This only
14382   // applies to non-temporal scatters because there's no instruction that takes
14383   // indicies.
14384   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
14385     Offset =
14386         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
14387     Opcode = AArch64ISD::SSTNT1_PRED;
14388   }
14389 
14390   // In the case of non-temporal gather loads there's only one SVE instruction
14391   // per data-size: "scalar + vector", i.e.
14392   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14393   // Since we do have intrinsics that allow the arguments to be in a different
14394   // order, we may need to swap them to match the spec.
14395   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
14396     std::swap(Base, Offset);
14397 
14398   // SST1_IMM requires that the offset is an immediate that is:
14399   //    * a multiple of #SizeInBytes,
14400   //    * in the range [0, 31 x #SizeInBytes],
14401   // where #SizeInBytes is the size in bytes of the stored items. For
14402   // immediates outside that range and non-immediate scalar offsets use SST1 or
14403   // SST1_UXTW instead.
14404   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
14405     if (!isValidImmForSVEVecImmAddrMode(Offset,
14406                                         SrcVT.getScalarSizeInBits() / 8)) {
14407       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14408         Opcode = AArch64ISD::SST1_UXTW_PRED;
14409       else
14410         Opcode = AArch64ISD::SST1_PRED;
14411 
14412       std::swap(Base, Offset);
14413     }
14414   }
14415 
14416   auto &TLI = DAG.getTargetLoweringInfo();
14417   if (!TLI.isTypeLegal(Base.getValueType()))
14418     return SDValue();
14419 
14420   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
14421   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14422   // nxv2i64. Legalize accordingly.
14423   if (!OnlyPackedOffsets &&
14424       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14425     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14426 
14427   if (!TLI.isTypeLegal(Offset.getValueType()))
14428     return SDValue();
14429 
14430   // Source value type that is representable in hardware
14431   EVT HwSrcVt = getSVEContainerType(SrcVT);
14432 
14433   // Keep the original type of the input data to store - this is needed to be
14434   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
14435   // FP values we want the integer equivalent, so just use HwSrcVt.
14436   SDValue InputVT = DAG.getValueType(SrcVT);
14437   if (SrcVT.isFloatingPoint())
14438     InputVT = DAG.getValueType(HwSrcVt);
14439 
14440   SDVTList VTs = DAG.getVTList(MVT::Other);
14441   SDValue SrcNew;
14442 
14443   if (Src.getValueType().isFloatingPoint())
14444     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
14445   else
14446     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
14447 
14448   SDValue Ops[] = {N->getOperand(0), // Chain
14449                    SrcNew,
14450                    N->getOperand(3), // Pg
14451                    Base,
14452                    Offset,
14453                    InputVT};
14454 
14455   return DAG.getNode(Opcode, DL, VTs, Ops);
14456 }
14457 
14458 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
14459                                         unsigned Opcode,
14460                                         bool OnlyPackedOffsets = true) {
14461   const EVT RetVT = N->getValueType(0);
14462   assert(RetVT.isScalableVector() &&
14463          "Gather loads are only possible for SVE vectors");
14464 
14465   SDLoc DL(N);
14466 
14467   // Make sure that the loaded data will fit into an SVE register
14468   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14469     return SDValue();
14470 
14471   // Depending on the addressing mode, this is either a pointer or a vector of
14472   // pointers (that fits into one register)
14473   SDValue Base = N->getOperand(3);
14474   // Depending on the addressing mode, this is either a single offset or a
14475   // vector of offsets  (that fits into one register)
14476   SDValue Offset = N->getOperand(4);
14477 
14478   // For "scalar + vector of indices", just scale the indices. This only
14479   // applies to non-temporal gathers because there's no instruction that takes
14480   // indicies.
14481   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
14482     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
14483                                         RetVT.getScalarSizeInBits());
14484     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
14485   }
14486 
14487   // In the case of non-temporal gather loads there's only one SVE instruction
14488   // per data-size: "scalar + vector", i.e.
14489   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14490   // Since we do have intrinsics that allow the arguments to be in a different
14491   // order, we may need to swap them to match the spec.
14492   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
14493       Offset.getValueType().isVector())
14494     std::swap(Base, Offset);
14495 
14496   // GLD{FF}1_IMM requires that the offset is an immediate that is:
14497   //    * a multiple of #SizeInBytes,
14498   //    * in the range [0, 31 x #SizeInBytes],
14499   // where #SizeInBytes is the size in bytes of the loaded items. For
14500   // immediates outside that range and non-immediate scalar offsets use
14501   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
14502   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
14503       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
14504     if (!isValidImmForSVEVecImmAddrMode(Offset,
14505                                         RetVT.getScalarSizeInBits() / 8)) {
14506       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14507         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14508                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
14509                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
14510       else
14511         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14512                      ? AArch64ISD::GLD1_MERGE_ZERO
14513                      : AArch64ISD::GLDFF1_MERGE_ZERO;
14514 
14515       std::swap(Base, Offset);
14516     }
14517   }
14518 
14519   auto &TLI = DAG.getTargetLoweringInfo();
14520   if (!TLI.isTypeLegal(Base.getValueType()))
14521     return SDValue();
14522 
14523   // Some gather load variants allow unpacked offsets, but only as nxv2i32
14524   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14525   // nxv2i64. Legalize accordingly.
14526   if (!OnlyPackedOffsets &&
14527       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14528     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14529 
14530   // Return value type that is representable in hardware
14531   EVT HwRetVt = getSVEContainerType(RetVT);
14532 
14533   // Keep the original output value type around - this is needed to be able to
14534   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
14535   // values we want the integer equivalent, so just use HwRetVT.
14536   SDValue OutVT = DAG.getValueType(RetVT);
14537   if (RetVT.isFloatingPoint())
14538     OutVT = DAG.getValueType(HwRetVt);
14539 
14540   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
14541   SDValue Ops[] = {N->getOperand(0), // Chain
14542                    N->getOperand(2), // Pg
14543                    Base, Offset, OutVT};
14544 
14545   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
14546   SDValue LoadChain = SDValue(Load.getNode(), 1);
14547 
14548   if (RetVT.isInteger() && (RetVT != HwRetVt))
14549     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
14550 
14551   // If the original return value was FP, bitcast accordingly. Doing it here
14552   // means that we can avoid adding TableGen patterns for FPs.
14553   if (RetVT.isFloatingPoint())
14554     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
14555 
14556   return DAG.getMergeValues({Load, LoadChain}, DL);
14557 }
14558 
14559 static SDValue
14560 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14561                               SelectionDAG &DAG) {
14562   if (DCI.isBeforeLegalizeOps())
14563     return SDValue();
14564 
14565   SDLoc DL(N);
14566   SDValue Src = N->getOperand(0);
14567   unsigned Opc = Src->getOpcode();
14568 
14569   // Sign extend of an unsigned unpack -> signed unpack
14570   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
14571 
14572     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
14573                                                : AArch64ISD::SUNPKLO;
14574 
14575     // Push the sign extend to the operand of the unpack
14576     // This is necessary where, for example, the operand of the unpack
14577     // is another unpack:
14578     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
14579     // ->
14580     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
14581     // ->
14582     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
14583     SDValue ExtOp = Src->getOperand(0);
14584     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
14585     EVT EltTy = VT.getVectorElementType();
14586     (void)EltTy;
14587 
14588     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
14589            "Sign extending from an invalid type");
14590 
14591     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
14592 
14593     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
14594                               ExtOp, DAG.getValueType(ExtVT));
14595 
14596     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
14597   }
14598 
14599   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
14600   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
14601   unsigned NewOpc;
14602   unsigned MemVTOpNum = 4;
14603   switch (Opc) {
14604   case AArch64ISD::LD1_MERGE_ZERO:
14605     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
14606     MemVTOpNum = 3;
14607     break;
14608   case AArch64ISD::LDNF1_MERGE_ZERO:
14609     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
14610     MemVTOpNum = 3;
14611     break;
14612   case AArch64ISD::LDFF1_MERGE_ZERO:
14613     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
14614     MemVTOpNum = 3;
14615     break;
14616   case AArch64ISD::GLD1_MERGE_ZERO:
14617     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
14618     break;
14619   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
14620     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
14621     break;
14622   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
14623     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
14624     break;
14625   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
14626     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
14627     break;
14628   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
14629     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
14630     break;
14631   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
14632     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
14633     break;
14634   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
14635     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
14636     break;
14637   case AArch64ISD::GLDFF1_MERGE_ZERO:
14638     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
14639     break;
14640   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
14641     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
14642     break;
14643   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
14644     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
14645     break;
14646   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
14647     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
14648     break;
14649   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
14650     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
14651     break;
14652   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
14653     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
14654     break;
14655   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
14656     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
14657     break;
14658   case AArch64ISD::GLDNT1_MERGE_ZERO:
14659     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
14660     break;
14661   default:
14662     return SDValue();
14663   }
14664 
14665   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
14666   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
14667 
14668   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
14669     return SDValue();
14670 
14671   EVT DstVT = N->getValueType(0);
14672   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
14673 
14674   SmallVector<SDValue, 5> Ops;
14675   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
14676     Ops.push_back(Src->getOperand(I));
14677 
14678   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
14679   DCI.CombineTo(N, ExtLoad);
14680   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
14681 
14682   // Return N so it doesn't get rechecked
14683   return SDValue(N, 0);
14684 }
14685 
14686 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
14687 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
14688 /// != nxv2i32) do not need legalization.
14689 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
14690   const unsigned OffsetPos = 4;
14691   SDValue Offset = N->getOperand(OffsetPos);
14692 
14693   // Not an unpacked vector, bail out.
14694   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
14695     return SDValue();
14696 
14697   // Extend the unpacked offset vector to 64-bit lanes.
14698   SDLoc DL(N);
14699   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
14700   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14701   // Replace the offset operand with the 64-bit one.
14702   Ops[OffsetPos] = Offset;
14703 
14704   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14705 }
14706 
14707 /// Combines a node carrying the intrinsic
14708 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
14709 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
14710 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
14711 /// sve gather prefetch instruction with vector plus immediate addressing mode.
14712 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
14713                                                unsigned ScalarSizeInBytes) {
14714   const unsigned ImmPos = 4, OffsetPos = 3;
14715   // No need to combine the node if the immediate is valid...
14716   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
14717     return SDValue();
14718 
14719   // ...otherwise swap the offset base with the offset...
14720   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14721   std::swap(Ops[ImmPos], Ops[OffsetPos]);
14722   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
14723   // `aarch64_sve_prfb_gather_uxtw_index`.
14724   SDLoc DL(N);
14725   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
14726                            MVT::i64);
14727 
14728   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14729 }
14730 
14731 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
14732                                                  DAGCombinerInfo &DCI) const {
14733   SelectionDAG &DAG = DCI.DAG;
14734   switch (N->getOpcode()) {
14735   default:
14736     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
14737     break;
14738   case ISD::ABS:
14739     return performABSCombine(N, DAG, DCI, Subtarget);
14740   case ISD::ADD:
14741   case ISD::SUB:
14742     return performAddSubLongCombine(N, DCI, DAG);
14743   case ISD::XOR:
14744     return performXorCombine(N, DAG, DCI, Subtarget);
14745   case ISD::MUL:
14746     return performMulCombine(N, DAG, DCI, Subtarget);
14747   case ISD::SINT_TO_FP:
14748   case ISD::UINT_TO_FP:
14749     return performIntToFpCombine(N, DAG, Subtarget);
14750   case ISD::FP_TO_SINT:
14751   case ISD::FP_TO_UINT:
14752     return performFpToIntCombine(N, DAG, DCI, Subtarget);
14753   case ISD::FDIV:
14754     return performFDivCombine(N, DAG, DCI, Subtarget);
14755   case ISD::OR:
14756     return performORCombine(N, DCI, Subtarget);
14757   case ISD::AND:
14758     return performANDCombine(N, DCI);
14759   case ISD::SRL:
14760     return performSRLCombine(N, DCI);
14761   case ISD::INTRINSIC_WO_CHAIN:
14762     return performIntrinsicCombine(N, DCI, Subtarget);
14763   case ISD::ANY_EXTEND:
14764   case ISD::ZERO_EXTEND:
14765   case ISD::SIGN_EXTEND:
14766     return performExtendCombine(N, DCI, DAG);
14767   case ISD::SIGN_EXTEND_INREG:
14768     return performSignExtendInRegCombine(N, DCI, DAG);
14769   case ISD::TRUNCATE:
14770     return performVectorTruncateCombine(N, DCI, DAG);
14771   case ISD::CONCAT_VECTORS:
14772     return performConcatVectorsCombine(N, DCI, DAG);
14773   case ISD::SELECT:
14774     return performSelectCombine(N, DCI);
14775   case ISD::VSELECT:
14776     return performVSelectCombine(N, DCI.DAG);
14777   case ISD::LOAD:
14778     if (performTBISimplification(N->getOperand(1), DCI, DAG))
14779       return SDValue(N, 0);
14780     break;
14781   case ISD::STORE:
14782     return performSTORECombine(N, DCI, DAG, Subtarget);
14783   case AArch64ISD::BRCOND:
14784     return performBRCONDCombine(N, DCI, DAG);
14785   case AArch64ISD::TBNZ:
14786   case AArch64ISD::TBZ:
14787     return performTBZCombine(N, DCI, DAG);
14788   case AArch64ISD::CSEL:
14789     return performCONDCombine(N, DCI, DAG, 2, 3);
14790   case AArch64ISD::DUP:
14791     return performPostLD1Combine(N, DCI, false);
14792   case AArch64ISD::NVCAST:
14793     return performNVCASTCombine(N);
14794   case AArch64ISD::UZP1:
14795     return performUzpCombine(N, DAG);
14796   case ISD::INSERT_VECTOR_ELT:
14797     return performPostLD1Combine(N, DCI, true);
14798   case ISD::EXTRACT_VECTOR_ELT:
14799     return performExtractVectorEltCombine(N, DAG);
14800   case ISD::VECREDUCE_ADD:
14801     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
14802   case ISD::INTRINSIC_VOID:
14803   case ISD::INTRINSIC_W_CHAIN:
14804     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14805     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
14806       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
14807     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
14808       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
14809     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
14810       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
14811     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
14812       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
14813     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
14814     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
14815     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
14816     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
14817     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
14818     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
14819     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
14820     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
14821       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
14822     case Intrinsic::aarch64_neon_ld2:
14823     case Intrinsic::aarch64_neon_ld3:
14824     case Intrinsic::aarch64_neon_ld4:
14825     case Intrinsic::aarch64_neon_ld1x2:
14826     case Intrinsic::aarch64_neon_ld1x3:
14827     case Intrinsic::aarch64_neon_ld1x4:
14828     case Intrinsic::aarch64_neon_ld2lane:
14829     case Intrinsic::aarch64_neon_ld3lane:
14830     case Intrinsic::aarch64_neon_ld4lane:
14831     case Intrinsic::aarch64_neon_ld2r:
14832     case Intrinsic::aarch64_neon_ld3r:
14833     case Intrinsic::aarch64_neon_ld4r:
14834     case Intrinsic::aarch64_neon_st2:
14835     case Intrinsic::aarch64_neon_st3:
14836     case Intrinsic::aarch64_neon_st4:
14837     case Intrinsic::aarch64_neon_st1x2:
14838     case Intrinsic::aarch64_neon_st1x3:
14839     case Intrinsic::aarch64_neon_st1x4:
14840     case Intrinsic::aarch64_neon_st2lane:
14841     case Intrinsic::aarch64_neon_st3lane:
14842     case Intrinsic::aarch64_neon_st4lane:
14843       return performNEONPostLDSTCombine(N, DCI, DAG);
14844     case Intrinsic::aarch64_sve_ldnt1:
14845       return performLDNT1Combine(N, DAG);
14846     case Intrinsic::aarch64_sve_ld1rq:
14847       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
14848     case Intrinsic::aarch64_sve_ld1ro:
14849       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
14850     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
14851       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14852     case Intrinsic::aarch64_sve_ldnt1_gather:
14853       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14854     case Intrinsic::aarch64_sve_ldnt1_gather_index:
14855       return performGatherLoadCombine(N, DAG,
14856                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
14857     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
14858       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14859     case Intrinsic::aarch64_sve_ld1:
14860       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
14861     case Intrinsic::aarch64_sve_ldnf1:
14862       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
14863     case Intrinsic::aarch64_sve_ldff1:
14864       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
14865     case Intrinsic::aarch64_sve_st1:
14866       return performST1Combine(N, DAG);
14867     case Intrinsic::aarch64_sve_stnt1:
14868       return performSTNT1Combine(N, DAG);
14869     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
14870       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14871     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
14872       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14873     case Intrinsic::aarch64_sve_stnt1_scatter:
14874       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14875     case Intrinsic::aarch64_sve_stnt1_scatter_index:
14876       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
14877     case Intrinsic::aarch64_sve_ld1_gather:
14878       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
14879     case Intrinsic::aarch64_sve_ld1_gather_index:
14880       return performGatherLoadCombine(N, DAG,
14881                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
14882     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
14883       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
14884                                       /*OnlyPackedOffsets=*/false);
14885     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
14886       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
14887                                       /*OnlyPackedOffsets=*/false);
14888     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
14889       return performGatherLoadCombine(N, DAG,
14890                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
14891                                       /*OnlyPackedOffsets=*/false);
14892     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
14893       return performGatherLoadCombine(N, DAG,
14894                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
14895                                       /*OnlyPackedOffsets=*/false);
14896     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
14897       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14898     case Intrinsic::aarch64_sve_ldff1_gather:
14899       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14900     case Intrinsic::aarch64_sve_ldff1_gather_index:
14901       return performGatherLoadCombine(N, DAG,
14902                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14903     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14904       return performGatherLoadCombine(N, DAG,
14905                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14906                                       /*OnlyPackedOffsets=*/false);
14907     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14908       return performGatherLoadCombine(N, DAG,
14909                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14910                                       /*OnlyPackedOffsets=*/false);
14911     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14912       return performGatherLoadCombine(N, DAG,
14913                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14914                                       /*OnlyPackedOffsets=*/false);
14915     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14916       return performGatherLoadCombine(N, DAG,
14917                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14918                                       /*OnlyPackedOffsets=*/false);
14919     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14920       return performGatherLoadCombine(N, DAG,
14921                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14922     case Intrinsic::aarch64_sve_st1_scatter:
14923       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14924     case Intrinsic::aarch64_sve_st1_scatter_index:
14925       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14926     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14927       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14928                                         /*OnlyPackedOffsets=*/false);
14929     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14930       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14931                                         /*OnlyPackedOffsets=*/false);
14932     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14933       return performScatterStoreCombine(N, DAG,
14934                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
14935                                         /*OnlyPackedOffsets=*/false);
14936     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14937       return performScatterStoreCombine(N, DAG,
14938                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
14939                                         /*OnlyPackedOffsets=*/false);
14940     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14941       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14942     case Intrinsic::aarch64_sve_tuple_get: {
14943       SDLoc DL(N);
14944       SDValue Chain = N->getOperand(0);
14945       SDValue Src1 = N->getOperand(2);
14946       SDValue Idx = N->getOperand(3);
14947 
14948       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14949       EVT ResVT = N->getValueType(0);
14950       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
14951       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
14952       SDValue Val =
14953           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
14954       return DAG.getMergeValues({Val, Chain}, DL);
14955     }
14956     case Intrinsic::aarch64_sve_tuple_set: {
14957       SDLoc DL(N);
14958       SDValue Chain = N->getOperand(0);
14959       SDValue Tuple = N->getOperand(2);
14960       SDValue Idx = N->getOperand(3);
14961       SDValue Vec = N->getOperand(4);
14962 
14963       EVT TupleVT = Tuple.getValueType();
14964       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
14965 
14966       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14967       uint64_t NumLanes =
14968           Vec.getValueType().getVectorElementCount().getKnownMinValue();
14969 
14970       if ((TupleLanes % NumLanes) != 0)
14971         report_fatal_error("invalid tuple vector!");
14972 
14973       uint64_t NumVecs = TupleLanes / NumLanes;
14974 
14975       SmallVector<SDValue, 4> Opnds;
14976       for (unsigned I = 0; I < NumVecs; ++I) {
14977         if (I == IdxConst)
14978           Opnds.push_back(Vec);
14979         else {
14980           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
14981           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
14982                                       Vec.getValueType(), Tuple, ExtIdx));
14983         }
14984       }
14985       SDValue Concat =
14986           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
14987       return DAG.getMergeValues({Concat, Chain}, DL);
14988     }
14989     case Intrinsic::aarch64_sve_tuple_create2:
14990     case Intrinsic::aarch64_sve_tuple_create3:
14991     case Intrinsic::aarch64_sve_tuple_create4: {
14992       SDLoc DL(N);
14993       SDValue Chain = N->getOperand(0);
14994 
14995       SmallVector<SDValue, 4> Opnds;
14996       for (unsigned I = 2; I < N->getNumOperands(); ++I)
14997         Opnds.push_back(N->getOperand(I));
14998 
14999       EVT VT = Opnds[0].getValueType();
15000       EVT EltVT = VT.getVectorElementType();
15001       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
15002                                     VT.getVectorElementCount() *
15003                                         (N->getNumOperands() - 2));
15004       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
15005       return DAG.getMergeValues({Concat, Chain}, DL);
15006     }
15007     case Intrinsic::aarch64_sve_ld2:
15008     case Intrinsic::aarch64_sve_ld3:
15009     case Intrinsic::aarch64_sve_ld4: {
15010       SDLoc DL(N);
15011       SDValue Chain = N->getOperand(0);
15012       SDValue Mask = N->getOperand(2);
15013       SDValue BasePtr = N->getOperand(3);
15014       SDValue LoadOps[] = {Chain, Mask, BasePtr};
15015       unsigned IntrinsicID =
15016           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15017       SDValue Result =
15018           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
15019       return DAG.getMergeValues({Result, Chain}, DL);
15020     }
15021     default:
15022       break;
15023     }
15024     break;
15025   case ISD::GlobalAddress:
15026     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
15027   }
15028   return SDValue();
15029 }
15030 
15031 // Check if the return value is used as only a return value, as otherwise
15032 // we can't perform a tail-call. In particular, we need to check for
15033 // target ISD nodes that are returns and any other "odd" constructs
15034 // that the generic analysis code won't necessarily catch.
15035 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
15036                                                SDValue &Chain) const {
15037   if (N->getNumValues() != 1)
15038     return false;
15039   if (!N->hasNUsesOfValue(1, 0))
15040     return false;
15041 
15042   SDValue TCChain = Chain;
15043   SDNode *Copy = *N->use_begin();
15044   if (Copy->getOpcode() == ISD::CopyToReg) {
15045     // If the copy has a glue operand, we conservatively assume it isn't safe to
15046     // perform a tail call.
15047     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
15048         MVT::Glue)
15049       return false;
15050     TCChain = Copy->getOperand(0);
15051   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
15052     return false;
15053 
15054   bool HasRet = false;
15055   for (SDNode *Node : Copy->uses()) {
15056     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
15057       return false;
15058     HasRet = true;
15059   }
15060 
15061   if (!HasRet)
15062     return false;
15063 
15064   Chain = TCChain;
15065   return true;
15066 }
15067 
15068 // Return whether the an instruction can potentially be optimized to a tail
15069 // call. This will cause the optimizers to attempt to move, or duplicate,
15070 // return instructions to help enable tail call optimizations for this
15071 // instruction.
15072 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15073   return CI->isTailCall();
15074 }
15075 
15076 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
15077                                                    SDValue &Offset,
15078                                                    ISD::MemIndexedMode &AM,
15079                                                    bool &IsInc,
15080                                                    SelectionDAG &DAG) const {
15081   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
15082     return false;
15083 
15084   Base = Op->getOperand(0);
15085   // All of the indexed addressing mode instructions take a signed
15086   // 9 bit immediate offset.
15087   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
15088     int64_t RHSC = RHS->getSExtValue();
15089     if (Op->getOpcode() == ISD::SUB)
15090       RHSC = -(uint64_t)RHSC;
15091     if (!isInt<9>(RHSC))
15092       return false;
15093     IsInc = (Op->getOpcode() == ISD::ADD);
15094     Offset = Op->getOperand(1);
15095     return true;
15096   }
15097   return false;
15098 }
15099 
15100 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15101                                                       SDValue &Offset,
15102                                                       ISD::MemIndexedMode &AM,
15103                                                       SelectionDAG &DAG) const {
15104   EVT VT;
15105   SDValue Ptr;
15106   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15107     VT = LD->getMemoryVT();
15108     Ptr = LD->getBasePtr();
15109   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15110     VT = ST->getMemoryVT();
15111     Ptr = ST->getBasePtr();
15112   } else
15113     return false;
15114 
15115   bool IsInc;
15116   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
15117     return false;
15118   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
15119   return true;
15120 }
15121 
15122 bool AArch64TargetLowering::getPostIndexedAddressParts(
15123     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
15124     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
15125   EVT VT;
15126   SDValue Ptr;
15127   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15128     VT = LD->getMemoryVT();
15129     Ptr = LD->getBasePtr();
15130   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15131     VT = ST->getMemoryVT();
15132     Ptr = ST->getBasePtr();
15133   } else
15134     return false;
15135 
15136   bool IsInc;
15137   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
15138     return false;
15139   // Post-indexing updates the base, so it's not a valid transform
15140   // if that's not the same as the load's pointer.
15141   if (Ptr != Base)
15142     return false;
15143   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
15144   return true;
15145 }
15146 
15147 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
15148                                   SelectionDAG &DAG) {
15149   SDLoc DL(N);
15150   SDValue Op = N->getOperand(0);
15151 
15152   if (N->getValueType(0) != MVT::i16 ||
15153       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
15154     return;
15155 
15156   Op = SDValue(
15157       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
15158                          DAG.getUNDEF(MVT::i32), Op,
15159                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
15160       0);
15161   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
15162   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
15163 }
15164 
15165 static void ReplaceReductionResults(SDNode *N,
15166                                     SmallVectorImpl<SDValue> &Results,
15167                                     SelectionDAG &DAG, unsigned InterOp,
15168                                     unsigned AcrossOp) {
15169   EVT LoVT, HiVT;
15170   SDValue Lo, Hi;
15171   SDLoc dl(N);
15172   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
15173   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
15174   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
15175   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
15176   Results.push_back(SplitVal);
15177 }
15178 
15179 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
15180   SDLoc DL(N);
15181   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
15182   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
15183                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
15184                                        DAG.getConstant(64, DL, MVT::i64)));
15185   return std::make_pair(Lo, Hi);
15186 }
15187 
15188 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
15189     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15190   SDValue In = N->getOperand(0);
15191   EVT InVT = In.getValueType();
15192 
15193   // Common code will handle these just fine.
15194   if (!InVT.isScalableVector() || !InVT.isInteger())
15195     return;
15196 
15197   SDLoc DL(N);
15198   EVT VT = N->getValueType(0);
15199 
15200   // The following checks bail if this is not a halving operation.
15201 
15202   ElementCount ResEC = VT.getVectorElementCount();
15203 
15204   if (InVT.getVectorElementCount() != (ResEC * 2))
15205     return;
15206 
15207   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
15208   if (!CIndex)
15209     return;
15210 
15211   unsigned Index = CIndex->getZExtValue();
15212   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
15213     return;
15214 
15215   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
15216   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
15217 
15218   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
15219   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
15220 }
15221 
15222 // Create an even/odd pair of X registers holding integer value V.
15223 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
15224   SDLoc dl(V.getNode());
15225   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
15226   SDValue VHi = DAG.getAnyExtOrTrunc(
15227       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
15228       dl, MVT::i64);
15229   if (DAG.getDataLayout().isBigEndian())
15230     std::swap (VLo, VHi);
15231   SDValue RegClass =
15232       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
15233   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
15234   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
15235   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
15236   return SDValue(
15237       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
15238 }
15239 
15240 static void ReplaceCMP_SWAP_128Results(SDNode *N,
15241                                        SmallVectorImpl<SDValue> &Results,
15242                                        SelectionDAG &DAG,
15243                                        const AArch64Subtarget *Subtarget) {
15244   assert(N->getValueType(0) == MVT::i128 &&
15245          "AtomicCmpSwap on types less than 128 should be legal");
15246 
15247   if (Subtarget->hasLSE()) {
15248     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
15249     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
15250     SDValue Ops[] = {
15251         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
15252         createGPRPairNode(DAG, N->getOperand(3)), // Store value
15253         N->getOperand(1), // Ptr
15254         N->getOperand(0), // Chain in
15255     };
15256 
15257     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15258 
15259     unsigned Opcode;
15260     switch (MemOp->getOrdering()) {
15261     case AtomicOrdering::Monotonic:
15262       Opcode = AArch64::CASPX;
15263       break;
15264     case AtomicOrdering::Acquire:
15265       Opcode = AArch64::CASPAX;
15266       break;
15267     case AtomicOrdering::Release:
15268       Opcode = AArch64::CASPLX;
15269       break;
15270     case AtomicOrdering::AcquireRelease:
15271     case AtomicOrdering::SequentiallyConsistent:
15272       Opcode = AArch64::CASPALX;
15273       break;
15274     default:
15275       llvm_unreachable("Unexpected ordering!");
15276     }
15277 
15278     MachineSDNode *CmpSwap = DAG.getMachineNode(
15279         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
15280     DAG.setNodeMemRefs(CmpSwap, {MemOp});
15281 
15282     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
15283     if (DAG.getDataLayout().isBigEndian())
15284       std::swap(SubReg1, SubReg2);
15285     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
15286                                             SDValue(CmpSwap, 0));
15287     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
15288                                             SDValue(CmpSwap, 0));
15289     Results.push_back(
15290         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
15291     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
15292     return;
15293   }
15294 
15295   auto Desired = splitInt128(N->getOperand(2), DAG);
15296   auto New = splitInt128(N->getOperand(3), DAG);
15297   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
15298                    New.first,        New.second,    N->getOperand(0)};
15299   SDNode *CmpSwap = DAG.getMachineNode(
15300       AArch64::CMP_SWAP_128, SDLoc(N),
15301       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
15302 
15303   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15304   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
15305 
15306   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15307                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
15308   Results.push_back(SDValue(CmpSwap, 3));
15309 }
15310 
15311 void AArch64TargetLowering::ReplaceNodeResults(
15312     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15313   switch (N->getOpcode()) {
15314   default:
15315     llvm_unreachable("Don't know how to custom expand this");
15316   case ISD::BITCAST:
15317     ReplaceBITCASTResults(N, Results, DAG);
15318     return;
15319   case ISD::VECREDUCE_ADD:
15320   case ISD::VECREDUCE_SMAX:
15321   case ISD::VECREDUCE_SMIN:
15322   case ISD::VECREDUCE_UMAX:
15323   case ISD::VECREDUCE_UMIN:
15324     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
15325     return;
15326 
15327   case ISD::CTPOP:
15328     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
15329     return;
15330   case AArch64ISD::SADDV:
15331     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
15332     return;
15333   case AArch64ISD::UADDV:
15334     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
15335     return;
15336   case AArch64ISD::SMINV:
15337     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
15338     return;
15339   case AArch64ISD::UMINV:
15340     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
15341     return;
15342   case AArch64ISD::SMAXV:
15343     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
15344     return;
15345   case AArch64ISD::UMAXV:
15346     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
15347     return;
15348   case ISD::FP_TO_UINT:
15349   case ISD::FP_TO_SINT:
15350     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
15351     // Let normal code take care of it by not adding anything to Results.
15352     return;
15353   case ISD::ATOMIC_CMP_SWAP:
15354     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
15355     return;
15356   case ISD::LOAD: {
15357     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
15358            "unexpected load's value type");
15359     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
15360     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
15361       // Non-volatile loads are optimized later in AArch64's load/store
15362       // optimizer.
15363       return;
15364     }
15365 
15366     SDValue Result = DAG.getMemIntrinsicNode(
15367         AArch64ISD::LDP, SDLoc(N),
15368         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
15369         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
15370         LoadNode->getMemOperand());
15371 
15372     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15373                                Result.getValue(0), Result.getValue(1));
15374     Results.append({Pair, Result.getValue(2) /* Chain */});
15375     return;
15376   }
15377   case ISD::EXTRACT_SUBVECTOR:
15378     ReplaceExtractSubVectorResults(N, Results, DAG);
15379     return;
15380   case ISD::INTRINSIC_WO_CHAIN: {
15381     EVT VT = N->getValueType(0);
15382     assert((VT == MVT::i8 || VT == MVT::i16) &&
15383            "custom lowering for unexpected type");
15384 
15385     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
15386     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15387     switch (IntID) {
15388     default:
15389       return;
15390     case Intrinsic::aarch64_sve_clasta_n: {
15391       SDLoc DL(N);
15392       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15393       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
15394                            N->getOperand(1), Op2, N->getOperand(3));
15395       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15396       return;
15397     }
15398     case Intrinsic::aarch64_sve_clastb_n: {
15399       SDLoc DL(N);
15400       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15401       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
15402                            N->getOperand(1), Op2, N->getOperand(3));
15403       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15404       return;
15405     }
15406     case Intrinsic::aarch64_sve_lasta: {
15407       SDLoc DL(N);
15408       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
15409                            N->getOperand(1), N->getOperand(2));
15410       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15411       return;
15412     }
15413     case Intrinsic::aarch64_sve_lastb: {
15414       SDLoc DL(N);
15415       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
15416                            N->getOperand(1), N->getOperand(2));
15417       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15418       return;
15419     }
15420     }
15421   }
15422   }
15423 }
15424 
15425 bool AArch64TargetLowering::useLoadStackGuardNode() const {
15426   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
15427     return TargetLowering::useLoadStackGuardNode();
15428   return true;
15429 }
15430 
15431 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
15432   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15433   // reciprocal if there are three or more FDIVs.
15434   return 3;
15435 }
15436 
15437 TargetLoweringBase::LegalizeTypeAction
15438 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
15439   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
15440   // v4i16, v2i32 instead of to promote.
15441   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
15442       VT == MVT::v1f32)
15443     return TypeWidenVector;
15444 
15445   return TargetLoweringBase::getPreferredVectorAction(VT);
15446 }
15447 
15448 // Loads and stores less than 128-bits are already atomic; ones above that
15449 // are doomed anyway, so defer to the default libcall and blame the OS when
15450 // things go wrong.
15451 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15452   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15453   return Size == 128;
15454 }
15455 
15456 // Loads and stores less than 128-bits are already atomic; ones above that
15457 // are doomed anyway, so defer to the default libcall and blame the OS when
15458 // things go wrong.
15459 TargetLowering::AtomicExpansionKind
15460 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15461   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15462   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
15463 }
15464 
15465 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
15466 TargetLowering::AtomicExpansionKind
15467 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15468   if (AI->isFloatingPointOperation())
15469     return AtomicExpansionKind::CmpXChg;
15470 
15471   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15472   if (Size > 128) return AtomicExpansionKind::None;
15473   // Nand not supported in LSE.
15474   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
15475   // Leave 128 bits to LLSC.
15476   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
15477 }
15478 
15479 TargetLowering::AtomicExpansionKind
15480 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
15481     AtomicCmpXchgInst *AI) const {
15482   // If subtarget has LSE, leave cmpxchg intact for codegen.
15483   if (Subtarget->hasLSE())
15484     return AtomicExpansionKind::None;
15485   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15486   // implement cmpxchg without spilling. If the address being exchanged is also
15487   // on the stack and close enough to the spill slot, this can lead to a
15488   // situation where the monitor always gets cleared and the atomic operation
15489   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15490   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
15491     return AtomicExpansionKind::None;
15492   return AtomicExpansionKind::LLSC;
15493 }
15494 
15495 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15496                                              AtomicOrdering Ord) const {
15497   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15498   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15499   bool IsAcquire = isAcquireOrStronger(Ord);
15500 
15501   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
15502   // intrinsic must return {i64, i64} and we have to recombine them into a
15503   // single i128 here.
15504   if (ValTy->getPrimitiveSizeInBits() == 128) {
15505     Intrinsic::ID Int =
15506         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
15507     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
15508 
15509     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15510     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
15511 
15512     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15513     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15514     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15515     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15516     return Builder.CreateOr(
15517         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
15518   }
15519 
15520   Type *Tys[] = { Addr->getType() };
15521   Intrinsic::ID Int =
15522       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
15523   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
15524 
15525   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
15526 
15527   const DataLayout &DL = M->getDataLayout();
15528   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
15529   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
15530 
15531   return Builder.CreateBitCast(Trunc, EltTy);
15532 }
15533 
15534 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15535     IRBuilder<> &Builder) const {
15536   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15537   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
15538 }
15539 
15540 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
15541                                                    Value *Val, Value *Addr,
15542                                                    AtomicOrdering Ord) const {
15543   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15544   bool IsRelease = isReleaseOrStronger(Ord);
15545 
15546   // Since the intrinsics must have legal type, the i128 intrinsics take two
15547   // parameters: "i64, i64". We must marshal Val into the appropriate form
15548   // before the call.
15549   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
15550     Intrinsic::ID Int =
15551         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
15552     Function *Stxr = Intrinsic::getDeclaration(M, Int);
15553     Type *Int64Ty = Type::getInt64Ty(M->getContext());
15554 
15555     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
15556     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
15557     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15558     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
15559   }
15560 
15561   Intrinsic::ID Int =
15562       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
15563   Type *Tys[] = { Addr->getType() };
15564   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
15565 
15566   const DataLayout &DL = M->getDataLayout();
15567   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
15568   Val = Builder.CreateBitCast(Val, IntValTy);
15569 
15570   return Builder.CreateCall(Stxr,
15571                             {Builder.CreateZExtOrBitCast(
15572                                  Val, Stxr->getFunctionType()->getParamType(0)),
15573                              Addr});
15574 }
15575 
15576 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
15577     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15578   if (Ty->isArrayTy())
15579     return true;
15580 
15581   const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
15582   if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
15583     return true;
15584 
15585   return false;
15586 }
15587 
15588 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
15589                                                             EVT) const {
15590   return false;
15591 }
15592 
15593 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
15594   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
15595   Function *ThreadPointerFunc =
15596       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
15597   return IRB.CreatePointerCast(
15598       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
15599                              Offset),
15600       IRB.getInt8PtrTy()->getPointerTo(0));
15601 }
15602 
15603 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
15604   // Android provides a fixed TLS slot for the stack cookie. See the definition
15605   // of TLS_SLOT_STACK_GUARD in
15606   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15607   if (Subtarget->isTargetAndroid())
15608     return UseTlsOffset(IRB, 0x28);
15609 
15610   // Fuchsia is similar.
15611   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
15612   if (Subtarget->isTargetFuchsia())
15613     return UseTlsOffset(IRB, -0x10);
15614 
15615   return TargetLowering::getIRStackGuard(IRB);
15616 }
15617 
15618 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
15619   // MSVC CRT provides functionalities for stack protection.
15620   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
15621     // MSVC CRT has a global variable holding security cookie.
15622     M.getOrInsertGlobal("__security_cookie",
15623                         Type::getInt8PtrTy(M.getContext()));
15624 
15625     // MSVC CRT has a function to validate security cookie.
15626     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15627         "__security_check_cookie", Type::getVoidTy(M.getContext()),
15628         Type::getInt8PtrTy(M.getContext()));
15629     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
15630       F->setCallingConv(CallingConv::Win64);
15631       F->addAttribute(1, Attribute::AttrKind::InReg);
15632     }
15633     return;
15634   }
15635   TargetLowering::insertSSPDeclarations(M);
15636 }
15637 
15638 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
15639   // MSVC CRT has a global variable holding security cookie.
15640   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15641     return M.getGlobalVariable("__security_cookie");
15642   return TargetLowering::getSDagStackGuard(M);
15643 }
15644 
15645 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
15646   // MSVC CRT has a function to validate security cookie.
15647   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15648     return M.getFunction("__security_check_cookie");
15649   return TargetLowering::getSSPStackGuardCheck(M);
15650 }
15651 
15652 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
15653   // Android provides a fixed TLS slot for the SafeStack pointer. See the
15654   // definition of TLS_SLOT_SAFESTACK in
15655   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15656   if (Subtarget->isTargetAndroid())
15657     return UseTlsOffset(IRB, 0x48);
15658 
15659   // Fuchsia is similar.
15660   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
15661   if (Subtarget->isTargetFuchsia())
15662     return UseTlsOffset(IRB, -0x8);
15663 
15664   return TargetLowering::getSafeStackPointerLocation(IRB);
15665 }
15666 
15667 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
15668     const Instruction &AndI) const {
15669   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
15670   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
15671   // may be beneficial to sink in other cases, but we would have to check that
15672   // the cmp would not get folded into the br to form a cbz for these to be
15673   // beneficial.
15674   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
15675   if (!Mask)
15676     return false;
15677   return Mask->getValue().isPowerOf2();
15678 }
15679 
15680 bool AArch64TargetLowering::
15681     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15682         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
15683         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
15684         SelectionDAG &DAG) const {
15685   // Does baseline recommend not to perform the fold by default?
15686   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15687           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
15688     return false;
15689   // Else, if this is a vector shift, prefer 'shl'.
15690   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
15691 }
15692 
15693 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
15694                                               SDNode *N) const {
15695   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15696       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
15697     return false;
15698   return true;
15699 }
15700 
15701 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15702   // Update IsSplitCSR in AArch64unctionInfo.
15703   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
15704   AFI->setIsSplitCSR(true);
15705 }
15706 
15707 void AArch64TargetLowering::insertCopiesSplitCSR(
15708     MachineBasicBlock *Entry,
15709     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15710   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
15711   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15712   if (!IStart)
15713     return;
15714 
15715   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15716   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15717   MachineBasicBlock::iterator MBBI = Entry->begin();
15718   for (const MCPhysReg *I = IStart; *I; ++I) {
15719     const TargetRegisterClass *RC = nullptr;
15720     if (AArch64::GPR64RegClass.contains(*I))
15721       RC = &AArch64::GPR64RegClass;
15722     else if (AArch64::FPR64RegClass.contains(*I))
15723       RC = &AArch64::FPR64RegClass;
15724     else
15725       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15726 
15727     Register NewVR = MRI->createVirtualRegister(RC);
15728     // Create copy from CSR to a virtual register.
15729     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15730     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15731     // nounwind. If we want to generalize this later, we may need to emit
15732     // CFI pseudo-instructions.
15733     assert(Entry->getParent()->getFunction().hasFnAttribute(
15734                Attribute::NoUnwind) &&
15735            "Function should be nounwind in insertCopiesSplitCSR!");
15736     Entry->addLiveIn(*I);
15737     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15738         .addReg(*I);
15739 
15740     // Insert the copy-back instructions right before the terminator.
15741     for (auto *Exit : Exits)
15742       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15743               TII->get(TargetOpcode::COPY), *I)
15744           .addReg(NewVR);
15745   }
15746 }
15747 
15748 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
15749   // Integer division on AArch64 is expensive. However, when aggressively
15750   // optimizing for code size, we prefer to use a div instruction, as it is
15751   // usually smaller than the alternative sequence.
15752   // The exception to this is vector division. Since AArch64 doesn't have vector
15753   // integer division, leaving the division as-is is a loss even in terms of
15754   // size, because it will have to be scalarized, while the alternative code
15755   // sequence can be performed in vector form.
15756   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
15757   return OptSize && !VT.isVector();
15758 }
15759 
15760 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
15761   // We want inc-of-add for scalars and sub-of-not for vectors.
15762   return VT.isScalarInteger();
15763 }
15764 
15765 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
15766   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
15767 }
15768 
15769 unsigned
15770 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
15771   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
15772     return getPointerTy(DL).getSizeInBits();
15773 
15774   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
15775 }
15776 
15777 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
15778   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15779   TargetLoweringBase::finalizeLowering(MF);
15780 }
15781 
15782 // Unlike X86, we let frame lowering assign offsets to all catch objects.
15783 bool AArch64TargetLowering::needsFixedCatchObjects() const {
15784   return false;
15785 }
15786 
15787 bool AArch64TargetLowering::shouldLocalize(
15788     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
15789   switch (MI.getOpcode()) {
15790   case TargetOpcode::G_GLOBAL_VALUE: {
15791     // On Darwin, TLS global vars get selected into function calls, which
15792     // we don't want localized, as they can get moved into the middle of a
15793     // another call sequence.
15794     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
15795     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
15796       return false;
15797     break;
15798   }
15799   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
15800   // localizable.
15801   case AArch64::ADRP:
15802   case AArch64::G_ADD_LOW:
15803     return true;
15804   default:
15805     break;
15806   }
15807   return TargetLoweringBase::shouldLocalize(MI, TTI);
15808 }
15809 
15810 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
15811   if (isa<ScalableVectorType>(Inst.getType()))
15812     return true;
15813 
15814   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
15815     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
15816       return true;
15817 
15818   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
15819     if (isa<ScalableVectorType>(AI->getAllocatedType()))
15820       return true;
15821   }
15822 
15823   return false;
15824 }
15825 
15826 // Return the largest legal scalable vector type that matches VT's element type.
15827 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
15828   assert(VT.isFixedLengthVector() &&
15829          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15830          "Expected legal fixed length vector!");
15831   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15832   default:
15833     llvm_unreachable("unexpected element type for SVE container");
15834   case MVT::i8:
15835     return EVT(MVT::nxv16i8);
15836   case MVT::i16:
15837     return EVT(MVT::nxv8i16);
15838   case MVT::i32:
15839     return EVT(MVT::nxv4i32);
15840   case MVT::i64:
15841     return EVT(MVT::nxv2i64);
15842   case MVT::f16:
15843     return EVT(MVT::nxv8f16);
15844   case MVT::f32:
15845     return EVT(MVT::nxv4f32);
15846   case MVT::f64:
15847     return EVT(MVT::nxv2f64);
15848   }
15849 }
15850 
15851 // Return a PTRUE with active lanes corresponding to the extent of VT.
15852 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
15853                                                 EVT VT) {
15854   assert(VT.isFixedLengthVector() &&
15855          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15856          "Expected legal fixed length vector!");
15857 
15858   int PgPattern;
15859   switch (VT.getVectorNumElements()) {
15860   default:
15861     llvm_unreachable("unexpected element count for SVE predicate");
15862   case 1:
15863     PgPattern = AArch64SVEPredPattern::vl1;
15864     break;
15865   case 2:
15866     PgPattern = AArch64SVEPredPattern::vl2;
15867     break;
15868   case 4:
15869     PgPattern = AArch64SVEPredPattern::vl4;
15870     break;
15871   case 8:
15872     PgPattern = AArch64SVEPredPattern::vl8;
15873     break;
15874   case 16:
15875     PgPattern = AArch64SVEPredPattern::vl16;
15876     break;
15877   case 32:
15878     PgPattern = AArch64SVEPredPattern::vl32;
15879     break;
15880   case 64:
15881     PgPattern = AArch64SVEPredPattern::vl64;
15882     break;
15883   case 128:
15884     PgPattern = AArch64SVEPredPattern::vl128;
15885     break;
15886   case 256:
15887     PgPattern = AArch64SVEPredPattern::vl256;
15888     break;
15889   }
15890 
15891   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
15892   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
15893   // variants of instructions when available.
15894 
15895   MVT MaskVT;
15896   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15897   default:
15898     llvm_unreachable("unexpected element type for SVE predicate");
15899   case MVT::i8:
15900     MaskVT = MVT::nxv16i1;
15901     break;
15902   case MVT::i16:
15903   case MVT::f16:
15904     MaskVT = MVT::nxv8i1;
15905     break;
15906   case MVT::i32:
15907   case MVT::f32:
15908     MaskVT = MVT::nxv4i1;
15909     break;
15910   case MVT::i64:
15911   case MVT::f64:
15912     MaskVT = MVT::nxv2i1;
15913     break;
15914   }
15915 
15916   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15917                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15918 }
15919 
15920 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15921                                              EVT VT) {
15922   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15923          "Expected legal scalable vector!");
15924   auto PredTy = VT.changeVectorElementType(MVT::i1);
15925   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15926 }
15927 
15928 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15929   if (VT.isFixedLengthVector())
15930     return getPredicateForFixedLengthVector(DAG, DL, VT);
15931 
15932   return getPredicateForScalableVector(DAG, DL, VT);
15933 }
15934 
15935 // Grow V to consume an entire SVE register.
15936 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15937   assert(VT.isScalableVector() &&
15938          "Expected to convert into a scalable vector!");
15939   assert(V.getValueType().isFixedLengthVector() &&
15940          "Expected a fixed length vector operand!");
15941   SDLoc DL(V);
15942   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15943   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
15944 }
15945 
15946 // Shrink V so it's just big enough to maintain a VT's worth of data.
15947 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15948   assert(VT.isFixedLengthVector() &&
15949          "Expected to convert into a fixed length vector!");
15950   assert(V.getValueType().isScalableVector() &&
15951          "Expected a scalable vector operand!");
15952   SDLoc DL(V);
15953   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15954   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
15955 }
15956 
15957 // Convert all fixed length vector loads larger than NEON to masked_loads.
15958 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
15959     SDValue Op, SelectionDAG &DAG) const {
15960   auto Load = cast<LoadSDNode>(Op);
15961 
15962   SDLoc DL(Op);
15963   EVT VT = Op.getValueType();
15964   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15965 
15966   auto NewLoad = DAG.getMaskedLoad(
15967       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
15968       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
15969       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
15970       Load->getExtensionType());
15971 
15972   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
15973   SDValue MergedValues[2] = {Result, Load->getChain()};
15974   return DAG.getMergeValues(MergedValues, DL);
15975 }
15976 
15977 // Convert all fixed length vector stores larger than NEON to masked_stores.
15978 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
15979     SDValue Op, SelectionDAG &DAG) const {
15980   auto Store = cast<StoreSDNode>(Op);
15981 
15982   SDLoc DL(Op);
15983   EVT VT = Store->getValue().getValueType();
15984   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15985 
15986   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
15987   return DAG.getMaskedStore(
15988       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
15989       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
15990       Store->getMemOperand(), Store->getAddressingMode(),
15991       Store->isTruncatingStore());
15992 }
15993 
15994 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
15995     SDValue Op, SelectionDAG &DAG) const {
15996   SDLoc dl(Op);
15997   EVT VT = Op.getValueType();
15998   EVT EltVT = VT.getVectorElementType();
15999 
16000   bool Signed = Op.getOpcode() == ISD::SDIV;
16001   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
16002 
16003   // Scalable vector i32/i64 DIV is supported.
16004   if (EltVT == MVT::i32 || EltVT == MVT::i64)
16005     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
16006 
16007   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
16008   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16009   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
16010   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
16011   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
16012 
16013   // Convert the operands to scalable vectors.
16014   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16015   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16016 
16017   // Extend the scalable operands.
16018   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16019   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
16020   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
16021   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
16022   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
16023   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
16024 
16025   // Convert back to fixed vectors so the DIV can be further lowered.
16026   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
16027   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
16028   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
16029   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
16030   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16031                                  Op0Lo, Op1Lo);
16032   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16033                                  Op0Hi, Op1Hi);
16034 
16035   // Convert again to scalable vectors to truncate.
16036   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
16037   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
16038   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
16039                                        ResultLo, ResultHi);
16040 
16041   return convertFromScalableVector(DAG, VT, ScalableResult);
16042 }
16043 
16044 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
16045     SDValue Op, SelectionDAG &DAG) const {
16046   EVT VT = Op.getValueType();
16047   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16048 
16049   SDLoc DL(Op);
16050   SDValue Val = Op.getOperand(0);
16051   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16052   Val = convertToScalableVector(DAG, ContainerVT, Val);
16053 
16054   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
16055   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16056 
16057   // Repeatedly unpack Val until the result is of the desired element type.
16058   switch (ContainerVT.getSimpleVT().SimpleTy) {
16059   default:
16060     llvm_unreachable("unimplemented container type");
16061   case MVT::nxv16i8:
16062     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
16063     if (VT.getVectorElementType() == MVT::i16)
16064       break;
16065     LLVM_FALLTHROUGH;
16066   case MVT::nxv8i16:
16067     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
16068     if (VT.getVectorElementType() == MVT::i32)
16069       break;
16070     LLVM_FALLTHROUGH;
16071   case MVT::nxv4i32:
16072     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
16073     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
16074     break;
16075   }
16076 
16077   return convertFromScalableVector(DAG, VT, Val);
16078 }
16079 
16080 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
16081     SDValue Op, SelectionDAG &DAG) const {
16082   EVT VT = Op.getValueType();
16083   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16084 
16085   SDLoc DL(Op);
16086   SDValue Val = Op.getOperand(0);
16087   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16088   Val = convertToScalableVector(DAG, ContainerVT, Val);
16089 
16090   // Repeatedly truncate Val until the result is of the desired element type.
16091   switch (ContainerVT.getSimpleVT().SimpleTy) {
16092   default:
16093     llvm_unreachable("unimplemented container type");
16094   case MVT::nxv2i64:
16095     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
16096     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
16097     if (VT.getVectorElementType() == MVT::i32)
16098       break;
16099     LLVM_FALLTHROUGH;
16100   case MVT::nxv4i32:
16101     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
16102     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
16103     if (VT.getVectorElementType() == MVT::i16)
16104       break;
16105     LLVM_FALLTHROUGH;
16106   case MVT::nxv8i16:
16107     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
16108     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
16109     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
16110     break;
16111   }
16112 
16113   return convertFromScalableVector(DAG, VT, Val);
16114 }
16115 
16116 // Convert vector operation 'Op' to an equivalent predicated operation whereby
16117 // the original operation's type is used to construct a suitable predicate.
16118 // NOTE: The results for inactive lanes are undefined.
16119 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
16120                                                    SelectionDAG &DAG,
16121                                                    unsigned NewOp,
16122                                                    bool OverrideNEON) const {
16123   EVT VT = Op.getValueType();
16124   SDLoc DL(Op);
16125   auto Pg = getPredicateForVector(DAG, DL, VT);
16126 
16127   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
16128     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16129 
16130     // Create list of operands by converting existing ones to scalable types.
16131     SmallVector<SDValue, 4> Operands = {Pg};
16132     for (const SDValue &V : Op->op_values()) {
16133       if (isa<CondCodeSDNode>(V)) {
16134         Operands.push_back(V);
16135         continue;
16136       }
16137 
16138       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
16139         EVT VTArg = VTNode->getVT().getVectorElementType();
16140         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
16141         Operands.push_back(DAG.getValueType(NewVTArg));
16142         continue;
16143       }
16144 
16145       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
16146              "Only fixed length vectors are supported!");
16147       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
16148     }
16149 
16150     if (isMergePassthruOpcode(NewOp))
16151       Operands.push_back(DAG.getUNDEF(ContainerVT));
16152 
16153     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
16154     return convertFromScalableVector(DAG, VT, ScalableRes);
16155   }
16156 
16157   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
16158 
16159   SmallVector<SDValue, 4> Operands = {Pg};
16160   for (const SDValue &V : Op->op_values()) {
16161     assert((!V.getValueType().isVector() ||
16162             V.getValueType().isScalableVector()) &&
16163            "Only scalable vectors are supported!");
16164     Operands.push_back(V);
16165   }
16166 
16167   if (isMergePassthruOpcode(NewOp))
16168     Operands.push_back(DAG.getUNDEF(VT));
16169 
16170   return DAG.getNode(NewOp, DL, VT, Operands);
16171 }
16172 
16173 // If a fixed length vector operation has no side effects when applied to
16174 // undefined elements, we can safely use scalable vectors to perform the same
16175 // operation without needing to worry about predication.
16176 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
16177                                                  SelectionDAG &DAG) const {
16178   EVT VT = Op.getValueType();
16179   assert(useSVEForFixedLengthVectorVT(VT) &&
16180          "Only expected to lower fixed length vector operation!");
16181   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16182 
16183   // Create list of operands by converting existing ones to scalable types.
16184   SmallVector<SDValue, 4> Ops;
16185   for (const SDValue &V : Op->op_values()) {
16186     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
16187 
16188     // Pass through non-vector operands.
16189     if (!V.getValueType().isVector()) {
16190       Ops.push_back(V);
16191       continue;
16192     }
16193 
16194     // "cast" fixed length vector to a scalable vector.
16195     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
16196            "Only fixed length vectors are supported!");
16197     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
16198   }
16199 
16200   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
16201   return convertFromScalableVector(DAG, VT, ScalableRes);
16202 }
16203 
16204 SDValue AArch64TargetLowering::LowerFixedLengthReductionToSVE(unsigned Opcode,
16205     SDValue ScalarOp, SelectionDAG &DAG) const {
16206   SDLoc DL(ScalarOp);
16207   SDValue VecOp = ScalarOp.getOperand(0);
16208   EVT SrcVT = VecOp.getValueType();
16209 
16210   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
16211   EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
16212   VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
16213 
16214   // UADDV always returns an i64 result.
16215   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
16216                                                    SrcVT.getVectorElementType();
16217 
16218   SDValue Rdx = DAG.getNode(Opcode, DL, getPackedSVEVectorVT(ResVT), Pg, VecOp);
16219   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
16220                             Rdx, DAG.getConstant(0, DL, MVT::i64));
16221 
16222   // The VEC_REDUCE nodes expect an element size result.
16223   if (ResVT != ScalarOp.getValueType())
16224     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
16225 
16226   return Res;
16227 }
16228 
16229 SDValue
16230 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
16231     SelectionDAG &DAG) const {
16232   EVT VT = Op.getValueType();
16233   SDLoc DL(Op);
16234 
16235   EVT InVT = Op.getOperand(1).getValueType();
16236   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16237   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
16238   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
16239 
16240   // Convert the mask to a predicated (NOTE: We don't need to worry about
16241   // inactive lanes since VSELECT is safe when given undefined elements).
16242   EVT MaskVT = Op.getOperand(0).getValueType();
16243   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
16244   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
16245   Mask = DAG.getNode(ISD::TRUNCATE, DL,
16246                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
16247 
16248   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
16249                                 Mask, Op1, Op2);
16250 
16251   return convertFromScalableVector(DAG, VT, ScalableRes);
16252 }
16253 
16254 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
16255     SDValue Op, SelectionDAG &DAG) const {
16256   SDLoc DL(Op);
16257   EVT InVT = Op.getOperand(0).getValueType();
16258   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16259 
16260   assert(useSVEForFixedLengthVectorVT(InVT) &&
16261          "Only expected to lower fixed length vector operation!");
16262   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
16263          "Expected integer result of the same bit length as the inputs!");
16264 
16265   // Expand floating point vector comparisons.
16266   if (InVT.isFloatingPoint())
16267     return SDValue();
16268 
16269   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16270   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16271   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
16272 
16273   EVT CmpVT = Pg.getValueType();
16274   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
16275                          {Pg, Op1, Op2, Op.getOperand(2)});
16276 
16277   EVT PromoteVT = ContainerVT.changeTypeToInteger();
16278   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
16279   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
16280 }
16281