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 /// Returns true if VT's elements occupy the lowest bit positions of its
120 /// associated register class without any intervening space.
121 ///
122 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
123 /// same register class, but only nxv8f16 can be treated as a packed vector.
124 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
125   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
126          "Expected legal vector type!");
127   return VT.isFixedLengthVector() ||
128          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
129 }
130 
131 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
132 // predicate and end with a passthru value matching the result type.
133 static bool isMergePassthruOpcode(unsigned Opc) {
134   switch (Opc) {
135   default:
136     return false;
137   case AArch64ISD::DUP_MERGE_PASSTHRU:
138   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
139   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
140     return true;
141   }
142 }
143 
144 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
145                                              const AArch64Subtarget &STI)
146     : TargetLowering(TM), Subtarget(&STI) {
147   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
148   // we have to make something up. Arbitrarily, choose ZeroOrOne.
149   setBooleanContents(ZeroOrOneBooleanContent);
150   // When comparing vectors the result sets the different elements in the
151   // vector to all-one or all-zero.
152   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
153 
154   // Set up the register classes.
155   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
156   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
157 
158   if (Subtarget->hasFPARMv8()) {
159     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
160     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
161     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
162     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
163     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
164   }
165 
166   if (Subtarget->hasNEON()) {
167     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
168     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
169     // Someone set us up the NEON.
170     addDRTypeForNEON(MVT::v2f32);
171     addDRTypeForNEON(MVT::v8i8);
172     addDRTypeForNEON(MVT::v4i16);
173     addDRTypeForNEON(MVT::v2i32);
174     addDRTypeForNEON(MVT::v1i64);
175     addDRTypeForNEON(MVT::v1f64);
176     addDRTypeForNEON(MVT::v4f16);
177     addDRTypeForNEON(MVT::v4bf16);
178 
179     addQRTypeForNEON(MVT::v4f32);
180     addQRTypeForNEON(MVT::v2f64);
181     addQRTypeForNEON(MVT::v16i8);
182     addQRTypeForNEON(MVT::v8i16);
183     addQRTypeForNEON(MVT::v4i32);
184     addQRTypeForNEON(MVT::v2i64);
185     addQRTypeForNEON(MVT::v8f16);
186     addQRTypeForNEON(MVT::v8bf16);
187   }
188 
189   if (Subtarget->hasSVE()) {
190     // Add legal sve predicate types
191     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
192     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
193     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
194     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
195 
196     // Add legal sve data types
197     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
198     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
199     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
200     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
201 
202     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
203     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
204     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
205     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
206     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
207     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
208 
209     if (Subtarget->hasBF16()) {
210       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
211       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
212       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
213     }
214 
215     if (useSVEForFixedLengthVectors()) {
216       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
217         if (useSVEForFixedLengthVectorVT(VT))
218           addRegisterClass(VT, &AArch64::ZPRRegClass);
219 
220       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
221         if (useSVEForFixedLengthVectorVT(VT))
222           addRegisterClass(VT, &AArch64::ZPRRegClass);
223     }
224 
225     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
226       setOperationAction(ISD::SADDSAT, VT, Legal);
227       setOperationAction(ISD::UADDSAT, VT, Legal);
228       setOperationAction(ISD::SSUBSAT, VT, Legal);
229       setOperationAction(ISD::USUBSAT, VT, Legal);
230       setOperationAction(ISD::UREM, VT, Expand);
231       setOperationAction(ISD::SREM, VT, Expand);
232       setOperationAction(ISD::SDIVREM, VT, Expand);
233       setOperationAction(ISD::UDIVREM, VT, Expand);
234     }
235 
236     for (auto VT :
237          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
238            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
239       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
240 
241     for (auto VT :
242          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
243            MVT::nxv2f64 }) {
244       setCondCodeAction(ISD::SETO, VT, Expand);
245       setCondCodeAction(ISD::SETOLT, VT, Expand);
246       setCondCodeAction(ISD::SETLT, VT, Expand);
247       setCondCodeAction(ISD::SETOLE, VT, Expand);
248       setCondCodeAction(ISD::SETLE, VT, Expand);
249       setCondCodeAction(ISD::SETULT, VT, Expand);
250       setCondCodeAction(ISD::SETULE, VT, Expand);
251       setCondCodeAction(ISD::SETUGE, VT, Expand);
252       setCondCodeAction(ISD::SETUGT, VT, Expand);
253       setCondCodeAction(ISD::SETUEQ, VT, Expand);
254       setCondCodeAction(ISD::SETUNE, VT, Expand);
255     }
256   }
257 
258   // Compute derived properties from the register classes
259   computeRegisterProperties(Subtarget->getRegisterInfo());
260 
261   // Provide all sorts of operation actions
262   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
263   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
264   setOperationAction(ISD::SETCC, MVT::i32, Custom);
265   setOperationAction(ISD::SETCC, MVT::i64, Custom);
266   setOperationAction(ISD::SETCC, MVT::f16, Custom);
267   setOperationAction(ISD::SETCC, MVT::f32, Custom);
268   setOperationAction(ISD::SETCC, MVT::f64, Custom);
269   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
270   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
271   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
272   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
273   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
274   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
275   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
276   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
277   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
278   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
279   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
280   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
281   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
282   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
283   setOperationAction(ISD::SELECT, MVT::i32, Custom);
284   setOperationAction(ISD::SELECT, MVT::i64, Custom);
285   setOperationAction(ISD::SELECT, MVT::f16, Custom);
286   setOperationAction(ISD::SELECT, MVT::f32, Custom);
287   setOperationAction(ISD::SELECT, MVT::f64, Custom);
288   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
289   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
290   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
291   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
292   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
293   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
294   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
295 
296   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
297   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
298   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
299 
300   setOperationAction(ISD::FREM, MVT::f32, Expand);
301   setOperationAction(ISD::FREM, MVT::f64, Expand);
302   setOperationAction(ISD::FREM, MVT::f80, Expand);
303 
304   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
305 
306   // Custom lowering hooks are needed for XOR
307   // to fold it into CSINC/CSINV.
308   setOperationAction(ISD::XOR, MVT::i32, Custom);
309   setOperationAction(ISD::XOR, MVT::i64, Custom);
310 
311   // Virtually no operation on f128 is legal, but LLVM can't expand them when
312   // there's a valid register class, so we need custom operations in most cases.
313   setOperationAction(ISD::FABS, MVT::f128, Expand);
314   setOperationAction(ISD::FADD, MVT::f128, Custom);
315   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
316   setOperationAction(ISD::FCOS, MVT::f128, Expand);
317   setOperationAction(ISD::FDIV, MVT::f128, Custom);
318   setOperationAction(ISD::FMA, MVT::f128, Expand);
319   setOperationAction(ISD::FMUL, MVT::f128, Custom);
320   setOperationAction(ISD::FNEG, MVT::f128, Expand);
321   setOperationAction(ISD::FPOW, MVT::f128, Expand);
322   setOperationAction(ISD::FREM, MVT::f128, Expand);
323   setOperationAction(ISD::FRINT, MVT::f128, Expand);
324   setOperationAction(ISD::FSIN, MVT::f128, Expand);
325   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
326   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
327   setOperationAction(ISD::FSUB, MVT::f128, Custom);
328   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
329   setOperationAction(ISD::SETCC, MVT::f128, Custom);
330   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
331   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
332   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
333   setOperationAction(ISD::SELECT, MVT::f128, Custom);
334   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
335   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
336 
337   // Lowering for many of the conversions is actually specified by the non-f128
338   // type. The LowerXXX function will be trivial when f128 isn't involved.
339   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
340   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
341   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
342   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
343   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
344   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
345   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
346   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
347   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
348   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
349   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
350   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
351   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
352   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
353   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
354   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
355   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
356   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
357   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
358   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
359   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
360   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
361   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
362   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
363   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
364   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
365   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
366   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
367 
368   // Variable arguments.
369   setOperationAction(ISD::VASTART, MVT::Other, Custom);
370   setOperationAction(ISD::VAARG, MVT::Other, Custom);
371   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
372   setOperationAction(ISD::VAEND, MVT::Other, Expand);
373 
374   // Variable-sized objects.
375   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
376   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
377 
378   if (Subtarget->isTargetWindows())
379     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
380   else
381     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
382 
383   // Constant pool entries
384   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
385 
386   // BlockAddress
387   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
388 
389   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
390   setOperationAction(ISD::ADDC, MVT::i32, Custom);
391   setOperationAction(ISD::ADDE, MVT::i32, Custom);
392   setOperationAction(ISD::SUBC, MVT::i32, Custom);
393   setOperationAction(ISD::SUBE, MVT::i32, Custom);
394   setOperationAction(ISD::ADDC, MVT::i64, Custom);
395   setOperationAction(ISD::ADDE, MVT::i64, Custom);
396   setOperationAction(ISD::SUBC, MVT::i64, Custom);
397   setOperationAction(ISD::SUBE, MVT::i64, Custom);
398 
399   // AArch64 lacks both left-rotate and popcount instructions.
400   setOperationAction(ISD::ROTL, MVT::i32, Expand);
401   setOperationAction(ISD::ROTL, MVT::i64, Expand);
402   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
403     setOperationAction(ISD::ROTL, VT, Expand);
404     setOperationAction(ISD::ROTR, VT, Expand);
405   }
406 
407   // AArch64 doesn't have i32 MULH{S|U}.
408   setOperationAction(ISD::MULHU, MVT::i32, Expand);
409   setOperationAction(ISD::MULHS, MVT::i32, Expand);
410 
411   // AArch64 doesn't have {U|S}MUL_LOHI.
412   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
413   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
414 
415   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
416   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
417   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
418 
419   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
420   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
421   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
422     setOperationAction(ISD::SDIVREM, VT, Expand);
423     setOperationAction(ISD::UDIVREM, VT, Expand);
424   }
425   setOperationAction(ISD::SREM, MVT::i32, Expand);
426   setOperationAction(ISD::SREM, MVT::i64, Expand);
427   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
428   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
429   setOperationAction(ISD::UREM, MVT::i32, Expand);
430   setOperationAction(ISD::UREM, MVT::i64, Expand);
431 
432   // Custom lower Add/Sub/Mul with overflow.
433   setOperationAction(ISD::SADDO, MVT::i32, Custom);
434   setOperationAction(ISD::SADDO, MVT::i64, Custom);
435   setOperationAction(ISD::UADDO, MVT::i32, Custom);
436   setOperationAction(ISD::UADDO, MVT::i64, Custom);
437   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
438   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
439   setOperationAction(ISD::USUBO, MVT::i32, Custom);
440   setOperationAction(ISD::USUBO, MVT::i64, Custom);
441   setOperationAction(ISD::SMULO, MVT::i32, Custom);
442   setOperationAction(ISD::SMULO, MVT::i64, Custom);
443   setOperationAction(ISD::UMULO, MVT::i32, Custom);
444   setOperationAction(ISD::UMULO, MVT::i64, Custom);
445 
446   setOperationAction(ISD::FSIN, MVT::f32, Expand);
447   setOperationAction(ISD::FSIN, MVT::f64, Expand);
448   setOperationAction(ISD::FCOS, MVT::f32, Expand);
449   setOperationAction(ISD::FCOS, MVT::f64, Expand);
450   setOperationAction(ISD::FPOW, MVT::f32, Expand);
451   setOperationAction(ISD::FPOW, MVT::f64, Expand);
452   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
453   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
454   if (Subtarget->hasFullFP16())
455     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
456   else
457     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
458 
459   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
460   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
461   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
462   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
463   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
464   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
465   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
466   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
467   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
468   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
469   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
470   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
471   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
472   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
473   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
474   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
475   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
476   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
477   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
478   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
479   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
480   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
481   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
482   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
483   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
484   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
485   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
486   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
487   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
488   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
489   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
490   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
491   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
492 
493   if (!Subtarget->hasFullFP16()) {
494     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
495     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
496     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
497     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
498     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
499     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
500     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
501     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
502     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
503     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
504     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
505     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
506     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
507     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
508     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
509     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
510     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
511     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
512     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
513     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
514     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
515     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
516 
517     // promote v4f16 to v4f32 when that is known to be safe.
518     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
519     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
520     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
521     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
522     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
523     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
524     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
525     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
526 
527     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
528     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
529     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
530     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
531     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
532     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
533     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
534     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
535     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
536     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
537     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
538     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
539     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
540     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
541     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
542 
543     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
544     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
545     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
546     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
547     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
548     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
549     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
550     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
551     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
552     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
553     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
554     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
555     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
556     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
557     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
558     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
559     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
560     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
561     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
562     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
563   }
564 
565   // AArch64 has implementations of a lot of rounding-like FP operations.
566   for (MVT Ty : {MVT::f32, MVT::f64}) {
567     setOperationAction(ISD::FFLOOR, Ty, Legal);
568     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
569     setOperationAction(ISD::FCEIL, Ty, Legal);
570     setOperationAction(ISD::FRINT, Ty, Legal);
571     setOperationAction(ISD::FTRUNC, Ty, Legal);
572     setOperationAction(ISD::FROUND, Ty, Legal);
573     setOperationAction(ISD::FMINNUM, Ty, Legal);
574     setOperationAction(ISD::FMAXNUM, Ty, Legal);
575     setOperationAction(ISD::FMINIMUM, Ty, Legal);
576     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
577     setOperationAction(ISD::LROUND, Ty, Legal);
578     setOperationAction(ISD::LLROUND, Ty, Legal);
579     setOperationAction(ISD::LRINT, Ty, Legal);
580     setOperationAction(ISD::LLRINT, Ty, Legal);
581   }
582 
583   if (Subtarget->hasFullFP16()) {
584     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
585     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
586     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
587     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
588     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
589     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
590     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
591     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
592     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
593     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
594   }
595 
596   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
597 
598   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
599 
600   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
601   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
602   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
603   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
604   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
605 
606   // 128-bit loads and stores can be done without expanding
607   setOperationAction(ISD::LOAD, MVT::i128, Custom);
608   setOperationAction(ISD::STORE, MVT::i128, Custom);
609 
610   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
611   // custom lowering, as there are no un-paired non-temporal stores and
612   // legalization will break up 256 bit inputs.
613   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
614   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
615   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
616   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
617   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
618   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
619   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
620 
621   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
622   // This requires the Performance Monitors extension.
623   if (Subtarget->hasPerfMon())
624     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
625 
626   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
627       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
628     // Issue __sincos_stret if available.
629     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
630     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
631   } else {
632     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
633     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
634   }
635 
636   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
637     // MSVCRT doesn't have powi; fall back to pow
638     setLibcallName(RTLIB::POWI_F32, nullptr);
639     setLibcallName(RTLIB::POWI_F64, nullptr);
640   }
641 
642   // Make floating-point constants legal for the large code model, so they don't
643   // become loads from the constant pool.
644   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
645     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
646     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
647   }
648 
649   // AArch64 does not have floating-point extending loads, i1 sign-extending
650   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
651   for (MVT VT : MVT::fp_valuetypes()) {
652     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
653     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
654     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
656   }
657   for (MVT VT : MVT::integer_valuetypes())
658     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
659 
660   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
661   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
662   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
664   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
665   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
666   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
667 
668   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
669   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
670   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
671 
672   // Indexed loads and stores are supported.
673   for (unsigned im = (unsigned)ISD::PRE_INC;
674        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
675     setIndexedLoadAction(im, MVT::i8, Legal);
676     setIndexedLoadAction(im, MVT::i16, Legal);
677     setIndexedLoadAction(im, MVT::i32, Legal);
678     setIndexedLoadAction(im, MVT::i64, Legal);
679     setIndexedLoadAction(im, MVT::f64, Legal);
680     setIndexedLoadAction(im, MVT::f32, Legal);
681     setIndexedLoadAction(im, MVT::f16, Legal);
682     setIndexedLoadAction(im, MVT::bf16, Legal);
683     setIndexedStoreAction(im, MVT::i8, Legal);
684     setIndexedStoreAction(im, MVT::i16, Legal);
685     setIndexedStoreAction(im, MVT::i32, Legal);
686     setIndexedStoreAction(im, MVT::i64, Legal);
687     setIndexedStoreAction(im, MVT::f64, Legal);
688     setIndexedStoreAction(im, MVT::f32, Legal);
689     setIndexedStoreAction(im, MVT::f16, Legal);
690     setIndexedStoreAction(im, MVT::bf16, Legal);
691   }
692 
693   // Trap.
694   setOperationAction(ISD::TRAP, MVT::Other, Legal);
695   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
696 
697   // We combine OR nodes for bitfield operations.
698   setTargetDAGCombine(ISD::OR);
699   // Try to create BICs for vector ANDs.
700   setTargetDAGCombine(ISD::AND);
701 
702   // Vector add and sub nodes may conceal a high-half opportunity.
703   // Also, try to fold ADD into CSINC/CSINV..
704   setTargetDAGCombine(ISD::ADD);
705   setTargetDAGCombine(ISD::SUB);
706   setTargetDAGCombine(ISD::SRL);
707   setTargetDAGCombine(ISD::XOR);
708   setTargetDAGCombine(ISD::SINT_TO_FP);
709   setTargetDAGCombine(ISD::UINT_TO_FP);
710 
711   setTargetDAGCombine(ISD::FP_TO_SINT);
712   setTargetDAGCombine(ISD::FP_TO_UINT);
713   setTargetDAGCombine(ISD::FDIV);
714 
715   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
716 
717   setTargetDAGCombine(ISD::ANY_EXTEND);
718   setTargetDAGCombine(ISD::ZERO_EXTEND);
719   setTargetDAGCombine(ISD::SIGN_EXTEND);
720   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
721   setTargetDAGCombine(ISD::TRUNCATE);
722   setTargetDAGCombine(ISD::CONCAT_VECTORS);
723   setTargetDAGCombine(ISD::STORE);
724   if (Subtarget->supportsAddressTopByteIgnored())
725     setTargetDAGCombine(ISD::LOAD);
726 
727   setTargetDAGCombine(ISD::MUL);
728 
729   setTargetDAGCombine(ISD::SELECT);
730   setTargetDAGCombine(ISD::VSELECT);
731 
732   setTargetDAGCombine(ISD::INTRINSIC_VOID);
733   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
734   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
735 
736   setTargetDAGCombine(ISD::GlobalAddress);
737 
738   // In case of strict alignment, avoid an excessive number of byte wide stores.
739   MaxStoresPerMemsetOptSize = 8;
740   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
741                        ? MaxStoresPerMemsetOptSize : 32;
742 
743   MaxGluedStoresPerMemcpy = 4;
744   MaxStoresPerMemcpyOptSize = 4;
745   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
746                        ? MaxStoresPerMemcpyOptSize : 16;
747 
748   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
749 
750   MaxLoadsPerMemcmpOptSize = 4;
751   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
752                       ? MaxLoadsPerMemcmpOptSize : 8;
753 
754   setStackPointerRegisterToSaveRestore(AArch64::SP);
755 
756   setSchedulingPreference(Sched::Hybrid);
757 
758   EnableExtLdPromotion = true;
759 
760   // Set required alignment.
761   setMinFunctionAlignment(Align(4));
762   // Set preferred alignments.
763   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
764   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
765 
766   // Only change the limit for entries in a jump table if specified by
767   // the sub target, but not at the command line.
768   unsigned MaxJT = STI.getMaximumJumpTableSize();
769   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
770     setMaximumJumpTableSize(MaxJT);
771 
772   setHasExtractBitsInsn(true);
773 
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
775 
776   if (Subtarget->hasNEON()) {
777     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
778     // silliness like this:
779     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
780     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
781     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
782     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
783     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
784     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
785     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
786     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
787     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
788     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
789     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
790     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
791     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
792     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
793     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
794     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
795     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
796     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
797     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
798     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
799     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
800     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
801     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
802     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
803     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
804 
805     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
806     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
807     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
808     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
809     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
810 
811     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
812 
813     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
814     // elements smaller than i32, so promote the input to i32 first.
815     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
816     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
817     // i8 vector elements also need promotion to i32 for v8i8
818     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
819     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
820     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
821     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
822     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
823     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
824     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
825     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
826     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
827     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
828     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
829 
830     if (Subtarget->hasFullFP16()) {
831       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
832       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
833       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
834       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
835     } else {
836       // when AArch64 doesn't have fullfp16 support, promote the input
837       // to i32 first.
838       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
839       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
840       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
841       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
842     }
843 
844     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
845     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
846 
847     // AArch64 doesn't have MUL.2d:
848     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
849     // Custom handling for some quad-vector types to detect MULL.
850     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
851     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
852     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
853 
854     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
855                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
856       // Vector reductions
857       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
858       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
859       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
860       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
861       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
862 
863       // Saturates
864       setOperationAction(ISD::SADDSAT, VT, Legal);
865       setOperationAction(ISD::UADDSAT, VT, Legal);
866       setOperationAction(ISD::SSUBSAT, VT, Legal);
867       setOperationAction(ISD::USUBSAT, VT, Legal);
868     }
869     for (MVT VT : { MVT::v4f16, MVT::v2f32,
870                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
871       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
872       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
873     }
874 
875     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
876     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
877     // Likewise, narrowing and extending vector loads/stores aren't handled
878     // directly.
879     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
880       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
881 
882       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
883         setOperationAction(ISD::MULHS, VT, Legal);
884         setOperationAction(ISD::MULHU, VT, Legal);
885       } else {
886         setOperationAction(ISD::MULHS, VT, Expand);
887         setOperationAction(ISD::MULHU, VT, Expand);
888       }
889       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
890       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
891 
892       setOperationAction(ISD::BSWAP, VT, Expand);
893       setOperationAction(ISD::CTTZ, VT, Expand);
894 
895       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
896         setTruncStoreAction(VT, InnerVT, Expand);
897         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
898         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
899         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
900       }
901     }
902 
903     // AArch64 has implementations of a lot of rounding-like FP operations.
904     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
905       setOperationAction(ISD::FFLOOR, Ty, Legal);
906       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
907       setOperationAction(ISD::FCEIL, Ty, Legal);
908       setOperationAction(ISD::FRINT, Ty, Legal);
909       setOperationAction(ISD::FTRUNC, Ty, Legal);
910       setOperationAction(ISD::FROUND, Ty, Legal);
911     }
912 
913     if (Subtarget->hasFullFP16()) {
914       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
915         setOperationAction(ISD::FFLOOR, Ty, Legal);
916         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
917         setOperationAction(ISD::FCEIL, Ty, Legal);
918         setOperationAction(ISD::FRINT, Ty, Legal);
919         setOperationAction(ISD::FTRUNC, Ty, Legal);
920         setOperationAction(ISD::FROUND, Ty, Legal);
921       }
922     }
923 
924     if (Subtarget->hasSVE())
925       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
926 
927     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
928   }
929 
930   if (Subtarget->hasSVE()) {
931     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
932     // splat of 0 or undef) once vector selects supported in SVE codegen. See
933     // D68877 for more details.
934     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
935       if (isTypeLegal(VT)) {
936         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
937         setOperationAction(ISD::MUL, VT, Custom);
938         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
939         setOperationAction(ISD::SELECT, VT, Custom);
940         setOperationAction(ISD::SDIV, VT, Custom);
941         setOperationAction(ISD::UDIV, VT, Custom);
942         setOperationAction(ISD::SMIN, VT, Custom);
943         setOperationAction(ISD::UMIN, VT, Custom);
944         setOperationAction(ISD::SMAX, VT, Custom);
945         setOperationAction(ISD::UMAX, VT, Custom);
946         setOperationAction(ISD::SHL, VT, Custom);
947         setOperationAction(ISD::SRL, VT, Custom);
948         setOperationAction(ISD::SRA, VT, Custom);
949         if (VT.getScalarType() == MVT::i1) {
950           setOperationAction(ISD::SETCC, VT, Custom);
951           setOperationAction(ISD::TRUNCATE, VT, Custom);
952           setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
953         }
954       }
955     }
956 
957     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32})
958       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
959 
960     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
961     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
962 
963     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
964       if (isTypeLegal(VT)) {
965         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
966         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
967         setOperationAction(ISD::SELECT, VT, Custom);
968         setOperationAction(ISD::FADD, VT, Custom);
969         setOperationAction(ISD::FDIV, VT, Custom);
970         setOperationAction(ISD::FMA, VT, Custom);
971         setOperationAction(ISD::FMUL, VT, Custom);
972         setOperationAction(ISD::FSUB, VT, Custom);
973       }
974     }
975 
976     // NOTE: Currently this has to happen after computeRegisterProperties rather
977     // than the preferred option of combining it with the addRegisterClass call.
978     if (useSVEForFixedLengthVectors()) {
979       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
980         if (useSVEForFixedLengthVectorVT(VT))
981           addTypeForFixedLengthSVE(VT);
982       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
983         if (useSVEForFixedLengthVectorVT(VT))
984           addTypeForFixedLengthSVE(VT);
985 
986       // 64bit results can mean a bigger than NEON input.
987       for (auto VT : {MVT::v8i8, MVT::v4i16})
988         setOperationAction(ISD::TRUNCATE, VT, Custom);
989       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
990 
991       // 128bit results imply a bigger than NEON input.
992       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
993         setOperationAction(ISD::TRUNCATE, VT, Custom);
994       for (auto VT : {MVT::v8f16, MVT::v4f32})
995         setOperationAction(ISD::FP_ROUND, VT, Expand);
996 
997       // These operations are not supported on NEON but SVE can do them.
998       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
999       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1000       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1001       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1002       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1003       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1004       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1005       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1006       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1007       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1008       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1009       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1010       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1011       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1012       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1013       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1014       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1015       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1016       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1017       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1018       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1019       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1020       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1021       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1022       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1023       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1024     }
1025   }
1026 
1027   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1028 }
1029 
1030 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
1031   assert(VT.isVector() && "VT should be a vector type");
1032 
1033   if (VT.isFloatingPoint()) {
1034     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1035     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1036     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1037   }
1038 
1039   // Mark vector float intrinsics as expand.
1040   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1041     setOperationAction(ISD::FSIN, VT, Expand);
1042     setOperationAction(ISD::FCOS, VT, Expand);
1043     setOperationAction(ISD::FPOW, VT, Expand);
1044     setOperationAction(ISD::FLOG, VT, Expand);
1045     setOperationAction(ISD::FLOG2, VT, Expand);
1046     setOperationAction(ISD::FLOG10, VT, Expand);
1047     setOperationAction(ISD::FEXP, VT, Expand);
1048     setOperationAction(ISD::FEXP2, VT, Expand);
1049 
1050     // But we do support custom-lowering for FCOPYSIGN.
1051     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1052   }
1053 
1054   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1055   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1056   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1057   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1058   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1059   setOperationAction(ISD::SRA, VT, Custom);
1060   setOperationAction(ISD::SRL, VT, Custom);
1061   setOperationAction(ISD::SHL, VT, Custom);
1062   setOperationAction(ISD::OR, VT, Custom);
1063   setOperationAction(ISD::SETCC, VT, Custom);
1064   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1065 
1066   setOperationAction(ISD::SELECT, VT, Expand);
1067   setOperationAction(ISD::SELECT_CC, VT, Expand);
1068   setOperationAction(ISD::VSELECT, VT, Expand);
1069   for (MVT InnerVT : MVT::all_valuetypes())
1070     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1071 
1072   // CNT supports only B element sizes, then use UADDLP to widen.
1073   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1074     setOperationAction(ISD::CTPOP, VT, Custom);
1075 
1076   setOperationAction(ISD::UDIV, VT, Expand);
1077   setOperationAction(ISD::SDIV, VT, Expand);
1078   setOperationAction(ISD::UREM, VT, Expand);
1079   setOperationAction(ISD::SREM, VT, Expand);
1080   setOperationAction(ISD::FREM, VT, Expand);
1081 
1082   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1083   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1084 
1085   if (!VT.isFloatingPoint())
1086     setOperationAction(ISD::ABS, VT, Legal);
1087 
1088   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1089   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1090     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1091       setOperationAction(Opcode, VT, Legal);
1092 
1093   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1094   if (VT.isFloatingPoint() &&
1095       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1096     for (unsigned Opcode :
1097          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1098       setOperationAction(Opcode, VT, Legal);
1099 
1100   if (Subtarget->isLittleEndian()) {
1101     for (unsigned im = (unsigned)ISD::PRE_INC;
1102          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1103       setIndexedLoadAction(im, VT, Legal);
1104       setIndexedStoreAction(im, VT, Legal);
1105     }
1106   }
1107 }
1108 
1109 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1110   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1111 
1112   // By default everything must be expanded.
1113   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1114     setOperationAction(Op, VT, Expand);
1115 
1116   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1118 
1119   // Lower fixed length vector operations to scalable equivalents.
1120   setOperationAction(ISD::ADD, VT, Custom);
1121   setOperationAction(ISD::AND, VT, Custom);
1122   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1123   setOperationAction(ISD::FADD, VT, Custom);
1124   setOperationAction(ISD::FDIV, VT, Custom);
1125   setOperationAction(ISD::FMA, VT, Custom);
1126   setOperationAction(ISD::FMAXNUM, VT, Custom);
1127   setOperationAction(ISD::FMINNUM, VT, Custom);
1128   setOperationAction(ISD::FMUL, VT, Custom);
1129   setOperationAction(ISD::FSUB, VT, Custom);
1130   setOperationAction(ISD::LOAD, VT, Custom);
1131   setOperationAction(ISD::MUL, VT, Custom);
1132   setOperationAction(ISD::OR, VT, Custom);
1133   setOperationAction(ISD::SDIV, VT, Custom);
1134   setOperationAction(ISD::SETCC, VT, Custom);
1135   setOperationAction(ISD::SHL, VT, Custom);
1136   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1137   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1138   setOperationAction(ISD::SMAX, VT, Custom);
1139   setOperationAction(ISD::SMIN, VT, Custom);
1140   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1141   setOperationAction(ISD::SRA, VT, Custom);
1142   setOperationAction(ISD::SRL, VT, Custom);
1143   setOperationAction(ISD::STORE, VT, Custom);
1144   setOperationAction(ISD::SUB, VT, Custom);
1145   setOperationAction(ISD::TRUNCATE, VT, Custom);
1146   setOperationAction(ISD::UDIV, VT, Custom);
1147   setOperationAction(ISD::UMAX, VT, Custom);
1148   setOperationAction(ISD::UMIN, VT, Custom);
1149   setOperationAction(ISD::XOR, VT, Custom);
1150   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1151 }
1152 
1153 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1154   addRegisterClass(VT, &AArch64::FPR64RegClass);
1155   addTypeForNEON(VT, MVT::v2i32);
1156 }
1157 
1158 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1159   addRegisterClass(VT, &AArch64::FPR128RegClass);
1160   addTypeForNEON(VT, MVT::v4i32);
1161 }
1162 
1163 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1164                                               LLVMContext &C, EVT VT) const {
1165   if (!VT.isVector())
1166     return MVT::i32;
1167   if (VT.isScalableVector())
1168     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1169   return VT.changeVectorElementTypeToInteger();
1170 }
1171 
1172 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1173                                const APInt &Demanded,
1174                                TargetLowering::TargetLoweringOpt &TLO,
1175                                unsigned NewOpc) {
1176   uint64_t OldImm = Imm, NewImm, Enc;
1177   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1178 
1179   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1180   // bimm64.
1181   if (Imm == 0 || Imm == Mask ||
1182       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1183     return false;
1184 
1185   unsigned EltSize = Size;
1186   uint64_t DemandedBits = Demanded.getZExtValue();
1187 
1188   // Clear bits that are not demanded.
1189   Imm &= DemandedBits;
1190 
1191   while (true) {
1192     // The goal here is to set the non-demanded bits in a way that minimizes
1193     // the number of switching between 0 and 1. In order to achieve this goal,
1194     // we set the non-demanded bits to the value of the preceding demanded bits.
1195     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1196     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1197     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1198     // The final result is 0b11000011.
1199     uint64_t NonDemandedBits = ~DemandedBits;
1200     uint64_t InvertedImm = ~Imm & DemandedBits;
1201     uint64_t RotatedImm =
1202         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1203         NonDemandedBits;
1204     uint64_t Sum = RotatedImm + NonDemandedBits;
1205     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1206     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1207     NewImm = (Imm | Ones) & Mask;
1208 
1209     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1210     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1211     // we halve the element size and continue the search.
1212     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1213       break;
1214 
1215     // We cannot shrink the element size any further if it is 2-bits.
1216     if (EltSize == 2)
1217       return false;
1218 
1219     EltSize /= 2;
1220     Mask >>= EltSize;
1221     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1222 
1223     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1224     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1225       return false;
1226 
1227     // Merge the upper and lower halves of Imm and DemandedBits.
1228     Imm |= Hi;
1229     DemandedBits |= DemandedBitsHi;
1230   }
1231 
1232   ++NumOptimizedImms;
1233 
1234   // Replicate the element across the register width.
1235   while (EltSize < Size) {
1236     NewImm |= NewImm << EltSize;
1237     EltSize *= 2;
1238   }
1239 
1240   (void)OldImm;
1241   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1242          "demanded bits should never be altered");
1243   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1244 
1245   // Create the new constant immediate node.
1246   EVT VT = Op.getValueType();
1247   SDLoc DL(Op);
1248   SDValue New;
1249 
1250   // If the new constant immediate is all-zeros or all-ones, let the target
1251   // independent DAG combine optimize this node.
1252   if (NewImm == 0 || NewImm == OrigMask) {
1253     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1254                           TLO.DAG.getConstant(NewImm, DL, VT));
1255   // Otherwise, create a machine node so that target independent DAG combine
1256   // doesn't undo this optimization.
1257   } else {
1258     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1259     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1260     New = SDValue(
1261         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1262   }
1263 
1264   return TLO.CombineTo(Op, New);
1265 }
1266 
1267 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1268     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1269     TargetLoweringOpt &TLO) const {
1270   // Delay this optimization to as late as possible.
1271   if (!TLO.LegalOps)
1272     return false;
1273 
1274   if (!EnableOptimizeLogicalImm)
1275     return false;
1276 
1277   EVT VT = Op.getValueType();
1278   if (VT.isVector())
1279     return false;
1280 
1281   unsigned Size = VT.getSizeInBits();
1282   assert((Size == 32 || Size == 64) &&
1283          "i32 or i64 is expected after legalization.");
1284 
1285   // Exit early if we demand all bits.
1286   if (DemandedBits.countPopulation() == Size)
1287     return false;
1288 
1289   unsigned NewOpc;
1290   switch (Op.getOpcode()) {
1291   default:
1292     return false;
1293   case ISD::AND:
1294     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1295     break;
1296   case ISD::OR:
1297     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1298     break;
1299   case ISD::XOR:
1300     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1301     break;
1302   }
1303   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1304   if (!C)
1305     return false;
1306   uint64_t Imm = C->getZExtValue();
1307   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1308 }
1309 
1310 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1311 /// Mask are known to be either zero or one and return them Known.
1312 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1313     const SDValue Op, KnownBits &Known,
1314     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1315   switch (Op.getOpcode()) {
1316   default:
1317     break;
1318   case AArch64ISD::CSEL: {
1319     KnownBits Known2;
1320     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1321     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1322     Known.Zero &= Known2.Zero;
1323     Known.One &= Known2.One;
1324     break;
1325   }
1326   case AArch64ISD::LOADgot:
1327   case AArch64ISD::ADDlow: {
1328     if (!Subtarget->isTargetILP32())
1329       break;
1330     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1331     Known.Zero = APInt::getHighBitsSet(64, 32);
1332     break;
1333   }
1334   case ISD::INTRINSIC_W_CHAIN: {
1335     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1336     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1337     switch (IntID) {
1338     default: return;
1339     case Intrinsic::aarch64_ldaxr:
1340     case Intrinsic::aarch64_ldxr: {
1341       unsigned BitWidth = Known.getBitWidth();
1342       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1343       unsigned MemBits = VT.getScalarSizeInBits();
1344       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1345       return;
1346     }
1347     }
1348     break;
1349   }
1350   case ISD::INTRINSIC_WO_CHAIN:
1351   case ISD::INTRINSIC_VOID: {
1352     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1353     switch (IntNo) {
1354     default:
1355       break;
1356     case Intrinsic::aarch64_neon_umaxv:
1357     case Intrinsic::aarch64_neon_uminv: {
1358       // Figure out the datatype of the vector operand. The UMINV instruction
1359       // will zero extend the result, so we can mark as known zero all the
1360       // bits larger than the element datatype. 32-bit or larget doesn't need
1361       // this as those are legal types and will be handled by isel directly.
1362       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1363       unsigned BitWidth = Known.getBitWidth();
1364       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1365         assert(BitWidth >= 8 && "Unexpected width!");
1366         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1367         Known.Zero |= Mask;
1368       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1369         assert(BitWidth >= 16 && "Unexpected width!");
1370         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1371         Known.Zero |= Mask;
1372       }
1373       break;
1374     } break;
1375     }
1376   }
1377   }
1378 }
1379 
1380 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1381                                                   EVT) const {
1382   return MVT::i64;
1383 }
1384 
1385 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1386     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1387     bool *Fast) const {
1388   if (Subtarget->requiresStrictAlign())
1389     return false;
1390 
1391   if (Fast) {
1392     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1393     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1394             // See comments in performSTORECombine() for more details about
1395             // these conditions.
1396 
1397             // Code that uses clang vector extensions can mark that it
1398             // wants unaligned accesses to be treated as fast by
1399             // underspecifying alignment to be 1 or 2.
1400             Align <= 2 ||
1401 
1402             // Disregard v2i64. Memcpy lowering produces those and splitting
1403             // them regresses performance on micro-benchmarks and olden/bh.
1404             VT == MVT::v2i64;
1405   }
1406   return true;
1407 }
1408 
1409 // Same as above but handling LLTs instead.
1410 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1411     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1412     bool *Fast) const {
1413   if (Subtarget->requiresStrictAlign())
1414     return false;
1415 
1416   if (Fast) {
1417     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1418     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1419             Ty.getSizeInBytes() != 16 ||
1420             // See comments in performSTORECombine() for more details about
1421             // these conditions.
1422 
1423             // Code that uses clang vector extensions can mark that it
1424             // wants unaligned accesses to be treated as fast by
1425             // underspecifying alignment to be 1 or 2.
1426             Alignment <= 2 ||
1427 
1428             // Disregard v2i64. Memcpy lowering produces those and splitting
1429             // them regresses performance on micro-benchmarks and olden/bh.
1430             Ty == LLT::vector(2, 64);
1431   }
1432   return true;
1433 }
1434 
1435 FastISel *
1436 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1437                                       const TargetLibraryInfo *libInfo) const {
1438   return AArch64::createFastISel(funcInfo, libInfo);
1439 }
1440 
1441 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1442 #define MAKE_CASE(V)                                                           \
1443   case V:                                                                      \
1444     return #V;
1445   switch ((AArch64ISD::NodeType)Opcode) {
1446   case AArch64ISD::FIRST_NUMBER:
1447     break;
1448     MAKE_CASE(AArch64ISD::CALL)
1449     MAKE_CASE(AArch64ISD::ADRP)
1450     MAKE_CASE(AArch64ISD::ADR)
1451     MAKE_CASE(AArch64ISD::ADDlow)
1452     MAKE_CASE(AArch64ISD::LOADgot)
1453     MAKE_CASE(AArch64ISD::RET_FLAG)
1454     MAKE_CASE(AArch64ISD::BRCOND)
1455     MAKE_CASE(AArch64ISD::CSEL)
1456     MAKE_CASE(AArch64ISD::FCSEL)
1457     MAKE_CASE(AArch64ISD::CSINV)
1458     MAKE_CASE(AArch64ISD::CSNEG)
1459     MAKE_CASE(AArch64ISD::CSINC)
1460     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1461     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1462     MAKE_CASE(AArch64ISD::ADD_PRED)
1463     MAKE_CASE(AArch64ISD::MUL_PRED)
1464     MAKE_CASE(AArch64ISD::SDIV_PRED)
1465     MAKE_CASE(AArch64ISD::SHL_PRED)
1466     MAKE_CASE(AArch64ISD::SMAX_PRED)
1467     MAKE_CASE(AArch64ISD::SMIN_PRED)
1468     MAKE_CASE(AArch64ISD::SRA_PRED)
1469     MAKE_CASE(AArch64ISD::SRL_PRED)
1470     MAKE_CASE(AArch64ISD::SUB_PRED)
1471     MAKE_CASE(AArch64ISD::UDIV_PRED)
1472     MAKE_CASE(AArch64ISD::UMAX_PRED)
1473     MAKE_CASE(AArch64ISD::UMIN_PRED)
1474     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1475     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1476     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1477     MAKE_CASE(AArch64ISD::ADC)
1478     MAKE_CASE(AArch64ISD::SBC)
1479     MAKE_CASE(AArch64ISD::ADDS)
1480     MAKE_CASE(AArch64ISD::SUBS)
1481     MAKE_CASE(AArch64ISD::ADCS)
1482     MAKE_CASE(AArch64ISD::SBCS)
1483     MAKE_CASE(AArch64ISD::ANDS)
1484     MAKE_CASE(AArch64ISD::CCMP)
1485     MAKE_CASE(AArch64ISD::CCMN)
1486     MAKE_CASE(AArch64ISD::FCCMP)
1487     MAKE_CASE(AArch64ISD::FCMP)
1488     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1489     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1490     MAKE_CASE(AArch64ISD::DUP)
1491     MAKE_CASE(AArch64ISD::DUPLANE8)
1492     MAKE_CASE(AArch64ISD::DUPLANE16)
1493     MAKE_CASE(AArch64ISD::DUPLANE32)
1494     MAKE_CASE(AArch64ISD::DUPLANE64)
1495     MAKE_CASE(AArch64ISD::MOVI)
1496     MAKE_CASE(AArch64ISD::MOVIshift)
1497     MAKE_CASE(AArch64ISD::MOVIedit)
1498     MAKE_CASE(AArch64ISD::MOVImsl)
1499     MAKE_CASE(AArch64ISD::FMOV)
1500     MAKE_CASE(AArch64ISD::MVNIshift)
1501     MAKE_CASE(AArch64ISD::MVNImsl)
1502     MAKE_CASE(AArch64ISD::BICi)
1503     MAKE_CASE(AArch64ISD::ORRi)
1504     MAKE_CASE(AArch64ISD::BSP)
1505     MAKE_CASE(AArch64ISD::NEG)
1506     MAKE_CASE(AArch64ISD::EXTR)
1507     MAKE_CASE(AArch64ISD::ZIP1)
1508     MAKE_CASE(AArch64ISD::ZIP2)
1509     MAKE_CASE(AArch64ISD::UZP1)
1510     MAKE_CASE(AArch64ISD::UZP2)
1511     MAKE_CASE(AArch64ISD::TRN1)
1512     MAKE_CASE(AArch64ISD::TRN2)
1513     MAKE_CASE(AArch64ISD::REV16)
1514     MAKE_CASE(AArch64ISD::REV32)
1515     MAKE_CASE(AArch64ISD::REV64)
1516     MAKE_CASE(AArch64ISD::EXT)
1517     MAKE_CASE(AArch64ISD::VSHL)
1518     MAKE_CASE(AArch64ISD::VLSHR)
1519     MAKE_CASE(AArch64ISD::VASHR)
1520     MAKE_CASE(AArch64ISD::VSLI)
1521     MAKE_CASE(AArch64ISD::VSRI)
1522     MAKE_CASE(AArch64ISD::CMEQ)
1523     MAKE_CASE(AArch64ISD::CMGE)
1524     MAKE_CASE(AArch64ISD::CMGT)
1525     MAKE_CASE(AArch64ISD::CMHI)
1526     MAKE_CASE(AArch64ISD::CMHS)
1527     MAKE_CASE(AArch64ISD::FCMEQ)
1528     MAKE_CASE(AArch64ISD::FCMGE)
1529     MAKE_CASE(AArch64ISD::FCMGT)
1530     MAKE_CASE(AArch64ISD::CMEQz)
1531     MAKE_CASE(AArch64ISD::CMGEz)
1532     MAKE_CASE(AArch64ISD::CMGTz)
1533     MAKE_CASE(AArch64ISD::CMLEz)
1534     MAKE_CASE(AArch64ISD::CMLTz)
1535     MAKE_CASE(AArch64ISD::FCMEQz)
1536     MAKE_CASE(AArch64ISD::FCMGEz)
1537     MAKE_CASE(AArch64ISD::FCMGTz)
1538     MAKE_CASE(AArch64ISD::FCMLEz)
1539     MAKE_CASE(AArch64ISD::FCMLTz)
1540     MAKE_CASE(AArch64ISD::SADDV)
1541     MAKE_CASE(AArch64ISD::UADDV)
1542     MAKE_CASE(AArch64ISD::SRHADD)
1543     MAKE_CASE(AArch64ISD::URHADD)
1544     MAKE_CASE(AArch64ISD::SHADD)
1545     MAKE_CASE(AArch64ISD::UHADD)
1546     MAKE_CASE(AArch64ISD::SMINV)
1547     MAKE_CASE(AArch64ISD::UMINV)
1548     MAKE_CASE(AArch64ISD::SMAXV)
1549     MAKE_CASE(AArch64ISD::UMAXV)
1550     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1551     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1552     MAKE_CASE(AArch64ISD::SMINV_PRED)
1553     MAKE_CASE(AArch64ISD::UMINV_PRED)
1554     MAKE_CASE(AArch64ISD::ORV_PRED)
1555     MAKE_CASE(AArch64ISD::EORV_PRED)
1556     MAKE_CASE(AArch64ISD::ANDV_PRED)
1557     MAKE_CASE(AArch64ISD::CLASTA_N)
1558     MAKE_CASE(AArch64ISD::CLASTB_N)
1559     MAKE_CASE(AArch64ISD::LASTA)
1560     MAKE_CASE(AArch64ISD::LASTB)
1561     MAKE_CASE(AArch64ISD::REV)
1562     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1563     MAKE_CASE(AArch64ISD::TBL)
1564     MAKE_CASE(AArch64ISD::FADD_PRED)
1565     MAKE_CASE(AArch64ISD::FADDA_PRED)
1566     MAKE_CASE(AArch64ISD::FADDV_PRED)
1567     MAKE_CASE(AArch64ISD::FDIV_PRED)
1568     MAKE_CASE(AArch64ISD::FMA_PRED)
1569     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1570     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
1571     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1572     MAKE_CASE(AArch64ISD::FMINV_PRED)
1573     MAKE_CASE(AArch64ISD::FMINNM_PRED)
1574     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1575     MAKE_CASE(AArch64ISD::FMUL_PRED)
1576     MAKE_CASE(AArch64ISD::FSUB_PRED)
1577     MAKE_CASE(AArch64ISD::NOT)
1578     MAKE_CASE(AArch64ISD::BIT)
1579     MAKE_CASE(AArch64ISD::CBZ)
1580     MAKE_CASE(AArch64ISD::CBNZ)
1581     MAKE_CASE(AArch64ISD::TBZ)
1582     MAKE_CASE(AArch64ISD::TBNZ)
1583     MAKE_CASE(AArch64ISD::TC_RETURN)
1584     MAKE_CASE(AArch64ISD::PREFETCH)
1585     MAKE_CASE(AArch64ISD::SITOF)
1586     MAKE_CASE(AArch64ISD::UITOF)
1587     MAKE_CASE(AArch64ISD::NVCAST)
1588     MAKE_CASE(AArch64ISD::SQSHL_I)
1589     MAKE_CASE(AArch64ISD::UQSHL_I)
1590     MAKE_CASE(AArch64ISD::SRSHR_I)
1591     MAKE_CASE(AArch64ISD::URSHR_I)
1592     MAKE_CASE(AArch64ISD::SQSHLU_I)
1593     MAKE_CASE(AArch64ISD::WrapperLarge)
1594     MAKE_CASE(AArch64ISD::LD2post)
1595     MAKE_CASE(AArch64ISD::LD3post)
1596     MAKE_CASE(AArch64ISD::LD4post)
1597     MAKE_CASE(AArch64ISD::ST2post)
1598     MAKE_CASE(AArch64ISD::ST3post)
1599     MAKE_CASE(AArch64ISD::ST4post)
1600     MAKE_CASE(AArch64ISD::LD1x2post)
1601     MAKE_CASE(AArch64ISD::LD1x3post)
1602     MAKE_CASE(AArch64ISD::LD1x4post)
1603     MAKE_CASE(AArch64ISD::ST1x2post)
1604     MAKE_CASE(AArch64ISD::ST1x3post)
1605     MAKE_CASE(AArch64ISD::ST1x4post)
1606     MAKE_CASE(AArch64ISD::LD1DUPpost)
1607     MAKE_CASE(AArch64ISD::LD2DUPpost)
1608     MAKE_CASE(AArch64ISD::LD3DUPpost)
1609     MAKE_CASE(AArch64ISD::LD4DUPpost)
1610     MAKE_CASE(AArch64ISD::LD1LANEpost)
1611     MAKE_CASE(AArch64ISD::LD2LANEpost)
1612     MAKE_CASE(AArch64ISD::LD3LANEpost)
1613     MAKE_CASE(AArch64ISD::LD4LANEpost)
1614     MAKE_CASE(AArch64ISD::ST2LANEpost)
1615     MAKE_CASE(AArch64ISD::ST3LANEpost)
1616     MAKE_CASE(AArch64ISD::ST4LANEpost)
1617     MAKE_CASE(AArch64ISD::SMULL)
1618     MAKE_CASE(AArch64ISD::UMULL)
1619     MAKE_CASE(AArch64ISD::FRECPE)
1620     MAKE_CASE(AArch64ISD::FRECPS)
1621     MAKE_CASE(AArch64ISD::FRSQRTE)
1622     MAKE_CASE(AArch64ISD::FRSQRTS)
1623     MAKE_CASE(AArch64ISD::STG)
1624     MAKE_CASE(AArch64ISD::STZG)
1625     MAKE_CASE(AArch64ISD::ST2G)
1626     MAKE_CASE(AArch64ISD::STZ2G)
1627     MAKE_CASE(AArch64ISD::SUNPKHI)
1628     MAKE_CASE(AArch64ISD::SUNPKLO)
1629     MAKE_CASE(AArch64ISD::UUNPKHI)
1630     MAKE_CASE(AArch64ISD::UUNPKLO)
1631     MAKE_CASE(AArch64ISD::INSR)
1632     MAKE_CASE(AArch64ISD::PTEST)
1633     MAKE_CASE(AArch64ISD::PTRUE)
1634     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1635     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1636     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1637     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1638     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1639     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1640     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1641     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1642     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1643     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1644     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1645     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1646     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1647     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1648     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1649     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1650     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1651     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1652     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1653     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1654     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1655     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1656     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1657     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1658     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1659     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1660     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1661     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1662     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1663     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1664     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1665     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1666     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1667     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1668     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1669     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1670     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1671     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1672     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1673     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1674     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1675     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1676     MAKE_CASE(AArch64ISD::ST1_PRED)
1677     MAKE_CASE(AArch64ISD::SST1_PRED)
1678     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1679     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1680     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1681     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1682     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1683     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1684     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1685     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1686     MAKE_CASE(AArch64ISD::LDP)
1687     MAKE_CASE(AArch64ISD::STP)
1688     MAKE_CASE(AArch64ISD::STNP)
1689     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1690     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1691   }
1692 #undef MAKE_CASE
1693   return nullptr;
1694 }
1695 
1696 MachineBasicBlock *
1697 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1698                                     MachineBasicBlock *MBB) const {
1699   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1700   // phi node:
1701 
1702   // OrigBB:
1703   //     [... previous instrs leading to comparison ...]
1704   //     b.ne TrueBB
1705   //     b EndBB
1706   // TrueBB:
1707   //     ; Fallthrough
1708   // EndBB:
1709   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1710 
1711   MachineFunction *MF = MBB->getParent();
1712   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1713   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1714   DebugLoc DL = MI.getDebugLoc();
1715   MachineFunction::iterator It = ++MBB->getIterator();
1716 
1717   Register DestReg = MI.getOperand(0).getReg();
1718   Register IfTrueReg = MI.getOperand(1).getReg();
1719   Register IfFalseReg = MI.getOperand(2).getReg();
1720   unsigned CondCode = MI.getOperand(3).getImm();
1721   bool NZCVKilled = MI.getOperand(4).isKill();
1722 
1723   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1724   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1725   MF->insert(It, TrueBB);
1726   MF->insert(It, EndBB);
1727 
1728   // Transfer rest of current basic-block to EndBB
1729   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1730                 MBB->end());
1731   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1732 
1733   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1734   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1735   MBB->addSuccessor(TrueBB);
1736   MBB->addSuccessor(EndBB);
1737 
1738   // TrueBB falls through to the end.
1739   TrueBB->addSuccessor(EndBB);
1740 
1741   if (!NZCVKilled) {
1742     TrueBB->addLiveIn(AArch64::NZCV);
1743     EndBB->addLiveIn(AArch64::NZCV);
1744   }
1745 
1746   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1747       .addReg(IfTrueReg)
1748       .addMBB(TrueBB)
1749       .addReg(IfFalseReg)
1750       .addMBB(MBB);
1751 
1752   MI.eraseFromParent();
1753   return EndBB;
1754 }
1755 
1756 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1757        MachineInstr &MI, MachineBasicBlock *BB) const {
1758   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1759              BB->getParent()->getFunction().getPersonalityFn())) &&
1760          "SEH does not use catchret!");
1761   return BB;
1762 }
1763 
1764 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1765     MachineInstr &MI, MachineBasicBlock *BB) const {
1766   switch (MI.getOpcode()) {
1767   default:
1768 #ifndef NDEBUG
1769     MI.dump();
1770 #endif
1771     llvm_unreachable("Unexpected instruction for custom inserter!");
1772 
1773   case AArch64::F128CSEL:
1774     return EmitF128CSEL(MI, BB);
1775 
1776   case TargetOpcode::STACKMAP:
1777   case TargetOpcode::PATCHPOINT:
1778     return emitPatchPoint(MI, BB);
1779 
1780   case AArch64::CATCHRET:
1781     return EmitLoweredCatchRet(MI, BB);
1782   }
1783 }
1784 
1785 //===----------------------------------------------------------------------===//
1786 // AArch64 Lowering private implementation.
1787 //===----------------------------------------------------------------------===//
1788 
1789 //===----------------------------------------------------------------------===//
1790 // Lowering Code
1791 //===----------------------------------------------------------------------===//
1792 
1793 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1794 /// CC
1795 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1796   switch (CC) {
1797   default:
1798     llvm_unreachable("Unknown condition code!");
1799   case ISD::SETNE:
1800     return AArch64CC::NE;
1801   case ISD::SETEQ:
1802     return AArch64CC::EQ;
1803   case ISD::SETGT:
1804     return AArch64CC::GT;
1805   case ISD::SETGE:
1806     return AArch64CC::GE;
1807   case ISD::SETLT:
1808     return AArch64CC::LT;
1809   case ISD::SETLE:
1810     return AArch64CC::LE;
1811   case ISD::SETUGT:
1812     return AArch64CC::HI;
1813   case ISD::SETUGE:
1814     return AArch64CC::HS;
1815   case ISD::SETULT:
1816     return AArch64CC::LO;
1817   case ISD::SETULE:
1818     return AArch64CC::LS;
1819   }
1820 }
1821 
1822 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1823 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1824                                   AArch64CC::CondCode &CondCode,
1825                                   AArch64CC::CondCode &CondCode2) {
1826   CondCode2 = AArch64CC::AL;
1827   switch (CC) {
1828   default:
1829     llvm_unreachable("Unknown FP condition!");
1830   case ISD::SETEQ:
1831   case ISD::SETOEQ:
1832     CondCode = AArch64CC::EQ;
1833     break;
1834   case ISD::SETGT:
1835   case ISD::SETOGT:
1836     CondCode = AArch64CC::GT;
1837     break;
1838   case ISD::SETGE:
1839   case ISD::SETOGE:
1840     CondCode = AArch64CC::GE;
1841     break;
1842   case ISD::SETOLT:
1843     CondCode = AArch64CC::MI;
1844     break;
1845   case ISD::SETOLE:
1846     CondCode = AArch64CC::LS;
1847     break;
1848   case ISD::SETONE:
1849     CondCode = AArch64CC::MI;
1850     CondCode2 = AArch64CC::GT;
1851     break;
1852   case ISD::SETO:
1853     CondCode = AArch64CC::VC;
1854     break;
1855   case ISD::SETUO:
1856     CondCode = AArch64CC::VS;
1857     break;
1858   case ISD::SETUEQ:
1859     CondCode = AArch64CC::EQ;
1860     CondCode2 = AArch64CC::VS;
1861     break;
1862   case ISD::SETUGT:
1863     CondCode = AArch64CC::HI;
1864     break;
1865   case ISD::SETUGE:
1866     CondCode = AArch64CC::PL;
1867     break;
1868   case ISD::SETLT:
1869   case ISD::SETULT:
1870     CondCode = AArch64CC::LT;
1871     break;
1872   case ISD::SETLE:
1873   case ISD::SETULE:
1874     CondCode = AArch64CC::LE;
1875     break;
1876   case ISD::SETNE:
1877   case ISD::SETUNE:
1878     CondCode = AArch64CC::NE;
1879     break;
1880   }
1881 }
1882 
1883 /// Convert a DAG fp condition code to an AArch64 CC.
1884 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1885 /// should be AND'ed instead of OR'ed.
1886 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1887                                      AArch64CC::CondCode &CondCode,
1888                                      AArch64CC::CondCode &CondCode2) {
1889   CondCode2 = AArch64CC::AL;
1890   switch (CC) {
1891   default:
1892     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1893     assert(CondCode2 == AArch64CC::AL);
1894     break;
1895   case ISD::SETONE:
1896     // (a one b)
1897     // == ((a olt b) || (a ogt b))
1898     // == ((a ord b) && (a une b))
1899     CondCode = AArch64CC::VC;
1900     CondCode2 = AArch64CC::NE;
1901     break;
1902   case ISD::SETUEQ:
1903     // (a ueq b)
1904     // == ((a uno b) || (a oeq b))
1905     // == ((a ule b) && (a uge b))
1906     CondCode = AArch64CC::PL;
1907     CondCode2 = AArch64CC::LE;
1908     break;
1909   }
1910 }
1911 
1912 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1913 /// CC usable with the vector instructions. Fewer operations are available
1914 /// without a real NZCV register, so we have to use less efficient combinations
1915 /// to get the same effect.
1916 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1917                                         AArch64CC::CondCode &CondCode,
1918                                         AArch64CC::CondCode &CondCode2,
1919                                         bool &Invert) {
1920   Invert = false;
1921   switch (CC) {
1922   default:
1923     // Mostly the scalar mappings work fine.
1924     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1925     break;
1926   case ISD::SETUO:
1927     Invert = true;
1928     LLVM_FALLTHROUGH;
1929   case ISD::SETO:
1930     CondCode = AArch64CC::MI;
1931     CondCode2 = AArch64CC::GE;
1932     break;
1933   case ISD::SETUEQ:
1934   case ISD::SETULT:
1935   case ISD::SETULE:
1936   case ISD::SETUGT:
1937   case ISD::SETUGE:
1938     // All of the compare-mask comparisons are ordered, but we can switch
1939     // between the two by a double inversion. E.g. ULE == !OGT.
1940     Invert = true;
1941     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1942                           CondCode, CondCode2);
1943     break;
1944   }
1945 }
1946 
1947 static bool isLegalArithImmed(uint64_t C) {
1948   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1949   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1950   LLVM_DEBUG(dbgs() << "Is imm " << C
1951                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1952   return IsLegal;
1953 }
1954 
1955 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1956 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1957 // can be set differently by this operation. It comes down to whether
1958 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1959 // everything is fine. If not then the optimization is wrong. Thus general
1960 // comparisons are only valid if op2 != 0.
1961 //
1962 // So, finally, the only LLVM-native comparisons that don't mention C and V
1963 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1964 // the absence of information about op2.
1965 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1966   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1967          (CC == ISD::SETEQ || CC == ISD::SETNE);
1968 }
1969 
1970 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1971                                       SelectionDAG &DAG, SDValue Chain,
1972                                       bool IsSignaling) {
1973   EVT VT = LHS.getValueType();
1974   assert(VT != MVT::f128);
1975   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1976   unsigned Opcode =
1977       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1978   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1979 }
1980 
1981 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1982                               const SDLoc &dl, SelectionDAG &DAG) {
1983   EVT VT = LHS.getValueType();
1984   const bool FullFP16 =
1985     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1986 
1987   if (VT.isFloatingPoint()) {
1988     assert(VT != MVT::f128);
1989     if (VT == MVT::f16 && !FullFP16) {
1990       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1991       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1992       VT = MVT::f32;
1993     }
1994     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1995   }
1996 
1997   // The CMP instruction is just an alias for SUBS, and representing it as
1998   // SUBS means that it's possible to get CSE with subtract operations.
1999   // A later phase can perform the optimization of setting the destination
2000   // register to WZR/XZR if it ends up being unused.
2001   unsigned Opcode = AArch64ISD::SUBS;
2002 
2003   if (isCMN(RHS, CC)) {
2004     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2005     Opcode = AArch64ISD::ADDS;
2006     RHS = RHS.getOperand(1);
2007   } else if (isCMN(LHS, CC)) {
2008     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2009     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2010     Opcode = AArch64ISD::ADDS;
2011     LHS = LHS.getOperand(1);
2012   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2013     if (LHS.getOpcode() == ISD::AND) {
2014       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2015       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2016       // of the signed comparisons.
2017       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2018                                            DAG.getVTList(VT, MVT_CC),
2019                                            LHS.getOperand(0),
2020                                            LHS.getOperand(1));
2021       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2022       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2023       return ANDSNode.getValue(1);
2024     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2025       // Use result of ANDS
2026       return LHS.getValue(1);
2027     }
2028   }
2029 
2030   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2031       .getValue(1);
2032 }
2033 
2034 /// \defgroup AArch64CCMP CMP;CCMP matching
2035 ///
2036 /// These functions deal with the formation of CMP;CCMP;... sequences.
2037 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2038 /// a comparison. They set the NZCV flags to a predefined value if their
2039 /// predicate is false. This allows to express arbitrary conjunctions, for
2040 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2041 /// expressed as:
2042 ///   cmp A
2043 ///   ccmp B, inv(CB), CA
2044 ///   check for CB flags
2045 ///
2046 /// This naturally lets us implement chains of AND operations with SETCC
2047 /// operands. And we can even implement some other situations by transforming
2048 /// them:
2049 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2050 ///     negating the flags used in a CCMP/FCCMP operations.
2051 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2052 ///     by negating the flags we test for afterwards. i.e.
2053 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2054 ///   - Note that we can only ever negate all previously processed results.
2055 ///     What we can not implement by flipping the flags to test is a negation
2056 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2057 ///     far, so the 2nd sub-tree we emit would also affect the first).
2058 /// With those tools we can implement some OR operations:
2059 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2060 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2061 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2062 ///     elimination rules from earlier to implement the whole thing as a
2063 ///     CCMP/FCCMP chain.
2064 ///
2065 /// As complete example:
2066 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2067 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2068 /// can be reassociated to:
2069 ///     or (and (setCC (cmp C)) setCD (cmp D))
2070 //         (or (setCA (cmp A)) (setCB (cmp B)))
2071 /// can be transformed to:
2072 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2073 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2074 /// which can be implemented as:
2075 ///   cmp C
2076 ///   ccmp D, inv(CD), CC
2077 ///   ccmp A, CA, inv(CD)
2078 ///   ccmp B, CB, inv(CA)
2079 ///   check for CB flags
2080 ///
2081 /// A counterexample is "or (and A B) (and C D)" which translates to
2082 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2083 /// can only implement 1 of the inner (not) operations, but not both!
2084 /// @{
2085 
2086 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2087 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2088                                          ISD::CondCode CC, SDValue CCOp,
2089                                          AArch64CC::CondCode Predicate,
2090                                          AArch64CC::CondCode OutCC,
2091                                          const SDLoc &DL, SelectionDAG &DAG) {
2092   unsigned Opcode = 0;
2093   const bool FullFP16 =
2094     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2095 
2096   if (LHS.getValueType().isFloatingPoint()) {
2097     assert(LHS.getValueType() != MVT::f128);
2098     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2099       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2100       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2101     }
2102     Opcode = AArch64ISD::FCCMP;
2103   } else if (RHS.getOpcode() == ISD::SUB) {
2104     SDValue SubOp0 = RHS.getOperand(0);
2105     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2106       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2107       Opcode = AArch64ISD::CCMN;
2108       RHS = RHS.getOperand(1);
2109     }
2110   }
2111   if (Opcode == 0)
2112     Opcode = AArch64ISD::CCMP;
2113 
2114   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2115   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2116   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2117   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2118   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2119 }
2120 
2121 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2122 /// expressed as a conjunction. See \ref AArch64CCMP.
2123 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2124 ///                     changing the conditions on the SETCC tests.
2125 ///                     (this means we can call emitConjunctionRec() with
2126 ///                      Negate==true on this sub-tree)
2127 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2128 ///                     cannot do the negation naturally. We are required to
2129 ///                     emit the subtree first in this case.
2130 /// \param WillNegate   Is true if are called when the result of this
2131 ///                     subexpression must be negated. This happens when the
2132 ///                     outer expression is an OR. We can use this fact to know
2133 ///                     that we have a double negation (or (or ...) ...) that
2134 ///                     can be implemented for free.
2135 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2136                                bool &MustBeFirst, bool WillNegate,
2137                                unsigned Depth = 0) {
2138   if (!Val.hasOneUse())
2139     return false;
2140   unsigned Opcode = Val->getOpcode();
2141   if (Opcode == ISD::SETCC) {
2142     if (Val->getOperand(0).getValueType() == MVT::f128)
2143       return false;
2144     CanNegate = true;
2145     MustBeFirst = false;
2146     return true;
2147   }
2148   // Protect against exponential runtime and stack overflow.
2149   if (Depth > 6)
2150     return false;
2151   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2152     bool IsOR = Opcode == ISD::OR;
2153     SDValue O0 = Val->getOperand(0);
2154     SDValue O1 = Val->getOperand(1);
2155     bool CanNegateL;
2156     bool MustBeFirstL;
2157     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2158       return false;
2159     bool CanNegateR;
2160     bool MustBeFirstR;
2161     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2162       return false;
2163 
2164     if (MustBeFirstL && MustBeFirstR)
2165       return false;
2166 
2167     if (IsOR) {
2168       // For an OR expression we need to be able to naturally negate at least
2169       // one side or we cannot do the transformation at all.
2170       if (!CanNegateL && !CanNegateR)
2171         return false;
2172       // If we the result of the OR will be negated and we can naturally negate
2173       // the leafs, then this sub-tree as a whole negates naturally.
2174       CanNegate = WillNegate && CanNegateL && CanNegateR;
2175       // If we cannot naturally negate the whole sub-tree, then this must be
2176       // emitted first.
2177       MustBeFirst = !CanNegate;
2178     } else {
2179       assert(Opcode == ISD::AND && "Must be OR or AND");
2180       // We cannot naturally negate an AND operation.
2181       CanNegate = false;
2182       MustBeFirst = MustBeFirstL || MustBeFirstR;
2183     }
2184     return true;
2185   }
2186   return false;
2187 }
2188 
2189 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2190 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2191 /// Tries to transform the given i1 producing node @p Val to a series compare
2192 /// and conditional compare operations. @returns an NZCV flags producing node
2193 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2194 /// transformation was not possible.
2195 /// \p Negate is true if we want this sub-tree being negated just by changing
2196 /// SETCC conditions.
2197 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2198     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2199     AArch64CC::CondCode Predicate) {
2200   // We're at a tree leaf, produce a conditional comparison operation.
2201   unsigned Opcode = Val->getOpcode();
2202   if (Opcode == ISD::SETCC) {
2203     SDValue LHS = Val->getOperand(0);
2204     SDValue RHS = Val->getOperand(1);
2205     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2206     bool isInteger = LHS.getValueType().isInteger();
2207     if (Negate)
2208       CC = getSetCCInverse(CC, LHS.getValueType());
2209     SDLoc DL(Val);
2210     // Determine OutCC and handle FP special case.
2211     if (isInteger) {
2212       OutCC = changeIntCCToAArch64CC(CC);
2213     } else {
2214       assert(LHS.getValueType().isFloatingPoint());
2215       AArch64CC::CondCode ExtraCC;
2216       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2217       // Some floating point conditions can't be tested with a single condition
2218       // code. Construct an additional comparison in this case.
2219       if (ExtraCC != AArch64CC::AL) {
2220         SDValue ExtraCmp;
2221         if (!CCOp.getNode())
2222           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2223         else
2224           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2225                                                ExtraCC, DL, DAG);
2226         CCOp = ExtraCmp;
2227         Predicate = ExtraCC;
2228       }
2229     }
2230 
2231     // Produce a normal comparison if we are first in the chain
2232     if (!CCOp)
2233       return emitComparison(LHS, RHS, CC, DL, DAG);
2234     // Otherwise produce a ccmp.
2235     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2236                                      DAG);
2237   }
2238   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2239 
2240   bool IsOR = Opcode == ISD::OR;
2241 
2242   SDValue LHS = Val->getOperand(0);
2243   bool CanNegateL;
2244   bool MustBeFirstL;
2245   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2246   assert(ValidL && "Valid conjunction/disjunction tree");
2247   (void)ValidL;
2248 
2249   SDValue RHS = Val->getOperand(1);
2250   bool CanNegateR;
2251   bool MustBeFirstR;
2252   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2253   assert(ValidR && "Valid conjunction/disjunction tree");
2254   (void)ValidR;
2255 
2256   // Swap sub-tree that must come first to the right side.
2257   if (MustBeFirstL) {
2258     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2259     std::swap(LHS, RHS);
2260     std::swap(CanNegateL, CanNegateR);
2261     std::swap(MustBeFirstL, MustBeFirstR);
2262   }
2263 
2264   bool NegateR;
2265   bool NegateAfterR;
2266   bool NegateL;
2267   bool NegateAfterAll;
2268   if (Opcode == ISD::OR) {
2269     // Swap the sub-tree that we can negate naturally to the left.
2270     if (!CanNegateL) {
2271       assert(CanNegateR && "at least one side must be negatable");
2272       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2273       assert(!Negate);
2274       std::swap(LHS, RHS);
2275       NegateR = false;
2276       NegateAfterR = true;
2277     } else {
2278       // Negate the left sub-tree if possible, otherwise negate the result.
2279       NegateR = CanNegateR;
2280       NegateAfterR = !CanNegateR;
2281     }
2282     NegateL = true;
2283     NegateAfterAll = !Negate;
2284   } else {
2285     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2286     assert(!Negate && "Valid conjunction/disjunction tree");
2287 
2288     NegateL = false;
2289     NegateR = false;
2290     NegateAfterR = false;
2291     NegateAfterAll = false;
2292   }
2293 
2294   // Emit sub-trees.
2295   AArch64CC::CondCode RHSCC;
2296   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2297   if (NegateAfterR)
2298     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2299   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2300   if (NegateAfterAll)
2301     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2302   return CmpL;
2303 }
2304 
2305 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2306 /// In some cases this is even possible with OR operations in the expression.
2307 /// See \ref AArch64CCMP.
2308 /// \see emitConjunctionRec().
2309 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2310                                AArch64CC::CondCode &OutCC) {
2311   bool DummyCanNegate;
2312   bool DummyMustBeFirst;
2313   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2314     return SDValue();
2315 
2316   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2317 }
2318 
2319 /// @}
2320 
2321 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2322 /// extension operations.
2323 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2324   auto isSupportedExtend = [&](SDValue V) {
2325     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2326       return true;
2327 
2328     if (V.getOpcode() == ISD::AND)
2329       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2330         uint64_t Mask = MaskCst->getZExtValue();
2331         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2332       }
2333 
2334     return false;
2335   };
2336 
2337   if (!Op.hasOneUse())
2338     return 0;
2339 
2340   if (isSupportedExtend(Op))
2341     return 1;
2342 
2343   unsigned Opc = Op.getOpcode();
2344   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2345     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2346       uint64_t Shift = ShiftCst->getZExtValue();
2347       if (isSupportedExtend(Op.getOperand(0)))
2348         return (Shift <= 4) ? 2 : 1;
2349       EVT VT = Op.getValueType();
2350       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2351         return 1;
2352     }
2353 
2354   return 0;
2355 }
2356 
2357 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2358                              SDValue &AArch64cc, SelectionDAG &DAG,
2359                              const SDLoc &dl) {
2360   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2361     EVT VT = RHS.getValueType();
2362     uint64_t C = RHSC->getZExtValue();
2363     if (!isLegalArithImmed(C)) {
2364       // Constant does not fit, try adjusting it by one?
2365       switch (CC) {
2366       default:
2367         break;
2368       case ISD::SETLT:
2369       case ISD::SETGE:
2370         if ((VT == MVT::i32 && C != 0x80000000 &&
2371              isLegalArithImmed((uint32_t)(C - 1))) ||
2372             (VT == MVT::i64 && C != 0x80000000ULL &&
2373              isLegalArithImmed(C - 1ULL))) {
2374           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2375           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2376           RHS = DAG.getConstant(C, dl, VT);
2377         }
2378         break;
2379       case ISD::SETULT:
2380       case ISD::SETUGE:
2381         if ((VT == MVT::i32 && C != 0 &&
2382              isLegalArithImmed((uint32_t)(C - 1))) ||
2383             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2384           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2385           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2386           RHS = DAG.getConstant(C, dl, VT);
2387         }
2388         break;
2389       case ISD::SETLE:
2390       case ISD::SETGT:
2391         if ((VT == MVT::i32 && C != INT32_MAX &&
2392              isLegalArithImmed((uint32_t)(C + 1))) ||
2393             (VT == MVT::i64 && C != INT64_MAX &&
2394              isLegalArithImmed(C + 1ULL))) {
2395           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2396           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2397           RHS = DAG.getConstant(C, dl, VT);
2398         }
2399         break;
2400       case ISD::SETULE:
2401       case ISD::SETUGT:
2402         if ((VT == MVT::i32 && C != UINT32_MAX &&
2403              isLegalArithImmed((uint32_t)(C + 1))) ||
2404             (VT == MVT::i64 && C != UINT64_MAX &&
2405              isLegalArithImmed(C + 1ULL))) {
2406           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2407           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2408           RHS = DAG.getConstant(C, dl, VT);
2409         }
2410         break;
2411       }
2412     }
2413   }
2414 
2415   // Comparisons are canonicalized so that the RHS operand is simpler than the
2416   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2417   // can fold some shift+extend operations on the RHS operand, so swap the
2418   // operands if that can be done.
2419   //
2420   // For example:
2421   //    lsl     w13, w11, #1
2422   //    cmp     w13, w12
2423   // can be turned into:
2424   //    cmp     w12, w11, lsl #1
2425   if (!isa<ConstantSDNode>(RHS) ||
2426       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2427     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2428 
2429     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2430       std::swap(LHS, RHS);
2431       CC = ISD::getSetCCSwappedOperands(CC);
2432     }
2433   }
2434 
2435   SDValue Cmp;
2436   AArch64CC::CondCode AArch64CC;
2437   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2438     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2439 
2440     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2441     // For the i8 operand, the largest immediate is 255, so this can be easily
2442     // encoded in the compare instruction. For the i16 operand, however, the
2443     // largest immediate cannot be encoded in the compare.
2444     // Therefore, use a sign extending load and cmn to avoid materializing the
2445     // -1 constant. For example,
2446     // movz w1, #65535
2447     // ldrh w0, [x0, #0]
2448     // cmp w0, w1
2449     // >
2450     // ldrsh w0, [x0, #0]
2451     // cmn w0, #1
2452     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2453     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2454     // ensure both the LHS and RHS are truly zero extended and to make sure the
2455     // transformation is profitable.
2456     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2457         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2458         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2459         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2460       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2461       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2462         SDValue SExt =
2463             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2464                         DAG.getValueType(MVT::i16));
2465         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2466                                                    RHS.getValueType()),
2467                              CC, dl, DAG);
2468         AArch64CC = changeIntCCToAArch64CC(CC);
2469       }
2470     }
2471 
2472     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2473       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2474         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2475           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2476       }
2477     }
2478   }
2479 
2480   if (!Cmp) {
2481     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2482     AArch64CC = changeIntCCToAArch64CC(CC);
2483   }
2484   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2485   return Cmp;
2486 }
2487 
2488 static std::pair<SDValue, SDValue>
2489 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2490   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2491          "Unsupported value type");
2492   SDValue Value, Overflow;
2493   SDLoc DL(Op);
2494   SDValue LHS = Op.getOperand(0);
2495   SDValue RHS = Op.getOperand(1);
2496   unsigned Opc = 0;
2497   switch (Op.getOpcode()) {
2498   default:
2499     llvm_unreachable("Unknown overflow instruction!");
2500   case ISD::SADDO:
2501     Opc = AArch64ISD::ADDS;
2502     CC = AArch64CC::VS;
2503     break;
2504   case ISD::UADDO:
2505     Opc = AArch64ISD::ADDS;
2506     CC = AArch64CC::HS;
2507     break;
2508   case ISD::SSUBO:
2509     Opc = AArch64ISD::SUBS;
2510     CC = AArch64CC::VS;
2511     break;
2512   case ISD::USUBO:
2513     Opc = AArch64ISD::SUBS;
2514     CC = AArch64CC::LO;
2515     break;
2516   // Multiply needs a little bit extra work.
2517   case ISD::SMULO:
2518   case ISD::UMULO: {
2519     CC = AArch64CC::NE;
2520     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2521     if (Op.getValueType() == MVT::i32) {
2522       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2523       // For a 32 bit multiply with overflow check we want the instruction
2524       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2525       // need to generate the following pattern:
2526       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2527       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2528       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2529       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2530       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2531                                 DAG.getConstant(0, DL, MVT::i64));
2532       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2533       // operation. We need to clear out the upper 32 bits, because we used a
2534       // widening multiply that wrote all 64 bits. In the end this should be a
2535       // noop.
2536       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2537       if (IsSigned) {
2538         // The signed overflow check requires more than just a simple check for
2539         // any bit set in the upper 32 bits of the result. These bits could be
2540         // just the sign bits of a negative number. To perform the overflow
2541         // check we have to arithmetic shift right the 32nd bit of the result by
2542         // 31 bits. Then we compare the result to the upper 32 bits.
2543         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2544                                         DAG.getConstant(32, DL, MVT::i64));
2545         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2546         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2547                                         DAG.getConstant(31, DL, MVT::i64));
2548         // It is important that LowerBits is last, otherwise the arithmetic
2549         // shift will not be folded into the compare (SUBS).
2550         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2551         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2552                        .getValue(1);
2553       } else {
2554         // The overflow check for unsigned multiply is easy. We only need to
2555         // check if any of the upper 32 bits are set. This can be done with a
2556         // CMP (shifted register). For that we need to generate the following
2557         // pattern:
2558         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2559         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2560                                         DAG.getConstant(32, DL, MVT::i64));
2561         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2562         Overflow =
2563             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2564                         DAG.getConstant(0, DL, MVT::i64),
2565                         UpperBits).getValue(1);
2566       }
2567       break;
2568     }
2569     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2570     // For the 64 bit multiply
2571     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2572     if (IsSigned) {
2573       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2574       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2575                                       DAG.getConstant(63, DL, MVT::i64));
2576       // It is important that LowerBits is last, otherwise the arithmetic
2577       // shift will not be folded into the compare (SUBS).
2578       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2579       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2580                      .getValue(1);
2581     } else {
2582       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2583       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2584       Overflow =
2585           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2586                       DAG.getConstant(0, DL, MVT::i64),
2587                       UpperBits).getValue(1);
2588     }
2589     break;
2590   }
2591   } // switch (...)
2592 
2593   if (Opc) {
2594     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2595 
2596     // Emit the AArch64 operation with overflow check.
2597     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2598     Overflow = Value.getValue(1);
2599   }
2600   return std::make_pair(Value, Overflow);
2601 }
2602 
2603 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2604                                              RTLIB::Libcall Call) const {
2605   bool IsStrict = Op->isStrictFPOpcode();
2606   unsigned Offset = IsStrict ? 1 : 0;
2607   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2608   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2609   MakeLibCallOptions CallOptions;
2610   SDValue Result;
2611   SDLoc dl(Op);
2612   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2613                                         CallOptions, dl, Chain);
2614   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2615 }
2616 
2617 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
2618   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
2619     return LowerToScalableOp(Op, DAG);
2620 
2621   SDValue Sel = Op.getOperand(0);
2622   SDValue Other = Op.getOperand(1);
2623   SDLoc dl(Sel);
2624 
2625   // If the operand is an overflow checking operation, invert the condition
2626   // code and kill the Not operation. I.e., transform:
2627   // (xor (overflow_op_bool, 1))
2628   //   -->
2629   // (csel 1, 0, invert(cc), overflow_op_bool)
2630   // ... which later gets transformed to just a cset instruction with an
2631   // inverted condition code, rather than a cset + eor sequence.
2632   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2633     // Only lower legal XALUO ops.
2634     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2635       return SDValue();
2636 
2637     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2638     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2639     AArch64CC::CondCode CC;
2640     SDValue Value, Overflow;
2641     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2642     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2643     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2644                        CCVal, Overflow);
2645   }
2646   // If neither operand is a SELECT_CC, give up.
2647   if (Sel.getOpcode() != ISD::SELECT_CC)
2648     std::swap(Sel, Other);
2649   if (Sel.getOpcode() != ISD::SELECT_CC)
2650     return Op;
2651 
2652   // The folding we want to perform is:
2653   // (xor x, (select_cc a, b, cc, 0, -1) )
2654   //   -->
2655   // (csel x, (xor x, -1), cc ...)
2656   //
2657   // The latter will get matched to a CSINV instruction.
2658 
2659   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2660   SDValue LHS = Sel.getOperand(0);
2661   SDValue RHS = Sel.getOperand(1);
2662   SDValue TVal = Sel.getOperand(2);
2663   SDValue FVal = Sel.getOperand(3);
2664 
2665   // FIXME: This could be generalized to non-integer comparisons.
2666   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2667     return Op;
2668 
2669   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2670   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2671 
2672   // The values aren't constants, this isn't the pattern we're looking for.
2673   if (!CFVal || !CTVal)
2674     return Op;
2675 
2676   // We can commute the SELECT_CC by inverting the condition.  This
2677   // might be needed to make this fit into a CSINV pattern.
2678   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2679     std::swap(TVal, FVal);
2680     std::swap(CTVal, CFVal);
2681     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2682   }
2683 
2684   // If the constants line up, perform the transform!
2685   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2686     SDValue CCVal;
2687     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2688 
2689     FVal = Other;
2690     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2691                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2692 
2693     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2694                        CCVal, Cmp);
2695   }
2696 
2697   return Op;
2698 }
2699 
2700 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2701   EVT VT = Op.getValueType();
2702 
2703   // Let legalize expand this if it isn't a legal type yet.
2704   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2705     return SDValue();
2706 
2707   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2708 
2709   unsigned Opc;
2710   bool ExtraOp = false;
2711   switch (Op.getOpcode()) {
2712   default:
2713     llvm_unreachable("Invalid code");
2714   case ISD::ADDC:
2715     Opc = AArch64ISD::ADDS;
2716     break;
2717   case ISD::SUBC:
2718     Opc = AArch64ISD::SUBS;
2719     break;
2720   case ISD::ADDE:
2721     Opc = AArch64ISD::ADCS;
2722     ExtraOp = true;
2723     break;
2724   case ISD::SUBE:
2725     Opc = AArch64ISD::SBCS;
2726     ExtraOp = true;
2727     break;
2728   }
2729 
2730   if (!ExtraOp)
2731     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2732   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2733                      Op.getOperand(2));
2734 }
2735 
2736 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2737   // Let legalize expand this if it isn't a legal type yet.
2738   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2739     return SDValue();
2740 
2741   SDLoc dl(Op);
2742   AArch64CC::CondCode CC;
2743   // The actual operation that sets the overflow or carry flag.
2744   SDValue Value, Overflow;
2745   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2746 
2747   // We use 0 and 1 as false and true values.
2748   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2749   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2750 
2751   // We use an inverted condition, because the conditional select is inverted
2752   // too. This will allow it to be selected to a single instruction:
2753   // CSINC Wd, WZR, WZR, invert(cond).
2754   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2755   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2756                          CCVal, Overflow);
2757 
2758   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2759   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2760 }
2761 
2762 // Prefetch operands are:
2763 // 1: Address to prefetch
2764 // 2: bool isWrite
2765 // 3: int locality (0 = no locality ... 3 = extreme locality)
2766 // 4: bool isDataCache
2767 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2768   SDLoc DL(Op);
2769   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2770   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2771   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2772 
2773   bool IsStream = !Locality;
2774   // When the locality number is set
2775   if (Locality) {
2776     // The front-end should have filtered out the out-of-range values
2777     assert(Locality <= 3 && "Prefetch locality out-of-range");
2778     // The locality degree is the opposite of the cache speed.
2779     // Put the number the other way around.
2780     // The encoding starts at 0 for level 1
2781     Locality = 3 - Locality;
2782   }
2783 
2784   // built the mask value encoding the expected behavior.
2785   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2786                    (!IsData << 3) |     // IsDataCache bit
2787                    (Locality << 1) |    // Cache level bits
2788                    (unsigned)IsStream;  // Stream bit
2789   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2790                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2791 }
2792 
2793 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2794                                               SelectionDAG &DAG) const {
2795   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2796 
2797   RTLIB::Libcall LC;
2798   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2799 
2800   return LowerF128Call(Op, DAG, LC);
2801 }
2802 
2803 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2804                                              SelectionDAG &DAG) const {
2805   bool IsStrict = Op->isStrictFPOpcode();
2806   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2807   EVT SrcVT = SrcVal.getValueType();
2808 
2809   if (SrcVT != MVT::f128) {
2810     // Expand cases where the input is a vector bigger than NEON.
2811     if (useSVEForFixedLengthVectorVT(SrcVT))
2812       return SDValue();
2813 
2814     // It's legal except when f128 is involved
2815     return Op;
2816   }
2817 
2818   RTLIB::Libcall LC;
2819   LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2820 
2821   // FP_ROUND node has a second operand indicating whether it is known to be
2822   // precise. That doesn't take part in the LibCall so we can't directly use
2823   // LowerF128Call.
2824   MakeLibCallOptions CallOptions;
2825   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2826   SDValue Result;
2827   SDLoc dl(Op);
2828   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2829                                         CallOptions, dl, Chain);
2830   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2831 }
2832 
2833 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2834                                                     SelectionDAG &DAG) const {
2835   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2836   // Any additional optimization in this function should be recorded
2837   // in the cost tables.
2838   EVT InVT = Op.getOperand(0).getValueType();
2839   EVT VT = Op.getValueType();
2840   unsigned NumElts = InVT.getVectorNumElements();
2841 
2842   // f16 conversions are promoted to f32 when full fp16 is not supported.
2843   if (InVT.getVectorElementType() == MVT::f16 &&
2844       !Subtarget->hasFullFP16()) {
2845     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2846     SDLoc dl(Op);
2847     return DAG.getNode(
2848         Op.getOpcode(), dl, Op.getValueType(),
2849         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2850   }
2851 
2852   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2853     SDLoc dl(Op);
2854     SDValue Cv =
2855         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2856                     Op.getOperand(0));
2857     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2858   }
2859 
2860   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2861     SDLoc dl(Op);
2862     MVT ExtVT =
2863         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2864                          VT.getVectorNumElements());
2865     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2866     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2867   }
2868 
2869   // Type changing conversions are illegal.
2870   return Op;
2871 }
2872 
2873 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2874                                               SelectionDAG &DAG) const {
2875   bool IsStrict = Op->isStrictFPOpcode();
2876   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2877 
2878   if (SrcVal.getValueType().isVector())
2879     return LowerVectorFP_TO_INT(Op, DAG);
2880 
2881   // f16 conversions are promoted to f32 when full fp16 is not supported.
2882   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2883     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2884     SDLoc dl(Op);
2885     return DAG.getNode(
2886         Op.getOpcode(), dl, Op.getValueType(),
2887         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2888   }
2889 
2890   if (SrcVal.getValueType() != MVT::f128) {
2891     // It's legal except when f128 is involved
2892     return Op;
2893   }
2894 
2895   RTLIB::Libcall LC;
2896   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2897       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2898     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2899   else
2900     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2901 
2902   return LowerF128Call(Op, DAG, LC);
2903 }
2904 
2905 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2906   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2907   // Any additional optimization in this function should be recorded
2908   // in the cost tables.
2909   EVT VT = Op.getValueType();
2910   SDLoc dl(Op);
2911   SDValue In = Op.getOperand(0);
2912   EVT InVT = In.getValueType();
2913 
2914   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2915     MVT CastVT =
2916         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2917                          InVT.getVectorNumElements());
2918     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2919     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2920   }
2921 
2922   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2923     unsigned CastOpc =
2924         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2925     EVT CastVT = VT.changeVectorElementTypeToInteger();
2926     In = DAG.getNode(CastOpc, dl, CastVT, In);
2927     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2928   }
2929 
2930   return Op;
2931 }
2932 
2933 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2934                                             SelectionDAG &DAG) const {
2935   if (Op.getValueType().isVector())
2936     return LowerVectorINT_TO_FP(Op, DAG);
2937 
2938   bool IsStrict = Op->isStrictFPOpcode();
2939   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2940 
2941   // f16 conversions are promoted to f32 when full fp16 is not supported.
2942   if (Op.getValueType() == MVT::f16 &&
2943       !Subtarget->hasFullFP16()) {
2944     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2945     SDLoc dl(Op);
2946     return DAG.getNode(
2947         ISD::FP_ROUND, dl, MVT::f16,
2948         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2949         DAG.getIntPtrConstant(0, dl));
2950   }
2951 
2952   // i128 conversions are libcalls.
2953   if (SrcVal.getValueType() == MVT::i128)
2954     return SDValue();
2955 
2956   // Other conversions are legal, unless it's to the completely software-based
2957   // fp128.
2958   if (Op.getValueType() != MVT::f128)
2959     return Op;
2960 
2961   RTLIB::Libcall LC;
2962   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2963       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2964     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2965   else
2966     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2967 
2968   return LowerF128Call(Op, DAG, LC);
2969 }
2970 
2971 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2972                                             SelectionDAG &DAG) const {
2973   // For iOS, we want to call an alternative entry point: __sincos_stret,
2974   // which returns the values in two S / D registers.
2975   SDLoc dl(Op);
2976   SDValue Arg = Op.getOperand(0);
2977   EVT ArgVT = Arg.getValueType();
2978   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2979 
2980   ArgListTy Args;
2981   ArgListEntry Entry;
2982 
2983   Entry.Node = Arg;
2984   Entry.Ty = ArgTy;
2985   Entry.IsSExt = false;
2986   Entry.IsZExt = false;
2987   Args.push_back(Entry);
2988 
2989   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2990                                         : RTLIB::SINCOS_STRET_F32;
2991   const char *LibcallName = getLibcallName(LC);
2992   SDValue Callee =
2993       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2994 
2995   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2996   TargetLowering::CallLoweringInfo CLI(DAG);
2997   CLI.setDebugLoc(dl)
2998       .setChain(DAG.getEntryNode())
2999       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3000 
3001   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3002   return CallResult.first;
3003 }
3004 
3005 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
3006   EVT OpVT = Op.getValueType();
3007   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3008     return SDValue();
3009 
3010   assert(Op.getOperand(0).getValueType() == MVT::i16);
3011   SDLoc DL(Op);
3012 
3013   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3014   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3015   return SDValue(
3016       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3017                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3018       0);
3019 }
3020 
3021 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3022   if (OrigVT.getSizeInBits() >= 64)
3023     return OrigVT;
3024 
3025   assert(OrigVT.isSimple() && "Expecting a simple value type");
3026 
3027   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3028   switch (OrigSimpleTy) {
3029   default: llvm_unreachable("Unexpected Vector Type");
3030   case MVT::v2i8:
3031   case MVT::v2i16:
3032      return MVT::v2i32;
3033   case MVT::v4i8:
3034     return  MVT::v4i16;
3035   }
3036 }
3037 
3038 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3039                                                  const EVT &OrigTy,
3040                                                  const EVT &ExtTy,
3041                                                  unsigned ExtOpcode) {
3042   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3043   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3044   // 64-bits we need to insert a new extension so that it will be 64-bits.
3045   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3046   if (OrigTy.getSizeInBits() >= 64)
3047     return N;
3048 
3049   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3050   EVT NewVT = getExtensionTo64Bits(OrigTy);
3051 
3052   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3053 }
3054 
3055 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3056                                    bool isSigned) {
3057   EVT VT = N->getValueType(0);
3058 
3059   if (N->getOpcode() != ISD::BUILD_VECTOR)
3060     return false;
3061 
3062   for (const SDValue &Elt : N->op_values()) {
3063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3064       unsigned EltSize = VT.getScalarSizeInBits();
3065       unsigned HalfSize = EltSize / 2;
3066       if (isSigned) {
3067         if (!isIntN(HalfSize, C->getSExtValue()))
3068           return false;
3069       } else {
3070         if (!isUIntN(HalfSize, C->getZExtValue()))
3071           return false;
3072       }
3073       continue;
3074     }
3075     return false;
3076   }
3077 
3078   return true;
3079 }
3080 
3081 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3082   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
3083     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3084                                              N->getOperand(0)->getValueType(0),
3085                                              N->getValueType(0),
3086                                              N->getOpcode());
3087 
3088   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3089   EVT VT = N->getValueType(0);
3090   SDLoc dl(N);
3091   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3092   unsigned NumElts = VT.getVectorNumElements();
3093   MVT TruncVT = MVT::getIntegerVT(EltSize);
3094   SmallVector<SDValue, 8> Ops;
3095   for (unsigned i = 0; i != NumElts; ++i) {
3096     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3097     const APInt &CInt = C->getAPIntValue();
3098     // Element types smaller than 32 bits are not legal, so use i32 elements.
3099     // The values are implicitly truncated so sext vs. zext doesn't matter.
3100     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3101   }
3102   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3103 }
3104 
3105 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3106   return N->getOpcode() == ISD::SIGN_EXTEND ||
3107          isExtendedBUILD_VECTOR(N, DAG, true);
3108 }
3109 
3110 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3111   return N->getOpcode() == ISD::ZERO_EXTEND ||
3112          isExtendedBUILD_VECTOR(N, DAG, false);
3113 }
3114 
3115 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3116   unsigned Opcode = N->getOpcode();
3117   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3118     SDNode *N0 = N->getOperand(0).getNode();
3119     SDNode *N1 = N->getOperand(1).getNode();
3120     return N0->hasOneUse() && N1->hasOneUse() &&
3121       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3122   }
3123   return false;
3124 }
3125 
3126 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3127   unsigned Opcode = N->getOpcode();
3128   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3129     SDNode *N0 = N->getOperand(0).getNode();
3130     SDNode *N1 = N->getOperand(1).getNode();
3131     return N0->hasOneUse() && N1->hasOneUse() &&
3132       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3133   }
3134   return false;
3135 }
3136 
3137 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3138                                                 SelectionDAG &DAG) const {
3139   // The rounding mode is in bits 23:22 of the FPSCR.
3140   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3141   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3142   // so that the shift + and get folded into a bitfield extract.
3143   SDLoc dl(Op);
3144 
3145   SDValue Chain = Op.getOperand(0);
3146   SDValue FPCR_64 = DAG.getNode(
3147       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3148       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3149   Chain = FPCR_64.getValue(1);
3150   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3151   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3152                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3153   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3154                               DAG.getConstant(22, dl, MVT::i32));
3155   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3156                             DAG.getConstant(3, dl, MVT::i32));
3157   return DAG.getMergeValues({AND, Chain}, dl);
3158 }
3159 
3160 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3161   EVT VT = Op.getValueType();
3162 
3163   // If SVE is available then i64 vector multiplications can also be made legal.
3164   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3165 
3166   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3167     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3168 
3169   // Multiplications are only custom-lowered for 128-bit vectors so that
3170   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3171   assert(VT.is128BitVector() && VT.isInteger() &&
3172          "unexpected type for custom-lowering ISD::MUL");
3173   SDNode *N0 = Op.getOperand(0).getNode();
3174   SDNode *N1 = Op.getOperand(1).getNode();
3175   unsigned NewOpc = 0;
3176   bool isMLA = false;
3177   bool isN0SExt = isSignExtended(N0, DAG);
3178   bool isN1SExt = isSignExtended(N1, DAG);
3179   if (isN0SExt && isN1SExt)
3180     NewOpc = AArch64ISD::SMULL;
3181   else {
3182     bool isN0ZExt = isZeroExtended(N0, DAG);
3183     bool isN1ZExt = isZeroExtended(N1, DAG);
3184     if (isN0ZExt && isN1ZExt)
3185       NewOpc = AArch64ISD::UMULL;
3186     else if (isN1SExt || isN1ZExt) {
3187       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3188       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3189       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3190         NewOpc = AArch64ISD::SMULL;
3191         isMLA = true;
3192       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3193         NewOpc =  AArch64ISD::UMULL;
3194         isMLA = true;
3195       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3196         std::swap(N0, N1);
3197         NewOpc =  AArch64ISD::UMULL;
3198         isMLA = true;
3199       }
3200     }
3201 
3202     if (!NewOpc) {
3203       if (VT == MVT::v2i64)
3204         // Fall through to expand this.  It is not legal.
3205         return SDValue();
3206       else
3207         // Other vector multiplications are legal.
3208         return Op;
3209     }
3210   }
3211 
3212   // Legalize to a S/UMULL instruction
3213   SDLoc DL(Op);
3214   SDValue Op0;
3215   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3216   if (!isMLA) {
3217     Op0 = skipExtensionForVectorMULL(N0, DAG);
3218     assert(Op0.getValueType().is64BitVector() &&
3219            Op1.getValueType().is64BitVector() &&
3220            "unexpected types for extended operands to VMULL");
3221     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3222   }
3223   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3224   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3225   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3226   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3227   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3228   EVT Op1VT = Op1.getValueType();
3229   return DAG.getNode(N0->getOpcode(), DL, VT,
3230                      DAG.getNode(NewOpc, DL, VT,
3231                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3232                      DAG.getNode(NewOpc, DL, VT,
3233                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3234 }
3235 
3236 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3237                                int Pattern) {
3238   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3239                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3240 }
3241 
3242 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3243                                                      SelectionDAG &DAG) const {
3244   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3245   SDLoc dl(Op);
3246   switch (IntNo) {
3247   default: return SDValue();    // Don't custom lower most intrinsics.
3248   case Intrinsic::thread_pointer: {
3249     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3251   }
3252   case Intrinsic::aarch64_neon_abs: {
3253     EVT Ty = Op.getValueType();
3254     if (Ty == MVT::i64) {
3255       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3256                                    Op.getOperand(1));
3257       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3258       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3259     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3260       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3261     } else {
3262       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3263     }
3264   }
3265   case Intrinsic::aarch64_neon_smax:
3266     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3267                        Op.getOperand(1), Op.getOperand(2));
3268   case Intrinsic::aarch64_neon_umax:
3269     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3270                        Op.getOperand(1), Op.getOperand(2));
3271   case Intrinsic::aarch64_neon_smin:
3272     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3273                        Op.getOperand(1), Op.getOperand(2));
3274   case Intrinsic::aarch64_neon_umin:
3275     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3276                        Op.getOperand(1), Op.getOperand(2));
3277 
3278   case Intrinsic::aarch64_sve_sunpkhi:
3279     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3280                        Op.getOperand(1));
3281   case Intrinsic::aarch64_sve_sunpklo:
3282     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3283                        Op.getOperand(1));
3284   case Intrinsic::aarch64_sve_uunpkhi:
3285     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3286                        Op.getOperand(1));
3287   case Intrinsic::aarch64_sve_uunpklo:
3288     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3289                        Op.getOperand(1));
3290   case Intrinsic::aarch64_sve_clasta_n:
3291     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3292                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3293   case Intrinsic::aarch64_sve_clastb_n:
3294     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3295                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3296   case Intrinsic::aarch64_sve_lasta:
3297     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3298                        Op.getOperand(1), Op.getOperand(2));
3299   case Intrinsic::aarch64_sve_lastb:
3300     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3301                        Op.getOperand(1), Op.getOperand(2));
3302   case Intrinsic::aarch64_sve_rev:
3303     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3304                        Op.getOperand(1));
3305   case Intrinsic::aarch64_sve_tbl:
3306     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3307                        Op.getOperand(1), Op.getOperand(2));
3308   case Intrinsic::aarch64_sve_trn1:
3309     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3310                        Op.getOperand(1), Op.getOperand(2));
3311   case Intrinsic::aarch64_sve_trn2:
3312     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3313                        Op.getOperand(1), Op.getOperand(2));
3314   case Intrinsic::aarch64_sve_uzp1:
3315     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3316                        Op.getOperand(1), Op.getOperand(2));
3317   case Intrinsic::aarch64_sve_uzp2:
3318     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3319                        Op.getOperand(1), Op.getOperand(2));
3320   case Intrinsic::aarch64_sve_zip1:
3321     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3322                        Op.getOperand(1), Op.getOperand(2));
3323   case Intrinsic::aarch64_sve_zip2:
3324     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3325                        Op.getOperand(1), Op.getOperand(2));
3326   case Intrinsic::aarch64_sve_ptrue:
3327     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3328                        Op.getOperand(1));
3329   case Intrinsic::aarch64_sve_dupq_lane:
3330     return LowerDUPQLane(Op, DAG);
3331   case Intrinsic::aarch64_sve_convert_from_svbool:
3332     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3333                        Op.getOperand(1));
3334   case Intrinsic::aarch64_sve_convert_to_svbool: {
3335     EVT OutVT = Op.getValueType();
3336     EVT InVT = Op.getOperand(1).getValueType();
3337     // Return the operand if the cast isn't changing type,
3338     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3339     if (InVT == OutVT)
3340       return Op.getOperand(1);
3341     // Otherwise, zero the newly introduced lanes.
3342     SDValue Reinterpret =
3343         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3344     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3345     SDValue MaskReinterpret =
3346         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3347     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3348   }
3349 
3350   case Intrinsic::aarch64_sve_insr: {
3351     SDValue Scalar = Op.getOperand(2);
3352     EVT ScalarTy = Scalar.getValueType();
3353     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3354       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3355 
3356     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3357                        Op.getOperand(1), Scalar);
3358   }
3359 
3360   case Intrinsic::aarch64_sve_sxtb:
3361     return DAG.getNode(
3362         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3363         Op.getOperand(2), Op.getOperand(3),
3364         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3365         Op.getOperand(1));
3366   case Intrinsic::aarch64_sve_sxth:
3367     return DAG.getNode(
3368         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3369         Op.getOperand(2), Op.getOperand(3),
3370         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3371         Op.getOperand(1));
3372   case Intrinsic::aarch64_sve_sxtw:
3373     return DAG.getNode(
3374         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3375         Op.getOperand(2), Op.getOperand(3),
3376         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3377         Op.getOperand(1));
3378   case Intrinsic::aarch64_sve_uxtb:
3379     return DAG.getNode(
3380         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3381         Op.getOperand(2), Op.getOperand(3),
3382         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3383         Op.getOperand(1));
3384   case Intrinsic::aarch64_sve_uxth:
3385     return DAG.getNode(
3386         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3387         Op.getOperand(2), Op.getOperand(3),
3388         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3389         Op.getOperand(1));
3390   case Intrinsic::aarch64_sve_uxtw:
3391     return DAG.getNode(
3392         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3393         Op.getOperand(2), Op.getOperand(3),
3394         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3395         Op.getOperand(1));
3396 
3397   case Intrinsic::localaddress: {
3398     const auto &MF = DAG.getMachineFunction();
3399     const auto *RegInfo = Subtarget->getRegisterInfo();
3400     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3401     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3402                               Op.getSimpleValueType());
3403   }
3404 
3405   case Intrinsic::eh_recoverfp: {
3406     // FIXME: This needs to be implemented to correctly handle highly aligned
3407     // stack objects. For now we simply return the incoming FP. Refer D53541
3408     // for more details.
3409     SDValue FnOp = Op.getOperand(1);
3410     SDValue IncomingFPOp = Op.getOperand(2);
3411     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3412     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3413     if (!Fn)
3414       report_fatal_error(
3415           "llvm.eh.recoverfp must take a function as the first argument");
3416     return IncomingFPOp;
3417   }
3418 
3419   case Intrinsic::aarch64_neon_vsri:
3420   case Intrinsic::aarch64_neon_vsli: {
3421     EVT Ty = Op.getValueType();
3422 
3423     if (!Ty.isVector())
3424       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3425 
3426     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3427 
3428     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3429     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3430     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3431                        Op.getOperand(3));
3432   }
3433 
3434   case Intrinsic::aarch64_neon_srhadd:
3435   case Intrinsic::aarch64_neon_urhadd:
3436   case Intrinsic::aarch64_neon_shadd:
3437   case Intrinsic::aarch64_neon_uhadd: {
3438     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3439                         IntNo == Intrinsic::aarch64_neon_shadd);
3440     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3441                           IntNo == Intrinsic::aarch64_neon_urhadd);
3442     unsigned Opcode =
3443         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
3444                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
3445     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3446                        Op.getOperand(2));
3447   }
3448   }
3449 }
3450 
3451 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3452   return ExtVal.getValueType().isScalableVector();
3453 }
3454 
3455 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3456 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3457                                         EVT VT, EVT MemVT,
3458                                         SelectionDAG &DAG) {
3459   assert(VT.isVector() && "VT should be a vector type");
3460   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3461 
3462   SDValue Value = ST->getValue();
3463 
3464   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3465   // the word lane which represent the v4i8 subvector.  It optimizes the store
3466   // to:
3467   //
3468   //   xtn  v0.8b, v0.8h
3469   //   str  s0, [x0]
3470 
3471   SDValue Undef = DAG.getUNDEF(MVT::i16);
3472   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3473                                         {Undef, Undef, Undef, Undef});
3474 
3475   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3476                                  Value, UndefVec);
3477   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3478 
3479   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3480   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3481                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3482 
3483   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3484                       ST->getBasePtr(), ST->getMemOperand());
3485 }
3486 
3487 // Custom lowering for any store, vector or scalar and/or default or with
3488 // a truncate operations.  Currently only custom lower truncate operation
3489 // from vector v4i16 to v4i8 or volatile stores of i128.
3490 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3491                                           SelectionDAG &DAG) const {
3492   SDLoc Dl(Op);
3493   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3494   assert (StoreNode && "Can only custom lower store nodes");
3495 
3496   SDValue Value = StoreNode->getValue();
3497 
3498   EVT VT = Value.getValueType();
3499   EVT MemVT = StoreNode->getMemoryVT();
3500 
3501   if (VT.isVector()) {
3502     if (useSVEForFixedLengthVectorVT(VT))
3503       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3504 
3505     unsigned AS = StoreNode->getAddressSpace();
3506     Align Alignment = StoreNode->getAlign();
3507     if (Alignment < MemVT.getStoreSize() &&
3508         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3509                                         StoreNode->getMemOperand()->getFlags(),
3510                                         nullptr)) {
3511       return scalarizeVectorStore(StoreNode, DAG);
3512     }
3513 
3514     if (StoreNode->isTruncatingStore()) {
3515       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3516     }
3517     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3518     // the custom lowering, as there are no un-paired non-temporal stores and
3519     // legalization will break up 256 bit inputs.
3520     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3521         MemVT.getVectorElementCount().Min % 2u == 0 &&
3522         ((MemVT.getScalarSizeInBits() == 8u ||
3523           MemVT.getScalarSizeInBits() == 16u ||
3524           MemVT.getScalarSizeInBits() == 32u ||
3525           MemVT.getScalarSizeInBits() == 64u))) {
3526       SDValue Lo =
3527           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3528                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3529                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3530       SDValue Hi = DAG.getNode(
3531           ISD::EXTRACT_SUBVECTOR, Dl,
3532           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3533           StoreNode->getValue(),
3534           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3535       SDValue Result = DAG.getMemIntrinsicNode(
3536           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3537           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3538           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3539       return Result;
3540     }
3541   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3542     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3543     SDValue Lo =
3544         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3545                     DAG.getConstant(0, Dl, MVT::i64));
3546     SDValue Hi =
3547         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3548                     DAG.getConstant(1, Dl, MVT::i64));
3549     SDValue Result = DAG.getMemIntrinsicNode(
3550         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3551         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3552         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3553     return Result;
3554   }
3555 
3556   return SDValue();
3557 }
3558 
3559 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3560                                               SelectionDAG &DAG) const {
3561   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3562   LLVM_DEBUG(Op.dump());
3563 
3564   switch (Op.getOpcode()) {
3565   default:
3566     llvm_unreachable("unimplemented operand");
3567     return SDValue();
3568   case ISD::BITCAST:
3569     return LowerBITCAST(Op, DAG);
3570   case ISD::GlobalAddress:
3571     return LowerGlobalAddress(Op, DAG);
3572   case ISD::GlobalTLSAddress:
3573     return LowerGlobalTLSAddress(Op, DAG);
3574   case ISD::SETCC:
3575   case ISD::STRICT_FSETCC:
3576   case ISD::STRICT_FSETCCS:
3577     return LowerSETCC(Op, DAG);
3578   case ISD::BR_CC:
3579     return LowerBR_CC(Op, DAG);
3580   case ISD::SELECT:
3581     return LowerSELECT(Op, DAG);
3582   case ISD::SELECT_CC:
3583     return LowerSELECT_CC(Op, DAG);
3584   case ISD::JumpTable:
3585     return LowerJumpTable(Op, DAG);
3586   case ISD::BR_JT:
3587     return LowerBR_JT(Op, DAG);
3588   case ISD::ConstantPool:
3589     return LowerConstantPool(Op, DAG);
3590   case ISD::BlockAddress:
3591     return LowerBlockAddress(Op, DAG);
3592   case ISD::VASTART:
3593     return LowerVASTART(Op, DAG);
3594   case ISD::VACOPY:
3595     return LowerVACOPY(Op, DAG);
3596   case ISD::VAARG:
3597     return LowerVAARG(Op, DAG);
3598   case ISD::ADDC:
3599   case ISD::ADDE:
3600   case ISD::SUBC:
3601   case ISD::SUBE:
3602     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3603   case ISD::SADDO:
3604   case ISD::UADDO:
3605   case ISD::SSUBO:
3606   case ISD::USUBO:
3607   case ISD::SMULO:
3608   case ISD::UMULO:
3609     return LowerXALUO(Op, DAG);
3610   case ISD::FADD:
3611     if (Op.getValueType() == MVT::f128)
3612       return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3613     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3614   case ISD::FSUB:
3615     if (Op.getValueType() == MVT::f128)
3616       return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3617     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
3618   case ISD::FMUL:
3619     if (Op.getValueType() == MVT::f128)
3620       return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3621     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
3622   case ISD::FMA:
3623     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3624   case ISD::FDIV:
3625     if (Op.getValueType() == MVT::f128)
3626       return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3627     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
3628   case ISD::FP_ROUND:
3629   case ISD::STRICT_FP_ROUND:
3630     return LowerFP_ROUND(Op, DAG);
3631   case ISD::FP_EXTEND:
3632     return LowerFP_EXTEND(Op, DAG);
3633   case ISD::FRAMEADDR:
3634     return LowerFRAMEADDR(Op, DAG);
3635   case ISD::SPONENTRY:
3636     return LowerSPONENTRY(Op, DAG);
3637   case ISD::RETURNADDR:
3638     return LowerRETURNADDR(Op, DAG);
3639   case ISD::ADDROFRETURNADDR:
3640     return LowerADDROFRETURNADDR(Op, DAG);
3641   case ISD::INSERT_VECTOR_ELT:
3642     return LowerINSERT_VECTOR_ELT(Op, DAG);
3643   case ISD::EXTRACT_VECTOR_ELT:
3644     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3645   case ISD::BUILD_VECTOR:
3646     return LowerBUILD_VECTOR(Op, DAG);
3647   case ISD::VECTOR_SHUFFLE:
3648     return LowerVECTOR_SHUFFLE(Op, DAG);
3649   case ISD::SPLAT_VECTOR:
3650     return LowerSPLAT_VECTOR(Op, DAG);
3651   case ISD::EXTRACT_SUBVECTOR:
3652     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3653   case ISD::INSERT_SUBVECTOR:
3654     return LowerINSERT_SUBVECTOR(Op, DAG);
3655   case ISD::SDIV:
3656   case ISD::UDIV:
3657     return LowerDIV(Op, DAG);
3658   case ISD::SMIN:
3659     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
3660                                /*OverrideNEON=*/true);
3661   case ISD::UMIN:
3662     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
3663                                /*OverrideNEON=*/true);
3664   case ISD::SMAX:
3665     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
3666                                /*OverrideNEON=*/true);
3667   case ISD::UMAX:
3668     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
3669                                /*OverrideNEON=*/true);
3670   case ISD::SRA:
3671   case ISD::SRL:
3672   case ISD::SHL:
3673     return LowerVectorSRA_SRL_SHL(Op, DAG);
3674   case ISD::SHL_PARTS:
3675     return LowerShiftLeftParts(Op, DAG);
3676   case ISD::SRL_PARTS:
3677   case ISD::SRA_PARTS:
3678     return LowerShiftRightParts(Op, DAG);
3679   case ISD::CTPOP:
3680     return LowerCTPOP(Op, DAG);
3681   case ISD::FCOPYSIGN:
3682     return LowerFCOPYSIGN(Op, DAG);
3683   case ISD::OR:
3684     return LowerVectorOR(Op, DAG);
3685   case ISD::XOR:
3686     return LowerXOR(Op, DAG);
3687   case ISD::PREFETCH:
3688     return LowerPREFETCH(Op, DAG);
3689   case ISD::SINT_TO_FP:
3690   case ISD::UINT_TO_FP:
3691   case ISD::STRICT_SINT_TO_FP:
3692   case ISD::STRICT_UINT_TO_FP:
3693     return LowerINT_TO_FP(Op, DAG);
3694   case ISD::FP_TO_SINT:
3695   case ISD::FP_TO_UINT:
3696   case ISD::STRICT_FP_TO_SINT:
3697   case ISD::STRICT_FP_TO_UINT:
3698     return LowerFP_TO_INT(Op, DAG);
3699   case ISD::FSINCOS:
3700     return LowerFSINCOS(Op, DAG);
3701   case ISD::FLT_ROUNDS_:
3702     return LowerFLT_ROUNDS_(Op, DAG);
3703   case ISD::MUL:
3704     return LowerMUL(Op, DAG);
3705   case ISD::INTRINSIC_WO_CHAIN:
3706     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3707   case ISD::STORE:
3708     return LowerSTORE(Op, DAG);
3709   case ISD::VECREDUCE_ADD:
3710   case ISD::VECREDUCE_SMAX:
3711   case ISD::VECREDUCE_SMIN:
3712   case ISD::VECREDUCE_UMAX:
3713   case ISD::VECREDUCE_UMIN:
3714   case ISD::VECREDUCE_FMAX:
3715   case ISD::VECREDUCE_FMIN:
3716     return LowerVECREDUCE(Op, DAG);
3717   case ISD::ATOMIC_LOAD_SUB:
3718     return LowerATOMIC_LOAD_SUB(Op, DAG);
3719   case ISD::ATOMIC_LOAD_AND:
3720     return LowerATOMIC_LOAD_AND(Op, DAG);
3721   case ISD::DYNAMIC_STACKALLOC:
3722     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3723   case ISD::VSCALE:
3724     return LowerVSCALE(Op, DAG);
3725   case ISD::ANY_EXTEND:
3726   case ISD::SIGN_EXTEND:
3727   case ISD::ZERO_EXTEND:
3728     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
3729   case ISD::SIGN_EXTEND_INREG:
3730     return LowerToPredicatedOp(Op, DAG,
3731                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
3732   case ISD::TRUNCATE:
3733     return LowerTRUNCATE(Op, DAG);
3734   case ISD::LOAD:
3735     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3736       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
3737     llvm_unreachable("Unexpected request to lower ISD::LOAD");
3738   case ISD::ADD:
3739     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
3740   case ISD::AND:
3741     return LowerToScalableOp(Op, DAG);
3742   case ISD::SUB:
3743     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
3744   case ISD::FMAXNUM:
3745     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
3746   case ISD::FMINNUM:
3747     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
3748   }
3749 }
3750 
3751 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
3752   // Prefer NEON unless larger SVE registers are available.
3753   return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
3754 }
3755 
3756 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
3757     EVT VT, bool OverrideNEON) const {
3758   if (!useSVEForFixedLengthVectors())
3759     return false;
3760 
3761   if (!VT.isFixedLengthVector())
3762     return false;
3763 
3764   // Don't use SVE for vectors we cannot scalarize if required.
3765   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
3766   // Fixed length predicates should be promoted to i8.
3767   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
3768   case MVT::i1:
3769   default:
3770     return false;
3771   case MVT::i8:
3772   case MVT::i16:
3773   case MVT::i32:
3774   case MVT::i64:
3775   case MVT::f16:
3776   case MVT::f32:
3777   case MVT::f64:
3778     break;
3779   }
3780 
3781   // All SVE implementations support NEON sized vectors.
3782   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
3783     return true;
3784 
3785   // Ensure NEON MVTs only belong to a single register class.
3786   if (VT.getSizeInBits() <= 128)
3787     return false;
3788 
3789   // Don't use SVE for types that don't fit.
3790   if (VT.getSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
3791     return false;
3792 
3793   // TODO: Perhaps an artificial restriction, but worth having whilst getting
3794   // the base fixed length SVE support in place.
3795   if (!VT.isPow2VectorType())
3796     return false;
3797 
3798   return true;
3799 }
3800 
3801 //===----------------------------------------------------------------------===//
3802 //                      Calling Convention Implementation
3803 //===----------------------------------------------------------------------===//
3804 
3805 /// Selects the correct CCAssignFn for a given CallingConvention value.
3806 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3807                                                      bool IsVarArg) const {
3808   switch (CC) {
3809   default:
3810     report_fatal_error("Unsupported calling convention.");
3811   case CallingConv::WebKit_JS:
3812     return CC_AArch64_WebKit_JS;
3813   case CallingConv::GHC:
3814     return CC_AArch64_GHC;
3815   case CallingConv::C:
3816   case CallingConv::Fast:
3817   case CallingConv::PreserveMost:
3818   case CallingConv::CXX_FAST_TLS:
3819   case CallingConv::Swift:
3820     if (Subtarget->isTargetWindows() && IsVarArg)
3821       return CC_AArch64_Win64_VarArg;
3822     if (!Subtarget->isTargetDarwin())
3823       return CC_AArch64_AAPCS;
3824     if (!IsVarArg)
3825       return CC_AArch64_DarwinPCS;
3826     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3827                                       : CC_AArch64_DarwinPCS_VarArg;
3828    case CallingConv::Win64:
3829     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3830    case CallingConv::CFGuard_Check:
3831      return CC_AArch64_Win64_CFGuard_Check;
3832    case CallingConv::AArch64_VectorCall:
3833    case CallingConv::AArch64_SVE_VectorCall:
3834      return CC_AArch64_AAPCS;
3835   }
3836 }
3837 
3838 CCAssignFn *
3839 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3840   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3841                                       : RetCC_AArch64_AAPCS;
3842 }
3843 
3844 SDValue AArch64TargetLowering::LowerFormalArguments(
3845     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3846     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3847     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3848   MachineFunction &MF = DAG.getMachineFunction();
3849   MachineFrameInfo &MFI = MF.getFrameInfo();
3850   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3851 
3852   // Assign locations to all of the incoming arguments.
3853   SmallVector<CCValAssign, 16> ArgLocs;
3854   DenseMap<unsigned, SDValue> CopiedRegs;
3855   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3856                  *DAG.getContext());
3857 
3858   // At this point, Ins[].VT may already be promoted to i32. To correctly
3859   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3860   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3861   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3862   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3863   // LocVT.
3864   unsigned NumArgs = Ins.size();
3865   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3866   unsigned CurArgIdx = 0;
3867   for (unsigned i = 0; i != NumArgs; ++i) {
3868     MVT ValVT = Ins[i].VT;
3869     if (Ins[i].isOrigArg()) {
3870       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3871       CurArgIdx = Ins[i].getOrigArgIndex();
3872 
3873       // Get type of the original argument.
3874       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3875                                   /*AllowUnknown*/ true);
3876       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3877       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3878       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3879         ValVT = MVT::i8;
3880       else if (ActualMVT == MVT::i16)
3881         ValVT = MVT::i16;
3882     }
3883     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3884     bool Res =
3885         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3886     assert(!Res && "Call operand has unhandled type");
3887     (void)Res;
3888   }
3889   assert(ArgLocs.size() == Ins.size());
3890   SmallVector<SDValue, 16> ArgValues;
3891   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3892     CCValAssign &VA = ArgLocs[i];
3893 
3894     if (Ins[i].Flags.isByVal()) {
3895       // Byval is used for HFAs in the PCS, but the system should work in a
3896       // non-compliant manner for larger structs.
3897       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3898       int Size = Ins[i].Flags.getByValSize();
3899       unsigned NumRegs = (Size + 7) / 8;
3900 
3901       // FIXME: This works on big-endian for composite byvals, which are the common
3902       // case. It should also work for fundamental types too.
3903       unsigned FrameIdx =
3904         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3905       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3906       InVals.push_back(FrameIdxN);
3907 
3908       continue;
3909     }
3910 
3911     SDValue ArgValue;
3912     if (VA.isRegLoc()) {
3913       // Arguments stored in registers.
3914       EVT RegVT = VA.getLocVT();
3915       const TargetRegisterClass *RC;
3916 
3917       if (RegVT == MVT::i32)
3918         RC = &AArch64::GPR32RegClass;
3919       else if (RegVT == MVT::i64)
3920         RC = &AArch64::GPR64RegClass;
3921       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
3922         RC = &AArch64::FPR16RegClass;
3923       else if (RegVT == MVT::f32)
3924         RC = &AArch64::FPR32RegClass;
3925       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3926         RC = &AArch64::FPR64RegClass;
3927       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3928         RC = &AArch64::FPR128RegClass;
3929       else if (RegVT.isScalableVector() &&
3930                RegVT.getVectorElementType() == MVT::i1)
3931         RC = &AArch64::PPRRegClass;
3932       else if (RegVT.isScalableVector())
3933         RC = &AArch64::ZPRRegClass;
3934       else
3935         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3936 
3937       // Transform the arguments in physical registers into virtual ones.
3938       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3939       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3940 
3941       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3942       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3943       // truncate to the right size.
3944       switch (VA.getLocInfo()) {
3945       default:
3946         llvm_unreachable("Unknown loc info!");
3947       case CCValAssign::Full:
3948         break;
3949       case CCValAssign::Indirect:
3950         assert(VA.getValVT().isScalableVector() &&
3951                "Only scalable vectors can be passed indirectly");
3952         break;
3953       case CCValAssign::BCvt:
3954         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3955         break;
3956       case CCValAssign::AExt:
3957       case CCValAssign::SExt:
3958       case CCValAssign::ZExt:
3959         break;
3960       case CCValAssign::AExtUpper:
3961         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3962                                DAG.getConstant(32, DL, RegVT));
3963         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3964         break;
3965       }
3966     } else { // VA.isRegLoc()
3967       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3968       unsigned ArgOffset = VA.getLocMemOffset();
3969       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3970                               ? VA.getLocVT().getSizeInBits()
3971                               : VA.getValVT().getSizeInBits()) / 8;
3972 
3973       uint32_t BEAlign = 0;
3974       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3975           !Ins[i].Flags.isInConsecutiveRegs())
3976         BEAlign = 8 - ArgSize;
3977 
3978       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3979 
3980       // Create load nodes to retrieve arguments from the stack.
3981       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3982 
3983       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3984       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3985       MVT MemVT = VA.getValVT();
3986 
3987       switch (VA.getLocInfo()) {
3988       default:
3989         break;
3990       case CCValAssign::Trunc:
3991       case CCValAssign::BCvt:
3992         MemVT = VA.getLocVT();
3993         break;
3994       case CCValAssign::Indirect:
3995         assert(VA.getValVT().isScalableVector() &&
3996                "Only scalable vectors can be passed indirectly");
3997         MemVT = VA.getLocVT();
3998         break;
3999       case CCValAssign::SExt:
4000         ExtType = ISD::SEXTLOAD;
4001         break;
4002       case CCValAssign::ZExt:
4003         ExtType = ISD::ZEXTLOAD;
4004         break;
4005       case CCValAssign::AExt:
4006         ExtType = ISD::EXTLOAD;
4007         break;
4008       }
4009 
4010       ArgValue = DAG.getExtLoad(
4011           ExtType, DL, VA.getLocVT(), Chain, FIN,
4012           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
4013           MemVT);
4014 
4015     }
4016 
4017     if (VA.getLocInfo() == CCValAssign::Indirect) {
4018       assert(VA.getValVT().isScalableVector() &&
4019            "Only scalable vectors can be passed indirectly");
4020       // If value is passed via pointer - do a load.
4021       ArgValue =
4022           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
4023     }
4024 
4025     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
4026       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
4027                              ArgValue, DAG.getValueType(MVT::i32));
4028     InVals.push_back(ArgValue);
4029   }
4030 
4031   // varargs
4032   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4033   if (isVarArg) {
4034     if (!Subtarget->isTargetDarwin() || IsWin64) {
4035       // The AAPCS variadic function ABI is identical to the non-variadic
4036       // one. As a result there may be more arguments in registers and we should
4037       // save them for future reference.
4038       // Win64 variadic functions also pass arguments in registers, but all float
4039       // arguments are passed in integer registers.
4040       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
4041     }
4042 
4043     // This will point to the next argument passed via stack.
4044     unsigned StackOffset = CCInfo.getNextStackOffset();
4045     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
4046     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
4047     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
4048 
4049     if (MFI.hasMustTailInVarArgFunc()) {
4050       SmallVector<MVT, 2> RegParmTypes;
4051       RegParmTypes.push_back(MVT::i64);
4052       RegParmTypes.push_back(MVT::f128);
4053       // Compute the set of forwarded registers. The rest are scratch.
4054       SmallVectorImpl<ForwardedRegister> &Forwards =
4055                                        FuncInfo->getForwardedMustTailRegParms();
4056       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
4057                                                CC_AArch64_AAPCS);
4058 
4059       // Conservatively forward X8, since it might be used for aggregate return.
4060       if (!CCInfo.isAllocated(AArch64::X8)) {
4061         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
4062         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
4063       }
4064     }
4065   }
4066 
4067   // On Windows, InReg pointers must be returned, so record the pointer in a
4068   // virtual register at the start of the function so it can be returned in the
4069   // epilogue.
4070   if (IsWin64) {
4071     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4072       if (Ins[I].Flags.isInReg()) {
4073         assert(!FuncInfo->getSRetReturnReg());
4074 
4075         MVT PtrTy = getPointerTy(DAG.getDataLayout());
4076         Register Reg =
4077             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4078         FuncInfo->setSRetReturnReg(Reg);
4079 
4080         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
4081         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4082         break;
4083       }
4084     }
4085   }
4086 
4087   unsigned StackArgSize = CCInfo.getNextStackOffset();
4088   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4089   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
4090     // This is a non-standard ABI so by fiat I say we're allowed to make full
4091     // use of the stack area to be popped, which must be aligned to 16 bytes in
4092     // any case:
4093     StackArgSize = alignTo(StackArgSize, 16);
4094 
4095     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
4096     // a multiple of 16.
4097     FuncInfo->setArgumentStackToRestore(StackArgSize);
4098 
4099     // This realignment carries over to the available bytes below. Our own
4100     // callers will guarantee the space is free by giving an aligned value to
4101     // CALLSEQ_START.
4102   }
4103   // Even if we're not expected to free up the space, it's useful to know how
4104   // much is there while considering tail calls (because we can reuse it).
4105   FuncInfo->setBytesInStackArgArea(StackArgSize);
4106 
4107   if (Subtarget->hasCustomCallingConv())
4108     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
4109 
4110   return Chain;
4111 }
4112 
4113 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
4114                                                 SelectionDAG &DAG,
4115                                                 const SDLoc &DL,
4116                                                 SDValue &Chain) const {
4117   MachineFunction &MF = DAG.getMachineFunction();
4118   MachineFrameInfo &MFI = MF.getFrameInfo();
4119   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4120   auto PtrVT = getPointerTy(DAG.getDataLayout());
4121   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4122 
4123   SmallVector<SDValue, 8> MemOps;
4124 
4125   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
4126                                           AArch64::X3, AArch64::X4, AArch64::X5,
4127                                           AArch64::X6, AArch64::X7 };
4128   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
4129   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
4130 
4131   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
4132   int GPRIdx = 0;
4133   if (GPRSaveSize != 0) {
4134     if (IsWin64) {
4135       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
4136       if (GPRSaveSize & 15)
4137         // The extra size here, if triggered, will always be 8.
4138         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
4139     } else
4140       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
4141 
4142     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
4143 
4144     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
4145       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
4146       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
4147       SDValue Store = DAG.getStore(
4148           Val.getValue(1), DL, Val, FIN,
4149           IsWin64
4150               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
4151                                                   GPRIdx,
4152                                                   (i - FirstVariadicGPR) * 8)
4153               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
4154       MemOps.push_back(Store);
4155       FIN =
4156           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
4157     }
4158   }
4159   FuncInfo->setVarArgsGPRIndex(GPRIdx);
4160   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4161 
4162   if (Subtarget->hasFPARMv8() && !IsWin64) {
4163     static const MCPhysReg FPRArgRegs[] = {
4164         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4165         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4166     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4167     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4168 
4169     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4170     int FPRIdx = 0;
4171     if (FPRSaveSize != 0) {
4172       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4173 
4174       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4175 
4176       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4177         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4178         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4179 
4180         SDValue Store = DAG.getStore(
4181             Val.getValue(1), DL, Val, FIN,
4182             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4183         MemOps.push_back(Store);
4184         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4185                           DAG.getConstant(16, DL, PtrVT));
4186       }
4187     }
4188     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4189     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4190   }
4191 
4192   if (!MemOps.empty()) {
4193     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4194   }
4195 }
4196 
4197 /// LowerCallResult - Lower the result values of a call into the
4198 /// appropriate copies out of appropriate physical registers.
4199 SDValue AArch64TargetLowering::LowerCallResult(
4200     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4201     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4202     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4203     SDValue ThisVal) const {
4204   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4205                           ? RetCC_AArch64_WebKit_JS
4206                           : RetCC_AArch64_AAPCS;
4207   // Assign locations to each value returned by this call.
4208   SmallVector<CCValAssign, 16> RVLocs;
4209   DenseMap<unsigned, SDValue> CopiedRegs;
4210   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4211                  *DAG.getContext());
4212   CCInfo.AnalyzeCallResult(Ins, RetCC);
4213 
4214   // Copy all of the result registers out of their specified physreg.
4215   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4216     CCValAssign VA = RVLocs[i];
4217 
4218     // Pass 'this' value directly from the argument to return value, to avoid
4219     // reg unit interference
4220     if (i == 0 && isThisReturn) {
4221       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4222              "unexpected return calling convention register assignment");
4223       InVals.push_back(ThisVal);
4224       continue;
4225     }
4226 
4227     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4228     // allows one use of a physreg per block.
4229     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4230     if (!Val) {
4231       Val =
4232           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4233       Chain = Val.getValue(1);
4234       InFlag = Val.getValue(2);
4235       CopiedRegs[VA.getLocReg()] = Val;
4236     }
4237 
4238     switch (VA.getLocInfo()) {
4239     default:
4240       llvm_unreachable("Unknown loc info!");
4241     case CCValAssign::Full:
4242       break;
4243     case CCValAssign::BCvt:
4244       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4245       break;
4246     case CCValAssign::AExtUpper:
4247       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4248                         DAG.getConstant(32, DL, VA.getLocVT()));
4249       LLVM_FALLTHROUGH;
4250     case CCValAssign::AExt:
4251       LLVM_FALLTHROUGH;
4252     case CCValAssign::ZExt:
4253       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4254       break;
4255     }
4256 
4257     InVals.push_back(Val);
4258   }
4259 
4260   return Chain;
4261 }
4262 
4263 /// Return true if the calling convention is one that we can guarantee TCO for.
4264 static bool canGuaranteeTCO(CallingConv::ID CC) {
4265   return CC == CallingConv::Fast;
4266 }
4267 
4268 /// Return true if we might ever do TCO for calls with this calling convention.
4269 static bool mayTailCallThisCC(CallingConv::ID CC) {
4270   switch (CC) {
4271   case CallingConv::C:
4272   case CallingConv::AArch64_SVE_VectorCall:
4273   case CallingConv::PreserveMost:
4274   case CallingConv::Swift:
4275     return true;
4276   default:
4277     return canGuaranteeTCO(CC);
4278   }
4279 }
4280 
4281 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4282     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4283     const SmallVectorImpl<ISD::OutputArg> &Outs,
4284     const SmallVectorImpl<SDValue> &OutVals,
4285     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4286   if (!mayTailCallThisCC(CalleeCC))
4287     return false;
4288 
4289   MachineFunction &MF = DAG.getMachineFunction();
4290   const Function &CallerF = MF.getFunction();
4291   CallingConv::ID CallerCC = CallerF.getCallingConv();
4292 
4293   // If this function uses the C calling convention but has an SVE signature,
4294   // then it preserves more registers and should assume the SVE_VectorCall CC.
4295   // The check for matching callee-saved regs will determine whether it is
4296   // eligible for TCO.
4297   if (CallerCC == CallingConv::C &&
4298       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
4299     CallerCC = CallingConv::AArch64_SVE_VectorCall;
4300 
4301   bool CCMatch = CallerCC == CalleeCC;
4302 
4303   // When using the Windows calling convention on a non-windows OS, we want
4304   // to back up and restore X18 in such functions; we can't do a tail call
4305   // from those functions.
4306   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4307       CalleeCC != CallingConv::Win64)
4308     return false;
4309 
4310   // Byval parameters hand the function a pointer directly into the stack area
4311   // we want to reuse during a tail call. Working around this *is* possible (see
4312   // X86) but less efficient and uglier in LowerCall.
4313   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4314                                     e = CallerF.arg_end();
4315        i != e; ++i) {
4316     if (i->hasByValAttr())
4317       return false;
4318 
4319     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4320     // In this case, it is necessary to save/restore X0 in the callee. Tail
4321     // call opt interferes with this. So we disable tail call opt when the
4322     // caller has an argument with "inreg" attribute.
4323 
4324     // FIXME: Check whether the callee also has an "inreg" argument.
4325     if (i->hasInRegAttr())
4326       return false;
4327   }
4328 
4329   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4330     return canGuaranteeTCO(CalleeCC) && CCMatch;
4331 
4332   // Externally-defined functions with weak linkage should not be
4333   // tail-called on AArch64 when the OS does not support dynamic
4334   // pre-emption of symbols, as the AAELF spec requires normal calls
4335   // to undefined weak functions to be replaced with a NOP or jump to the
4336   // next instruction. The behaviour of branch instructions in this
4337   // situation (as used for tail calls) is implementation-defined, so we
4338   // cannot rely on the linker replacing the tail call with a return.
4339   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4340     const GlobalValue *GV = G->getGlobal();
4341     const Triple &TT = getTargetMachine().getTargetTriple();
4342     if (GV->hasExternalWeakLinkage() &&
4343         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4344       return false;
4345   }
4346 
4347   // Now we search for cases where we can use a tail call without changing the
4348   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4349   // concept.
4350 
4351   // I want anyone implementing a new calling convention to think long and hard
4352   // about this assert.
4353   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4354          "Unexpected variadic calling convention");
4355 
4356   LLVMContext &C = *DAG.getContext();
4357   if (isVarArg && !Outs.empty()) {
4358     // At least two cases here: if caller is fastcc then we can't have any
4359     // memory arguments (we'd be expected to clean up the stack afterwards). If
4360     // caller is C then we could potentially use its argument area.
4361 
4362     // FIXME: for now we take the most conservative of these in both cases:
4363     // disallow all variadic memory operands.
4364     SmallVector<CCValAssign, 16> ArgLocs;
4365     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4366 
4367     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4368     for (const CCValAssign &ArgLoc : ArgLocs)
4369       if (!ArgLoc.isRegLoc())
4370         return false;
4371   }
4372 
4373   // Check that the call results are passed in the same way.
4374   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4375                                   CCAssignFnForCall(CalleeCC, isVarArg),
4376                                   CCAssignFnForCall(CallerCC, isVarArg)))
4377     return false;
4378   // The callee has to preserve all registers the caller needs to preserve.
4379   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4380   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4381   if (!CCMatch) {
4382     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4383     if (Subtarget->hasCustomCallingConv()) {
4384       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4385       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4386     }
4387     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4388       return false;
4389   }
4390 
4391   // Nothing more to check if the callee is taking no arguments
4392   if (Outs.empty())
4393     return true;
4394 
4395   SmallVector<CCValAssign, 16> ArgLocs;
4396   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4397 
4398   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4399 
4400   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4401 
4402   // If any of the arguments is passed indirectly, it must be SVE, so the
4403   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4404   // allocate space on the stack. That is why we determine this explicitly here
4405   // the call cannot be a tailcall.
4406   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4407         assert((A.getLocInfo() != CCValAssign::Indirect ||
4408                 A.getValVT().isScalableVector()) &&
4409                "Expected value to be scalable");
4410         return A.getLocInfo() == CCValAssign::Indirect;
4411       }))
4412     return false;
4413 
4414   // If the stack arguments for this call do not fit into our own save area then
4415   // the call cannot be made tail.
4416   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4417     return false;
4418 
4419   const MachineRegisterInfo &MRI = MF.getRegInfo();
4420   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4421     return false;
4422 
4423   return true;
4424 }
4425 
4426 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4427                                                    SelectionDAG &DAG,
4428                                                    MachineFrameInfo &MFI,
4429                                                    int ClobberedFI) const {
4430   SmallVector<SDValue, 8> ArgChains;
4431   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4432   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4433 
4434   // Include the original chain at the beginning of the list. When this is
4435   // used by target LowerCall hooks, this helps legalize find the
4436   // CALLSEQ_BEGIN node.
4437   ArgChains.push_back(Chain);
4438 
4439   // Add a chain value for each stack argument corresponding
4440   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4441                             UE = DAG.getEntryNode().getNode()->use_end();
4442        U != UE; ++U)
4443     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4444       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4445         if (FI->getIndex() < 0) {
4446           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4447           int64_t InLastByte = InFirstByte;
4448           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4449 
4450           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4451               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4452             ArgChains.push_back(SDValue(L, 1));
4453         }
4454 
4455   // Build a tokenfactor for all the chains.
4456   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4457 }
4458 
4459 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4460                                                    bool TailCallOpt) const {
4461   return CallCC == CallingConv::Fast && TailCallOpt;
4462 }
4463 
4464 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4465 /// and add input and output parameter nodes.
4466 SDValue
4467 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4468                                  SmallVectorImpl<SDValue> &InVals) const {
4469   SelectionDAG &DAG = CLI.DAG;
4470   SDLoc &DL = CLI.DL;
4471   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4472   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4473   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4474   SDValue Chain = CLI.Chain;
4475   SDValue Callee = CLI.Callee;
4476   bool &IsTailCall = CLI.IsTailCall;
4477   CallingConv::ID CallConv = CLI.CallConv;
4478   bool IsVarArg = CLI.IsVarArg;
4479 
4480   MachineFunction &MF = DAG.getMachineFunction();
4481   MachineFunction::CallSiteInfo CSInfo;
4482   bool IsThisReturn = false;
4483 
4484   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4485   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4486   bool IsSibCall = false;
4487 
4488   // Check callee args/returns for SVE registers and set calling convention
4489   // accordingly.
4490   if (CallConv == CallingConv::C) {
4491     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4492       return Out.VT.isScalableVector();
4493     });
4494     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4495       return In.VT.isScalableVector();
4496     });
4497 
4498     if (CalleeInSVE || CalleeOutSVE)
4499       CallConv = CallingConv::AArch64_SVE_VectorCall;
4500   }
4501 
4502   if (IsTailCall) {
4503     // Check if it's really possible to do a tail call.
4504     IsTailCall = isEligibleForTailCallOptimization(
4505         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4506     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4507       report_fatal_error("failed to perform tail call elimination on a call "
4508                          "site marked musttail");
4509 
4510     // A sibling call is one where we're under the usual C ABI and not planning
4511     // to change that but can still do a tail call:
4512     if (!TailCallOpt && IsTailCall)
4513       IsSibCall = true;
4514 
4515     if (IsTailCall)
4516       ++NumTailCalls;
4517   }
4518 
4519   // Analyze operands of the call, assigning locations to each operand.
4520   SmallVector<CCValAssign, 16> ArgLocs;
4521   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4522                  *DAG.getContext());
4523 
4524   if (IsVarArg) {
4525     // Handle fixed and variable vector arguments differently.
4526     // Variable vector arguments always go into memory.
4527     unsigned NumArgs = Outs.size();
4528 
4529     for (unsigned i = 0; i != NumArgs; ++i) {
4530       MVT ArgVT = Outs[i].VT;
4531       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4532       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4533                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4534       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4535       assert(!Res && "Call operand has unhandled type");
4536       (void)Res;
4537     }
4538   } else {
4539     // At this point, Outs[].VT may already be promoted to i32. To correctly
4540     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4541     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4542     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4543     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4544     // LocVT.
4545     unsigned NumArgs = Outs.size();
4546     for (unsigned i = 0; i != NumArgs; ++i) {
4547       MVT ValVT = Outs[i].VT;
4548       // Get type of the original argument.
4549       EVT ActualVT = getValueType(DAG.getDataLayout(),
4550                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4551                                   /*AllowUnknown*/ true);
4552       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4553       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4554       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4555       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4556         ValVT = MVT::i8;
4557       else if (ActualMVT == MVT::i16)
4558         ValVT = MVT::i16;
4559 
4560       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4561       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4562       assert(!Res && "Call operand has unhandled type");
4563       (void)Res;
4564     }
4565   }
4566 
4567   // Get a count of how many bytes are to be pushed on the stack.
4568   unsigned NumBytes = CCInfo.getNextStackOffset();
4569 
4570   if (IsSibCall) {
4571     // Since we're not changing the ABI to make this a tail call, the memory
4572     // operands are already available in the caller's incoming argument space.
4573     NumBytes = 0;
4574   }
4575 
4576   // FPDiff is the byte offset of the call's argument area from the callee's.
4577   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4578   // by this amount for a tail call. In a sibling call it must be 0 because the
4579   // caller will deallocate the entire stack and the callee still expects its
4580   // arguments to begin at SP+0. Completely unused for non-tail calls.
4581   int FPDiff = 0;
4582 
4583   if (IsTailCall && !IsSibCall) {
4584     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4585 
4586     // Since callee will pop argument stack as a tail call, we must keep the
4587     // popped size 16-byte aligned.
4588     NumBytes = alignTo(NumBytes, 16);
4589 
4590     // FPDiff will be negative if this tail call requires more space than we
4591     // would automatically have in our incoming argument space. Positive if we
4592     // can actually shrink the stack.
4593     FPDiff = NumReusableBytes - NumBytes;
4594 
4595     // The stack pointer must be 16-byte aligned at all times it's used for a
4596     // memory operation, which in practice means at *all* times and in
4597     // particular across call boundaries. Therefore our own arguments started at
4598     // a 16-byte aligned SP and the delta applied for the tail call should
4599     // satisfy the same constraint.
4600     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4601   }
4602 
4603   // Adjust the stack pointer for the new arguments...
4604   // These operations are automatically eliminated by the prolog/epilog pass
4605   if (!IsSibCall)
4606     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4607 
4608   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4609                                         getPointerTy(DAG.getDataLayout()));
4610 
4611   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4612   SmallSet<unsigned, 8> RegsUsed;
4613   SmallVector<SDValue, 8> MemOpChains;
4614   auto PtrVT = getPointerTy(DAG.getDataLayout());
4615 
4616   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4617     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4618     for (const auto &F : Forwards) {
4619       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4620        RegsToPass.emplace_back(F.PReg, Val);
4621     }
4622   }
4623 
4624   // Walk the register/memloc assignments, inserting copies/loads.
4625   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4626     CCValAssign &VA = ArgLocs[i];
4627     SDValue Arg = OutVals[i];
4628     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4629 
4630     // Promote the value if needed.
4631     switch (VA.getLocInfo()) {
4632     default:
4633       llvm_unreachable("Unknown loc info!");
4634     case CCValAssign::Full:
4635       break;
4636     case CCValAssign::SExt:
4637       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4638       break;
4639     case CCValAssign::ZExt:
4640       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4641       break;
4642     case CCValAssign::AExt:
4643       if (Outs[i].ArgVT == MVT::i1) {
4644         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4645         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4646         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4647       }
4648       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4649       break;
4650     case CCValAssign::AExtUpper:
4651       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4652       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4653       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4654                         DAG.getConstant(32, DL, VA.getLocVT()));
4655       break;
4656     case CCValAssign::BCvt:
4657       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4658       break;
4659     case CCValAssign::Trunc:
4660       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4661       break;
4662     case CCValAssign::FPExt:
4663       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4664       break;
4665     case CCValAssign::Indirect:
4666       assert(VA.getValVT().isScalableVector() &&
4667              "Only scalable vectors can be passed indirectly");
4668       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4669       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4670       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4671       int FI = MFI.CreateStackObject(
4672           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4673       MFI.setStackID(FI, TargetStackID::SVEVector);
4674 
4675       SDValue SpillSlot = DAG.getFrameIndex(
4676           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4677       Chain = DAG.getStore(
4678           Chain, DL, Arg, SpillSlot,
4679           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4680       Arg = SpillSlot;
4681       break;
4682     }
4683 
4684     if (VA.isRegLoc()) {
4685       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4686           Outs[0].VT == MVT::i64) {
4687         assert(VA.getLocVT() == MVT::i64 &&
4688                "unexpected calling convention register assignment");
4689         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4690                "unexpected use of 'returned'");
4691         IsThisReturn = true;
4692       }
4693       if (RegsUsed.count(VA.getLocReg())) {
4694         // If this register has already been used then we're trying to pack
4695         // parts of an [N x i32] into an X-register. The extension type will
4696         // take care of putting the two halves in the right place but we have to
4697         // combine them.
4698         SDValue &Bits =
4699             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4700                          [=](const std::pair<unsigned, SDValue> &Elt) {
4701                            return Elt.first == VA.getLocReg();
4702                          })
4703                 ->second;
4704         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4705         // Call site info is used for function's parameter entry value
4706         // tracking. For now we track only simple cases when parameter
4707         // is transferred through whole register.
4708         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4709                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4710                                       return ArgReg.Reg == VA.getLocReg();
4711                                     }),
4712                      CSInfo.end());
4713       } else {
4714         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4715         RegsUsed.insert(VA.getLocReg());
4716         const TargetOptions &Options = DAG.getTarget().Options;
4717         if (Options.EmitCallSiteInfo)
4718           CSInfo.emplace_back(VA.getLocReg(), i);
4719       }
4720     } else {
4721       assert(VA.isMemLoc());
4722 
4723       SDValue DstAddr;
4724       MachinePointerInfo DstInfo;
4725 
4726       // FIXME: This works on big-endian for composite byvals, which are the
4727       // common case. It should also work for fundamental types too.
4728       uint32_t BEAlign = 0;
4729       unsigned OpSize;
4730       if (VA.getLocInfo() == CCValAssign::Indirect)
4731         OpSize = VA.getLocVT().getSizeInBits();
4732       else
4733         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4734                                  : VA.getValVT().getSizeInBits();
4735       OpSize = (OpSize + 7) / 8;
4736       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4737           !Flags.isInConsecutiveRegs()) {
4738         if (OpSize < 8)
4739           BEAlign = 8 - OpSize;
4740       }
4741       unsigned LocMemOffset = VA.getLocMemOffset();
4742       int32_t Offset = LocMemOffset + BEAlign;
4743       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4744       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4745 
4746       if (IsTailCall) {
4747         Offset = Offset + FPDiff;
4748         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4749 
4750         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4751         DstInfo =
4752             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4753 
4754         // Make sure any stack arguments overlapping with where we're storing
4755         // are loaded before this eventual operation. Otherwise they'll be
4756         // clobbered.
4757         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4758       } else {
4759         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4760 
4761         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4762         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4763                                                LocMemOffset);
4764       }
4765 
4766       if (Outs[i].Flags.isByVal()) {
4767         SDValue SizeNode =
4768             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4769         SDValue Cpy = DAG.getMemcpy(
4770             Chain, DL, DstAddr, Arg, SizeNode,
4771             Outs[i].Flags.getNonZeroByValAlign(),
4772             /*isVol = */ false, /*AlwaysInline = */ false,
4773             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4774 
4775         MemOpChains.push_back(Cpy);
4776       } else {
4777         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4778         // promoted to a legal register type i32, we should truncate Arg back to
4779         // i1/i8/i16.
4780         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4781             VA.getValVT() == MVT::i16)
4782           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4783 
4784         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4785         MemOpChains.push_back(Store);
4786       }
4787     }
4788   }
4789 
4790   if (!MemOpChains.empty())
4791     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4792 
4793   // Build a sequence of copy-to-reg nodes chained together with token chain
4794   // and flag operands which copy the outgoing args into the appropriate regs.
4795   SDValue InFlag;
4796   for (auto &RegToPass : RegsToPass) {
4797     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4798                              RegToPass.second, InFlag);
4799     InFlag = Chain.getValue(1);
4800   }
4801 
4802   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4803   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4804   // node so that legalize doesn't hack it.
4805   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4806     auto GV = G->getGlobal();
4807     unsigned OpFlags =
4808         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4809     if (OpFlags & AArch64II::MO_GOT) {
4810       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4811       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4812     } else {
4813       const GlobalValue *GV = G->getGlobal();
4814       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4815     }
4816   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4817     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4818         Subtarget->isTargetMachO()) {
4819       const char *Sym = S->getSymbol();
4820       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4821       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4822     } else {
4823       const char *Sym = S->getSymbol();
4824       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4825     }
4826   }
4827 
4828   // We don't usually want to end the call-sequence here because we would tidy
4829   // the frame up *after* the call, however in the ABI-changing tail-call case
4830   // we've carefully laid out the parameters so that when sp is reset they'll be
4831   // in the correct location.
4832   if (IsTailCall && !IsSibCall) {
4833     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4834                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4835     InFlag = Chain.getValue(1);
4836   }
4837 
4838   std::vector<SDValue> Ops;
4839   Ops.push_back(Chain);
4840   Ops.push_back(Callee);
4841 
4842   if (IsTailCall) {
4843     // Each tail call may have to adjust the stack by a different amount, so
4844     // this information must travel along with the operation for eventual
4845     // consumption by emitEpilogue.
4846     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4847   }
4848 
4849   // Add argument registers to the end of the list so that they are known live
4850   // into the call.
4851   for (auto &RegToPass : RegsToPass)
4852     Ops.push_back(DAG.getRegister(RegToPass.first,
4853                                   RegToPass.second.getValueType()));
4854 
4855   // Add a register mask operand representing the call-preserved registers.
4856   const uint32_t *Mask;
4857   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4858   if (IsThisReturn) {
4859     // For 'this' returns, use the X0-preserving mask if applicable
4860     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4861     if (!Mask) {
4862       IsThisReturn = false;
4863       Mask = TRI->getCallPreservedMask(MF, CallConv);
4864     }
4865   } else
4866     Mask = TRI->getCallPreservedMask(MF, CallConv);
4867 
4868   if (Subtarget->hasCustomCallingConv())
4869     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4870 
4871   if (TRI->isAnyArgRegReserved(MF))
4872     TRI->emitReservedArgRegCallError(MF);
4873 
4874   assert(Mask && "Missing call preserved mask for calling convention");
4875   Ops.push_back(DAG.getRegisterMask(Mask));
4876 
4877   if (InFlag.getNode())
4878     Ops.push_back(InFlag);
4879 
4880   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4881 
4882   // If we're doing a tall call, use a TC_RETURN here rather than an
4883   // actual call instruction.
4884   if (IsTailCall) {
4885     MF.getFrameInfo().setHasTailCall();
4886     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4887     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4888     return Ret;
4889   }
4890 
4891   // Returns a chain and a flag for retval copy to use.
4892   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4893   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4894   InFlag = Chain.getValue(1);
4895   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4896 
4897   uint64_t CalleePopBytes =
4898       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4899 
4900   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4901                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4902                              InFlag, DL);
4903   if (!Ins.empty())
4904     InFlag = Chain.getValue(1);
4905 
4906   // Handle result values, copying them out of physregs into vregs that we
4907   // return.
4908   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4909                          InVals, IsThisReturn,
4910                          IsThisReturn ? OutVals[0] : SDValue());
4911 }
4912 
4913 bool AArch64TargetLowering::CanLowerReturn(
4914     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4915     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4916   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4917                           ? RetCC_AArch64_WebKit_JS
4918                           : RetCC_AArch64_AAPCS;
4919   SmallVector<CCValAssign, 16> RVLocs;
4920   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4921   return CCInfo.CheckReturn(Outs, RetCC);
4922 }
4923 
4924 SDValue
4925 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4926                                    bool isVarArg,
4927                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4928                                    const SmallVectorImpl<SDValue> &OutVals,
4929                                    const SDLoc &DL, SelectionDAG &DAG) const {
4930   auto &MF = DAG.getMachineFunction();
4931   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4932 
4933   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4934                           ? RetCC_AArch64_WebKit_JS
4935                           : RetCC_AArch64_AAPCS;
4936   SmallVector<CCValAssign, 16> RVLocs;
4937   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4938                  *DAG.getContext());
4939   CCInfo.AnalyzeReturn(Outs, RetCC);
4940 
4941   // Copy the result values into the output registers.
4942   SDValue Flag;
4943   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4944   SmallSet<unsigned, 4> RegsUsed;
4945   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4946        ++i, ++realRVLocIdx) {
4947     CCValAssign &VA = RVLocs[i];
4948     assert(VA.isRegLoc() && "Can only return in registers!");
4949     SDValue Arg = OutVals[realRVLocIdx];
4950 
4951     switch (VA.getLocInfo()) {
4952     default:
4953       llvm_unreachable("Unknown loc info!");
4954     case CCValAssign::Full:
4955       if (Outs[i].ArgVT == MVT::i1) {
4956         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4957         // value. This is strictly redundant on Darwin (which uses "zeroext
4958         // i1"), but will be optimised out before ISel.
4959         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4960         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4961       }
4962       break;
4963     case CCValAssign::BCvt:
4964       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4965       break;
4966     case CCValAssign::AExt:
4967     case CCValAssign::ZExt:
4968       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4969       break;
4970     case CCValAssign::AExtUpper:
4971       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4972       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4973       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4974                         DAG.getConstant(32, DL, VA.getLocVT()));
4975       break;
4976     }
4977 
4978     if (RegsUsed.count(VA.getLocReg())) {
4979       SDValue &Bits =
4980           std::find_if(RetVals.begin(), RetVals.end(),
4981                        [=](const std::pair<unsigned, SDValue> &Elt) {
4982                          return Elt.first == VA.getLocReg();
4983                        })
4984               ->second;
4985       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4986     } else {
4987       RetVals.emplace_back(VA.getLocReg(), Arg);
4988       RegsUsed.insert(VA.getLocReg());
4989     }
4990   }
4991 
4992   SmallVector<SDValue, 4> RetOps(1, Chain);
4993   for (auto &RetVal : RetVals) {
4994     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4995     Flag = Chain.getValue(1);
4996     RetOps.push_back(
4997         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4998   }
4999 
5000   // Windows AArch64 ABIs require that for returning structs by value we copy
5001   // the sret argument into X0 for the return.
5002   // We saved the argument into a virtual register in the entry block,
5003   // so now we copy the value out and into X0.
5004   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
5005     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
5006                                      getPointerTy(MF.getDataLayout()));
5007 
5008     unsigned RetValReg = AArch64::X0;
5009     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
5010     Flag = Chain.getValue(1);
5011 
5012     RetOps.push_back(
5013       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
5014   }
5015 
5016   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5017   const MCPhysReg *I =
5018       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5019   if (I) {
5020     for (; *I; ++I) {
5021       if (AArch64::GPR64RegClass.contains(*I))
5022         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5023       else if (AArch64::FPR64RegClass.contains(*I))
5024         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5025       else
5026         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5027     }
5028   }
5029 
5030   RetOps[0] = Chain; // Update chain.
5031 
5032   // Add the flag if we have it.
5033   if (Flag.getNode())
5034     RetOps.push_back(Flag);
5035 
5036   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
5037 }
5038 
5039 //===----------------------------------------------------------------------===//
5040 //  Other Lowering Code
5041 //===----------------------------------------------------------------------===//
5042 
5043 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
5044                                              SelectionDAG &DAG,
5045                                              unsigned Flag) const {
5046   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
5047                                     N->getOffset(), Flag);
5048 }
5049 
5050 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
5051                                              SelectionDAG &DAG,
5052                                              unsigned Flag) const {
5053   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
5054 }
5055 
5056 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
5057                                              SelectionDAG &DAG,
5058                                              unsigned Flag) const {
5059   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
5060                                    N->getOffset(), Flag);
5061 }
5062 
5063 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
5064                                              SelectionDAG &DAG,
5065                                              unsigned Flag) const {
5066   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
5067 }
5068 
5069 // (loadGOT sym)
5070 template <class NodeTy>
5071 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
5072                                       unsigned Flags) const {
5073   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
5074   SDLoc DL(N);
5075   EVT Ty = getPointerTy(DAG.getDataLayout());
5076   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
5077   // FIXME: Once remat is capable of dealing with instructions with register
5078   // operands, expand this into two nodes instead of using a wrapper node.
5079   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
5080 }
5081 
5082 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
5083 template <class NodeTy>
5084 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
5085                                             unsigned Flags) const {
5086   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
5087   SDLoc DL(N);
5088   EVT Ty = getPointerTy(DAG.getDataLayout());
5089   const unsigned char MO_NC = AArch64II::MO_NC;
5090   return DAG.getNode(
5091       AArch64ISD::WrapperLarge, DL, Ty,
5092       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
5093       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
5094       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
5095       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
5096 }
5097 
5098 // (addlow (adrp %hi(sym)) %lo(sym))
5099 template <class NodeTy>
5100 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
5101                                        unsigned Flags) const {
5102   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
5103   SDLoc DL(N);
5104   EVT Ty = getPointerTy(DAG.getDataLayout());
5105   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
5106   SDValue Lo = getTargetNode(N, Ty, DAG,
5107                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
5108   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
5109   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
5110 }
5111 
5112 // (adr sym)
5113 template <class NodeTy>
5114 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
5115                                            unsigned Flags) const {
5116   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
5117   SDLoc DL(N);
5118   EVT Ty = getPointerTy(DAG.getDataLayout());
5119   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
5120   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
5121 }
5122 
5123 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
5124                                                   SelectionDAG &DAG) const {
5125   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
5126   const GlobalValue *GV = GN->getGlobal();
5127   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5128 
5129   if (OpFlags != AArch64II::MO_NO_FLAG)
5130     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
5131            "unexpected offset in global node");
5132 
5133   // This also catches the large code model case for Darwin, and tiny code
5134   // model with got relocations.
5135   if ((OpFlags & AArch64II::MO_GOT) != 0) {
5136     return getGOT(GN, DAG, OpFlags);
5137   }
5138 
5139   SDValue Result;
5140   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5141     Result = getAddrLarge(GN, DAG, OpFlags);
5142   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5143     Result = getAddrTiny(GN, DAG, OpFlags);
5144   } else {
5145     Result = getAddr(GN, DAG, OpFlags);
5146   }
5147   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5148   SDLoc DL(GN);
5149   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
5150     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
5151                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
5152   return Result;
5153 }
5154 
5155 /// Convert a TLS address reference into the correct sequence of loads
5156 /// and calls to compute the variable's address (for Darwin, currently) and
5157 /// return an SDValue containing the final node.
5158 
5159 /// Darwin only has one TLS scheme which must be capable of dealing with the
5160 /// fully general situation, in the worst case. This means:
5161 ///     + "extern __thread" declaration.
5162 ///     + Defined in a possibly unknown dynamic library.
5163 ///
5164 /// The general system is that each __thread variable has a [3 x i64] descriptor
5165 /// which contains information used by the runtime to calculate the address. The
5166 /// only part of this the compiler needs to know about is the first xword, which
5167 /// contains a function pointer that must be called with the address of the
5168 /// entire descriptor in "x0".
5169 ///
5170 /// Since this descriptor may be in a different unit, in general even the
5171 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5172 /// is:
5173 ///     adrp x0, _var@TLVPPAGE
5174 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5175 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5176 ///                                      ; the function pointer
5177 ///     blr x1                           ; Uses descriptor address in x0
5178 ///     ; Address of _var is now in x0.
5179 ///
5180 /// If the address of _var's descriptor *is* known to the linker, then it can
5181 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5182 /// a slight efficiency gain.
5183 SDValue
5184 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5185                                                    SelectionDAG &DAG) const {
5186   assert(Subtarget->isTargetDarwin() &&
5187          "This function expects a Darwin target");
5188 
5189   SDLoc DL(Op);
5190   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5191   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5192   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5193 
5194   SDValue TLVPAddr =
5195       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5196   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5197 
5198   // The first entry in the descriptor is a function pointer that we must call
5199   // to obtain the address of the variable.
5200   SDValue Chain = DAG.getEntryNode();
5201   SDValue FuncTLVGet = DAG.getLoad(
5202       PtrMemVT, DL, Chain, DescAddr,
5203       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5204       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
5205       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5206   Chain = FuncTLVGet.getValue(1);
5207 
5208   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5209   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5210 
5211   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5212   MFI.setAdjustsStack(true);
5213 
5214   // TLS calls preserve all registers except those that absolutely must be
5215   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5216   // silly).
5217   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5218   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5219   if (Subtarget->hasCustomCallingConv())
5220     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5221 
5222   // Finally, we can make the call. This is just a degenerate version of a
5223   // normal AArch64 call node: x0 takes the address of the descriptor, and
5224   // returns the address of the variable in this thread.
5225   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5226   Chain =
5227       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5228                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5229                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5230   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5231 }
5232 
5233 /// Convert a thread-local variable reference into a sequence of instructions to
5234 /// compute the variable's address for the local exec TLS model of ELF targets.
5235 /// The sequence depends on the maximum TLS area size.
5236 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5237                                                     SDValue ThreadBase,
5238                                                     const SDLoc &DL,
5239                                                     SelectionDAG &DAG) const {
5240   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5241   SDValue TPOff, Addr;
5242 
5243   switch (DAG.getTarget().Options.TLSSize) {
5244   default:
5245     llvm_unreachable("Unexpected TLS size");
5246 
5247   case 12: {
5248     // mrs   x0, TPIDR_EL0
5249     // add   x0, x0, :tprel_lo12:a
5250     SDValue Var = DAG.getTargetGlobalAddress(
5251         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5252     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5253                                       Var,
5254                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5255                    0);
5256   }
5257 
5258   case 24: {
5259     // mrs   x0, TPIDR_EL0
5260     // add   x0, x0, :tprel_hi12:a
5261     // add   x0, x0, :tprel_lo12_nc:a
5262     SDValue HiVar = DAG.getTargetGlobalAddress(
5263         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5264     SDValue LoVar = DAG.getTargetGlobalAddress(
5265         GV, DL, PtrVT, 0,
5266         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5267     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5268                                       HiVar,
5269                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5270                    0);
5271     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5272                                       LoVar,
5273                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5274                    0);
5275   }
5276 
5277   case 32: {
5278     // mrs   x1, TPIDR_EL0
5279     // movz  x0, #:tprel_g1:a
5280     // movk  x0, #:tprel_g0_nc:a
5281     // add   x0, x1, x0
5282     SDValue HiVar = DAG.getTargetGlobalAddress(
5283         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5284     SDValue LoVar = DAG.getTargetGlobalAddress(
5285         GV, DL, PtrVT, 0,
5286         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5287     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5288                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5289                     0);
5290     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5291                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5292                     0);
5293     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5294   }
5295 
5296   case 48: {
5297     // mrs   x1, TPIDR_EL0
5298     // movz  x0, #:tprel_g2:a
5299     // movk  x0, #:tprel_g1_nc:a
5300     // movk  x0, #:tprel_g0_nc:a
5301     // add   x0, x1, x0
5302     SDValue HiVar = DAG.getTargetGlobalAddress(
5303         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5304     SDValue MiVar = DAG.getTargetGlobalAddress(
5305         GV, DL, PtrVT, 0,
5306         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5307     SDValue LoVar = DAG.getTargetGlobalAddress(
5308         GV, DL, PtrVT, 0,
5309         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5310     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5311                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5312                     0);
5313     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5314                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5315                     0);
5316     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5317                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5318                     0);
5319     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5320   }
5321   }
5322 }
5323 
5324 /// When accessing thread-local variables under either the general-dynamic or
5325 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5326 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5327 /// is a function pointer to carry out the resolution.
5328 ///
5329 /// The sequence is:
5330 ///    adrp  x0, :tlsdesc:var
5331 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5332 ///    add   x0, x0, #:tlsdesc_lo12:var
5333 ///    .tlsdesccall var
5334 ///    blr   x1
5335 ///    (TPIDR_EL0 offset now in x0)
5336 ///
5337 ///  The above sequence must be produced unscheduled, to enable the linker to
5338 ///  optimize/relax this sequence.
5339 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5340 ///  above sequence, and expanded really late in the compilation flow, to ensure
5341 ///  the sequence is produced as per above.
5342 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5343                                                       const SDLoc &DL,
5344                                                       SelectionDAG &DAG) const {
5345   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5346 
5347   SDValue Chain = DAG.getEntryNode();
5348   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5349 
5350   Chain =
5351       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5352   SDValue Glue = Chain.getValue(1);
5353 
5354   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5355 }
5356 
5357 SDValue
5358 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5359                                                 SelectionDAG &DAG) const {
5360   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5361 
5362   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5363 
5364   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5365 
5366   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5367     if (Model == TLSModel::LocalDynamic)
5368       Model = TLSModel::GeneralDynamic;
5369   }
5370 
5371   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5372       Model != TLSModel::LocalExec)
5373     report_fatal_error("ELF TLS only supported in small memory model or "
5374                        "in local exec TLS model");
5375   // Different choices can be made for the maximum size of the TLS area for a
5376   // module. For the small address model, the default TLS size is 16MiB and the
5377   // maximum TLS size is 4GiB.
5378   // FIXME: add tiny and large code model support for TLS access models other
5379   // than local exec. We currently generate the same code as small for tiny,
5380   // which may be larger than needed.
5381 
5382   SDValue TPOff;
5383   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5384   SDLoc DL(Op);
5385   const GlobalValue *GV = GA->getGlobal();
5386 
5387   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5388 
5389   if (Model == TLSModel::LocalExec) {
5390     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5391   } else if (Model == TLSModel::InitialExec) {
5392     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5393     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5394   } else if (Model == TLSModel::LocalDynamic) {
5395     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5396     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5397     // the beginning of the module's TLS region, followed by a DTPREL offset
5398     // calculation.
5399 
5400     // These accesses will need deduplicating if there's more than one.
5401     AArch64FunctionInfo *MFI =
5402         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5403     MFI->incNumLocalDynamicTLSAccesses();
5404 
5405     // The call needs a relocation too for linker relaxation. It doesn't make
5406     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5407     // the address.
5408     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5409                                                   AArch64II::MO_TLS);
5410 
5411     // Now we can calculate the offset from TPIDR_EL0 to this module's
5412     // thread-local area.
5413     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5414 
5415     // Now use :dtprel_whatever: operations to calculate this variable's offset
5416     // in its thread-storage area.
5417     SDValue HiVar = DAG.getTargetGlobalAddress(
5418         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5419     SDValue LoVar = DAG.getTargetGlobalAddress(
5420         GV, DL, MVT::i64, 0,
5421         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5422 
5423     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5424                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5425                     0);
5426     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5427                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5428                     0);
5429   } else if (Model == TLSModel::GeneralDynamic) {
5430     // The call needs a relocation too for linker relaxation. It doesn't make
5431     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5432     // the address.
5433     SDValue SymAddr =
5434         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5435 
5436     // Finally we can make a call to calculate the offset from tpidr_el0.
5437     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5438   } else
5439     llvm_unreachable("Unsupported ELF TLS access model");
5440 
5441   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5442 }
5443 
5444 SDValue
5445 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5446                                                     SelectionDAG &DAG) const {
5447   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5448 
5449   SDValue Chain = DAG.getEntryNode();
5450   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5451   SDLoc DL(Op);
5452 
5453   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5454 
5455   // Load the ThreadLocalStoragePointer from the TEB
5456   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5457   SDValue TLSArray =
5458       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5459   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5460   Chain = TLSArray.getValue(1);
5461 
5462   // Load the TLS index from the C runtime;
5463   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5464   // This also does the same as LOADgot, but using a generic i32 load,
5465   // while LOADgot only loads i64.
5466   SDValue TLSIndexHi =
5467       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5468   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5469       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5470   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5471   SDValue TLSIndex =
5472       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5473   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5474   Chain = TLSIndex.getValue(1);
5475 
5476   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5477   // offset into the TLSArray.
5478   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5479   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5480                              DAG.getConstant(3, DL, PtrVT));
5481   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5482                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5483                             MachinePointerInfo());
5484   Chain = TLS.getValue(1);
5485 
5486   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5487   const GlobalValue *GV = GA->getGlobal();
5488   SDValue TGAHi = DAG.getTargetGlobalAddress(
5489       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5490   SDValue TGALo = DAG.getTargetGlobalAddress(
5491       GV, DL, PtrVT, 0,
5492       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5493 
5494   // Add the offset from the start of the .tls section (section base).
5495   SDValue Addr =
5496       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5497                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5498               0);
5499   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5500   return Addr;
5501 }
5502 
5503 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5504                                                      SelectionDAG &DAG) const {
5505   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5506   if (DAG.getTarget().useEmulatedTLS())
5507     return LowerToTLSEmulatedModel(GA, DAG);
5508 
5509   if (Subtarget->isTargetDarwin())
5510     return LowerDarwinGlobalTLSAddress(Op, DAG);
5511   if (Subtarget->isTargetELF())
5512     return LowerELFGlobalTLSAddress(Op, DAG);
5513   if (Subtarget->isTargetWindows())
5514     return LowerWindowsGlobalTLSAddress(Op, DAG);
5515 
5516   llvm_unreachable("Unexpected platform trying to use TLS");
5517 }
5518 
5519 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5520   SDValue Chain = Op.getOperand(0);
5521   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5522   SDValue LHS = Op.getOperand(2);
5523   SDValue RHS = Op.getOperand(3);
5524   SDValue Dest = Op.getOperand(4);
5525   SDLoc dl(Op);
5526 
5527   MachineFunction &MF = DAG.getMachineFunction();
5528   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5529   // will not be produced, as they are conditional branch instructions that do
5530   // not set flags.
5531   bool ProduceNonFlagSettingCondBr =
5532       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5533 
5534   // Handle f128 first, since lowering it will result in comparing the return
5535   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5536   // is expecting to deal with.
5537   if (LHS.getValueType() == MVT::f128) {
5538     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5539 
5540     // If softenSetCCOperands returned a scalar, we need to compare the result
5541     // against zero to select between true and false values.
5542     if (!RHS.getNode()) {
5543       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5544       CC = ISD::SETNE;
5545     }
5546   }
5547 
5548   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5549   // instruction.
5550   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5551       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5552     // Only lower legal XALUO ops.
5553     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5554       return SDValue();
5555 
5556     // The actual operation with overflow check.
5557     AArch64CC::CondCode OFCC;
5558     SDValue Value, Overflow;
5559     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5560 
5561     if (CC == ISD::SETNE)
5562       OFCC = getInvertedCondCode(OFCC);
5563     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5564 
5565     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5566                        Overflow);
5567   }
5568 
5569   if (LHS.getValueType().isInteger()) {
5570     assert((LHS.getValueType() == RHS.getValueType()) &&
5571            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5572 
5573     // If the RHS of the comparison is zero, we can potentially fold this
5574     // to a specialized branch.
5575     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5576     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5577       if (CC == ISD::SETEQ) {
5578         // See if we can use a TBZ to fold in an AND as well.
5579         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5580         // out of bounds, a late MI-layer pass rewrites branches.
5581         // 403.gcc is an example that hits this case.
5582         if (LHS.getOpcode() == ISD::AND &&
5583             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5584             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5585           SDValue Test = LHS.getOperand(0);
5586           uint64_t Mask = LHS.getConstantOperandVal(1);
5587           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5588                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5589                              Dest);
5590         }
5591 
5592         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5593       } else if (CC == ISD::SETNE) {
5594         // See if we can use a TBZ to fold in an AND as well.
5595         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5596         // out of bounds, a late MI-layer pass rewrites branches.
5597         // 403.gcc is an example that hits this case.
5598         if (LHS.getOpcode() == ISD::AND &&
5599             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5600             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5601           SDValue Test = LHS.getOperand(0);
5602           uint64_t Mask = LHS.getConstantOperandVal(1);
5603           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5604                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5605                              Dest);
5606         }
5607 
5608         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5609       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5610         // Don't combine AND since emitComparison converts the AND to an ANDS
5611         // (a.k.a. TST) and the test in the test bit and branch instruction
5612         // becomes redundant.  This would also increase register pressure.
5613         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5614         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5615                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5616       }
5617     }
5618     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5619         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5620       // Don't combine AND since emitComparison converts the AND to an ANDS
5621       // (a.k.a. TST) and the test in the test bit and branch instruction
5622       // becomes redundant.  This would also increase register pressure.
5623       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5624       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5625                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5626     }
5627 
5628     SDValue CCVal;
5629     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5630     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5631                        Cmp);
5632   }
5633 
5634   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5635          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5636 
5637   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5638   // clean.  Some of them require two branches to implement.
5639   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5640   AArch64CC::CondCode CC1, CC2;
5641   changeFPCCToAArch64CC(CC, CC1, CC2);
5642   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5643   SDValue BR1 =
5644       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5645   if (CC2 != AArch64CC::AL) {
5646     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5647     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5648                        Cmp);
5649   }
5650 
5651   return BR1;
5652 }
5653 
5654 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5655                                               SelectionDAG &DAG) const {
5656   EVT VT = Op.getValueType();
5657   SDLoc DL(Op);
5658 
5659   SDValue In1 = Op.getOperand(0);
5660   SDValue In2 = Op.getOperand(1);
5661   EVT SrcVT = In2.getValueType();
5662 
5663   if (SrcVT.bitsLT(VT))
5664     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5665   else if (SrcVT.bitsGT(VT))
5666     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5667 
5668   EVT VecVT;
5669   uint64_t EltMask;
5670   SDValue VecVal1, VecVal2;
5671 
5672   auto setVecVal = [&] (int Idx) {
5673     if (!VT.isVector()) {
5674       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5675                                           DAG.getUNDEF(VecVT), In1);
5676       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5677                                           DAG.getUNDEF(VecVT), In2);
5678     } else {
5679       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5680       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5681     }
5682   };
5683 
5684   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5685     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5686     EltMask = 0x80000000ULL;
5687     setVecVal(AArch64::ssub);
5688   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5689     VecVT = MVT::v2i64;
5690 
5691     // We want to materialize a mask with the high bit set, but the AdvSIMD
5692     // immediate moves cannot materialize that in a single instruction for
5693     // 64-bit elements. Instead, materialize zero and then negate it.
5694     EltMask = 0;
5695 
5696     setVecVal(AArch64::dsub);
5697   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5698     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5699     EltMask = 0x8000ULL;
5700     setVecVal(AArch64::hsub);
5701   } else {
5702     llvm_unreachable("Invalid type for copysign!");
5703   }
5704 
5705   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5706 
5707   // If we couldn't materialize the mask above, then the mask vector will be
5708   // the zero vector, and we need to negate it here.
5709   if (VT == MVT::f64 || VT == MVT::v2f64) {
5710     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5711     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5712     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5713   }
5714 
5715   SDValue Sel =
5716       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5717 
5718   if (VT == MVT::f16)
5719     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5720   if (VT == MVT::f32)
5721     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5722   else if (VT == MVT::f64)
5723     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5724   else
5725     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5726 }
5727 
5728 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5729   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5730           Attribute::NoImplicitFloat))
5731     return SDValue();
5732 
5733   if (!Subtarget->hasNEON())
5734     return SDValue();
5735 
5736   // While there is no integer popcount instruction, it can
5737   // be more efficiently lowered to the following sequence that uses
5738   // AdvSIMD registers/instructions as long as the copies to/from
5739   // the AdvSIMD registers are cheap.
5740   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5741   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5742   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5743   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5744   SDValue Val = Op.getOperand(0);
5745   SDLoc DL(Op);
5746   EVT VT = Op.getValueType();
5747 
5748   if (VT == MVT::i32 || VT == MVT::i64) {
5749     if (VT == MVT::i32)
5750       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5751     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5752 
5753     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5754     SDValue UaddLV = DAG.getNode(
5755         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5756         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5757 
5758     if (VT == MVT::i64)
5759       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5760     return UaddLV;
5761   } else if (VT == MVT::i128) {
5762     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
5763 
5764     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
5765     SDValue UaddLV = DAG.getNode(
5766         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5767         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5768 
5769     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
5770   }
5771 
5772   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5773           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5774          "Unexpected type for custom ctpop lowering");
5775 
5776   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5777   Val = DAG.getBitcast(VT8Bit, Val);
5778   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5779 
5780   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5781   unsigned EltSize = 8;
5782   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5783   while (EltSize != VT.getScalarSizeInBits()) {
5784     EltSize *= 2;
5785     NumElts /= 2;
5786     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5787     Val = DAG.getNode(
5788         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5789         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5790   }
5791 
5792   return Val;
5793 }
5794 
5795 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5796 
5797   if (Op.getValueType().isVector())
5798     return LowerVSETCC(Op, DAG);
5799 
5800   bool IsStrict = Op->isStrictFPOpcode();
5801   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5802   unsigned OpNo = IsStrict ? 1 : 0;
5803   SDValue Chain;
5804   if (IsStrict)
5805     Chain = Op.getOperand(0);
5806   SDValue LHS = Op.getOperand(OpNo + 0);
5807   SDValue RHS = Op.getOperand(OpNo + 1);
5808   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5809   SDLoc dl(Op);
5810 
5811   // We chose ZeroOrOneBooleanContents, so use zero and one.
5812   EVT VT = Op.getValueType();
5813   SDValue TVal = DAG.getConstant(1, dl, VT);
5814   SDValue FVal = DAG.getConstant(0, dl, VT);
5815 
5816   // Handle f128 first, since one possible outcome is a normal integer
5817   // comparison which gets picked up by the next if statement.
5818   if (LHS.getValueType() == MVT::f128) {
5819     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5820                         IsSignaling);
5821 
5822     // If softenSetCCOperands returned a scalar, use it.
5823     if (!RHS.getNode()) {
5824       assert(LHS.getValueType() == Op.getValueType() &&
5825              "Unexpected setcc expansion!");
5826       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5827     }
5828   }
5829 
5830   if (LHS.getValueType().isInteger()) {
5831     SDValue CCVal;
5832     SDValue Cmp = getAArch64Cmp(
5833         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5834 
5835     // Note that we inverted the condition above, so we reverse the order of
5836     // the true and false operands here.  This will allow the setcc to be
5837     // matched to a single CSINC instruction.
5838     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5839     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5840   }
5841 
5842   // Now we know we're dealing with FP values.
5843   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5844          LHS.getValueType() == MVT::f64);
5845 
5846   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5847   // and do the comparison.
5848   SDValue Cmp;
5849   if (IsStrict)
5850     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5851   else
5852     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5853 
5854   AArch64CC::CondCode CC1, CC2;
5855   changeFPCCToAArch64CC(CC, CC1, CC2);
5856   SDValue Res;
5857   if (CC2 == AArch64CC::AL) {
5858     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5859                           CC2);
5860     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5861 
5862     // Note that we inverted the condition above, so we reverse the order of
5863     // the true and false operands here.  This will allow the setcc to be
5864     // matched to a single CSINC instruction.
5865     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5866   } else {
5867     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5868     // totally clean.  Some of them require two CSELs to implement.  As is in
5869     // this case, we emit the first CSEL and then emit a second using the output
5870     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5871 
5872     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5873     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5874     SDValue CS1 =
5875         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5876 
5877     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5878     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5879   }
5880   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5881 }
5882 
5883 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5884                                               SDValue RHS, SDValue TVal,
5885                                               SDValue FVal, const SDLoc &dl,
5886                                               SelectionDAG &DAG) const {
5887   // Handle f128 first, because it will result in a comparison of some RTLIB
5888   // call result against zero.
5889   if (LHS.getValueType() == MVT::f128) {
5890     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5891 
5892     // If softenSetCCOperands returned a scalar, we need to compare the result
5893     // against zero to select between true and false values.
5894     if (!RHS.getNode()) {
5895       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5896       CC = ISD::SETNE;
5897     }
5898   }
5899 
5900   // Also handle f16, for which we need to do a f32 comparison.
5901   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5902     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5903     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5904   }
5905 
5906   // Next, handle integers.
5907   if (LHS.getValueType().isInteger()) {
5908     assert((LHS.getValueType() == RHS.getValueType()) &&
5909            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5910 
5911     unsigned Opcode = AArch64ISD::CSEL;
5912 
5913     // If both the TVal and the FVal are constants, see if we can swap them in
5914     // order to for a CSINV or CSINC out of them.
5915     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5916     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5917 
5918     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5919       std::swap(TVal, FVal);
5920       std::swap(CTVal, CFVal);
5921       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5922     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5923       std::swap(TVal, FVal);
5924       std::swap(CTVal, CFVal);
5925       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5926     } else if (TVal.getOpcode() == ISD::XOR) {
5927       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5928       // with a CSINV rather than a CSEL.
5929       if (isAllOnesConstant(TVal.getOperand(1))) {
5930         std::swap(TVal, FVal);
5931         std::swap(CTVal, CFVal);
5932         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5933       }
5934     } else if (TVal.getOpcode() == ISD::SUB) {
5935       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5936       // that we can match with a CSNEG rather than a CSEL.
5937       if (isNullConstant(TVal.getOperand(0))) {
5938         std::swap(TVal, FVal);
5939         std::swap(CTVal, CFVal);
5940         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5941       }
5942     } else if (CTVal && CFVal) {
5943       const int64_t TrueVal = CTVal->getSExtValue();
5944       const int64_t FalseVal = CFVal->getSExtValue();
5945       bool Swap = false;
5946 
5947       // If both TVal and FVal are constants, see if FVal is the
5948       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5949       // instead of a CSEL in that case.
5950       if (TrueVal == ~FalseVal) {
5951         Opcode = AArch64ISD::CSINV;
5952       } else if (TrueVal == -FalseVal) {
5953         Opcode = AArch64ISD::CSNEG;
5954       } else if (TVal.getValueType() == MVT::i32) {
5955         // If our operands are only 32-bit wide, make sure we use 32-bit
5956         // arithmetic for the check whether we can use CSINC. This ensures that
5957         // the addition in the check will wrap around properly in case there is
5958         // an overflow (which would not be the case if we do the check with
5959         // 64-bit arithmetic).
5960         const uint32_t TrueVal32 = CTVal->getZExtValue();
5961         const uint32_t FalseVal32 = CFVal->getZExtValue();
5962 
5963         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5964           Opcode = AArch64ISD::CSINC;
5965 
5966           if (TrueVal32 > FalseVal32) {
5967             Swap = true;
5968           }
5969         }
5970         // 64-bit check whether we can use CSINC.
5971       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5972         Opcode = AArch64ISD::CSINC;
5973 
5974         if (TrueVal > FalseVal) {
5975           Swap = true;
5976         }
5977       }
5978 
5979       // Swap TVal and FVal if necessary.
5980       if (Swap) {
5981         std::swap(TVal, FVal);
5982         std::swap(CTVal, CFVal);
5983         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5984       }
5985 
5986       if (Opcode != AArch64ISD::CSEL) {
5987         // Drop FVal since we can get its value by simply inverting/negating
5988         // TVal.
5989         FVal = TVal;
5990       }
5991     }
5992 
5993     // Avoid materializing a constant when possible by reusing a known value in
5994     // a register.  However, don't perform this optimization if the known value
5995     // is one, zero or negative one in the case of a CSEL.  We can always
5996     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5997     // FVal, respectively.
5998     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5999     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
6000         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
6001       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6002       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
6003       // "a != C ? x : a" to avoid materializing C.
6004       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
6005         TVal = LHS;
6006       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
6007         FVal = LHS;
6008     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
6009       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
6010       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
6011       // avoid materializing C.
6012       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6013       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
6014         Opcode = AArch64ISD::CSINV;
6015         TVal = LHS;
6016         FVal = DAG.getConstant(0, dl, FVal.getValueType());
6017       }
6018     }
6019 
6020     SDValue CCVal;
6021     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6022     EVT VT = TVal.getValueType();
6023     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
6024   }
6025 
6026   // Now we know we're dealing with FP values.
6027   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6028          LHS.getValueType() == MVT::f64);
6029   assert(LHS.getValueType() == RHS.getValueType());
6030   EVT VT = TVal.getValueType();
6031   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6032 
6033   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6034   // clean.  Some of them require two CSELs to implement.
6035   AArch64CC::CondCode CC1, CC2;
6036   changeFPCCToAArch64CC(CC, CC1, CC2);
6037 
6038   if (DAG.getTarget().Options.UnsafeFPMath) {
6039     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
6040     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
6041     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
6042     if (RHSVal && RHSVal->isZero()) {
6043       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
6044       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
6045 
6046       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
6047           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
6048         TVal = LHS;
6049       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
6050                CFVal && CFVal->isZero() &&
6051                FVal.getValueType() == LHS.getValueType())
6052         FVal = LHS;
6053     }
6054   }
6055 
6056   // Emit first, and possibly only, CSEL.
6057   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6058   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6059 
6060   // If we need a second CSEL, emit it, using the output of the first as the
6061   // RHS.  We're effectively OR'ing the two CC's together.
6062   if (CC2 != AArch64CC::AL) {
6063     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6064     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6065   }
6066 
6067   // Otherwise, return the output of the first CSEL.
6068   return CS1;
6069 }
6070 
6071 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
6072                                               SelectionDAG &DAG) const {
6073   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6074   SDValue LHS = Op.getOperand(0);
6075   SDValue RHS = Op.getOperand(1);
6076   SDValue TVal = Op.getOperand(2);
6077   SDValue FVal = Op.getOperand(3);
6078   SDLoc DL(Op);
6079   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6080 }
6081 
6082 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
6083                                            SelectionDAG &DAG) const {
6084   SDValue CCVal = Op->getOperand(0);
6085   SDValue TVal = Op->getOperand(1);
6086   SDValue FVal = Op->getOperand(2);
6087   SDLoc DL(Op);
6088 
6089   EVT Ty = Op.getValueType();
6090   if (Ty.isScalableVector()) {
6091     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
6092     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
6093     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
6094     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
6095   }
6096 
6097   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
6098   // instruction.
6099   if (ISD::isOverflowIntrOpRes(CCVal)) {
6100     // Only lower legal XALUO ops.
6101     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
6102       return SDValue();
6103 
6104     AArch64CC::CondCode OFCC;
6105     SDValue Value, Overflow;
6106     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
6107     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
6108 
6109     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
6110                        CCVal, Overflow);
6111   }
6112 
6113   // Lower it the same way as we would lower a SELECT_CC node.
6114   ISD::CondCode CC;
6115   SDValue LHS, RHS;
6116   if (CCVal.getOpcode() == ISD::SETCC) {
6117     LHS = CCVal.getOperand(0);
6118     RHS = CCVal.getOperand(1);
6119     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
6120   } else {
6121     LHS = CCVal;
6122     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
6123     CC = ISD::SETNE;
6124   }
6125   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6126 }
6127 
6128 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
6129                                               SelectionDAG &DAG) const {
6130   // Jump table entries as PC relative offsets. No additional tweaking
6131   // is necessary here. Just get the address of the jump table.
6132   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6133 
6134   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6135       !Subtarget->isTargetMachO()) {
6136     return getAddrLarge(JT, DAG);
6137   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6138     return getAddrTiny(JT, DAG);
6139   }
6140   return getAddr(JT, DAG);
6141 }
6142 
6143 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
6144                                           SelectionDAG &DAG) const {
6145   // Jump table entries as PC relative offsets. No additional tweaking
6146   // is necessary here. Just get the address of the jump table.
6147   SDLoc DL(Op);
6148   SDValue JT = Op.getOperand(1);
6149   SDValue Entry = Op.getOperand(2);
6150   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
6151 
6152   SDNode *Dest =
6153       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
6154                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
6155   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
6156                      SDValue(Dest, 0));
6157 }
6158 
6159 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6160                                                  SelectionDAG &DAG) const {
6161   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6162 
6163   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6164     // Use the GOT for the large code model on iOS.
6165     if (Subtarget->isTargetMachO()) {
6166       return getGOT(CP, DAG);
6167     }
6168     return getAddrLarge(CP, DAG);
6169   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6170     return getAddrTiny(CP, DAG);
6171   } else {
6172     return getAddr(CP, DAG);
6173   }
6174 }
6175 
6176 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6177                                                SelectionDAG &DAG) const {
6178   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6179   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6180       !Subtarget->isTargetMachO()) {
6181     return getAddrLarge(BA, DAG);
6182   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6183     return getAddrTiny(BA, DAG);
6184   }
6185   return getAddr(BA, DAG);
6186 }
6187 
6188 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6189                                                  SelectionDAG &DAG) const {
6190   AArch64FunctionInfo *FuncInfo =
6191       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6192 
6193   SDLoc DL(Op);
6194   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6195                                  getPointerTy(DAG.getDataLayout()));
6196   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6197   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6198   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6199                       MachinePointerInfo(SV));
6200 }
6201 
6202 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6203                                                   SelectionDAG &DAG) const {
6204   AArch64FunctionInfo *FuncInfo =
6205       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6206 
6207   SDLoc DL(Op);
6208   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6209                                      ? FuncInfo->getVarArgsGPRIndex()
6210                                      : FuncInfo->getVarArgsStackIndex(),
6211                                  getPointerTy(DAG.getDataLayout()));
6212   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6213   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6214                       MachinePointerInfo(SV));
6215 }
6216 
6217 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6218                                                 SelectionDAG &DAG) const {
6219   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6220   // Standard, section B.3.
6221   MachineFunction &MF = DAG.getMachineFunction();
6222   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6223   auto PtrVT = getPointerTy(DAG.getDataLayout());
6224   SDLoc DL(Op);
6225 
6226   SDValue Chain = Op.getOperand(0);
6227   SDValue VAList = Op.getOperand(1);
6228   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6229   SmallVector<SDValue, 4> MemOps;
6230 
6231   // void *__stack at offset 0
6232   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6233   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
6234                                 MachinePointerInfo(SV), /* Alignment = */ 8));
6235 
6236   // void *__gr_top at offset 8
6237   int GPRSize = FuncInfo->getVarArgsGPRSize();
6238   if (GPRSize > 0) {
6239     SDValue GRTop, GRTopAddr;
6240 
6241     GRTopAddr =
6242         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6243 
6244     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6245     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6246                         DAG.getConstant(GPRSize, DL, PtrVT));
6247 
6248     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6249                                   MachinePointerInfo(SV, 8),
6250                                   /* Alignment = */ 8));
6251   }
6252 
6253   // void *__vr_top at offset 16
6254   int FPRSize = FuncInfo->getVarArgsFPRSize();
6255   if (FPRSize > 0) {
6256     SDValue VRTop, VRTopAddr;
6257     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6258                             DAG.getConstant(16, DL, PtrVT));
6259 
6260     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6261     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6262                         DAG.getConstant(FPRSize, DL, PtrVT));
6263 
6264     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6265                                   MachinePointerInfo(SV, 16),
6266                                   /* Alignment = */ 8));
6267   }
6268 
6269   // int __gr_offs at offset 24
6270   SDValue GROffsAddr =
6271       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6272   MemOps.push_back(DAG.getStore(
6273       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
6274       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
6275 
6276   // int __vr_offs at offset 28
6277   SDValue VROffsAddr =
6278       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6279   MemOps.push_back(DAG.getStore(
6280       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
6281       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
6282 
6283   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6284 }
6285 
6286 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6287                                             SelectionDAG &DAG) const {
6288   MachineFunction &MF = DAG.getMachineFunction();
6289 
6290   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6291     return LowerWin64_VASTART(Op, DAG);
6292   else if (Subtarget->isTargetDarwin())
6293     return LowerDarwin_VASTART(Op, DAG);
6294   else
6295     return LowerAAPCS_VASTART(Op, DAG);
6296 }
6297 
6298 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6299                                            SelectionDAG &DAG) const {
6300   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6301   // pointer.
6302   SDLoc DL(Op);
6303   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6304   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6305                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6306   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6307   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6308 
6309   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6310                        DAG.getConstant(VaListSize, DL, MVT::i32),
6311                        Align(PtrSize), false, false, false,
6312                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6313 }
6314 
6315 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6316   assert(Subtarget->isTargetDarwin() &&
6317          "automatic va_arg instruction only works on Darwin");
6318 
6319   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6320   EVT VT = Op.getValueType();
6321   SDLoc DL(Op);
6322   SDValue Chain = Op.getOperand(0);
6323   SDValue Addr = Op.getOperand(1);
6324   MaybeAlign Align(Op.getConstantOperandVal(3));
6325   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6326   auto PtrVT = getPointerTy(DAG.getDataLayout());
6327   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6328   SDValue VAList =
6329       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6330   Chain = VAList.getValue(1);
6331   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6332 
6333   if (Align && *Align > MinSlotSize) {
6334     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6335                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6336     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6337                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6338   }
6339 
6340   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6341   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6342 
6343   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6344   // up to 64 bits.  At the very least, we have to increase the striding of the
6345   // vaargs list to match this, and for FP values we need to introduce
6346   // FP_ROUND nodes as well.
6347   if (VT.isInteger() && !VT.isVector())
6348     ArgSize = std::max(ArgSize, MinSlotSize);
6349   bool NeedFPTrunc = false;
6350   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6351     ArgSize = 8;
6352     NeedFPTrunc = true;
6353   }
6354 
6355   // Increment the pointer, VAList, to the next vaarg
6356   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6357                                DAG.getConstant(ArgSize, DL, PtrVT));
6358   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6359 
6360   // Store the incremented VAList to the legalized pointer
6361   SDValue APStore =
6362       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6363 
6364   // Load the actual argument out of the pointer VAList
6365   if (NeedFPTrunc) {
6366     // Load the value as an f64.
6367     SDValue WideFP =
6368         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6369     // Round the value down to an f32.
6370     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6371                                    DAG.getIntPtrConstant(1, DL));
6372     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6373     // Merge the rounded value with the chain output of the load.
6374     return DAG.getMergeValues(Ops, DL);
6375   }
6376 
6377   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6378 }
6379 
6380 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6381                                               SelectionDAG &DAG) const {
6382   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6383   MFI.setFrameAddressIsTaken(true);
6384 
6385   EVT VT = Op.getValueType();
6386   SDLoc DL(Op);
6387   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6388   SDValue FrameAddr =
6389       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6390   while (Depth--)
6391     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6392                             MachinePointerInfo());
6393 
6394   if (Subtarget->isTargetILP32())
6395     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6396                             DAG.getValueType(VT));
6397 
6398   return FrameAddr;
6399 }
6400 
6401 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6402                                               SelectionDAG &DAG) const {
6403   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6404 
6405   EVT VT = getPointerTy(DAG.getDataLayout());
6406   SDLoc DL(Op);
6407   int FI = MFI.CreateFixedObject(4, 0, false);
6408   return DAG.getFrameIndex(FI, VT);
6409 }
6410 
6411 #define GET_REGISTER_MATCHER
6412 #include "AArch64GenAsmMatcher.inc"
6413 
6414 // FIXME? Maybe this could be a TableGen attribute on some registers and
6415 // this table could be generated automatically from RegInfo.
6416 Register AArch64TargetLowering::
6417 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6418   Register Reg = MatchRegisterName(RegName);
6419   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6420     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6421     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6422     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6423       Reg = 0;
6424   }
6425   if (Reg)
6426     return Reg;
6427   report_fatal_error(Twine("Invalid register name \""
6428                               + StringRef(RegName)  + "\"."));
6429 }
6430 
6431 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6432                                                      SelectionDAG &DAG) const {
6433   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6434 
6435   EVT VT = Op.getValueType();
6436   SDLoc DL(Op);
6437 
6438   SDValue FrameAddr =
6439       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6440   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6441 
6442   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6443 }
6444 
6445 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6446                                                SelectionDAG &DAG) const {
6447   MachineFunction &MF = DAG.getMachineFunction();
6448   MachineFrameInfo &MFI = MF.getFrameInfo();
6449   MFI.setReturnAddressIsTaken(true);
6450 
6451   EVT VT = Op.getValueType();
6452   SDLoc DL(Op);
6453   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6454   if (Depth) {
6455     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6456     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6457     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6458                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6459                        MachinePointerInfo());
6460   }
6461 
6462   // Return LR, which contains the return address. Mark it an implicit live-in.
6463   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6464   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6465 }
6466 
6467 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6468 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6469 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6470                                                     SelectionDAG &DAG) const {
6471   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6472   EVT VT = Op.getValueType();
6473   unsigned VTBits = VT.getSizeInBits();
6474   SDLoc dl(Op);
6475   SDValue ShOpLo = Op.getOperand(0);
6476   SDValue ShOpHi = Op.getOperand(1);
6477   SDValue ShAmt = Op.getOperand(2);
6478   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6479 
6480   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6481 
6482   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6483                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6484   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6485 
6486   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6487   // is "undef". We wanted 0, so CSEL it directly.
6488   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6489                                ISD::SETEQ, dl, DAG);
6490   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6491   HiBitsForLo =
6492       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6493                   HiBitsForLo, CCVal, Cmp);
6494 
6495   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6496                                    DAG.getConstant(VTBits, dl, MVT::i64));
6497 
6498   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6499   SDValue LoForNormalShift =
6500       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6501 
6502   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6503                        dl, DAG);
6504   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6505   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6506   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6507                            LoForNormalShift, CCVal, Cmp);
6508 
6509   // AArch64 shifts larger than the register width are wrapped rather than
6510   // clamped, so we can't just emit "hi >> x".
6511   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6512   SDValue HiForBigShift =
6513       Opc == ISD::SRA
6514           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6515                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6516           : DAG.getConstant(0, dl, VT);
6517   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6518                            HiForNormalShift, CCVal, Cmp);
6519 
6520   SDValue Ops[2] = { Lo, Hi };
6521   return DAG.getMergeValues(Ops, dl);
6522 }
6523 
6524 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6525 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6526 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6527                                                    SelectionDAG &DAG) const {
6528   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6529   EVT VT = Op.getValueType();
6530   unsigned VTBits = VT.getSizeInBits();
6531   SDLoc dl(Op);
6532   SDValue ShOpLo = Op.getOperand(0);
6533   SDValue ShOpHi = Op.getOperand(1);
6534   SDValue ShAmt = Op.getOperand(2);
6535 
6536   assert(Op.getOpcode() == ISD::SHL_PARTS);
6537   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6538                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6539   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6540 
6541   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6542   // is "undef". We wanted 0, so CSEL it directly.
6543   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6544                                ISD::SETEQ, dl, DAG);
6545   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6546   LoBitsForHi =
6547       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6548                   LoBitsForHi, CCVal, Cmp);
6549 
6550   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6551                                    DAG.getConstant(VTBits, dl, MVT::i64));
6552   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6553   SDValue HiForNormalShift =
6554       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6555 
6556   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6557 
6558   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6559                        dl, DAG);
6560   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6561   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6562                            HiForNormalShift, CCVal, Cmp);
6563 
6564   // AArch64 shifts of larger than register sizes are wrapped rather than
6565   // clamped, so we can't just emit "lo << a" if a is too big.
6566   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6567   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6568   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6569                            LoForNormalShift, CCVal, Cmp);
6570 
6571   SDValue Ops[2] = { Lo, Hi };
6572   return DAG.getMergeValues(Ops, dl);
6573 }
6574 
6575 bool AArch64TargetLowering::isOffsetFoldingLegal(
6576     const GlobalAddressSDNode *GA) const {
6577   // Offsets are folded in the DAG combine rather than here so that we can
6578   // intelligently choose an offset based on the uses.
6579   return false;
6580 }
6581 
6582 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6583                                          bool OptForSize) const {
6584   bool IsLegal = false;
6585   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6586   // 16-bit case when target has full fp16 support.
6587   // FIXME: We should be able to handle f128 as well with a clever lowering.
6588   const APInt ImmInt = Imm.bitcastToAPInt();
6589   if (VT == MVT::f64)
6590     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6591   else if (VT == MVT::f32)
6592     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6593   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6594     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6595   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6596   //       generate that fmov.
6597 
6598   // If we can not materialize in immediate field for fmov, check if the
6599   // value can be encoded as the immediate operand of a logical instruction.
6600   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6601   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6602     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6603     // however the mov+fmov sequence is always better because of the reduced
6604     // cache pressure. The timings are still the same if you consider
6605     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6606     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6607     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6608     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6609 			      Insn);
6610     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6611     IsLegal = Insn.size() <= Limit;
6612   }
6613 
6614   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6615                     << " imm value: "; Imm.dump(););
6616   return IsLegal;
6617 }
6618 
6619 //===----------------------------------------------------------------------===//
6620 //                          AArch64 Optimization Hooks
6621 //===----------------------------------------------------------------------===//
6622 
6623 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6624                            SDValue Operand, SelectionDAG &DAG,
6625                            int &ExtraSteps) {
6626   EVT VT = Operand.getValueType();
6627   if (ST->hasNEON() &&
6628       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6629        VT == MVT::f32 || VT == MVT::v1f32 ||
6630        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6631     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6632       // For the reciprocal estimates, convergence is quadratic, so the number
6633       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6634       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6635       // the result for float (23 mantissa bits) is 2 and for double (52
6636       // mantissa bits) is 3.
6637       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6638 
6639     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6640   }
6641 
6642   return SDValue();
6643 }
6644 
6645 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6646                                                SelectionDAG &DAG, int Enabled,
6647                                                int &ExtraSteps,
6648                                                bool &UseOneConst,
6649                                                bool Reciprocal) const {
6650   if (Enabled == ReciprocalEstimate::Enabled ||
6651       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6652     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6653                                        DAG, ExtraSteps)) {
6654       SDLoc DL(Operand);
6655       EVT VT = Operand.getValueType();
6656 
6657       SDNodeFlags Flags;
6658       Flags.setAllowReassociation(true);
6659 
6660       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6661       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6662       for (int i = ExtraSteps; i > 0; --i) {
6663         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6664                                    Flags);
6665         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6666         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6667       }
6668       if (!Reciprocal) {
6669         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6670                                       VT);
6671         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6672         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6673 
6674         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6675         // Correct the result if the operand is 0.0.
6676         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6677                                VT, Eq, Operand, Estimate);
6678       }
6679 
6680       ExtraSteps = 0;
6681       return Estimate;
6682     }
6683 
6684   return SDValue();
6685 }
6686 
6687 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6688                                                 SelectionDAG &DAG, int Enabled,
6689                                                 int &ExtraSteps) const {
6690   if (Enabled == ReciprocalEstimate::Enabled)
6691     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6692                                        DAG, ExtraSteps)) {
6693       SDLoc DL(Operand);
6694       EVT VT = Operand.getValueType();
6695 
6696       SDNodeFlags Flags;
6697       Flags.setAllowReassociation(true);
6698 
6699       // Newton reciprocal iteration: E * (2 - X * E)
6700       // AArch64 reciprocal iteration instruction: (2 - M * N)
6701       for (int i = ExtraSteps; i > 0; --i) {
6702         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6703                                    Estimate, Flags);
6704         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6705       }
6706 
6707       ExtraSteps = 0;
6708       return Estimate;
6709     }
6710 
6711   return SDValue();
6712 }
6713 
6714 //===----------------------------------------------------------------------===//
6715 //                          AArch64 Inline Assembly Support
6716 //===----------------------------------------------------------------------===//
6717 
6718 // Table of Constraints
6719 // TODO: This is the current set of constraints supported by ARM for the
6720 // compiler, not all of them may make sense.
6721 //
6722 // r - A general register
6723 // w - An FP/SIMD register of some size in the range v0-v31
6724 // x - An FP/SIMD register of some size in the range v0-v15
6725 // I - Constant that can be used with an ADD instruction
6726 // J - Constant that can be used with a SUB instruction
6727 // K - Constant that can be used with a 32-bit logical instruction
6728 // L - Constant that can be used with a 64-bit logical instruction
6729 // M - Constant that can be used as a 32-bit MOV immediate
6730 // N - Constant that can be used as a 64-bit MOV immediate
6731 // Q - A memory reference with base register and no offset
6732 // S - A symbolic address
6733 // Y - Floating point constant zero
6734 // Z - Integer constant zero
6735 //
6736 //   Note that general register operands will be output using their 64-bit x
6737 // register name, whatever the size of the variable, unless the asm operand
6738 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6739 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6740 // %q modifier.
6741 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6742   // At this point, we have to lower this constraint to something else, so we
6743   // lower it to an "r" or "w". However, by doing this we will force the result
6744   // to be in register, while the X constraint is much more permissive.
6745   //
6746   // Although we are correct (we are free to emit anything, without
6747   // constraints), we might break use cases that would expect us to be more
6748   // efficient and emit something else.
6749   if (!Subtarget->hasFPARMv8())
6750     return "r";
6751 
6752   if (ConstraintVT.isFloatingPoint())
6753     return "w";
6754 
6755   if (ConstraintVT.isVector() &&
6756      (ConstraintVT.getSizeInBits() == 64 ||
6757       ConstraintVT.getSizeInBits() == 128))
6758     return "w";
6759 
6760   return "r";
6761 }
6762 
6763 enum PredicateConstraint {
6764   Upl,
6765   Upa,
6766   Invalid
6767 };
6768 
6769 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6770   PredicateConstraint P = PredicateConstraint::Invalid;
6771   if (Constraint == "Upa")
6772     P = PredicateConstraint::Upa;
6773   if (Constraint == "Upl")
6774     P = PredicateConstraint::Upl;
6775   return P;
6776 }
6777 
6778 /// getConstraintType - Given a constraint letter, return the type of
6779 /// constraint it is for this target.
6780 AArch64TargetLowering::ConstraintType
6781 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6782   if (Constraint.size() == 1) {
6783     switch (Constraint[0]) {
6784     default:
6785       break;
6786     case 'x':
6787     case 'w':
6788     case 'y':
6789       return C_RegisterClass;
6790     // An address with a single base register. Due to the way we
6791     // currently handle addresses it is the same as 'r'.
6792     case 'Q':
6793       return C_Memory;
6794     case 'I':
6795     case 'J':
6796     case 'K':
6797     case 'L':
6798     case 'M':
6799     case 'N':
6800     case 'Y':
6801     case 'Z':
6802       return C_Immediate;
6803     case 'z':
6804     case 'S': // A symbolic address
6805       return C_Other;
6806     }
6807   } else if (parsePredicateConstraint(Constraint) !=
6808              PredicateConstraint::Invalid)
6809       return C_RegisterClass;
6810   return TargetLowering::getConstraintType(Constraint);
6811 }
6812 
6813 /// Examine constraint type and operand type and determine a weight value.
6814 /// This object must already have been set up with the operand type
6815 /// and the current alternative constraint selected.
6816 TargetLowering::ConstraintWeight
6817 AArch64TargetLowering::getSingleConstraintMatchWeight(
6818     AsmOperandInfo &info, const char *constraint) const {
6819   ConstraintWeight weight = CW_Invalid;
6820   Value *CallOperandVal = info.CallOperandVal;
6821   // If we don't have a value, we can't do a match,
6822   // but allow it at the lowest weight.
6823   if (!CallOperandVal)
6824     return CW_Default;
6825   Type *type = CallOperandVal->getType();
6826   // Look at the constraint type.
6827   switch (*constraint) {
6828   default:
6829     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6830     break;
6831   case 'x':
6832   case 'w':
6833   case 'y':
6834     if (type->isFloatingPointTy() || type->isVectorTy())
6835       weight = CW_Register;
6836     break;
6837   case 'z':
6838     weight = CW_Constant;
6839     break;
6840   case 'U':
6841     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6842       weight = CW_Register;
6843     break;
6844   }
6845   return weight;
6846 }
6847 
6848 std::pair<unsigned, const TargetRegisterClass *>
6849 AArch64TargetLowering::getRegForInlineAsmConstraint(
6850     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6851   if (Constraint.size() == 1) {
6852     switch (Constraint[0]) {
6853     case 'r':
6854       if (VT.getSizeInBits() == 64)
6855         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6856       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6857     case 'w':
6858       if (!Subtarget->hasFPARMv8())
6859         break;
6860       if (VT.isScalableVector())
6861         return std::make_pair(0U, &AArch64::ZPRRegClass);
6862       if (VT.getSizeInBits() == 16)
6863         return std::make_pair(0U, &AArch64::FPR16RegClass);
6864       if (VT.getSizeInBits() == 32)
6865         return std::make_pair(0U, &AArch64::FPR32RegClass);
6866       if (VT.getSizeInBits() == 64)
6867         return std::make_pair(0U, &AArch64::FPR64RegClass);
6868       if (VT.getSizeInBits() == 128)
6869         return std::make_pair(0U, &AArch64::FPR128RegClass);
6870       break;
6871     // The instructions that this constraint is designed for can
6872     // only take 128-bit registers so just use that regclass.
6873     case 'x':
6874       if (!Subtarget->hasFPARMv8())
6875         break;
6876       if (VT.isScalableVector())
6877         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6878       if (VT.getSizeInBits() == 128)
6879         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6880       break;
6881     case 'y':
6882       if (!Subtarget->hasFPARMv8())
6883         break;
6884       if (VT.isScalableVector())
6885         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6886       break;
6887     }
6888   } else {
6889     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6890     if (PC != PredicateConstraint::Invalid) {
6891       assert(VT.isScalableVector());
6892       bool restricted = (PC == PredicateConstraint::Upl);
6893       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6894                           : std::make_pair(0U, &AArch64::PPRRegClass);
6895     }
6896   }
6897   if (StringRef("{cc}").equals_lower(Constraint))
6898     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6899 
6900   // Use the default implementation in TargetLowering to convert the register
6901   // constraint into a member of a register class.
6902   std::pair<unsigned, const TargetRegisterClass *> Res;
6903   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6904 
6905   // Not found as a standard register?
6906   if (!Res.second) {
6907     unsigned Size = Constraint.size();
6908     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6909         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6910       int RegNo;
6911       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6912       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6913         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6914         // By default we'll emit v0-v31 for this unless there's a modifier where
6915         // we'll emit the correct register as well.
6916         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6917           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6918           Res.second = &AArch64::FPR64RegClass;
6919         } else {
6920           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6921           Res.second = &AArch64::FPR128RegClass;
6922         }
6923       }
6924     }
6925   }
6926 
6927   if (Res.second && !Subtarget->hasFPARMv8() &&
6928       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6929       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6930     return std::make_pair(0U, nullptr);
6931 
6932   return Res;
6933 }
6934 
6935 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6936 /// vector.  If it is invalid, don't add anything to Ops.
6937 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6938     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6939     SelectionDAG &DAG) const {
6940   SDValue Result;
6941 
6942   // Currently only support length 1 constraints.
6943   if (Constraint.length() != 1)
6944     return;
6945 
6946   char ConstraintLetter = Constraint[0];
6947   switch (ConstraintLetter) {
6948   default:
6949     break;
6950 
6951   // This set of constraints deal with valid constants for various instructions.
6952   // Validate and return a target constant for them if we can.
6953   case 'z': {
6954     // 'z' maps to xzr or wzr so it needs an input of 0.
6955     if (!isNullConstant(Op))
6956       return;
6957 
6958     if (Op.getValueType() == MVT::i64)
6959       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6960     else
6961       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6962     break;
6963   }
6964   case 'S': {
6965     // An absolute symbolic address or label reference.
6966     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6967       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6968                                           GA->getValueType(0));
6969     } else if (const BlockAddressSDNode *BA =
6970                    dyn_cast<BlockAddressSDNode>(Op)) {
6971       Result =
6972           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6973     } else if (const ExternalSymbolSDNode *ES =
6974                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6975       Result =
6976           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6977     } else
6978       return;
6979     break;
6980   }
6981 
6982   case 'I':
6983   case 'J':
6984   case 'K':
6985   case 'L':
6986   case 'M':
6987   case 'N':
6988     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6989     if (!C)
6990       return;
6991 
6992     // Grab the value and do some validation.
6993     uint64_t CVal = C->getZExtValue();
6994     switch (ConstraintLetter) {
6995     // The I constraint applies only to simple ADD or SUB immediate operands:
6996     // i.e. 0 to 4095 with optional shift by 12
6997     // The J constraint applies only to ADD or SUB immediates that would be
6998     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6999     // instruction [or vice versa], in other words -1 to -4095 with optional
7000     // left shift by 12.
7001     case 'I':
7002       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
7003         break;
7004       return;
7005     case 'J': {
7006       uint64_t NVal = -C->getSExtValue();
7007       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
7008         CVal = C->getSExtValue();
7009         break;
7010       }
7011       return;
7012     }
7013     // The K and L constraints apply *only* to logical immediates, including
7014     // what used to be the MOVI alias for ORR (though the MOVI alias has now
7015     // been removed and MOV should be used). So these constraints have to
7016     // distinguish between bit patterns that are valid 32-bit or 64-bit
7017     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
7018     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
7019     // versa.
7020     case 'K':
7021       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7022         break;
7023       return;
7024     case 'L':
7025       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7026         break;
7027       return;
7028     // The M and N constraints are a superset of K and L respectively, for use
7029     // with the MOV (immediate) alias. As well as the logical immediates they
7030     // also match 32 or 64-bit immediates that can be loaded either using a
7031     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
7032     // (M) or 64-bit 0x1234000000000000 (N) etc.
7033     // As a note some of this code is liberally stolen from the asm parser.
7034     case 'M': {
7035       if (!isUInt<32>(CVal))
7036         return;
7037       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7038         break;
7039       if ((CVal & 0xFFFF) == CVal)
7040         break;
7041       if ((CVal & 0xFFFF0000ULL) == CVal)
7042         break;
7043       uint64_t NCVal = ~(uint32_t)CVal;
7044       if ((NCVal & 0xFFFFULL) == NCVal)
7045         break;
7046       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7047         break;
7048       return;
7049     }
7050     case 'N': {
7051       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7052         break;
7053       if ((CVal & 0xFFFFULL) == CVal)
7054         break;
7055       if ((CVal & 0xFFFF0000ULL) == CVal)
7056         break;
7057       if ((CVal & 0xFFFF00000000ULL) == CVal)
7058         break;
7059       if ((CVal & 0xFFFF000000000000ULL) == CVal)
7060         break;
7061       uint64_t NCVal = ~CVal;
7062       if ((NCVal & 0xFFFFULL) == NCVal)
7063         break;
7064       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7065         break;
7066       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
7067         break;
7068       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
7069         break;
7070       return;
7071     }
7072     default:
7073       return;
7074     }
7075 
7076     // All assembler immediates are 64-bit integers.
7077     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
7078     break;
7079   }
7080 
7081   if (Result.getNode()) {
7082     Ops.push_back(Result);
7083     return;
7084   }
7085 
7086   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7087 }
7088 
7089 //===----------------------------------------------------------------------===//
7090 //                     AArch64 Advanced SIMD Support
7091 //===----------------------------------------------------------------------===//
7092 
7093 /// WidenVector - Given a value in the V64 register class, produce the
7094 /// equivalent value in the V128 register class.
7095 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
7096   EVT VT = V64Reg.getValueType();
7097   unsigned NarrowSize = VT.getVectorNumElements();
7098   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7099   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
7100   SDLoc DL(V64Reg);
7101 
7102   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
7103                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
7104 }
7105 
7106 /// getExtFactor - Determine the adjustment factor for the position when
7107 /// generating an "extract from vector registers" instruction.
7108 static unsigned getExtFactor(SDValue &V) {
7109   EVT EltType = V.getValueType().getVectorElementType();
7110   return EltType.getSizeInBits() / 8;
7111 }
7112 
7113 /// NarrowVector - Given a value in the V128 register class, produce the
7114 /// equivalent value in the V64 register class.
7115 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
7116   EVT VT = V128Reg.getValueType();
7117   unsigned WideSize = VT.getVectorNumElements();
7118   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7119   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
7120   SDLoc DL(V128Reg);
7121 
7122   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
7123 }
7124 
7125 // Gather data to see if the operation can be modelled as a
7126 // shuffle in combination with VEXTs.
7127 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
7128                                                   SelectionDAG &DAG) const {
7129   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7130   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
7131   SDLoc dl(Op);
7132   EVT VT = Op.getValueType();
7133   unsigned NumElts = VT.getVectorNumElements();
7134 
7135   struct ShuffleSourceInfo {
7136     SDValue Vec;
7137     unsigned MinElt;
7138     unsigned MaxElt;
7139 
7140     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7141     // be compatible with the shuffle we intend to construct. As a result
7142     // ShuffleVec will be some sliding window into the original Vec.
7143     SDValue ShuffleVec;
7144 
7145     // Code should guarantee that element i in Vec starts at element "WindowBase
7146     // + i * WindowScale in ShuffleVec".
7147     int WindowBase;
7148     int WindowScale;
7149 
7150     ShuffleSourceInfo(SDValue Vec)
7151       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
7152           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
7153 
7154     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7155   };
7156 
7157   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7158   // node.
7159   SmallVector<ShuffleSourceInfo, 2> Sources;
7160   for (unsigned i = 0; i < NumElts; ++i) {
7161     SDValue V = Op.getOperand(i);
7162     if (V.isUndef())
7163       continue;
7164     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7165              !isa<ConstantSDNode>(V.getOperand(1))) {
7166       LLVM_DEBUG(
7167           dbgs() << "Reshuffle failed: "
7168                     "a shuffle can only come from building a vector from "
7169                     "various elements of other vectors, provided their "
7170                     "indices are constant\n");
7171       return SDValue();
7172     }
7173 
7174     // Add this element source to the list if it's not already there.
7175     SDValue SourceVec = V.getOperand(0);
7176     auto Source = find(Sources, SourceVec);
7177     if (Source == Sources.end())
7178       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7179 
7180     // Update the minimum and maximum lane number seen.
7181     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7182     Source->MinElt = std::min(Source->MinElt, EltNo);
7183     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7184   }
7185 
7186   if (Sources.size() > 2) {
7187     LLVM_DEBUG(
7188         dbgs() << "Reshuffle failed: currently only do something sane when at "
7189                   "most two source vectors are involved\n");
7190     return SDValue();
7191   }
7192 
7193   // Find out the smallest element size among result and two sources, and use
7194   // it as element size to build the shuffle_vector.
7195   EVT SmallestEltTy = VT.getVectorElementType();
7196   for (auto &Source : Sources) {
7197     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7198     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7199       SmallestEltTy = SrcEltTy;
7200     }
7201   }
7202   unsigned ResMultiplier =
7203       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7204   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7205   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7206 
7207   // If the source vector is too wide or too narrow, we may nevertheless be able
7208   // to construct a compatible shuffle either by concatenating it with UNDEF or
7209   // extracting a suitable range of elements.
7210   for (auto &Src : Sources) {
7211     EVT SrcVT = Src.ShuffleVec.getValueType();
7212 
7213     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7214       continue;
7215 
7216     // This stage of the search produces a source with the same element type as
7217     // the original, but with a total width matching the BUILD_VECTOR output.
7218     EVT EltVT = SrcVT.getVectorElementType();
7219     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7220     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7221 
7222     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7223       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
7224       // We can pad out the smaller vector for free, so if it's part of a
7225       // shuffle...
7226       Src.ShuffleVec =
7227           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7228                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7229       continue;
7230     }
7231 
7232     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
7233 
7234     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7235       LLVM_DEBUG(
7236           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7237       return SDValue();
7238     }
7239 
7240     if (Src.MinElt >= NumSrcElts) {
7241       // The extraction can just take the second half
7242       Src.ShuffleVec =
7243           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7244                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7245       Src.WindowBase = -NumSrcElts;
7246     } else if (Src.MaxElt < NumSrcElts) {
7247       // The extraction can just take the first half
7248       Src.ShuffleVec =
7249           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7250                       DAG.getConstant(0, dl, MVT::i64));
7251     } else {
7252       // An actual VEXT is needed
7253       SDValue VEXTSrc1 =
7254           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7255                       DAG.getConstant(0, dl, MVT::i64));
7256       SDValue VEXTSrc2 =
7257           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7258                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7259       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7260 
7261       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7262                                    VEXTSrc2,
7263                                    DAG.getConstant(Imm, dl, MVT::i32));
7264       Src.WindowBase = -Src.MinElt;
7265     }
7266   }
7267 
7268   // Another possible incompatibility occurs from the vector element types. We
7269   // can fix this by bitcasting the source vectors to the same type we intend
7270   // for the shuffle.
7271   for (auto &Src : Sources) {
7272     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7273     if (SrcEltTy == SmallestEltTy)
7274       continue;
7275     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7276     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7277     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7278     Src.WindowBase *= Src.WindowScale;
7279   }
7280 
7281   // Final sanity check before we try to actually produce a shuffle.
7282   LLVM_DEBUG(for (auto Src
7283                   : Sources)
7284                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7285 
7286   // The stars all align, our next step is to produce the mask for the shuffle.
7287   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7288   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7289   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7290     SDValue Entry = Op.getOperand(i);
7291     if (Entry.isUndef())
7292       continue;
7293 
7294     auto Src = find(Sources, Entry.getOperand(0));
7295     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7296 
7297     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7298     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7299     // segment.
7300     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7301     int BitsDefined =
7302         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
7303     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7304 
7305     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7306     // starting at the appropriate offset.
7307     int *LaneMask = &Mask[i * ResMultiplier];
7308 
7309     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7310     ExtractBase += NumElts * (Src - Sources.begin());
7311     for (int j = 0; j < LanesDefined; ++j)
7312       LaneMask[j] = ExtractBase + j;
7313   }
7314 
7315   // Final check before we try to produce nonsense...
7316   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7317     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7318     return SDValue();
7319   }
7320 
7321   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7322   for (unsigned i = 0; i < Sources.size(); ++i)
7323     ShuffleOps[i] = Sources[i].ShuffleVec;
7324 
7325   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7326                                          ShuffleOps[1], Mask);
7327   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7328 
7329   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7330              dbgs() << "Reshuffle, creating node: "; V.dump(););
7331 
7332   return V;
7333 }
7334 
7335 // check if an EXT instruction can handle the shuffle mask when the
7336 // vector sources of the shuffle are the same.
7337 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7338   unsigned NumElts = VT.getVectorNumElements();
7339 
7340   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7341   if (M[0] < 0)
7342     return false;
7343 
7344   Imm = M[0];
7345 
7346   // If this is a VEXT shuffle, the immediate value is the index of the first
7347   // element.  The other shuffle indices must be the successive elements after
7348   // the first one.
7349   unsigned ExpectedElt = Imm;
7350   for (unsigned i = 1; i < NumElts; ++i) {
7351     // Increment the expected index.  If it wraps around, just follow it
7352     // back to index zero and keep going.
7353     ++ExpectedElt;
7354     if (ExpectedElt == NumElts)
7355       ExpectedElt = 0;
7356 
7357     if (M[i] < 0)
7358       continue; // ignore UNDEF indices
7359     if (ExpectedElt != static_cast<unsigned>(M[i]))
7360       return false;
7361   }
7362 
7363   return true;
7364 }
7365 
7366 // check if an EXT instruction can handle the shuffle mask when the
7367 // vector sources of the shuffle are different.
7368 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7369                       unsigned &Imm) {
7370   // Look for the first non-undef element.
7371   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7372 
7373   // Benefit form APInt to handle overflow when calculating expected element.
7374   unsigned NumElts = VT.getVectorNumElements();
7375   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7376   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7377   // The following shuffle indices must be the successive elements after the
7378   // first real element.
7379   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7380       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7381   if (FirstWrongElt != M.end())
7382     return false;
7383 
7384   // The index of an EXT is the first element if it is not UNDEF.
7385   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7386   // value of the first element.  E.g.
7387   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7388   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7389   // ExpectedElt is the last mask index plus 1.
7390   Imm = ExpectedElt.getZExtValue();
7391 
7392   // There are two difference cases requiring to reverse input vectors.
7393   // For example, for vector <4 x i32> we have the following cases,
7394   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7395   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7396   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7397   // to reverse two input vectors.
7398   if (Imm < NumElts)
7399     ReverseEXT = true;
7400   else
7401     Imm -= NumElts;
7402 
7403   return true;
7404 }
7405 
7406 /// isREVMask - Check if a vector shuffle corresponds to a REV
7407 /// instruction with the specified blocksize.  (The order of the elements
7408 /// within each block of the vector is reversed.)
7409 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7410   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7411          "Only possible block sizes for REV are: 16, 32, 64");
7412 
7413   unsigned EltSz = VT.getScalarSizeInBits();
7414   if (EltSz == 64)
7415     return false;
7416 
7417   unsigned NumElts = VT.getVectorNumElements();
7418   unsigned BlockElts = M[0] + 1;
7419   // If the first shuffle index is UNDEF, be optimistic.
7420   if (M[0] < 0)
7421     BlockElts = BlockSize / EltSz;
7422 
7423   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7424     return false;
7425 
7426   for (unsigned i = 0; i < NumElts; ++i) {
7427     if (M[i] < 0)
7428       continue; // ignore UNDEF indices
7429     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7430       return false;
7431   }
7432 
7433   return true;
7434 }
7435 
7436 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7437   unsigned NumElts = VT.getVectorNumElements();
7438   if (NumElts % 2 != 0)
7439     return false;
7440   WhichResult = (M[0] == 0 ? 0 : 1);
7441   unsigned Idx = WhichResult * NumElts / 2;
7442   for (unsigned i = 0; i != NumElts; i += 2) {
7443     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7444         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7445       return false;
7446     Idx += 1;
7447   }
7448 
7449   return true;
7450 }
7451 
7452 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7453   unsigned NumElts = VT.getVectorNumElements();
7454   WhichResult = (M[0] == 0 ? 0 : 1);
7455   for (unsigned i = 0; i != NumElts; ++i) {
7456     if (M[i] < 0)
7457       continue; // ignore UNDEF indices
7458     if ((unsigned)M[i] != 2 * i + WhichResult)
7459       return false;
7460   }
7461 
7462   return true;
7463 }
7464 
7465 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7466   unsigned NumElts = VT.getVectorNumElements();
7467   if (NumElts % 2 != 0)
7468     return false;
7469   WhichResult = (M[0] == 0 ? 0 : 1);
7470   for (unsigned i = 0; i < NumElts; i += 2) {
7471     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7472         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7473       return false;
7474   }
7475   return true;
7476 }
7477 
7478 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7479 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7480 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7481 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7482   unsigned NumElts = VT.getVectorNumElements();
7483   if (NumElts % 2 != 0)
7484     return false;
7485   WhichResult = (M[0] == 0 ? 0 : 1);
7486   unsigned Idx = WhichResult * NumElts / 2;
7487   for (unsigned i = 0; i != NumElts; i += 2) {
7488     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7489         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7490       return false;
7491     Idx += 1;
7492   }
7493 
7494   return true;
7495 }
7496 
7497 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7498 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7499 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7500 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7501   unsigned Half = VT.getVectorNumElements() / 2;
7502   WhichResult = (M[0] == 0 ? 0 : 1);
7503   for (unsigned j = 0; j != 2; ++j) {
7504     unsigned Idx = WhichResult;
7505     for (unsigned i = 0; i != Half; ++i) {
7506       int MIdx = M[i + j * Half];
7507       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7508         return false;
7509       Idx += 2;
7510     }
7511   }
7512 
7513   return true;
7514 }
7515 
7516 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7517 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7518 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7519 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7520   unsigned NumElts = VT.getVectorNumElements();
7521   if (NumElts % 2 != 0)
7522     return false;
7523   WhichResult = (M[0] == 0 ? 0 : 1);
7524   for (unsigned i = 0; i < NumElts; i += 2) {
7525     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7526         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7527       return false;
7528   }
7529   return true;
7530 }
7531 
7532 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7533                       bool &DstIsLeft, int &Anomaly) {
7534   if (M.size() != static_cast<size_t>(NumInputElements))
7535     return false;
7536 
7537   int NumLHSMatch = 0, NumRHSMatch = 0;
7538   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7539 
7540   for (int i = 0; i < NumInputElements; ++i) {
7541     if (M[i] == -1) {
7542       ++NumLHSMatch;
7543       ++NumRHSMatch;
7544       continue;
7545     }
7546 
7547     if (M[i] == i)
7548       ++NumLHSMatch;
7549     else
7550       LastLHSMismatch = i;
7551 
7552     if (M[i] == i + NumInputElements)
7553       ++NumRHSMatch;
7554     else
7555       LastRHSMismatch = i;
7556   }
7557 
7558   if (NumLHSMatch == NumInputElements - 1) {
7559     DstIsLeft = true;
7560     Anomaly = LastLHSMismatch;
7561     return true;
7562   } else if (NumRHSMatch == NumInputElements - 1) {
7563     DstIsLeft = false;
7564     Anomaly = LastRHSMismatch;
7565     return true;
7566   }
7567 
7568   return false;
7569 }
7570 
7571 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7572   if (VT.getSizeInBits() != 128)
7573     return false;
7574 
7575   unsigned NumElts = VT.getVectorNumElements();
7576 
7577   for (int I = 0, E = NumElts / 2; I != E; I++) {
7578     if (Mask[I] != I)
7579       return false;
7580   }
7581 
7582   int Offset = NumElts / 2;
7583   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7584     if (Mask[I] != I + SplitLHS * Offset)
7585       return false;
7586   }
7587 
7588   return true;
7589 }
7590 
7591 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7592   SDLoc DL(Op);
7593   EVT VT = Op.getValueType();
7594   SDValue V0 = Op.getOperand(0);
7595   SDValue V1 = Op.getOperand(1);
7596   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7597 
7598   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7599       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7600     return SDValue();
7601 
7602   bool SplitV0 = V0.getValueSizeInBits() == 128;
7603 
7604   if (!isConcatMask(Mask, VT, SplitV0))
7605     return SDValue();
7606 
7607   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7608   if (SplitV0) {
7609     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7610                      DAG.getConstant(0, DL, MVT::i64));
7611   }
7612   if (V1.getValueSizeInBits() == 128) {
7613     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7614                      DAG.getConstant(0, DL, MVT::i64));
7615   }
7616   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7617 }
7618 
7619 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7620 /// the specified operations to build the shuffle.
7621 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7622                                       SDValue RHS, SelectionDAG &DAG,
7623                                       const SDLoc &dl) {
7624   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7625   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7626   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7627 
7628   enum {
7629     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7630     OP_VREV,
7631     OP_VDUP0,
7632     OP_VDUP1,
7633     OP_VDUP2,
7634     OP_VDUP3,
7635     OP_VEXT1,
7636     OP_VEXT2,
7637     OP_VEXT3,
7638     OP_VUZPL, // VUZP, left result
7639     OP_VUZPR, // VUZP, right result
7640     OP_VZIPL, // VZIP, left result
7641     OP_VZIPR, // VZIP, right result
7642     OP_VTRNL, // VTRN, left result
7643     OP_VTRNR  // VTRN, right result
7644   };
7645 
7646   if (OpNum == OP_COPY) {
7647     if (LHSID == (1 * 9 + 2) * 9 + 3)
7648       return LHS;
7649     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7650     return RHS;
7651   }
7652 
7653   SDValue OpLHS, OpRHS;
7654   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7655   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7656   EVT VT = OpLHS.getValueType();
7657 
7658   switch (OpNum) {
7659   default:
7660     llvm_unreachable("Unknown shuffle opcode!");
7661   case OP_VREV:
7662     // VREV divides the vector in half and swaps within the half.
7663     if (VT.getVectorElementType() == MVT::i32 ||
7664         VT.getVectorElementType() == MVT::f32)
7665       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7666     // vrev <4 x i16> -> REV32
7667     if (VT.getVectorElementType() == MVT::i16 ||
7668         VT.getVectorElementType() == MVT::f16 ||
7669         VT.getVectorElementType() == MVT::bf16)
7670       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7671     // vrev <4 x i8> -> REV16
7672     assert(VT.getVectorElementType() == MVT::i8);
7673     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7674   case OP_VDUP0:
7675   case OP_VDUP1:
7676   case OP_VDUP2:
7677   case OP_VDUP3: {
7678     EVT EltTy = VT.getVectorElementType();
7679     unsigned Opcode;
7680     if (EltTy == MVT::i8)
7681       Opcode = AArch64ISD::DUPLANE8;
7682     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
7683       Opcode = AArch64ISD::DUPLANE16;
7684     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7685       Opcode = AArch64ISD::DUPLANE32;
7686     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7687       Opcode = AArch64ISD::DUPLANE64;
7688     else
7689       llvm_unreachable("Invalid vector element type?");
7690 
7691     if (VT.getSizeInBits() == 64)
7692       OpLHS = WidenVector(OpLHS, DAG);
7693     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7694     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7695   }
7696   case OP_VEXT1:
7697   case OP_VEXT2:
7698   case OP_VEXT3: {
7699     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7700     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7701                        DAG.getConstant(Imm, dl, MVT::i32));
7702   }
7703   case OP_VUZPL:
7704     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7705                        OpRHS);
7706   case OP_VUZPR:
7707     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7708                        OpRHS);
7709   case OP_VZIPL:
7710     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7711                        OpRHS);
7712   case OP_VZIPR:
7713     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7714                        OpRHS);
7715   case OP_VTRNL:
7716     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7717                        OpRHS);
7718   case OP_VTRNR:
7719     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7720                        OpRHS);
7721   }
7722 }
7723 
7724 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7725                            SelectionDAG &DAG) {
7726   // Check to see if we can use the TBL instruction.
7727   SDValue V1 = Op.getOperand(0);
7728   SDValue V2 = Op.getOperand(1);
7729   SDLoc DL(Op);
7730 
7731   EVT EltVT = Op.getValueType().getVectorElementType();
7732   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7733 
7734   SmallVector<SDValue, 8> TBLMask;
7735   for (int Val : ShuffleMask) {
7736     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7737       unsigned Offset = Byte + Val * BytesPerElt;
7738       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7739     }
7740   }
7741 
7742   MVT IndexVT = MVT::v8i8;
7743   unsigned IndexLen = 8;
7744   if (Op.getValueSizeInBits() == 128) {
7745     IndexVT = MVT::v16i8;
7746     IndexLen = 16;
7747   }
7748 
7749   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7750   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7751 
7752   SDValue Shuffle;
7753   if (V2.getNode()->isUndef()) {
7754     if (IndexLen == 8)
7755       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7756     Shuffle = DAG.getNode(
7757         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7758         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7759         DAG.getBuildVector(IndexVT, DL,
7760                            makeArrayRef(TBLMask.data(), IndexLen)));
7761   } else {
7762     if (IndexLen == 8) {
7763       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7764       Shuffle = DAG.getNode(
7765           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7766           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7767           DAG.getBuildVector(IndexVT, DL,
7768                              makeArrayRef(TBLMask.data(), IndexLen)));
7769     } else {
7770       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7771       // cannot currently represent the register constraints on the input
7772       // table registers.
7773       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7774       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7775       //                   IndexLen));
7776       Shuffle = DAG.getNode(
7777           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7778           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7779           V2Cst, DAG.getBuildVector(IndexVT, DL,
7780                                     makeArrayRef(TBLMask.data(), IndexLen)));
7781     }
7782   }
7783   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7784 }
7785 
7786 static unsigned getDUPLANEOp(EVT EltType) {
7787   if (EltType == MVT::i8)
7788     return AArch64ISD::DUPLANE8;
7789   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
7790     return AArch64ISD::DUPLANE16;
7791   if (EltType == MVT::i32 || EltType == MVT::f32)
7792     return AArch64ISD::DUPLANE32;
7793   if (EltType == MVT::i64 || EltType == MVT::f64)
7794     return AArch64ISD::DUPLANE64;
7795 
7796   llvm_unreachable("Invalid vector element type?");
7797 }
7798 
7799 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7800                                                    SelectionDAG &DAG) const {
7801   SDLoc dl(Op);
7802   EVT VT = Op.getValueType();
7803 
7804   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7805 
7806   // Convert shuffles that are directly supported on NEON to target-specific
7807   // DAG nodes, instead of keeping them as shuffles and matching them again
7808   // during code selection.  This is more efficient and avoids the possibility
7809   // of inconsistencies between legalization and selection.
7810   ArrayRef<int> ShuffleMask = SVN->getMask();
7811 
7812   SDValue V1 = Op.getOperand(0);
7813   SDValue V2 = Op.getOperand(1);
7814 
7815   if (SVN->isSplat()) {
7816     int Lane = SVN->getSplatIndex();
7817     // If this is undef splat, generate it via "just" vdup, if possible.
7818     if (Lane == -1)
7819       Lane = 0;
7820 
7821     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7822       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7823                          V1.getOperand(0));
7824     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7825     // constant. If so, we can just reference the lane's definition directly.
7826     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7827         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7828       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7829 
7830     // Otherwise, duplicate from the lane of the input vector.
7831     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7832 
7833     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7834     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7835       // Match: dup (bitcast (extract_subv X, C)), LaneC
7836       if (BitCast.getOpcode() != ISD::BITCAST ||
7837           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7838         return false;
7839 
7840       // The extract index must align in the destination type. That may not
7841       // happen if the bitcast is from narrow to wide type.
7842       SDValue Extract = BitCast.getOperand(0);
7843       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7844       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7845       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7846       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7847       if (ExtIdxInBits % CastedEltBitWidth != 0)
7848         return false;
7849 
7850       // Update the lane value by offsetting with the scaled extract index.
7851       LaneC += ExtIdxInBits / CastedEltBitWidth;
7852 
7853       // Determine the casted vector type of the wide vector input.
7854       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7855       // Examples:
7856       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7857       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7858       unsigned SrcVecNumElts =
7859           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7860       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7861                                 SrcVecNumElts);
7862       return true;
7863     };
7864     MVT CastVT;
7865     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7866       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7867     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7868       // The lane is incremented by the index of the extract.
7869       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7870       Lane += V1.getConstantOperandVal(1);
7871       V1 = V1.getOperand(0);
7872     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7873       // The lane is decremented if we are splatting from the 2nd operand.
7874       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7875       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7876       Lane -= Idx * VT.getVectorNumElements() / 2;
7877       V1 = WidenVector(V1.getOperand(Idx), DAG);
7878     } else if (VT.getSizeInBits() == 64) {
7879       // Widen the operand to 128-bit register with undef.
7880       V1 = WidenVector(V1, DAG);
7881     }
7882     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7883   }
7884 
7885   if (isREVMask(ShuffleMask, VT, 64))
7886     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7887   if (isREVMask(ShuffleMask, VT, 32))
7888     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7889   if (isREVMask(ShuffleMask, VT, 16))
7890     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7891 
7892   bool ReverseEXT = false;
7893   unsigned Imm;
7894   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7895     if (ReverseEXT)
7896       std::swap(V1, V2);
7897     Imm *= getExtFactor(V1);
7898     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7899                        DAG.getConstant(Imm, dl, MVT::i32));
7900   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7901     Imm *= getExtFactor(V1);
7902     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7903                        DAG.getConstant(Imm, dl, MVT::i32));
7904   }
7905 
7906   unsigned WhichResult;
7907   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7908     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7909     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7910   }
7911   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7912     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7913     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7914   }
7915   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7916     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7917     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7918   }
7919 
7920   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7921     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7922     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7923   }
7924   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7925     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7926     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7927   }
7928   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7929     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7930     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7931   }
7932 
7933   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7934     return Concat;
7935 
7936   bool DstIsLeft;
7937   int Anomaly;
7938   int NumInputElements = V1.getValueType().getVectorNumElements();
7939   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7940     SDValue DstVec = DstIsLeft ? V1 : V2;
7941     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7942 
7943     SDValue SrcVec = V1;
7944     int SrcLane = ShuffleMask[Anomaly];
7945     if (SrcLane >= NumInputElements) {
7946       SrcVec = V2;
7947       SrcLane -= VT.getVectorNumElements();
7948     }
7949     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7950 
7951     EVT ScalarVT = VT.getVectorElementType();
7952 
7953     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7954       ScalarVT = MVT::i32;
7955 
7956     return DAG.getNode(
7957         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7958         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7959         DstLaneV);
7960   }
7961 
7962   // If the shuffle is not directly supported and it has 4 elements, use
7963   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7964   unsigned NumElts = VT.getVectorNumElements();
7965   if (NumElts == 4) {
7966     unsigned PFIndexes[4];
7967     for (unsigned i = 0; i != 4; ++i) {
7968       if (ShuffleMask[i] < 0)
7969         PFIndexes[i] = 8;
7970       else
7971         PFIndexes[i] = ShuffleMask[i];
7972     }
7973 
7974     // Compute the index in the perfect shuffle table.
7975     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7976                             PFIndexes[2] * 9 + PFIndexes[3];
7977     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7978     unsigned Cost = (PFEntry >> 30);
7979 
7980     if (Cost <= 4)
7981       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7982   }
7983 
7984   return GenerateTBL(Op, ShuffleMask, DAG);
7985 }
7986 
7987 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7988                                                  SelectionDAG &DAG) const {
7989   SDLoc dl(Op);
7990   EVT VT = Op.getValueType();
7991   EVT ElemVT = VT.getScalarType();
7992   SDValue SplatVal = Op.getOperand(0);
7993 
7994   if (useSVEForFixedLengthVectorVT(VT))
7995     return LowerToScalableOp(Op, DAG);
7996 
7997   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7998   // FPRs don't have this restriction.
7999   switch (ElemVT.getSimpleVT().SimpleTy) {
8000   case MVT::i1: {
8001     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
8002     // lowering code.
8003     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
8004       if (ConstVal->isOne())
8005         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
8006       // TODO: Add special case for constant false
8007     }
8008     // The general case of i1.  There isn't any natural way to do this,
8009     // so we use some trickery with whilelo.
8010     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8011     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
8012                            DAG.getValueType(MVT::i1));
8013     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
8014                                        MVT::i64);
8015     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
8016                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
8017   }
8018   case MVT::i8:
8019   case MVT::i16:
8020   case MVT::i32:
8021     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
8022     break;
8023   case MVT::i64:
8024     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8025     break;
8026   case MVT::f16:
8027   case MVT::bf16:
8028   case MVT::f32:
8029   case MVT::f64:
8030     // Fine as is
8031     break;
8032   default:
8033     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
8034   }
8035 
8036   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
8037 }
8038 
8039 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
8040                                              SelectionDAG &DAG) const {
8041   SDLoc DL(Op);
8042 
8043   EVT VT = Op.getValueType();
8044   if (!isTypeLegal(VT) || !VT.isScalableVector())
8045     return SDValue();
8046 
8047   // Current lowering only supports the SVE-ACLE types.
8048   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
8049     return SDValue();
8050 
8051   // The DUPQ operation is indepedent of element type so normalise to i64s.
8052   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
8053   SDValue Idx128 = Op.getOperand(2);
8054 
8055   // DUPQ can be used when idx is in range.
8056   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
8057   if (CIdx && (CIdx->getZExtValue() <= 3)) {
8058     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
8059     SDNode *DUPQ =
8060         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
8061     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
8062   }
8063 
8064   // The ACLE says this must produce the same result as:
8065   //   svtbl(data, svadd_x(svptrue_b64(),
8066   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
8067   //                       index * 2))
8068   SDValue One = DAG.getConstant(1, DL, MVT::i64);
8069   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
8070 
8071   // create the vector 0,1,0,1,...
8072   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
8073   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
8074                            DL, MVT::nxv2i64, Zero, One);
8075   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
8076 
8077   // create the vector idx64,idx64+1,idx64,idx64+1,...
8078   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
8079   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
8080   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
8081 
8082   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
8083   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
8084   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
8085 }
8086 
8087 
8088 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
8089                                APInt &UndefBits) {
8090   EVT VT = BVN->getValueType(0);
8091   APInt SplatBits, SplatUndef;
8092   unsigned SplatBitSize;
8093   bool HasAnyUndefs;
8094   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8095     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
8096 
8097     for (unsigned i = 0; i < NumSplats; ++i) {
8098       CnstBits <<= SplatBitSize;
8099       UndefBits <<= SplatBitSize;
8100       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
8101       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
8102     }
8103 
8104     return true;
8105   }
8106 
8107   return false;
8108 }
8109 
8110 // Try 64-bit splatted SIMD immediate.
8111 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8112                                  const APInt &Bits) {
8113   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8114     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8115     EVT VT = Op.getValueType();
8116     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
8117 
8118     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
8119       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
8120 
8121       SDLoc dl(Op);
8122       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8123                                 DAG.getConstant(Value, dl, MVT::i32));
8124       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8125     }
8126   }
8127 
8128   return SDValue();
8129 }
8130 
8131 // Try 32-bit splatted SIMD immediate.
8132 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8133                                   const APInt &Bits,
8134                                   const SDValue *LHS = nullptr) {
8135   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8136     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8137     EVT VT = Op.getValueType();
8138     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8139     bool isAdvSIMDModImm = false;
8140     uint64_t Shift;
8141 
8142     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
8143       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
8144       Shift = 0;
8145     }
8146     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
8147       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
8148       Shift = 8;
8149     }
8150     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
8151       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
8152       Shift = 16;
8153     }
8154     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
8155       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
8156       Shift = 24;
8157     }
8158 
8159     if (isAdvSIMDModImm) {
8160       SDLoc dl(Op);
8161       SDValue Mov;
8162 
8163       if (LHS)
8164         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8165                           DAG.getConstant(Value, dl, MVT::i32),
8166                           DAG.getConstant(Shift, dl, MVT::i32));
8167       else
8168         Mov = DAG.getNode(NewOp, dl, MovTy,
8169                           DAG.getConstant(Value, dl, MVT::i32),
8170                           DAG.getConstant(Shift, dl, MVT::i32));
8171 
8172       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8173     }
8174   }
8175 
8176   return SDValue();
8177 }
8178 
8179 // Try 16-bit splatted SIMD immediate.
8180 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8181                                   const APInt &Bits,
8182                                   const SDValue *LHS = nullptr) {
8183   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8184     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8185     EVT VT = Op.getValueType();
8186     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8187     bool isAdvSIMDModImm = false;
8188     uint64_t Shift;
8189 
8190     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8191       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8192       Shift = 0;
8193     }
8194     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8195       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8196       Shift = 8;
8197     }
8198 
8199     if (isAdvSIMDModImm) {
8200       SDLoc dl(Op);
8201       SDValue Mov;
8202 
8203       if (LHS)
8204         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8205                           DAG.getConstant(Value, dl, MVT::i32),
8206                           DAG.getConstant(Shift, dl, MVT::i32));
8207       else
8208         Mov = DAG.getNode(NewOp, dl, MovTy,
8209                           DAG.getConstant(Value, dl, MVT::i32),
8210                           DAG.getConstant(Shift, dl, MVT::i32));
8211 
8212       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8213     }
8214   }
8215 
8216   return SDValue();
8217 }
8218 
8219 // Try 32-bit splatted SIMD immediate with shifted ones.
8220 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8221                                     SelectionDAG &DAG, const APInt &Bits) {
8222   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8223     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8224     EVT VT = Op.getValueType();
8225     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8226     bool isAdvSIMDModImm = false;
8227     uint64_t Shift;
8228 
8229     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8230       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8231       Shift = 264;
8232     }
8233     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8234       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8235       Shift = 272;
8236     }
8237 
8238     if (isAdvSIMDModImm) {
8239       SDLoc dl(Op);
8240       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8241                                 DAG.getConstant(Value, dl, MVT::i32),
8242                                 DAG.getConstant(Shift, dl, MVT::i32));
8243       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8244     }
8245   }
8246 
8247   return SDValue();
8248 }
8249 
8250 // Try 8-bit splatted SIMD immediate.
8251 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8252                                  const APInt &Bits) {
8253   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8254     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8255     EVT VT = Op.getValueType();
8256     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8257 
8258     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8259       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8260 
8261       SDLoc dl(Op);
8262       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8263                                 DAG.getConstant(Value, dl, MVT::i32));
8264       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8265     }
8266   }
8267 
8268   return SDValue();
8269 }
8270 
8271 // Try FP splatted SIMD immediate.
8272 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8273                                   const APInt &Bits) {
8274   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8275     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8276     EVT VT = Op.getValueType();
8277     bool isWide = (VT.getSizeInBits() == 128);
8278     MVT MovTy;
8279     bool isAdvSIMDModImm = false;
8280 
8281     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8282       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8283       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8284     }
8285     else if (isWide &&
8286              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8287       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8288       MovTy = MVT::v2f64;
8289     }
8290 
8291     if (isAdvSIMDModImm) {
8292       SDLoc dl(Op);
8293       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8294                                 DAG.getConstant(Value, dl, MVT::i32));
8295       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8296     }
8297   }
8298 
8299   return SDValue();
8300 }
8301 
8302 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8303 // consists of only the same constant int value, returned in reference arg
8304 // ConstVal
8305 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8306                                      uint64_t &ConstVal) {
8307   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8308   if (!Bvec)
8309     return false;
8310   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8311   if (!FirstElt)
8312     return false;
8313   EVT VT = Bvec->getValueType(0);
8314   unsigned NumElts = VT.getVectorNumElements();
8315   for (unsigned i = 1; i < NumElts; ++i)
8316     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8317       return false;
8318   ConstVal = FirstElt->getZExtValue();
8319   return true;
8320 }
8321 
8322 static unsigned getIntrinsicID(const SDNode *N) {
8323   unsigned Opcode = N->getOpcode();
8324   switch (Opcode) {
8325   default:
8326     return Intrinsic::not_intrinsic;
8327   case ISD::INTRINSIC_WO_CHAIN: {
8328     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8329     if (IID < Intrinsic::num_intrinsics)
8330       return IID;
8331     return Intrinsic::not_intrinsic;
8332   }
8333   }
8334 }
8335 
8336 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8337 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8338 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8339 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8340 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8341 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8342 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8343   EVT VT = N->getValueType(0);
8344 
8345   if (!VT.isVector())
8346     return SDValue();
8347 
8348   SDLoc DL(N);
8349 
8350   SDValue And;
8351   SDValue Shift;
8352 
8353   SDValue FirstOp = N->getOperand(0);
8354   unsigned FirstOpc = FirstOp.getOpcode();
8355   SDValue SecondOp = N->getOperand(1);
8356   unsigned SecondOpc = SecondOp.getOpcode();
8357 
8358   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8359   // a BICi in order to use an immediate instead of a register.
8360   // Is the other operand an shl or lshr? This will have been turned into:
8361   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8362   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8363       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8364     And = FirstOp;
8365     Shift = SecondOp;
8366 
8367   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8368              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8369     And = SecondOp;
8370     Shift = FirstOp;
8371   } else
8372     return SDValue();
8373 
8374   bool IsAnd = And.getOpcode() == ISD::AND;
8375   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8376 
8377   // Is the shift amount constant?
8378   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8379   if (!C2node)
8380     return SDValue();
8381 
8382   uint64_t C1;
8383   if (IsAnd) {
8384     // Is the and mask vector all constant?
8385     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8386       return SDValue();
8387   } else {
8388     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8389     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8390     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8391     assert(C1nodeImm && C1nodeShift);
8392     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8393   }
8394 
8395   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8396   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8397   // how much one can shift elements of a particular size?
8398   uint64_t C2 = C2node->getZExtValue();
8399   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8400   if (C2 > ElemSizeInBits)
8401     return SDValue();
8402 
8403   APInt C1AsAPInt(ElemSizeInBits, C1);
8404   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8405                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8406   if (C1AsAPInt != RequiredC1)
8407     return SDValue();
8408 
8409   SDValue X = And.getOperand(0);
8410   SDValue Y = Shift.getOperand(0);
8411 
8412   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8413   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8414 
8415   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8416   LLVM_DEBUG(N->dump(&DAG));
8417   LLVM_DEBUG(dbgs() << "into: \n");
8418   LLVM_DEBUG(ResultSLI->dump(&DAG));
8419 
8420   ++NumShiftInserts;
8421   return ResultSLI;
8422 }
8423 
8424 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8425                                              SelectionDAG &DAG) const {
8426   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
8427     return LowerToScalableOp(Op, DAG);
8428 
8429   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8430   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8431     return Res;
8432 
8433   EVT VT = Op.getValueType();
8434 
8435   SDValue LHS = Op.getOperand(0);
8436   BuildVectorSDNode *BVN =
8437       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8438   if (!BVN) {
8439     // OR commutes, so try swapping the operands.
8440     LHS = Op.getOperand(1);
8441     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8442   }
8443   if (!BVN)
8444     return Op;
8445 
8446   APInt DefBits(VT.getSizeInBits(), 0);
8447   APInt UndefBits(VT.getSizeInBits(), 0);
8448   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8449     SDValue NewOp;
8450 
8451     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8452                                     DefBits, &LHS)) ||
8453         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8454                                     DefBits, &LHS)))
8455       return NewOp;
8456 
8457     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8458                                     UndefBits, &LHS)) ||
8459         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8460                                     UndefBits, &LHS)))
8461       return NewOp;
8462   }
8463 
8464   // We can always fall back to a non-immediate OR.
8465   return Op;
8466 }
8467 
8468 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8469 // be truncated to fit element width.
8470 static SDValue NormalizeBuildVector(SDValue Op,
8471                                     SelectionDAG &DAG) {
8472   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8473   SDLoc dl(Op);
8474   EVT VT = Op.getValueType();
8475   EVT EltTy= VT.getVectorElementType();
8476 
8477   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8478     return Op;
8479 
8480   SmallVector<SDValue, 16> Ops;
8481   for (SDValue Lane : Op->ops()) {
8482     // For integer vectors, type legalization would have promoted the
8483     // operands already. Otherwise, if Op is a floating-point splat
8484     // (with operands cast to integers), then the only possibilities
8485     // are constants and UNDEFs.
8486     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8487       APInt LowBits(EltTy.getSizeInBits(),
8488                     CstLane->getZExtValue());
8489       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8490     } else if (Lane.getNode()->isUndef()) {
8491       Lane = DAG.getUNDEF(MVT::i32);
8492     } else {
8493       assert(Lane.getValueType() == MVT::i32 &&
8494              "Unexpected BUILD_VECTOR operand type");
8495     }
8496     Ops.push_back(Lane);
8497   }
8498   return DAG.getBuildVector(VT, dl, Ops);
8499 }
8500 
8501 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8502   EVT VT = Op.getValueType();
8503 
8504   APInt DefBits(VT.getSizeInBits(), 0);
8505   APInt UndefBits(VT.getSizeInBits(), 0);
8506   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8507   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8508     SDValue NewOp;
8509     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8510         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8511         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8512         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8513         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8514         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8515       return NewOp;
8516 
8517     DefBits = ~DefBits;
8518     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8519         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8520         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8521       return NewOp;
8522 
8523     DefBits = UndefBits;
8524     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8525         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8526         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8527         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8528         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8529         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8530       return NewOp;
8531 
8532     DefBits = ~UndefBits;
8533     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8534         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8535         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8536       return NewOp;
8537   }
8538 
8539   return SDValue();
8540 }
8541 
8542 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8543                                                  SelectionDAG &DAG) const {
8544   EVT VT = Op.getValueType();
8545 
8546   // Try to build a simple constant vector.
8547   Op = NormalizeBuildVector(Op, DAG);
8548   if (VT.isInteger()) {
8549     // Certain vector constants, used to express things like logical NOT and
8550     // arithmetic NEG, are passed through unmodified.  This allows special
8551     // patterns for these operations to match, which will lower these constants
8552     // to whatever is proven necessary.
8553     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8554     if (BVN->isConstant())
8555       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8556         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8557         APInt Val(BitSize,
8558                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8559         if (Val.isNullValue() || Val.isAllOnesValue())
8560           return Op;
8561       }
8562   }
8563 
8564   if (SDValue V = ConstantBuildVector(Op, DAG))
8565     return V;
8566 
8567   // Scan through the operands to find some interesting properties we can
8568   // exploit:
8569   //   1) If only one value is used, we can use a DUP, or
8570   //   2) if only the low element is not undef, we can just insert that, or
8571   //   3) if only one constant value is used (w/ some non-constant lanes),
8572   //      we can splat the constant value into the whole vector then fill
8573   //      in the non-constant lanes.
8574   //   4) FIXME: If different constant values are used, but we can intelligently
8575   //             select the values we'll be overwriting for the non-constant
8576   //             lanes such that we can directly materialize the vector
8577   //             some other way (MOVI, e.g.), we can be sneaky.
8578   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8579   SDLoc dl(Op);
8580   unsigned NumElts = VT.getVectorNumElements();
8581   bool isOnlyLowElement = true;
8582   bool usesOnlyOneValue = true;
8583   bool usesOnlyOneConstantValue = true;
8584   bool isConstant = true;
8585   bool AllLanesExtractElt = true;
8586   unsigned NumConstantLanes = 0;
8587   SDValue Value;
8588   SDValue ConstantValue;
8589   for (unsigned i = 0; i < NumElts; ++i) {
8590     SDValue V = Op.getOperand(i);
8591     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8592       AllLanesExtractElt = false;
8593     if (V.isUndef())
8594       continue;
8595     if (i > 0)
8596       isOnlyLowElement = false;
8597     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8598       isConstant = false;
8599 
8600     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8601       ++NumConstantLanes;
8602       if (!ConstantValue.getNode())
8603         ConstantValue = V;
8604       else if (ConstantValue != V)
8605         usesOnlyOneConstantValue = false;
8606     }
8607 
8608     if (!Value.getNode())
8609       Value = V;
8610     else if (V != Value)
8611       usesOnlyOneValue = false;
8612   }
8613 
8614   if (!Value.getNode()) {
8615     LLVM_DEBUG(
8616         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8617     return DAG.getUNDEF(VT);
8618   }
8619 
8620   // Convert BUILD_VECTOR where all elements but the lowest are undef into
8621   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8622   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8623   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8624     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8625                          "SCALAR_TO_VECTOR node\n");
8626     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8627   }
8628 
8629   if (AllLanesExtractElt) {
8630     SDNode *Vector = nullptr;
8631     bool Even = false;
8632     bool Odd = false;
8633     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8634     // the Odd pattern <1,3,5,...>.
8635     for (unsigned i = 0; i < NumElts; ++i) {
8636       SDValue V = Op.getOperand(i);
8637       const SDNode *N = V.getNode();
8638       if (!isa<ConstantSDNode>(N->getOperand(1)))
8639         break;
8640       SDValue N0 = N->getOperand(0);
8641 
8642       // All elements are extracted from the same vector.
8643       if (!Vector) {
8644         Vector = N0.getNode();
8645         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8646         // BUILD_VECTOR.
8647         if (VT.getVectorElementType() !=
8648             N0.getValueType().getVectorElementType())
8649           break;
8650       } else if (Vector != N0.getNode()) {
8651         Odd = false;
8652         Even = false;
8653         break;
8654       }
8655 
8656       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8657       // indices <1,3,5,...>.
8658       uint64_t Val = N->getConstantOperandVal(1);
8659       if (Val == 2 * i) {
8660         Even = true;
8661         continue;
8662       }
8663       if (Val - 1 == 2 * i) {
8664         Odd = true;
8665         continue;
8666       }
8667 
8668       // Something does not match: abort.
8669       Odd = false;
8670       Even = false;
8671       break;
8672     }
8673     if (Even || Odd) {
8674       SDValue LHS =
8675           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8676                       DAG.getConstant(0, dl, MVT::i64));
8677       SDValue RHS =
8678           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8679                       DAG.getConstant(NumElts, dl, MVT::i64));
8680 
8681       if (Even && !Odd)
8682         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8683                            RHS);
8684       if (Odd && !Even)
8685         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8686                            RHS);
8687     }
8688   }
8689 
8690   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8691   // i32 and try again.
8692   if (usesOnlyOneValue) {
8693     if (!isConstant) {
8694       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8695           Value.getValueType() != VT) {
8696         LLVM_DEBUG(
8697             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8698         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8699       }
8700 
8701       // This is actually a DUPLANExx operation, which keeps everything vectory.
8702 
8703       SDValue Lane = Value.getOperand(1);
8704       Value = Value.getOperand(0);
8705       if (Value.getValueSizeInBits() == 64) {
8706         LLVM_DEBUG(
8707             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8708                       "widening it\n");
8709         Value = WidenVector(Value, DAG);
8710       }
8711 
8712       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8713       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8714     }
8715 
8716     if (VT.getVectorElementType().isFloatingPoint()) {
8717       SmallVector<SDValue, 8> Ops;
8718       EVT EltTy = VT.getVectorElementType();
8719       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
8720                EltTy == MVT::f64) && "Unsupported floating-point vector type");
8721       LLVM_DEBUG(
8722           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8723                     "BITCASTS, and try again\n");
8724       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8725       for (unsigned i = 0; i < NumElts; ++i)
8726         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8727       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8728       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8729       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8730                  Val.dump(););
8731       Val = LowerBUILD_VECTOR(Val, DAG);
8732       if (Val.getNode())
8733         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8734     }
8735   }
8736 
8737   // If there was only one constant value used and for more than one lane,
8738   // start by splatting that value, then replace the non-constant lanes. This
8739   // is better than the default, which will perform a separate initialization
8740   // for each lane.
8741   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8742     // Firstly, try to materialize the splat constant.
8743     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8744             Val = ConstantBuildVector(Vec, DAG);
8745     if (!Val) {
8746       // Otherwise, materialize the constant and splat it.
8747       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8748       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8749     }
8750 
8751     // Now insert the non-constant lanes.
8752     for (unsigned i = 0; i < NumElts; ++i) {
8753       SDValue V = Op.getOperand(i);
8754       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8755       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8756         // Note that type legalization likely mucked about with the VT of the
8757         // source operand, so we may have to convert it here before inserting.
8758         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8759     }
8760     return Val;
8761   }
8762 
8763   // This will generate a load from the constant pool.
8764   if (isConstant) {
8765     LLVM_DEBUG(
8766         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8767                   "expansion\n");
8768     return SDValue();
8769   }
8770 
8771   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8772   if (NumElts >= 4) {
8773     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8774       return shuffle;
8775   }
8776 
8777   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8778   // know the default expansion would otherwise fall back on something even
8779   // worse. For a vector with one or two non-undef values, that's
8780   // scalar_to_vector for the elements followed by a shuffle (provided the
8781   // shuffle is valid for the target) and materialization element by element
8782   // on the stack followed by a load for everything else.
8783   if (!isConstant && !usesOnlyOneValue) {
8784     LLVM_DEBUG(
8785         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8786                   "of INSERT_VECTOR_ELT\n");
8787 
8788     SDValue Vec = DAG.getUNDEF(VT);
8789     SDValue Op0 = Op.getOperand(0);
8790     unsigned i = 0;
8791 
8792     // Use SCALAR_TO_VECTOR for lane zero to
8793     // a) Avoid a RMW dependency on the full vector register, and
8794     // b) Allow the register coalescer to fold away the copy if the
8795     //    value is already in an S or D register, and we're forced to emit an
8796     //    INSERT_SUBREG that we can't fold anywhere.
8797     //
8798     // We also allow types like i8 and i16 which are illegal scalar but legal
8799     // vector element types. After type-legalization the inserted value is
8800     // extended (i32) and it is safe to cast them to the vector type by ignoring
8801     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8802     if (!Op0.isUndef()) {
8803       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8804       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8805       ++i;
8806     }
8807     LLVM_DEBUG(if (i < NumElts) dbgs()
8808                    << "Creating nodes for the other vector elements:\n";);
8809     for (; i < NumElts; ++i) {
8810       SDValue V = Op.getOperand(i);
8811       if (V.isUndef())
8812         continue;
8813       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8814       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8815     }
8816     return Vec;
8817   }
8818 
8819   LLVM_DEBUG(
8820       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8821                 "better alternative\n");
8822   return SDValue();
8823 }
8824 
8825 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8826                                                       SelectionDAG &DAG) const {
8827   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8828 
8829   // Check for non-constant or out of range lane.
8830   EVT VT = Op.getOperand(0).getValueType();
8831   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8832   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8833     return SDValue();
8834 
8835 
8836   // Insertion/extraction are legal for V128 types.
8837   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8838       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8839       VT == MVT::v8f16 || VT == MVT::v8bf16)
8840     return Op;
8841 
8842   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8843       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8844       VT != MVT::v4bf16)
8845     return SDValue();
8846 
8847   // For V64 types, we perform insertion by expanding the value
8848   // to a V128 type and perform the insertion on that.
8849   SDLoc DL(Op);
8850   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8851   EVT WideTy = WideVec.getValueType();
8852 
8853   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8854                              Op.getOperand(1), Op.getOperand(2));
8855   // Re-narrow the resultant vector.
8856   return NarrowVector(Node, DAG);
8857 }
8858 
8859 SDValue
8860 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8861                                                SelectionDAG &DAG) const {
8862   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8863 
8864   // Check for non-constant or out of range lane.
8865   EVT VT = Op.getOperand(0).getValueType();
8866   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8867   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8868     return SDValue();
8869 
8870 
8871   // Insertion/extraction are legal for V128 types.
8872   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8873       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8874       VT == MVT::v8f16 || VT == MVT::v8bf16)
8875     return Op;
8876 
8877   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8878       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8879       VT != MVT::v4bf16)
8880     return SDValue();
8881 
8882   // For V64 types, we perform extraction by expanding the value
8883   // to a V128 type and perform the extraction on that.
8884   SDLoc DL(Op);
8885   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8886   EVT WideTy = WideVec.getValueType();
8887 
8888   EVT ExtrTy = WideTy.getVectorElementType();
8889   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8890     ExtrTy = MVT::i32;
8891 
8892   // For extractions, we just return the result directly.
8893   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8894                      Op.getOperand(1));
8895 }
8896 
8897 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8898                                                       SelectionDAG &DAG) const {
8899   assert(Op.getValueType().isFixedLengthVector() &&
8900          "Only cases that extract a fixed length vector are supported!");
8901 
8902   EVT InVT = Op.getOperand(0).getValueType();
8903   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8904   unsigned Size = Op.getValueSizeInBits();
8905 
8906   if (InVT.isScalableVector()) {
8907     // This will be matched by custom code during ISelDAGToDAG.
8908     if (Idx == 0 && isPackedVectorType(InVT, DAG))
8909       return Op;
8910 
8911     return SDValue();
8912   }
8913 
8914   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8915   if (Idx == 0 && InVT.getSizeInBits() <= 128)
8916     return Op;
8917 
8918   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8919   // that directly.
8920   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64)
8921     return Op;
8922 
8923   return SDValue();
8924 }
8925 
8926 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
8927                                                      SelectionDAG &DAG) const {
8928   assert(Op.getValueType().isScalableVector() &&
8929          "Only expect to lower inserts into scalable vectors!");
8930 
8931   EVT InVT = Op.getOperand(1).getValueType();
8932   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8933 
8934   // We don't have any patterns for scalable vector yet.
8935   if (InVT.isScalableVector())
8936     return SDValue();
8937 
8938   // This will be matched by custom code during ISelDAGToDAG.
8939   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
8940     return Op;
8941 
8942   return SDValue();
8943 }
8944 
8945 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
8946   EVT VT = Op.getValueType();
8947 
8948   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
8949     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
8950 
8951   assert(VT.isScalableVector() && "Expected a scalable vector.");
8952 
8953   bool Signed = Op.getOpcode() == ISD::SDIV;
8954   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
8955 
8956   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
8957     return LowerToPredicatedOp(Op, DAG, PredOpcode);
8958 
8959   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
8960   // operations, and truncate the result.
8961   EVT WidenedVT;
8962   if (VT == MVT::nxv16i8)
8963     WidenedVT = MVT::nxv8i16;
8964   else if (VT == MVT::nxv8i16)
8965     WidenedVT = MVT::nxv4i32;
8966   else
8967     llvm_unreachable("Unexpected Custom DIV operation");
8968 
8969   SDLoc dl(Op);
8970   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
8971   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
8972   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
8973   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
8974   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
8975   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
8976   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
8977   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
8978   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
8979 }
8980 
8981 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8982   // Currently no fixed length shuffles that require SVE are legal.
8983   if (useSVEForFixedLengthVectorVT(VT))
8984     return false;
8985 
8986   if (VT.getVectorNumElements() == 4 &&
8987       (VT.is128BitVector() || VT.is64BitVector())) {
8988     unsigned PFIndexes[4];
8989     for (unsigned i = 0; i != 4; ++i) {
8990       if (M[i] < 0)
8991         PFIndexes[i] = 8;
8992       else
8993         PFIndexes[i] = M[i];
8994     }
8995 
8996     // Compute the index in the perfect shuffle table.
8997     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8998                             PFIndexes[2] * 9 + PFIndexes[3];
8999     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9000     unsigned Cost = (PFEntry >> 30);
9001 
9002     if (Cost <= 4)
9003       return true;
9004   }
9005 
9006   bool DummyBool;
9007   int DummyInt;
9008   unsigned DummyUnsigned;
9009 
9010   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
9011           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
9012           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
9013           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
9014           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
9015           isZIPMask(M, VT, DummyUnsigned) ||
9016           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
9017           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
9018           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
9019           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
9020           isConcatMask(M, VT, VT.getSizeInBits() == 128));
9021 }
9022 
9023 /// getVShiftImm - Check if this is a valid build_vector for the immediate
9024 /// operand of a vector shift operation, where all the elements of the
9025 /// build_vector must have the same constant integer value.
9026 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9027   // Ignore bit_converts.
9028   while (Op.getOpcode() == ISD::BITCAST)
9029     Op = Op.getOperand(0);
9030   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9031   APInt SplatBits, SplatUndef;
9032   unsigned SplatBitSize;
9033   bool HasAnyUndefs;
9034   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9035                                     HasAnyUndefs, ElementBits) ||
9036       SplatBitSize > ElementBits)
9037     return false;
9038   Cnt = SplatBits.getSExtValue();
9039   return true;
9040 }
9041 
9042 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9043 /// operand of a vector shift left operation.  That value must be in the range:
9044 ///   0 <= Value < ElementBits for a left shift; or
9045 ///   0 <= Value <= ElementBits for a long left shift.
9046 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9047   assert(VT.isVector() && "vector shift count is not a vector type");
9048   int64_t ElementBits = VT.getScalarSizeInBits();
9049   if (!getVShiftImm(Op, ElementBits, Cnt))
9050     return false;
9051   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
9052 }
9053 
9054 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9055 /// operand of a vector shift right operation. The value must be in the range:
9056 ///   1 <= Value <= ElementBits for a right shift; or
9057 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
9058   assert(VT.isVector() && "vector shift count is not a vector type");
9059   int64_t ElementBits = VT.getScalarSizeInBits();
9060   if (!getVShiftImm(Op, ElementBits, Cnt))
9061     return false;
9062   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
9063 }
9064 
9065 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
9066                                              SelectionDAG &DAG) const {
9067   EVT VT = Op.getValueType();
9068 
9069   if (VT.getScalarType() == MVT::i1) {
9070     // Lower i1 truncate to `(x & 1) != 0`.
9071     SDLoc dl(Op);
9072     EVT OpVT = Op.getOperand(0).getValueType();
9073     SDValue Zero = DAG.getConstant(0, dl, OpVT);
9074     SDValue One = DAG.getConstant(1, dl, OpVT);
9075     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
9076     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
9077   }
9078 
9079   if (!VT.isVector() || VT.isScalableVector())
9080     return SDValue();
9081 
9082   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9083     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
9084 
9085   return SDValue();
9086 }
9087 
9088 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
9089                                                       SelectionDAG &DAG) const {
9090   EVT VT = Op.getValueType();
9091   SDLoc DL(Op);
9092   int64_t Cnt;
9093 
9094   if (!Op.getOperand(1).getValueType().isVector())
9095     return Op;
9096   unsigned EltSize = VT.getScalarSizeInBits();
9097 
9098   switch (Op.getOpcode()) {
9099   default:
9100     llvm_unreachable("unexpected shift opcode");
9101 
9102   case ISD::SHL:
9103     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
9104       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
9105 
9106     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
9107       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
9108                          DAG.getConstant(Cnt, DL, MVT::i32));
9109     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9110                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
9111                                        MVT::i32),
9112                        Op.getOperand(0), Op.getOperand(1));
9113   case ISD::SRA:
9114   case ISD::SRL:
9115     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
9116       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
9117                                                 : AArch64ISD::SRL_PRED;
9118       return LowerToPredicatedOp(Op, DAG, Opc);
9119     }
9120 
9121     // Right shift immediate
9122     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
9123       unsigned Opc =
9124           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
9125       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
9126                          DAG.getConstant(Cnt, DL, MVT::i32));
9127     }
9128 
9129     // Right shift register.  Note, there is not a shift right register
9130     // instruction, but the shift left register instruction takes a signed
9131     // value, where negative numbers specify a right shift.
9132     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
9133                                                 : Intrinsic::aarch64_neon_ushl;
9134     // negate the shift amount
9135     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
9136     SDValue NegShiftLeft =
9137         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9138                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
9139                     NegShift);
9140     return NegShiftLeft;
9141   }
9142 
9143   return SDValue();
9144 }
9145 
9146 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
9147                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
9148                                     const SDLoc &dl, SelectionDAG &DAG) {
9149   EVT SrcVT = LHS.getValueType();
9150   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9151          "function only supposed to emit natural comparisons");
9152 
9153   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9154   APInt CnstBits(VT.getSizeInBits(), 0);
9155   APInt UndefBits(VT.getSizeInBits(), 0);
9156   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9157   bool IsZero = IsCnst && (CnstBits == 0);
9158 
9159   if (SrcVT.getVectorElementType().isFloatingPoint()) {
9160     switch (CC) {
9161     default:
9162       return SDValue();
9163     case AArch64CC::NE: {
9164       SDValue Fcmeq;
9165       if (IsZero)
9166         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9167       else
9168         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9169       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9170     }
9171     case AArch64CC::EQ:
9172       if (IsZero)
9173         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9174       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9175     case AArch64CC::GE:
9176       if (IsZero)
9177         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9178       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9179     case AArch64CC::GT:
9180       if (IsZero)
9181         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9182       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9183     case AArch64CC::LS:
9184       if (IsZero)
9185         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9186       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9187     case AArch64CC::LT:
9188       if (!NoNans)
9189         return SDValue();
9190       // If we ignore NaNs then we can use to the MI implementation.
9191       LLVM_FALLTHROUGH;
9192     case AArch64CC::MI:
9193       if (IsZero)
9194         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9195       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9196     }
9197   }
9198 
9199   switch (CC) {
9200   default:
9201     return SDValue();
9202   case AArch64CC::NE: {
9203     SDValue Cmeq;
9204     if (IsZero)
9205       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9206     else
9207       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9208     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9209   }
9210   case AArch64CC::EQ:
9211     if (IsZero)
9212       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9213     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9214   case AArch64CC::GE:
9215     if (IsZero)
9216       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9217     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9218   case AArch64CC::GT:
9219     if (IsZero)
9220       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9221     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9222   case AArch64CC::LE:
9223     if (IsZero)
9224       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9225     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9226   case AArch64CC::LS:
9227     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9228   case AArch64CC::LO:
9229     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9230   case AArch64CC::LT:
9231     if (IsZero)
9232       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9233     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9234   case AArch64CC::HI:
9235     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9236   case AArch64CC::HS:
9237     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9238   }
9239 }
9240 
9241 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9242                                            SelectionDAG &DAG) const {
9243   if (Op.getValueType().isScalableVector()) {
9244     if (Op.getOperand(0).getValueType().isFloatingPoint())
9245       return Op;
9246     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9247   }
9248 
9249   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9250     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
9251 
9252   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9253   SDValue LHS = Op.getOperand(0);
9254   SDValue RHS = Op.getOperand(1);
9255   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9256   SDLoc dl(Op);
9257 
9258   if (LHS.getValueType().getVectorElementType().isInteger()) {
9259     assert(LHS.getValueType() == RHS.getValueType());
9260     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9261     SDValue Cmp =
9262         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9263     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9264   }
9265 
9266   const bool FullFP16 =
9267     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9268 
9269   // Make v4f16 (only) fcmp operations utilise vector instructions
9270   // v8f16 support will be a litle more complicated
9271   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9272     if (LHS.getValueType().getVectorNumElements() == 4) {
9273       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9274       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9275       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9276       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9277       CmpVT = MVT::v4i32;
9278     } else
9279       return SDValue();
9280   }
9281 
9282   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9283           LHS.getValueType().getVectorElementType() != MVT::f128);
9284 
9285   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9286   // clean.  Some of them require two branches to implement.
9287   AArch64CC::CondCode CC1, CC2;
9288   bool ShouldInvert;
9289   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9290 
9291   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9292   SDValue Cmp =
9293       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9294   if (!Cmp.getNode())
9295     return SDValue();
9296 
9297   if (CC2 != AArch64CC::AL) {
9298     SDValue Cmp2 =
9299         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9300     if (!Cmp2.getNode())
9301       return SDValue();
9302 
9303     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9304   }
9305 
9306   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9307 
9308   if (ShouldInvert)
9309     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9310 
9311   return Cmp;
9312 }
9313 
9314 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9315                                   SelectionDAG &DAG) {
9316   SDValue VecOp = ScalarOp.getOperand(0);
9317   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9318   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9319                      DAG.getConstant(0, DL, MVT::i64));
9320 }
9321 
9322 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9323                                               SelectionDAG &DAG) const {
9324   SDLoc dl(Op);
9325   switch (Op.getOpcode()) {
9326   case ISD::VECREDUCE_ADD:
9327     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9328   case ISD::VECREDUCE_SMAX:
9329     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9330   case ISD::VECREDUCE_SMIN:
9331     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9332   case ISD::VECREDUCE_UMAX:
9333     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9334   case ISD::VECREDUCE_UMIN:
9335     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9336   case ISD::VECREDUCE_FMAX: {
9337     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
9338     return DAG.getNode(
9339         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9340         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9341         Op.getOperand(0));
9342   }
9343   case ISD::VECREDUCE_FMIN: {
9344     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
9345     return DAG.getNode(
9346         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9347         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9348         Op.getOperand(0));
9349   }
9350   default:
9351     llvm_unreachable("Unhandled reduction");
9352   }
9353 }
9354 
9355 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9356                                                     SelectionDAG &DAG) const {
9357   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9358   if (!Subtarget.hasLSE())
9359     return SDValue();
9360 
9361   // LSE has an atomic load-add instruction, but not a load-sub.
9362   SDLoc dl(Op);
9363   MVT VT = Op.getSimpleValueType();
9364   SDValue RHS = Op.getOperand(2);
9365   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9366   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9367   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9368                        Op.getOperand(0), Op.getOperand(1), RHS,
9369                        AN->getMemOperand());
9370 }
9371 
9372 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9373                                                     SelectionDAG &DAG) const {
9374   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9375   if (!Subtarget.hasLSE())
9376     return SDValue();
9377 
9378   // LSE has an atomic load-clear instruction, but not a load-and.
9379   SDLoc dl(Op);
9380   MVT VT = Op.getSimpleValueType();
9381   SDValue RHS = Op.getOperand(2);
9382   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9383   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9384   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9385                        Op.getOperand(0), Op.getOperand(1), RHS,
9386                        AN->getMemOperand());
9387 }
9388 
9389 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9390     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9391   SDLoc dl(Op);
9392   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9393   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9394 
9395   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9396   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9397   if (Subtarget->hasCustomCallingConv())
9398     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9399 
9400   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9401                      DAG.getConstant(4, dl, MVT::i64));
9402   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9403   Chain =
9404       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9405                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9406                   DAG.getRegisterMask(Mask), Chain.getValue(1));
9407   // To match the actual intent better, we should read the output from X15 here
9408   // again (instead of potentially spilling it to the stack), but rereading Size
9409   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9410   // here.
9411 
9412   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9413                      DAG.getConstant(4, dl, MVT::i64));
9414   return Chain;
9415 }
9416 
9417 SDValue
9418 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9419                                                SelectionDAG &DAG) const {
9420   assert(Subtarget->isTargetWindows() &&
9421          "Only Windows alloca probing supported");
9422   SDLoc dl(Op);
9423   // Get the inputs.
9424   SDNode *Node = Op.getNode();
9425   SDValue Chain = Op.getOperand(0);
9426   SDValue Size = Op.getOperand(1);
9427   MaybeAlign Align =
9428       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9429   EVT VT = Node->getValueType(0);
9430 
9431   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9432           "no-stack-arg-probe")) {
9433     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9434     Chain = SP.getValue(1);
9435     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9436     if (Align)
9437       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9438                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9439     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9440     SDValue Ops[2] = {SP, Chain};
9441     return DAG.getMergeValues(Ops, dl);
9442   }
9443 
9444   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9445 
9446   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9447 
9448   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9449   Chain = SP.getValue(1);
9450   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9451   if (Align)
9452     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9453                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9454   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9455 
9456   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9457                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9458 
9459   SDValue Ops[2] = {SP, Chain};
9460   return DAG.getMergeValues(Ops, dl);
9461 }
9462 
9463 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9464                                            SelectionDAG &DAG) const {
9465   EVT VT = Op.getValueType();
9466   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9467 
9468   SDLoc DL(Op);
9469   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9470   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9471                             DL, VT);
9472 }
9473 
9474 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9475 template <unsigned NumVecs>
9476 static bool
9477 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
9478               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
9479   Info.opc = ISD::INTRINSIC_VOID;
9480   // Retrieve EC from first vector argument.
9481   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
9482   ElementCount EC = VT.getVectorElementCount();
9483 #ifndef NDEBUG
9484   // Check the assumption that all input vectors are the same type.
9485   for (unsigned I = 0; I < NumVecs; ++I)
9486     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
9487            "Invalid type.");
9488 #endif
9489   // memVT is `NumVecs * VT`.
9490   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9491                                 EC * NumVecs);
9492   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9493   Info.offset = 0;
9494   Info.align.reset();
9495   Info.flags = MachineMemOperand::MOStore;
9496   return true;
9497 }
9498 
9499 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9500 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9501 /// specified in the intrinsic calls.
9502 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9503                                                const CallInst &I,
9504                                                MachineFunction &MF,
9505                                                unsigned Intrinsic) const {
9506   auto &DL = I.getModule()->getDataLayout();
9507   switch (Intrinsic) {
9508   case Intrinsic::aarch64_sve_st2:
9509     return setInfoSVEStN<2>(*this, DL, Info, I);
9510   case Intrinsic::aarch64_sve_st3:
9511     return setInfoSVEStN<3>(*this, DL, Info, I);
9512   case Intrinsic::aarch64_sve_st4:
9513     return setInfoSVEStN<4>(*this, DL, Info, I);
9514   case Intrinsic::aarch64_neon_ld2:
9515   case Intrinsic::aarch64_neon_ld3:
9516   case Intrinsic::aarch64_neon_ld4:
9517   case Intrinsic::aarch64_neon_ld1x2:
9518   case Intrinsic::aarch64_neon_ld1x3:
9519   case Intrinsic::aarch64_neon_ld1x4:
9520   case Intrinsic::aarch64_neon_ld2lane:
9521   case Intrinsic::aarch64_neon_ld3lane:
9522   case Intrinsic::aarch64_neon_ld4lane:
9523   case Intrinsic::aarch64_neon_ld2r:
9524   case Intrinsic::aarch64_neon_ld3r:
9525   case Intrinsic::aarch64_neon_ld4r: {
9526     Info.opc = ISD::INTRINSIC_W_CHAIN;
9527     // Conservatively set memVT to the entire set of vectors loaded.
9528     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
9529     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9530     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9531     Info.offset = 0;
9532     Info.align.reset();
9533     // volatile loads with NEON intrinsics not supported
9534     Info.flags = MachineMemOperand::MOLoad;
9535     return true;
9536   }
9537   case Intrinsic::aarch64_neon_st2:
9538   case Intrinsic::aarch64_neon_st3:
9539   case Intrinsic::aarch64_neon_st4:
9540   case Intrinsic::aarch64_neon_st1x2:
9541   case Intrinsic::aarch64_neon_st1x3:
9542   case Intrinsic::aarch64_neon_st1x4:
9543   case Intrinsic::aarch64_neon_st2lane:
9544   case Intrinsic::aarch64_neon_st3lane:
9545   case Intrinsic::aarch64_neon_st4lane: {
9546     Info.opc = ISD::INTRINSIC_VOID;
9547     // Conservatively set memVT to the entire set of vectors stored.
9548     unsigned NumElts = 0;
9549     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9550       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9551       if (!ArgTy->isVectorTy())
9552         break;
9553       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
9554     }
9555     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9556     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9557     Info.offset = 0;
9558     Info.align.reset();
9559     // volatile stores with NEON intrinsics not supported
9560     Info.flags = MachineMemOperand::MOStore;
9561     return true;
9562   }
9563   case Intrinsic::aarch64_ldaxr:
9564   case Intrinsic::aarch64_ldxr: {
9565     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
9566     Info.opc = ISD::INTRINSIC_W_CHAIN;
9567     Info.memVT = MVT::getVT(PtrTy->getElementType());
9568     Info.ptrVal = I.getArgOperand(0);
9569     Info.offset = 0;
9570     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9571     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9572     return true;
9573   }
9574   case Intrinsic::aarch64_stlxr:
9575   case Intrinsic::aarch64_stxr: {
9576     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9577     Info.opc = ISD::INTRINSIC_W_CHAIN;
9578     Info.memVT = MVT::getVT(PtrTy->getElementType());
9579     Info.ptrVal = I.getArgOperand(1);
9580     Info.offset = 0;
9581     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9582     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9583     return true;
9584   }
9585   case Intrinsic::aarch64_ldaxp:
9586   case Intrinsic::aarch64_ldxp:
9587     Info.opc = ISD::INTRINSIC_W_CHAIN;
9588     Info.memVT = MVT::i128;
9589     Info.ptrVal = I.getArgOperand(0);
9590     Info.offset = 0;
9591     Info.align = Align(16);
9592     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9593     return true;
9594   case Intrinsic::aarch64_stlxp:
9595   case Intrinsic::aarch64_stxp:
9596     Info.opc = ISD::INTRINSIC_W_CHAIN;
9597     Info.memVT = MVT::i128;
9598     Info.ptrVal = I.getArgOperand(2);
9599     Info.offset = 0;
9600     Info.align = Align(16);
9601     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9602     return true;
9603   case Intrinsic::aarch64_sve_ldnt1: {
9604     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9605     Info.opc = ISD::INTRINSIC_W_CHAIN;
9606     Info.memVT = MVT::getVT(I.getType());
9607     Info.ptrVal = I.getArgOperand(1);
9608     Info.offset = 0;
9609     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9610     Info.flags = MachineMemOperand::MOLoad;
9611     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9612       Info.flags |= MachineMemOperand::MONonTemporal;
9613     return true;
9614   }
9615   case Intrinsic::aarch64_sve_stnt1: {
9616     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9617     Info.opc = ISD::INTRINSIC_W_CHAIN;
9618     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9619     Info.ptrVal = I.getArgOperand(2);
9620     Info.offset = 0;
9621     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9622     Info.flags = MachineMemOperand::MOStore;
9623     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9624       Info.flags |= MachineMemOperand::MONonTemporal;
9625     return true;
9626   }
9627   default:
9628     break;
9629   }
9630 
9631   return false;
9632 }
9633 
9634 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9635                                                   ISD::LoadExtType ExtTy,
9636                                                   EVT NewVT) const {
9637   // TODO: This may be worth removing. Check regression tests for diffs.
9638   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9639     return false;
9640 
9641   // If we're reducing the load width in order to avoid having to use an extra
9642   // instruction to do extension then it's probably a good idea.
9643   if (ExtTy != ISD::NON_EXTLOAD)
9644     return true;
9645   // Don't reduce load width if it would prevent us from combining a shift into
9646   // the offset.
9647   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9648   assert(Mem);
9649   const SDValue &Base = Mem->getBasePtr();
9650   if (Base.getOpcode() == ISD::ADD &&
9651       Base.getOperand(1).getOpcode() == ISD::SHL &&
9652       Base.getOperand(1).hasOneUse() &&
9653       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9654     // The shift can be combined if it matches the size of the value being
9655     // loaded (and so reducing the width would make it not match).
9656     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9657     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9658     if (ShiftAmount == Log2_32(LoadBytes))
9659       return false;
9660   }
9661   // We have no reason to disallow reducing the load width, so allow it.
9662   return true;
9663 }
9664 
9665 // Truncations from 64-bit GPR to 32-bit GPR is free.
9666 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9667   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9668     return false;
9669   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9670   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9671   return NumBits1 > NumBits2;
9672 }
9673 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9674   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9675     return false;
9676   unsigned NumBits1 = VT1.getSizeInBits();
9677   unsigned NumBits2 = VT2.getSizeInBits();
9678   return NumBits1 > NumBits2;
9679 }
9680 
9681 /// Check if it is profitable to hoist instruction in then/else to if.
9682 /// Not profitable if I and it's user can form a FMA instruction
9683 /// because we prefer FMSUB/FMADD.
9684 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9685   if (I->getOpcode() != Instruction::FMul)
9686     return true;
9687 
9688   if (!I->hasOneUse())
9689     return true;
9690 
9691   Instruction *User = I->user_back();
9692 
9693   if (User &&
9694       !(User->getOpcode() == Instruction::FSub ||
9695         User->getOpcode() == Instruction::FAdd))
9696     return true;
9697 
9698   const TargetOptions &Options = getTargetMachine().Options;
9699   const Function *F = I->getFunction();
9700   const DataLayout &DL = F->getParent()->getDataLayout();
9701   Type *Ty = User->getOperand(0)->getType();
9702 
9703   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9704            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9705            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9706             Options.UnsafeFPMath));
9707 }
9708 
9709 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9710 // 64-bit GPR.
9711 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9712   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9713     return false;
9714   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9715   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9716   return NumBits1 == 32 && NumBits2 == 64;
9717 }
9718 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9719   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9720     return false;
9721   unsigned NumBits1 = VT1.getSizeInBits();
9722   unsigned NumBits2 = VT2.getSizeInBits();
9723   return NumBits1 == 32 && NumBits2 == 64;
9724 }
9725 
9726 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9727   EVT VT1 = Val.getValueType();
9728   if (isZExtFree(VT1, VT2)) {
9729     return true;
9730   }
9731 
9732   if (Val.getOpcode() != ISD::LOAD)
9733     return false;
9734 
9735   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9736   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9737           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9738           VT1.getSizeInBits() <= 32);
9739 }
9740 
9741 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9742   if (isa<FPExtInst>(Ext))
9743     return false;
9744 
9745   // Vector types are not free.
9746   if (Ext->getType()->isVectorTy())
9747     return false;
9748 
9749   for (const Use &U : Ext->uses()) {
9750     // The extension is free if we can fold it with a left shift in an
9751     // addressing mode or an arithmetic operation: add, sub, and cmp.
9752 
9753     // Is there a shift?
9754     const Instruction *Instr = cast<Instruction>(U.getUser());
9755 
9756     // Is this a constant shift?
9757     switch (Instr->getOpcode()) {
9758     case Instruction::Shl:
9759       if (!isa<ConstantInt>(Instr->getOperand(1)))
9760         return false;
9761       break;
9762     case Instruction::GetElementPtr: {
9763       gep_type_iterator GTI = gep_type_begin(Instr);
9764       auto &DL = Ext->getModule()->getDataLayout();
9765       std::advance(GTI, U.getOperandNo()-1);
9766       Type *IdxTy = GTI.getIndexedType();
9767       // This extension will end up with a shift because of the scaling factor.
9768       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9769       // Get the shift amount based on the scaling factor:
9770       // log2(sizeof(IdxTy)) - log2(8).
9771       uint64_t ShiftAmt =
9772         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9773       // Is the constant foldable in the shift of the addressing mode?
9774       // I.e., shift amount is between 1 and 4 inclusive.
9775       if (ShiftAmt == 0 || ShiftAmt > 4)
9776         return false;
9777       break;
9778     }
9779     case Instruction::Trunc:
9780       // Check if this is a noop.
9781       // trunc(sext ty1 to ty2) to ty1.
9782       if (Instr->getType() == Ext->getOperand(0)->getType())
9783         continue;
9784       LLVM_FALLTHROUGH;
9785     default:
9786       return false;
9787     }
9788 
9789     // At this point we can use the bfm family, so this extension is free
9790     // for that use.
9791   }
9792   return true;
9793 }
9794 
9795 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9796 /// or upper half of the vector elements.
9797 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9798   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9799     auto *FullTy = FullV->getType();
9800     auto *HalfTy = HalfV->getType();
9801     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
9802            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
9803   };
9804 
9805   auto extractHalf = [](Value *FullV, Value *HalfV) {
9806     auto *FullVT = cast<FixedVectorType>(FullV->getType());
9807     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
9808     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9809   };
9810 
9811   ArrayRef<int> M1, M2;
9812   Value *S1Op1, *S2Op1;
9813   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9814       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9815     return false;
9816 
9817   // Check that the operands are half as wide as the result and we extract
9818   // half of the elements of the input vectors.
9819   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9820       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9821     return false;
9822 
9823   // Check the mask extracts either the lower or upper half of vector
9824   // elements.
9825   int M1Start = -1;
9826   int M2Start = -1;
9827   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
9828   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9829       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9830       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9831     return false;
9832 
9833   return true;
9834 }
9835 
9836 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9837 /// of the vector elements.
9838 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9839   auto areExtDoubled = [](Instruction *Ext) {
9840     return Ext->getType()->getScalarSizeInBits() ==
9841            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9842   };
9843 
9844   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9845       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9846       !areExtDoubled(cast<Instruction>(Ext1)) ||
9847       !areExtDoubled(cast<Instruction>(Ext2)))
9848     return false;
9849 
9850   return true;
9851 }
9852 
9853 /// Check if Op could be used with vmull_high_p64 intrinsic.
9854 static bool isOperandOfVmullHighP64(Value *Op) {
9855   Value *VectorOperand = nullptr;
9856   ConstantInt *ElementIndex = nullptr;
9857   return match(Op, m_ExtractElt(m_Value(VectorOperand),
9858                                 m_ConstantInt(ElementIndex))) &&
9859          ElementIndex->getValue() == 1 &&
9860          isa<FixedVectorType>(VectorOperand->getType()) &&
9861          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
9862 }
9863 
9864 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
9865 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
9866   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
9867 }
9868 
9869 /// Check if sinking \p I's operands to I's basic block is profitable, because
9870 /// the operands can be folded into a target instruction, e.g.
9871 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9872 bool AArch64TargetLowering::shouldSinkOperands(
9873     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9874   if (!I->getType()->isVectorTy())
9875     return false;
9876 
9877   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9878     switch (II->getIntrinsicID()) {
9879     case Intrinsic::aarch64_neon_umull:
9880       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9881         return false;
9882       Ops.push_back(&II->getOperandUse(0));
9883       Ops.push_back(&II->getOperandUse(1));
9884       return true;
9885 
9886     case Intrinsic::aarch64_neon_pmull64:
9887       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
9888                                      II->getArgOperand(1)))
9889         return false;
9890       Ops.push_back(&II->getArgOperandUse(0));
9891       Ops.push_back(&II->getArgOperandUse(1));
9892       return true;
9893 
9894     default:
9895       return false;
9896     }
9897   }
9898 
9899   switch (I->getOpcode()) {
9900   case Instruction::Sub:
9901   case Instruction::Add: {
9902     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9903       return false;
9904 
9905     // If the exts' operands extract either the lower or upper elements, we
9906     // can sink them too.
9907     auto Ext1 = cast<Instruction>(I->getOperand(0));
9908     auto Ext2 = cast<Instruction>(I->getOperand(1));
9909     if (areExtractShuffleVectors(Ext1, Ext2)) {
9910       Ops.push_back(&Ext1->getOperandUse(0));
9911       Ops.push_back(&Ext2->getOperandUse(0));
9912     }
9913 
9914     Ops.push_back(&I->getOperandUse(0));
9915     Ops.push_back(&I->getOperandUse(1));
9916 
9917     return true;
9918   }
9919   default:
9920     return false;
9921   }
9922   return false;
9923 }
9924 
9925 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9926                                           Align &RequiredAligment) const {
9927   if (!LoadedType.isSimple() ||
9928       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9929     return false;
9930   // Cyclone supports unaligned accesses.
9931   RequiredAligment = Align(1);
9932   unsigned NumBits = LoadedType.getSizeInBits();
9933   return NumBits == 32 || NumBits == 64;
9934 }
9935 
9936 /// A helper function for determining the number of interleaved accesses we
9937 /// will generate when lowering accesses of the given type.
9938 unsigned
9939 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9940                                                  const DataLayout &DL) const {
9941   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9942 }
9943 
9944 MachineMemOperand::Flags
9945 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9946   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9947       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9948     return MOStridedAccess;
9949   return MachineMemOperand::MONone;
9950 }
9951 
9952 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9953     VectorType *VecTy, const DataLayout &DL) const {
9954 
9955   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9956   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9957 
9958   // Ensure the number of vector elements is greater than 1.
9959   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
9960     return false;
9961 
9962   // Ensure the element type is legal.
9963   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9964     return false;
9965 
9966   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9967   // 128 will be split into multiple interleaved accesses.
9968   return VecSize == 64 || VecSize % 128 == 0;
9969 }
9970 
9971 /// Lower an interleaved load into a ldN intrinsic.
9972 ///
9973 /// E.g. Lower an interleaved load (Factor = 2):
9974 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9975 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9976 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9977 ///
9978 ///      Into:
9979 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9980 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9981 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9982 bool AArch64TargetLowering::lowerInterleavedLoad(
9983     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9984     ArrayRef<unsigned> Indices, unsigned Factor) const {
9985   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9986          "Invalid interleave factor");
9987   assert(!Shuffles.empty() && "Empty shufflevector input");
9988   assert(Shuffles.size() == Indices.size() &&
9989          "Unmatched number of shufflevectors and indices");
9990 
9991   const DataLayout &DL = LI->getModule()->getDataLayout();
9992 
9993   VectorType *VTy = Shuffles[0]->getType();
9994 
9995   // Skip if we do not have NEON and skip illegal vector types. We can
9996   // "legalize" wide vector types into multiple interleaved accesses as long as
9997   // the vector types are divisible by 128.
9998   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
9999     return false;
10000 
10001   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
10002 
10003   auto *FVTy = cast<FixedVectorType>(VTy);
10004 
10005   // A pointer vector can not be the return type of the ldN intrinsics. Need to
10006   // load integer vectors first and then convert to pointer vectors.
10007   Type *EltTy = FVTy->getElementType();
10008   if (EltTy->isPointerTy())
10009     FVTy =
10010         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
10011 
10012   IRBuilder<> Builder(LI);
10013 
10014   // The base address of the load.
10015   Value *BaseAddr = LI->getPointerOperand();
10016 
10017   if (NumLoads > 1) {
10018     // If we're going to generate more than one load, reset the sub-vector type
10019     // to something legal.
10020     FVTy = FixedVectorType::get(FVTy->getElementType(),
10021                                 FVTy->getNumElements() / NumLoads);
10022 
10023     // We will compute the pointer operand of each load from the original base
10024     // address using GEPs. Cast the base address to a pointer to the scalar
10025     // element type.
10026     BaseAddr = Builder.CreateBitCast(
10027         BaseAddr,
10028         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
10029   }
10030 
10031   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
10032   Type *Tys[2] = {FVTy, PtrTy};
10033   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
10034                                             Intrinsic::aarch64_neon_ld3,
10035                                             Intrinsic::aarch64_neon_ld4};
10036   Function *LdNFunc =
10037       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
10038 
10039   // Holds sub-vectors extracted from the load intrinsic return values. The
10040   // sub-vectors are associated with the shufflevector instructions they will
10041   // replace.
10042   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
10043 
10044   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
10045 
10046     // If we're generating more than one load, compute the base address of
10047     // subsequent loads as an offset from the previous.
10048     if (LoadCount > 0)
10049       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
10050                                             FVTy->getNumElements() * Factor);
10051 
10052     CallInst *LdN = Builder.CreateCall(
10053         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
10054 
10055     // Extract and store the sub-vectors returned by the load intrinsic.
10056     for (unsigned i = 0; i < Shuffles.size(); i++) {
10057       ShuffleVectorInst *SVI = Shuffles[i];
10058       unsigned Index = Indices[i];
10059 
10060       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
10061 
10062       // Convert the integer vector to pointer vector if the element is pointer.
10063       if (EltTy->isPointerTy())
10064         SubVec = Builder.CreateIntToPtr(
10065             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
10066                                          FVTy->getNumElements()));
10067       SubVecs[SVI].push_back(SubVec);
10068     }
10069   }
10070 
10071   // Replace uses of the shufflevector instructions with the sub-vectors
10072   // returned by the load intrinsic. If a shufflevector instruction is
10073   // associated with more than one sub-vector, those sub-vectors will be
10074   // concatenated into a single wide vector.
10075   for (ShuffleVectorInst *SVI : Shuffles) {
10076     auto &SubVec = SubVecs[SVI];
10077     auto *WideVec =
10078         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
10079     SVI->replaceAllUsesWith(WideVec);
10080   }
10081 
10082   return true;
10083 }
10084 
10085 /// Lower an interleaved store into a stN intrinsic.
10086 ///
10087 /// E.g. Lower an interleaved store (Factor = 3):
10088 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
10089 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
10090 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10091 ///
10092 ///      Into:
10093 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
10094 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
10095 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
10096 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10097 ///
10098 /// Note that the new shufflevectors will be removed and we'll only generate one
10099 /// st3 instruction in CodeGen.
10100 ///
10101 /// Example for a more general valid mask (Factor 3). Lower:
10102 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
10103 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
10104 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10105 ///
10106 ///      Into:
10107 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
10108 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
10109 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
10110 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10111 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
10112                                                   ShuffleVectorInst *SVI,
10113                                                   unsigned Factor) const {
10114   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10115          "Invalid interleave factor");
10116 
10117   auto *VecTy = cast<FixedVectorType>(SVI->getType());
10118   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
10119 
10120   unsigned LaneLen = VecTy->getNumElements() / Factor;
10121   Type *EltTy = VecTy->getElementType();
10122   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
10123 
10124   const DataLayout &DL = SI->getModule()->getDataLayout();
10125 
10126   // Skip if we do not have NEON and skip illegal vector types. We can
10127   // "legalize" wide vector types into multiple interleaved accesses as long as
10128   // the vector types are divisible by 128.
10129   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
10130     return false;
10131 
10132   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
10133 
10134   Value *Op0 = SVI->getOperand(0);
10135   Value *Op1 = SVI->getOperand(1);
10136   IRBuilder<> Builder(SI);
10137 
10138   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
10139   // vectors to integer vectors.
10140   if (EltTy->isPointerTy()) {
10141     Type *IntTy = DL.getIntPtrType(EltTy);
10142     unsigned NumOpElts =
10143         cast<FixedVectorType>(Op0->getType())->getNumElements();
10144 
10145     // Convert to the corresponding integer vector.
10146     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
10147     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
10148     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
10149 
10150     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
10151   }
10152 
10153   // The base address of the store.
10154   Value *BaseAddr = SI->getPointerOperand();
10155 
10156   if (NumStores > 1) {
10157     // If we're going to generate more than one store, reset the lane length
10158     // and sub-vector type to something legal.
10159     LaneLen /= NumStores;
10160     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10161 
10162     // We will compute the pointer operand of each store from the original base
10163     // address using GEPs. Cast the base address to a pointer to the scalar
10164     // element type.
10165     BaseAddr = Builder.CreateBitCast(
10166         BaseAddr,
10167         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10168   }
10169 
10170   auto Mask = SVI->getShuffleMask();
10171 
10172   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10173   Type *Tys[2] = {SubVecTy, PtrTy};
10174   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10175                                              Intrinsic::aarch64_neon_st3,
10176                                              Intrinsic::aarch64_neon_st4};
10177   Function *StNFunc =
10178       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10179 
10180   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10181 
10182     SmallVector<Value *, 5> Ops;
10183 
10184     // Split the shufflevector operands into sub vectors for the new stN call.
10185     for (unsigned i = 0; i < Factor; i++) {
10186       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10187       if (Mask[IdxI] >= 0) {
10188         Ops.push_back(Builder.CreateShuffleVector(
10189             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10190       } else {
10191         unsigned StartMask = 0;
10192         for (unsigned j = 1; j < LaneLen; j++) {
10193           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10194           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10195             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10196             break;
10197           }
10198         }
10199         // Note: Filling undef gaps with random elements is ok, since
10200         // those elements were being written anyway (with undefs).
10201         // In the case of all undefs we're defaulting to using elems from 0
10202         // Note: StartMask cannot be negative, it's checked in
10203         // isReInterleaveMask
10204         Ops.push_back(Builder.CreateShuffleVector(
10205             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10206       }
10207     }
10208 
10209     // If we generating more than one store, we compute the base address of
10210     // subsequent stores as an offset from the previous.
10211     if (StoreCount > 0)
10212       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10213                                             BaseAddr, LaneLen * Factor);
10214 
10215     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10216     Builder.CreateCall(StNFunc, Ops);
10217   }
10218   return true;
10219 }
10220 
10221 // Lower an SVE structured load intrinsic returning a tuple type to target
10222 // specific intrinsic taking the same input but returning a multi-result value
10223 // of the split tuple type.
10224 //
10225 // E.g. Lowering an LD3:
10226 //
10227 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10228 //                                                    <vscale x 4 x i1> %pred,
10229 //                                                    <vscale x 4 x i32>* %addr)
10230 //
10231 //  Output DAG:
10232 //
10233 //    t0: ch = EntryToken
10234 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10235 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10236 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10237 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10238 //
10239 // This is called pre-legalization to avoid widening/splitting issues with
10240 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10241 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10242                                                   ArrayRef<SDValue> LoadOps,
10243                                                   EVT VT, SelectionDAG &DAG,
10244                                                   const SDLoc &DL) const {
10245   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10246 
10247   unsigned N, Opcode;
10248   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10249       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10250       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10251       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10252 
10253   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10254   assert(VT.getVectorElementCount().Min % N == 0 &&
10255          "invalid tuple vector type!");
10256 
10257   EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10258                                  VT.getVectorElementCount() / N);
10259   assert(isTypeLegal(SplitVT));
10260 
10261   SmallVector<EVT, 5> VTs(N, SplitVT);
10262   VTs.push_back(MVT::Other); // Chain
10263   SDVTList NodeTys = DAG.getVTList(VTs);
10264 
10265   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10266   SmallVector<SDValue, 4> PseudoLoadOps;
10267   for (unsigned I = 0; I < N; ++I)
10268     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10269   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10270 }
10271 
10272 EVT AArch64TargetLowering::getOptimalMemOpType(
10273     const MemOp &Op, const AttributeList &FuncAttributes) const {
10274   bool CanImplicitFloat =
10275       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10276   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10277   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10278   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10279   // taken one instruction to materialize the v2i64 zero and one store (with
10280   // restrictive addressing mode). Just do i64 stores.
10281   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10282   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10283     if (Op.isAligned(AlignCheck))
10284       return true;
10285     bool Fast;
10286     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10287                                           &Fast) &&
10288            Fast;
10289   };
10290 
10291   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10292       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10293     return MVT::v2i64;
10294   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10295     return MVT::f128;
10296   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10297     return MVT::i64;
10298   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10299     return MVT::i32;
10300   return MVT::Other;
10301 }
10302 
10303 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10304     const MemOp &Op, const AttributeList &FuncAttributes) const {
10305   bool CanImplicitFloat =
10306       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10307   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10308   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10309   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10310   // taken one instruction to materialize the v2i64 zero and one store (with
10311   // restrictive addressing mode). Just do i64 stores.
10312   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10313   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10314     if (Op.isAligned(AlignCheck))
10315       return true;
10316     bool Fast;
10317     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10318                                           &Fast) &&
10319            Fast;
10320   };
10321 
10322   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10323       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10324     return LLT::vector(2, 64);
10325   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10326     return LLT::scalar(128);
10327   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10328     return LLT::scalar(64);
10329   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10330     return LLT::scalar(32);
10331   return LLT();
10332 }
10333 
10334 // 12-bit optionally shifted immediates are legal for adds.
10335 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10336   if (Immed == std::numeric_limits<int64_t>::min()) {
10337     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10338                       << ": avoid UB for INT64_MIN\n");
10339     return false;
10340   }
10341   // Same encoding for add/sub, just flip the sign.
10342   Immed = std::abs(Immed);
10343   bool IsLegal = ((Immed >> 12) == 0 ||
10344                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10345   LLVM_DEBUG(dbgs() << "Is " << Immed
10346                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10347   return IsLegal;
10348 }
10349 
10350 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10351 // immediates is the same as for an add or a sub.
10352 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10353   return isLegalAddImmediate(Immed);
10354 }
10355 
10356 /// isLegalAddressingMode - Return true if the addressing mode represented
10357 /// by AM is legal for this target, for a load/store of the specified type.
10358 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10359                                                   const AddrMode &AM, Type *Ty,
10360                                                   unsigned AS, Instruction *I) const {
10361   // AArch64 has five basic addressing modes:
10362   //  reg
10363   //  reg + 9-bit signed offset
10364   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
10365   //  reg1 + reg2
10366   //  reg + SIZE_IN_BYTES * reg
10367 
10368   // No global is ever allowed as a base.
10369   if (AM.BaseGV)
10370     return false;
10371 
10372   // No reg+reg+imm addressing.
10373   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10374     return false;
10375 
10376   // FIXME: Update this method to support scalable addressing modes.
10377   if (isa<ScalableVectorType>(Ty))
10378     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10379 
10380   // check reg + imm case:
10381   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10382   uint64_t NumBytes = 0;
10383   if (Ty->isSized()) {
10384     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10385     NumBytes = NumBits / 8;
10386     if (!isPowerOf2_64(NumBits))
10387       NumBytes = 0;
10388   }
10389 
10390   if (!AM.Scale) {
10391     int64_t Offset = AM.BaseOffs;
10392 
10393     // 9-bit signed offset
10394     if (isInt<9>(Offset))
10395       return true;
10396 
10397     // 12-bit unsigned offset
10398     unsigned shift = Log2_64(NumBytes);
10399     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10400         // Must be a multiple of NumBytes (NumBytes is a power of 2)
10401         (Offset >> shift) << shift == Offset)
10402       return true;
10403     return false;
10404   }
10405 
10406   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10407 
10408   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10409 }
10410 
10411 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10412   // Consider splitting large offset of struct or array.
10413   return true;
10414 }
10415 
10416 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10417                                                 const AddrMode &AM, Type *Ty,
10418                                                 unsigned AS) const {
10419   // Scaling factors are not free at all.
10420   // Operands                     | Rt Latency
10421   // -------------------------------------------
10422   // Rt, [Xn, Xm]                 | 4
10423   // -------------------------------------------
10424   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
10425   // Rt, [Xn, Wm, <extend> #imm]  |
10426   if (isLegalAddressingMode(DL, AM, Ty, AS))
10427     // Scale represents reg2 * scale, thus account for 1 if
10428     // it is not equal to 0 or 1.
10429     return AM.Scale != 0 && AM.Scale != 1;
10430   return -1;
10431 }
10432 
10433 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10434     const MachineFunction &MF, EVT VT) const {
10435   VT = VT.getScalarType();
10436 
10437   if (!VT.isSimple())
10438     return false;
10439 
10440   switch (VT.getSimpleVT().SimpleTy) {
10441   case MVT::f32:
10442   case MVT::f64:
10443     return true;
10444   default:
10445     break;
10446   }
10447 
10448   return false;
10449 }
10450 
10451 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10452                                                        Type *Ty) const {
10453   switch (Ty->getScalarType()->getTypeID()) {
10454   case Type::FloatTyID:
10455   case Type::DoubleTyID:
10456     return true;
10457   default:
10458     return false;
10459   }
10460 }
10461 
10462 const MCPhysReg *
10463 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10464   // LR is a callee-save register, but we must treat it as clobbered by any call
10465   // site. Hence we include LR in the scratch registers, which are in turn added
10466   // as implicit-defs for stackmaps and patchpoints.
10467   static const MCPhysReg ScratchRegs[] = {
10468     AArch64::X16, AArch64::X17, AArch64::LR, 0
10469   };
10470   return ScratchRegs;
10471 }
10472 
10473 bool
10474 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10475                                                      CombineLevel Level) const {
10476   N = N->getOperand(0).getNode();
10477   EVT VT = N->getValueType(0);
10478     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10479     // it with shift to let it be lowered to UBFX.
10480   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10481       isa<ConstantSDNode>(N->getOperand(1))) {
10482     uint64_t TruncMask = N->getConstantOperandVal(1);
10483     if (isMask_64(TruncMask) &&
10484       N->getOperand(0).getOpcode() == ISD::SRL &&
10485       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10486       return false;
10487   }
10488   return true;
10489 }
10490 
10491 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10492                                                               Type *Ty) const {
10493   assert(Ty->isIntegerTy());
10494 
10495   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10496   if (BitSize == 0)
10497     return false;
10498 
10499   int64_t Val = Imm.getSExtValue();
10500   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10501     return true;
10502 
10503   if ((int64_t)Val < 0)
10504     Val = ~Val;
10505   if (BitSize == 32)
10506     Val &= (1LL << 32) - 1;
10507 
10508   unsigned LZ = countLeadingZeros((uint64_t)Val);
10509   unsigned Shift = (63 - LZ) / 16;
10510   // MOVZ is free so return true for one or fewer MOVK.
10511   return Shift < 3;
10512 }
10513 
10514 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10515                                                     unsigned Index) const {
10516   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10517     return false;
10518 
10519   return (Index == 0 || Index == ResVT.getVectorNumElements());
10520 }
10521 
10522 /// Turn vector tests of the signbit in the form of:
10523 ///   xor (sra X, elt_size(X)-1), -1
10524 /// into:
10525 ///   cmge X, X, #0
10526 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
10527                                          const AArch64Subtarget *Subtarget) {
10528   EVT VT = N->getValueType(0);
10529   if (!Subtarget->hasNEON() || !VT.isVector())
10530     return SDValue();
10531 
10532   // There must be a shift right algebraic before the xor, and the xor must be a
10533   // 'not' operation.
10534   SDValue Shift = N->getOperand(0);
10535   SDValue Ones = N->getOperand(1);
10536   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
10537       !ISD::isBuildVectorAllOnes(Ones.getNode()))
10538     return SDValue();
10539 
10540   // The shift should be smearing the sign bit across each vector element.
10541   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10542   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
10543   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
10544     return SDValue();
10545 
10546   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
10547 }
10548 
10549 // Generate SUBS and CSEL for integer abs.
10550 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
10551   EVT VT = N->getValueType(0);
10552 
10553   SDValue N0 = N->getOperand(0);
10554   SDValue N1 = N->getOperand(1);
10555   SDLoc DL(N);
10556 
10557   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
10558   // and change it to SUB and CSEL.
10559   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
10560       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
10561       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
10562     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
10563       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
10564         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
10565                                   N0.getOperand(0));
10566         // Generate SUBS & CSEL.
10567         SDValue Cmp =
10568             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
10569                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
10570         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
10571                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
10572                            SDValue(Cmp.getNode(), 1));
10573       }
10574   return SDValue();
10575 }
10576 
10577 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
10578                                  TargetLowering::DAGCombinerInfo &DCI,
10579                                  const AArch64Subtarget *Subtarget) {
10580   if (DCI.isBeforeLegalizeOps())
10581     return SDValue();
10582 
10583   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
10584     return Cmp;
10585 
10586   return performIntegerAbsCombine(N, DAG);
10587 }
10588 
10589 SDValue
10590 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10591                                      SelectionDAG &DAG,
10592                                      SmallVectorImpl<SDNode *> &Created) const {
10593   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10594   if (isIntDivCheap(N->getValueType(0), Attr))
10595     return SDValue(N,0); // Lower SDIV as SDIV
10596 
10597   // fold (sdiv X, pow2)
10598   EVT VT = N->getValueType(0);
10599   if ((VT != MVT::i32 && VT != MVT::i64) ||
10600       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10601     return SDValue();
10602 
10603   SDLoc DL(N);
10604   SDValue N0 = N->getOperand(0);
10605   unsigned Lg2 = Divisor.countTrailingZeros();
10606   SDValue Zero = DAG.getConstant(0, DL, VT);
10607   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10608 
10609   // Add (N0 < 0) ? Pow2 - 1 : 0;
10610   SDValue CCVal;
10611   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
10612   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10613   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
10614 
10615   Created.push_back(Cmp.getNode());
10616   Created.push_back(Add.getNode());
10617   Created.push_back(CSel.getNode());
10618 
10619   // Divide by pow2.
10620   SDValue SRA =
10621       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
10622 
10623   // If we're dividing by a positive value, we're done.  Otherwise, we must
10624   // negate the result.
10625   if (Divisor.isNonNegative())
10626     return SRA;
10627 
10628   Created.push_back(SRA.getNode());
10629   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10630 }
10631 
10632 static bool IsSVECntIntrinsic(SDValue S) {
10633   switch(getIntrinsicID(S.getNode())) {
10634   default:
10635     break;
10636   case Intrinsic::aarch64_sve_cntb:
10637   case Intrinsic::aarch64_sve_cnth:
10638   case Intrinsic::aarch64_sve_cntw:
10639   case Intrinsic::aarch64_sve_cntd:
10640     return true;
10641   }
10642   return false;
10643 }
10644 
10645 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
10646                                  TargetLowering::DAGCombinerInfo &DCI,
10647                                  const AArch64Subtarget *Subtarget) {
10648   if (DCI.isBeforeLegalizeOps())
10649     return SDValue();
10650 
10651   // The below optimizations require a constant RHS.
10652   if (!isa<ConstantSDNode>(N->getOperand(1)))
10653     return SDValue();
10654 
10655   SDValue N0 = N->getOperand(0);
10656   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
10657   const APInt &ConstValue = C->getAPIntValue();
10658 
10659   // Allow the scaling to be folded into the `cnt` instruction by preventing
10660   // the scaling to be obscured here. This makes it easier to pattern match.
10661   if (IsSVECntIntrinsic(N0) ||
10662      (N0->getOpcode() == ISD::TRUNCATE &&
10663       (IsSVECntIntrinsic(N0->getOperand(0)))))
10664        if (ConstValue.sge(1) && ConstValue.sle(16))
10665          return SDValue();
10666 
10667   // Multiplication of a power of two plus/minus one can be done more
10668   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
10669   // future CPUs have a cheaper MADD instruction, this may need to be
10670   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
10671   // 64-bit is 5 cycles, so this is always a win.
10672   // More aggressively, some multiplications N0 * C can be lowered to
10673   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
10674   // e.g. 6=3*2=(2+1)*2.
10675   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
10676   // which equals to (1+2)*16-(1+2).
10677   // TrailingZeroes is used to test if the mul can be lowered to
10678   // shift+add+shift.
10679   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10680   if (TrailingZeroes) {
10681     // Conservatively do not lower to shift+add+shift if the mul might be
10682     // folded into smul or umul.
10683     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10684                             isZeroExtended(N0.getNode(), DAG)))
10685       return SDValue();
10686     // Conservatively do not lower to shift+add+shift if the mul might be
10687     // folded into madd or msub.
10688     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10689                            N->use_begin()->getOpcode() == ISD::SUB))
10690       return SDValue();
10691   }
10692   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10693   // and shift+add+shift.
10694   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10695 
10696   unsigned ShiftAmt, AddSubOpc;
10697   // Is the shifted value the LHS operand of the add/sub?
10698   bool ShiftValUseIsN0 = true;
10699   // Do we need to negate the result?
10700   bool NegateResult = false;
10701 
10702   if (ConstValue.isNonNegative()) {
10703     // (mul x, 2^N + 1) => (add (shl x, N), x)
10704     // (mul x, 2^N - 1) => (sub (shl x, N), x)
10705     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10706     APInt SCVMinus1 = ShiftedConstValue - 1;
10707     APInt CVPlus1 = ConstValue + 1;
10708     if (SCVMinus1.isPowerOf2()) {
10709       ShiftAmt = SCVMinus1.logBase2();
10710       AddSubOpc = ISD::ADD;
10711     } else if (CVPlus1.isPowerOf2()) {
10712       ShiftAmt = CVPlus1.logBase2();
10713       AddSubOpc = ISD::SUB;
10714     } else
10715       return SDValue();
10716   } else {
10717     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10718     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10719     APInt CVNegPlus1 = -ConstValue + 1;
10720     APInt CVNegMinus1 = -ConstValue - 1;
10721     if (CVNegPlus1.isPowerOf2()) {
10722       ShiftAmt = CVNegPlus1.logBase2();
10723       AddSubOpc = ISD::SUB;
10724       ShiftValUseIsN0 = false;
10725     } else if (CVNegMinus1.isPowerOf2()) {
10726       ShiftAmt = CVNegMinus1.logBase2();
10727       AddSubOpc = ISD::ADD;
10728       NegateResult = true;
10729     } else
10730       return SDValue();
10731   }
10732 
10733   SDLoc DL(N);
10734   EVT VT = N->getValueType(0);
10735   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10736                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
10737 
10738   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10739   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10740   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10741   assert(!(NegateResult && TrailingZeroes) &&
10742          "NegateResult and TrailingZeroes cannot both be true for now.");
10743   // Negate the result.
10744   if (NegateResult)
10745     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10746   // Shift the result.
10747   if (TrailingZeroes)
10748     return DAG.getNode(ISD::SHL, DL, VT, Res,
10749                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10750   return Res;
10751 }
10752 
10753 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10754                                                          SelectionDAG &DAG) {
10755   // Take advantage of vector comparisons producing 0 or -1 in each lane to
10756   // optimize away operation when it's from a constant.
10757   //
10758   // The general transformation is:
10759   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10760   //       AND(VECTOR_CMP(x,y), constant2)
10761   //    constant2 = UNARYOP(constant)
10762 
10763   // Early exit if this isn't a vector operation, the operand of the
10764   // unary operation isn't a bitwise AND, or if the sizes of the operations
10765   // aren't the same.
10766   EVT VT = N->getValueType(0);
10767   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10768       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10769       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10770     return SDValue();
10771 
10772   // Now check that the other operand of the AND is a constant. We could
10773   // make the transformation for non-constant splats as well, but it's unclear
10774   // that would be a benefit as it would not eliminate any operations, just
10775   // perform one more step in scalar code before moving to the vector unit.
10776   if (BuildVectorSDNode *BV =
10777           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10778     // Bail out if the vector isn't a constant.
10779     if (!BV->isConstant())
10780       return SDValue();
10781 
10782     // Everything checks out. Build up the new and improved node.
10783     SDLoc DL(N);
10784     EVT IntVT = BV->getValueType(0);
10785     // Create a new constant of the appropriate type for the transformed
10786     // DAG.
10787     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10788     // The AND node needs bitcasts to/from an integer vector type around it.
10789     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10790     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10791                                  N->getOperand(0)->getOperand(0), MaskConst);
10792     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10793     return Res;
10794   }
10795 
10796   return SDValue();
10797 }
10798 
10799 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10800                                      const AArch64Subtarget *Subtarget) {
10801   // First try to optimize away the conversion when it's conditionally from
10802   // a constant. Vectors only.
10803   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10804     return Res;
10805 
10806   EVT VT = N->getValueType(0);
10807   if (VT != MVT::f32 && VT != MVT::f64)
10808     return SDValue();
10809 
10810   // Only optimize when the source and destination types have the same width.
10811   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10812     return SDValue();
10813 
10814   // If the result of an integer load is only used by an integer-to-float
10815   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10816   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10817   SDValue N0 = N->getOperand(0);
10818   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10819       // Do not change the width of a volatile load.
10820       !cast<LoadSDNode>(N0)->isVolatile()) {
10821     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10822     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10823                                LN0->getPointerInfo(), LN0->getAlignment(),
10824                                LN0->getMemOperand()->getFlags());
10825 
10826     // Make sure successors of the original load stay after it by updating them
10827     // to use the new Chain.
10828     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10829 
10830     unsigned Opcode =
10831         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10832     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10833   }
10834 
10835   return SDValue();
10836 }
10837 
10838 /// Fold a floating-point multiply by power of two into floating-point to
10839 /// fixed-point conversion.
10840 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10841                                      TargetLowering::DAGCombinerInfo &DCI,
10842                                      const AArch64Subtarget *Subtarget) {
10843   if (!Subtarget->hasNEON())
10844     return SDValue();
10845 
10846   if (!N->getValueType(0).isSimple())
10847     return SDValue();
10848 
10849   SDValue Op = N->getOperand(0);
10850   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10851       Op.getOpcode() != ISD::FMUL)
10852     return SDValue();
10853 
10854   SDValue ConstVec = Op->getOperand(1);
10855   if (!isa<BuildVectorSDNode>(ConstVec))
10856     return SDValue();
10857 
10858   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10859   uint32_t FloatBits = FloatTy.getSizeInBits();
10860   if (FloatBits != 32 && FloatBits != 64)
10861     return SDValue();
10862 
10863   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10864   uint32_t IntBits = IntTy.getSizeInBits();
10865   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10866     return SDValue();
10867 
10868   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10869   if (IntBits > FloatBits)
10870     return SDValue();
10871 
10872   BitVector UndefElements;
10873   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10874   int32_t Bits = IntBits == 64 ? 64 : 32;
10875   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10876   if (C == -1 || C == 0 || C > Bits)
10877     return SDValue();
10878 
10879   MVT ResTy;
10880   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10881   switch (NumLanes) {
10882   default:
10883     return SDValue();
10884   case 2:
10885     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10886     break;
10887   case 4:
10888     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10889     break;
10890   }
10891 
10892   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10893     return SDValue();
10894 
10895   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10896          "Illegal vector type after legalization");
10897 
10898   SDLoc DL(N);
10899   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10900   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10901                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10902   SDValue FixConv =
10903       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10904                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10905                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10906   // We can handle smaller integers by generating an extra trunc.
10907   if (IntBits < FloatBits)
10908     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10909 
10910   return FixConv;
10911 }
10912 
10913 /// Fold a floating-point divide by power of two into fixed-point to
10914 /// floating-point conversion.
10915 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10916                                   TargetLowering::DAGCombinerInfo &DCI,
10917                                   const AArch64Subtarget *Subtarget) {
10918   if (!Subtarget->hasNEON())
10919     return SDValue();
10920 
10921   SDValue Op = N->getOperand(0);
10922   unsigned Opc = Op->getOpcode();
10923   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10924       !Op.getOperand(0).getValueType().isSimple() ||
10925       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10926     return SDValue();
10927 
10928   SDValue ConstVec = N->getOperand(1);
10929   if (!isa<BuildVectorSDNode>(ConstVec))
10930     return SDValue();
10931 
10932   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10933   int32_t IntBits = IntTy.getSizeInBits();
10934   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10935     return SDValue();
10936 
10937   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10938   int32_t FloatBits = FloatTy.getSizeInBits();
10939   if (FloatBits != 32 && FloatBits != 64)
10940     return SDValue();
10941 
10942   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10943   if (IntBits > FloatBits)
10944     return SDValue();
10945 
10946   BitVector UndefElements;
10947   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10948   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10949   if (C == -1 || C == 0 || C > FloatBits)
10950     return SDValue();
10951 
10952   MVT ResTy;
10953   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10954   switch (NumLanes) {
10955   default:
10956     return SDValue();
10957   case 2:
10958     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10959     break;
10960   case 4:
10961     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10962     break;
10963   }
10964 
10965   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10966     return SDValue();
10967 
10968   SDLoc DL(N);
10969   SDValue ConvInput = Op.getOperand(0);
10970   bool IsSigned = Opc == ISD::SINT_TO_FP;
10971   if (IntBits < FloatBits)
10972     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10973                             ResTy, ConvInput);
10974 
10975   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10976                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10977   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10978                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10979                      DAG.getConstant(C, DL, MVT::i32));
10980 }
10981 
10982 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10983 /// searches for and classifies those shifts.
10984 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10985                          bool &FromHi) {
10986   if (N.getOpcode() == ISD::SHL)
10987     FromHi = false;
10988   else if (N.getOpcode() == ISD::SRL)
10989     FromHi = true;
10990   else
10991     return false;
10992 
10993   if (!isa<ConstantSDNode>(N.getOperand(1)))
10994     return false;
10995 
10996   ShiftAmount = N->getConstantOperandVal(1);
10997   Src = N->getOperand(0);
10998   return true;
10999 }
11000 
11001 /// EXTR instruction extracts a contiguous chunk of bits from two existing
11002 /// registers viewed as a high/low pair. This function looks for the pattern:
11003 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
11004 /// with an EXTR. Can't quite be done in TableGen because the two immediates
11005 /// aren't independent.
11006 static SDValue tryCombineToEXTR(SDNode *N,
11007                                 TargetLowering::DAGCombinerInfo &DCI) {
11008   SelectionDAG &DAG = DCI.DAG;
11009   SDLoc DL(N);
11010   EVT VT = N->getValueType(0);
11011 
11012   assert(N->getOpcode() == ISD::OR && "Unexpected root");
11013 
11014   if (VT != MVT::i32 && VT != MVT::i64)
11015     return SDValue();
11016 
11017   SDValue LHS;
11018   uint32_t ShiftLHS = 0;
11019   bool LHSFromHi = false;
11020   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
11021     return SDValue();
11022 
11023   SDValue RHS;
11024   uint32_t ShiftRHS = 0;
11025   bool RHSFromHi = false;
11026   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
11027     return SDValue();
11028 
11029   // If they're both trying to come from the high part of the register, they're
11030   // not really an EXTR.
11031   if (LHSFromHi == RHSFromHi)
11032     return SDValue();
11033 
11034   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
11035     return SDValue();
11036 
11037   if (LHSFromHi) {
11038     std::swap(LHS, RHS);
11039     std::swap(ShiftLHS, ShiftRHS);
11040   }
11041 
11042   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
11043                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
11044 }
11045 
11046 static SDValue tryCombineToBSL(SDNode *N,
11047                                 TargetLowering::DAGCombinerInfo &DCI) {
11048   EVT VT = N->getValueType(0);
11049   SelectionDAG &DAG = DCI.DAG;
11050   SDLoc DL(N);
11051 
11052   if (!VT.isVector())
11053     return SDValue();
11054 
11055   SDValue N0 = N->getOperand(0);
11056   if (N0.getOpcode() != ISD::AND)
11057     return SDValue();
11058 
11059   SDValue N1 = N->getOperand(1);
11060   if (N1.getOpcode() != ISD::AND)
11061     return SDValue();
11062 
11063   // We only have to look for constant vectors here since the general, variable
11064   // case can be handled in TableGen.
11065   unsigned Bits = VT.getScalarSizeInBits();
11066   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
11067   for (int i = 1; i >= 0; --i)
11068     for (int j = 1; j >= 0; --j) {
11069       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
11070       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
11071       if (!BVN0 || !BVN1)
11072         continue;
11073 
11074       bool FoundMatch = true;
11075       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
11076         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
11077         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
11078         if (!CN0 || !CN1 ||
11079             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
11080           FoundMatch = false;
11081           break;
11082         }
11083       }
11084 
11085       if (FoundMatch)
11086         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
11087                            N0->getOperand(1 - i), N1->getOperand(1 - j));
11088     }
11089 
11090   return SDValue();
11091 }
11092 
11093 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11094                                 const AArch64Subtarget *Subtarget) {
11095   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
11096   SelectionDAG &DAG = DCI.DAG;
11097   EVT VT = N->getValueType(0);
11098 
11099   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11100     return SDValue();
11101 
11102   if (SDValue Res = tryCombineToEXTR(N, DCI))
11103     return Res;
11104 
11105   if (SDValue Res = tryCombineToBSL(N, DCI))
11106     return Res;
11107 
11108   return SDValue();
11109 }
11110 
11111 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
11112   if (!MemVT.getVectorElementType().isSimple())
11113     return false;
11114 
11115   uint64_t MaskForTy = 0ull;
11116   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
11117   case MVT::i8:
11118     MaskForTy = 0xffull;
11119     break;
11120   case MVT::i16:
11121     MaskForTy = 0xffffull;
11122     break;
11123   case MVT::i32:
11124     MaskForTy = 0xffffffffull;
11125     break;
11126   default:
11127     return false;
11128     break;
11129   }
11130 
11131   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
11132     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
11133       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
11134 
11135   return false;
11136 }
11137 
11138 static SDValue performSVEAndCombine(SDNode *N,
11139                                     TargetLowering::DAGCombinerInfo &DCI) {
11140   if (DCI.isBeforeLegalizeOps())
11141     return SDValue();
11142 
11143   SelectionDAG &DAG = DCI.DAG;
11144   SDValue Src = N->getOperand(0);
11145   unsigned Opc = Src->getOpcode();
11146 
11147   // Zero/any extend of an unsigned unpack
11148   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
11149     SDValue UnpkOp = Src->getOperand(0);
11150     SDValue Dup = N->getOperand(1);
11151 
11152     if (Dup.getOpcode() != AArch64ISD::DUP)
11153       return SDValue();
11154 
11155     SDLoc DL(N);
11156     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11157     uint64_t ExtVal = C->getZExtValue();
11158 
11159     // If the mask is fully covered by the unpack, we don't need to push
11160     // a new AND onto the operand
11161     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11162     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11163         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11164         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11165       return Src;
11166 
11167     // Truncate to prevent a DUP with an over wide constant
11168     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11169 
11170     // Otherwise, make sure we propagate the AND to the operand
11171     // of the unpack
11172     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11173                       UnpkOp->getValueType(0),
11174                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11175 
11176     SDValue And = DAG.getNode(ISD::AND, DL,
11177                               UnpkOp->getValueType(0), UnpkOp, Dup);
11178 
11179     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11180   }
11181 
11182   SDValue Mask = N->getOperand(1);
11183 
11184   if (!Src.hasOneUse())
11185     return SDValue();
11186 
11187   EVT MemVT;
11188 
11189   // SVE load instructions perform an implicit zero-extend, which makes them
11190   // perfect candidates for combining.
11191   switch (Opc) {
11192   case AArch64ISD::LD1_MERGE_ZERO:
11193   case AArch64ISD::LDNF1_MERGE_ZERO:
11194   case AArch64ISD::LDFF1_MERGE_ZERO:
11195     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11196     break;
11197   case AArch64ISD::GLD1_MERGE_ZERO:
11198   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11199   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11200   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11201   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11202   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11203   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11204   case AArch64ISD::GLDFF1_MERGE_ZERO:
11205   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11206   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11207   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11208   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11209   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11210   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11211   case AArch64ISD::GLDNT1_MERGE_ZERO:
11212     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11213     break;
11214   default:
11215     return SDValue();
11216   }
11217 
11218   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11219     return Src;
11220 
11221   return SDValue();
11222 }
11223 
11224 static SDValue performANDCombine(SDNode *N,
11225                                  TargetLowering::DAGCombinerInfo &DCI) {
11226   SelectionDAG &DAG = DCI.DAG;
11227   SDValue LHS = N->getOperand(0);
11228   EVT VT = N->getValueType(0);
11229   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11230     return SDValue();
11231 
11232   if (VT.isScalableVector())
11233     return performSVEAndCombine(N, DCI);
11234 
11235   // The combining code below works only for NEON vectors. In particular, it
11236   // does not work for SVE when dealing with vectors wider than 128 bits.
11237   if (!(VT.is64BitVector() || VT.is128BitVector()))
11238     return SDValue();
11239 
11240   BuildVectorSDNode *BVN =
11241       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11242   if (!BVN)
11243     return SDValue();
11244 
11245   // AND does not accept an immediate, so check if we can use a BIC immediate
11246   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11247   // pattern in isel, because some immediates may be lowered to the preferred
11248   // (and x, (movi imm)) form, even though an mvni representation also exists.
11249   APInt DefBits(VT.getSizeInBits(), 0);
11250   APInt UndefBits(VT.getSizeInBits(), 0);
11251   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11252     SDValue NewOp;
11253 
11254     DefBits = ~DefBits;
11255     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11256                                     DefBits, &LHS)) ||
11257         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11258                                     DefBits, &LHS)))
11259       return NewOp;
11260 
11261     UndefBits = ~UndefBits;
11262     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11263                                     UndefBits, &LHS)) ||
11264         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11265                                     UndefBits, &LHS)))
11266       return NewOp;
11267   }
11268 
11269   return SDValue();
11270 }
11271 
11272 static SDValue performSRLCombine(SDNode *N,
11273                                  TargetLowering::DAGCombinerInfo &DCI) {
11274   SelectionDAG &DAG = DCI.DAG;
11275   EVT VT = N->getValueType(0);
11276   if (VT != MVT::i32 && VT != MVT::i64)
11277     return SDValue();
11278 
11279   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11280   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11281   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11282   SDValue N0 = N->getOperand(0);
11283   if (N0.getOpcode() == ISD::BSWAP) {
11284     SDLoc DL(N);
11285     SDValue N1 = N->getOperand(1);
11286     SDValue N00 = N0.getOperand(0);
11287     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11288       uint64_t ShiftAmt = C->getZExtValue();
11289       if (VT == MVT::i32 && ShiftAmt == 16 &&
11290           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11291         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11292       if (VT == MVT::i64 && ShiftAmt == 32 &&
11293           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11294         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11295     }
11296   }
11297   return SDValue();
11298 }
11299 
11300 // Attempt to form urhadd(OpA, OpB) from
11301 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
11302 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
11303 // The original form of the first expression is
11304 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
11305 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
11306 // Before this function is called the srl will have been lowered to
11307 // AArch64ISD::VLSHR.
11308 // This pass can also recognize signed variants of the patterns that use sign
11309 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
11310 // shadd(OpA, OpB) from them.
11311 static SDValue
11312 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11313                              SelectionDAG &DAG) {
11314   EVT VT = N->getValueType(0);
11315 
11316   // Since we are looking for a right shift by a constant value of 1 and we are
11317   // operating on types at least 16 bits in length (sign/zero extended OpA and
11318   // OpB, which are at least 8 bits), it follows that the truncate will always
11319   // discard the shifted-in bit and therefore the right shift will be logical
11320   // regardless of the signedness of OpA and OpB.
11321   SDValue Shift = N->getOperand(0);
11322   if (Shift.getOpcode() != AArch64ISD::VLSHR)
11323     return SDValue();
11324 
11325   // Is the right shift using an immediate value of 1?
11326   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
11327   if (ShiftAmount != 1)
11328     return SDValue();
11329 
11330   SDValue ExtendOpA, ExtendOpB;
11331   SDValue ShiftOp0 = Shift.getOperand(0);
11332   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
11333   if (ShiftOp0Opc == ISD::SUB) {
11334 
11335     SDValue Xor = ShiftOp0.getOperand(1);
11336     if (Xor.getOpcode() != ISD::XOR)
11337       return SDValue();
11338 
11339     // Is the XOR using a constant amount of all ones in the right hand side?
11340     uint64_t C;
11341     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
11342       return SDValue();
11343 
11344     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
11345     APInt CAsAPInt(ElemSizeInBits, C);
11346     if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
11347       return SDValue();
11348 
11349     ExtendOpA = Xor.getOperand(0);
11350     ExtendOpB = ShiftOp0.getOperand(0);
11351   } else if (ShiftOp0Opc == ISD::ADD) {
11352     ExtendOpA = ShiftOp0.getOperand(0);
11353     ExtendOpB = ShiftOp0.getOperand(1);
11354   } else
11355     return SDValue();
11356 
11357   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
11358   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
11359   if (!(ExtendOpAOpc == ExtendOpBOpc &&
11360         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
11361     return SDValue();
11362 
11363   // Is the result of the right shift being truncated to the same value type as
11364   // the original operands, OpA and OpB?
11365   SDValue OpA = ExtendOpA.getOperand(0);
11366   SDValue OpB = ExtendOpB.getOperand(0);
11367   EVT OpAVT = OpA.getValueType();
11368   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
11369   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
11370     return SDValue();
11371 
11372   SDLoc DL(N);
11373   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
11374   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
11375   unsigned HADDOpc = IsSignExtend
11376                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
11377                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
11378   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
11379 
11380   return ResultHADD;
11381 }
11382 
11383 static SDValue performConcatVectorsCombine(SDNode *N,
11384                                            TargetLowering::DAGCombinerInfo &DCI,
11385                                            SelectionDAG &DAG) {
11386   SDLoc dl(N);
11387   EVT VT = N->getValueType(0);
11388   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11389   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11390 
11391   // Optimize concat_vectors of truncated vectors, where the intermediate
11392   // type is illegal, to avoid said illegality,  e.g.,
11393   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11394   //                          (v2i16 (truncate (v2i64)))))
11395   // ->
11396   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11397   //                                    (v4i32 (bitcast (v2i64))),
11398   //                                    <0, 2, 4, 6>)))
11399   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
11400   // on both input and result type, so we might generate worse code.
11401   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
11402   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
11403       N1Opc == ISD::TRUNCATE) {
11404     SDValue N00 = N0->getOperand(0);
11405     SDValue N10 = N1->getOperand(0);
11406     EVT N00VT = N00.getValueType();
11407 
11408     if (N00VT == N10.getValueType() &&
11409         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
11410         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
11411       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
11412       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
11413       for (size_t i = 0; i < Mask.size(); ++i)
11414         Mask[i] = i * 2;
11415       return DAG.getNode(ISD::TRUNCATE, dl, VT,
11416                          DAG.getVectorShuffle(
11417                              MidVT, dl,
11418                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
11419                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
11420     }
11421   }
11422 
11423   // Wait 'til after everything is legalized to try this. That way we have
11424   // legal vector types and such.
11425   if (DCI.isBeforeLegalizeOps())
11426     return SDValue();
11427 
11428   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
11429   // subvectors from the same original vectors. Combine these into a single
11430   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
11431   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
11432   //                                        extract_subvector (v16i8 OpB,
11433   //                                        <0>))),
11434   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
11435   //                                        extract_subvector (v16i8 OpB,
11436   //                                        <8>)))))
11437   // ->
11438   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
11439   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
11440       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
11441        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
11442     SDValue N00 = N0->getOperand(0);
11443     SDValue N01 = N0->getOperand(1);
11444     SDValue N10 = N1->getOperand(0);
11445     SDValue N11 = N1->getOperand(1);
11446 
11447     EVT N00VT = N00.getValueType();
11448     EVT N10VT = N10.getValueType();
11449 
11450     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11451         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11452         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11453         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
11454       SDValue N00Source = N00->getOperand(0);
11455       SDValue N01Source = N01->getOperand(0);
11456       SDValue N10Source = N10->getOperand(0);
11457       SDValue N11Source = N11->getOperand(0);
11458 
11459       if (N00Source == N10Source && N01Source == N11Source &&
11460           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
11461         assert(N0.getValueType() == N1.getValueType());
11462 
11463         uint64_t N00Index = N00.getConstantOperandVal(1);
11464         uint64_t N01Index = N01.getConstantOperandVal(1);
11465         uint64_t N10Index = N10.getConstantOperandVal(1);
11466         uint64_t N11Index = N11.getConstantOperandVal(1);
11467 
11468         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
11469             N10Index == N00VT.getVectorNumElements())
11470           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
11471       }
11472     }
11473   }
11474 
11475   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
11476   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
11477   // canonicalise to that.
11478   if (N0 == N1 && VT.getVectorNumElements() == 2) {
11479     assert(VT.getScalarSizeInBits() == 64);
11480     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
11481                        DAG.getConstant(0, dl, MVT::i64));
11482   }
11483 
11484   // Canonicalise concat_vectors so that the right-hand vector has as few
11485   // bit-casts as possible before its real operation. The primary matching
11486   // destination for these operations will be the narrowing "2" instructions,
11487   // which depend on the operation being performed on this right-hand vector.
11488   // For example,
11489   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
11490   // becomes
11491   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
11492 
11493   if (N1Opc != ISD::BITCAST)
11494     return SDValue();
11495   SDValue RHS = N1->getOperand(0);
11496   MVT RHSTy = RHS.getValueType().getSimpleVT();
11497   // If the RHS is not a vector, this is not the pattern we're looking for.
11498   if (!RHSTy.isVector())
11499     return SDValue();
11500 
11501   LLVM_DEBUG(
11502       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
11503 
11504   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
11505                                   RHSTy.getVectorNumElements() * 2);
11506   return DAG.getNode(ISD::BITCAST, dl, VT,
11507                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
11508                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
11509                                  RHS));
11510 }
11511 
11512 static SDValue tryCombineFixedPointConvert(SDNode *N,
11513                                            TargetLowering::DAGCombinerInfo &DCI,
11514                                            SelectionDAG &DAG) {
11515   // Wait until after everything is legalized to try this. That way we have
11516   // legal vector types and such.
11517   if (DCI.isBeforeLegalizeOps())
11518     return SDValue();
11519   // Transform a scalar conversion of a value from a lane extract into a
11520   // lane extract of a vector conversion. E.g., from foo1 to foo2:
11521   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
11522   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
11523   //
11524   // The second form interacts better with instruction selection and the
11525   // register allocator to avoid cross-class register copies that aren't
11526   // coalescable due to a lane reference.
11527 
11528   // Check the operand and see if it originates from a lane extract.
11529   SDValue Op1 = N->getOperand(1);
11530   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11531     // Yep, no additional predication needed. Perform the transform.
11532     SDValue IID = N->getOperand(0);
11533     SDValue Shift = N->getOperand(2);
11534     SDValue Vec = Op1.getOperand(0);
11535     SDValue Lane = Op1.getOperand(1);
11536     EVT ResTy = N->getValueType(0);
11537     EVT VecResTy;
11538     SDLoc DL(N);
11539 
11540     // The vector width should be 128 bits by the time we get here, even
11541     // if it started as 64 bits (the extract_vector handling will have
11542     // done so).
11543     assert(Vec.getValueSizeInBits() == 128 &&
11544            "unexpected vector size on extract_vector_elt!");
11545     if (Vec.getValueType() == MVT::v4i32)
11546       VecResTy = MVT::v4f32;
11547     else if (Vec.getValueType() == MVT::v2i64)
11548       VecResTy = MVT::v2f64;
11549     else
11550       llvm_unreachable("unexpected vector type!");
11551 
11552     SDValue Convert =
11553         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
11554     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
11555   }
11556   return SDValue();
11557 }
11558 
11559 // AArch64 high-vector "long" operations are formed by performing the non-high
11560 // version on an extract_subvector of each operand which gets the high half:
11561 //
11562 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
11563 //
11564 // However, there are cases which don't have an extract_high explicitly, but
11565 // have another operation that can be made compatible with one for free. For
11566 // example:
11567 //
11568 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
11569 //
11570 // This routine does the actual conversion of such DUPs, once outer routines
11571 // have determined that everything else is in order.
11572 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
11573 // similarly here.
11574 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
11575   switch (N.getOpcode()) {
11576   case AArch64ISD::DUP:
11577   case AArch64ISD::DUPLANE8:
11578   case AArch64ISD::DUPLANE16:
11579   case AArch64ISD::DUPLANE32:
11580   case AArch64ISD::DUPLANE64:
11581   case AArch64ISD::MOVI:
11582   case AArch64ISD::MOVIshift:
11583   case AArch64ISD::MOVIedit:
11584   case AArch64ISD::MOVImsl:
11585   case AArch64ISD::MVNIshift:
11586   case AArch64ISD::MVNImsl:
11587     break;
11588   default:
11589     // FMOV could be supported, but isn't very useful, as it would only occur
11590     // if you passed a bitcast' floating point immediate to an eligible long
11591     // integer op (addl, smull, ...).
11592     return SDValue();
11593   }
11594 
11595   MVT NarrowTy = N.getSimpleValueType();
11596   if (!NarrowTy.is64BitVector())
11597     return SDValue();
11598 
11599   MVT ElementTy = NarrowTy.getVectorElementType();
11600   unsigned NumElems = NarrowTy.getVectorNumElements();
11601   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
11602 
11603   SDLoc dl(N);
11604   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
11605                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
11606                      DAG.getConstant(NumElems, dl, MVT::i64));
11607 }
11608 
11609 static bool isEssentiallyExtractHighSubvector(SDValue N) {
11610   if (N.getOpcode() == ISD::BITCAST)
11611     N = N.getOperand(0);
11612   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11613     return false;
11614   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
11615          N.getOperand(0).getValueType().getVectorNumElements() / 2;
11616 }
11617 
11618 /// Helper structure to keep track of ISD::SET_CC operands.
11619 struct GenericSetCCInfo {
11620   const SDValue *Opnd0;
11621   const SDValue *Opnd1;
11622   ISD::CondCode CC;
11623 };
11624 
11625 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
11626 struct AArch64SetCCInfo {
11627   const SDValue *Cmp;
11628   AArch64CC::CondCode CC;
11629 };
11630 
11631 /// Helper structure to keep track of SetCC information.
11632 union SetCCInfo {
11633   GenericSetCCInfo Generic;
11634   AArch64SetCCInfo AArch64;
11635 };
11636 
11637 /// Helper structure to be able to read SetCC information.  If set to
11638 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
11639 /// GenericSetCCInfo.
11640 struct SetCCInfoAndKind {
11641   SetCCInfo Info;
11642   bool IsAArch64;
11643 };
11644 
11645 /// Check whether or not \p Op is a SET_CC operation, either a generic or
11646 /// an
11647 /// AArch64 lowered one.
11648 /// \p SetCCInfo is filled accordingly.
11649 /// \post SetCCInfo is meanginfull only when this function returns true.
11650 /// \return True when Op is a kind of SET_CC operation.
11651 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
11652   // If this is a setcc, this is straight forward.
11653   if (Op.getOpcode() == ISD::SETCC) {
11654     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
11655     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
11656     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11657     SetCCInfo.IsAArch64 = false;
11658     return true;
11659   }
11660   // Otherwise, check if this is a matching csel instruction.
11661   // In other words:
11662   // - csel 1, 0, cc
11663   // - csel 0, 1, !cc
11664   if (Op.getOpcode() != AArch64ISD::CSEL)
11665     return false;
11666   // Set the information about the operands.
11667   // TODO: we want the operands of the Cmp not the csel
11668   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
11669   SetCCInfo.IsAArch64 = true;
11670   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
11671       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11672 
11673   // Check that the operands matches the constraints:
11674   // (1) Both operands must be constants.
11675   // (2) One must be 1 and the other must be 0.
11676   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
11677   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11678 
11679   // Check (1).
11680   if (!TValue || !FValue)
11681     return false;
11682 
11683   // Check (2).
11684   if (!TValue->isOne()) {
11685     // Update the comparison when we are interested in !cc.
11686     std::swap(TValue, FValue);
11687     SetCCInfo.Info.AArch64.CC =
11688         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
11689   }
11690   return TValue->isOne() && FValue->isNullValue();
11691 }
11692 
11693 // Returns true if Op is setcc or zext of setcc.
11694 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
11695   if (isSetCC(Op, Info))
11696     return true;
11697   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
11698     isSetCC(Op->getOperand(0), Info));
11699 }
11700 
11701 // The folding we want to perform is:
11702 // (add x, [zext] (setcc cc ...) )
11703 //   -->
11704 // (csel x, (add x, 1), !cc ...)
11705 //
11706 // The latter will get matched to a CSINC instruction.
11707 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
11708   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
11709   SDValue LHS = Op->getOperand(0);
11710   SDValue RHS = Op->getOperand(1);
11711   SetCCInfoAndKind InfoAndKind;
11712 
11713   // If neither operand is a SET_CC, give up.
11714   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
11715     std::swap(LHS, RHS);
11716     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
11717       return SDValue();
11718   }
11719 
11720   // FIXME: This could be generatized to work for FP comparisons.
11721   EVT CmpVT = InfoAndKind.IsAArch64
11722                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
11723                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
11724   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
11725     return SDValue();
11726 
11727   SDValue CCVal;
11728   SDValue Cmp;
11729   SDLoc dl(Op);
11730   if (InfoAndKind.IsAArch64) {
11731     CCVal = DAG.getConstant(
11732         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
11733         MVT::i32);
11734     Cmp = *InfoAndKind.Info.AArch64.Cmp;
11735   } else
11736     Cmp = getAArch64Cmp(
11737         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
11738         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
11739         dl);
11740 
11741   EVT VT = Op->getValueType(0);
11742   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
11743   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
11744 }
11745 
11746 // The basic add/sub long vector instructions have variants with "2" on the end
11747 // which act on the high-half of their inputs. They are normally matched by
11748 // patterns like:
11749 //
11750 // (add (zeroext (extract_high LHS)),
11751 //      (zeroext (extract_high RHS)))
11752 // -> uaddl2 vD, vN, vM
11753 //
11754 // However, if one of the extracts is something like a duplicate, this
11755 // instruction can still be used profitably. This function puts the DAG into a
11756 // more appropriate form for those patterns to trigger.
11757 static SDValue performAddSubLongCombine(SDNode *N,
11758                                         TargetLowering::DAGCombinerInfo &DCI,
11759                                         SelectionDAG &DAG) {
11760   if (DCI.isBeforeLegalizeOps())
11761     return SDValue();
11762 
11763   MVT VT = N->getSimpleValueType(0);
11764   if (!VT.is128BitVector()) {
11765     if (N->getOpcode() == ISD::ADD)
11766       return performSetccAddFolding(N, DAG);
11767     return SDValue();
11768   }
11769 
11770   // Make sure both branches are extended in the same way.
11771   SDValue LHS = N->getOperand(0);
11772   SDValue RHS = N->getOperand(1);
11773   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
11774        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
11775       LHS.getOpcode() != RHS.getOpcode())
11776     return SDValue();
11777 
11778   unsigned ExtType = LHS.getOpcode();
11779 
11780   // It's not worth doing if at least one of the inputs isn't already an
11781   // extract, but we don't know which it'll be so we have to try both.
11782   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
11783     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
11784     if (!RHS.getNode())
11785       return SDValue();
11786 
11787     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
11788   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
11789     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
11790     if (!LHS.getNode())
11791       return SDValue();
11792 
11793     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
11794   }
11795 
11796   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
11797 }
11798 
11799 // Massage DAGs which we can use the high-half "long" operations on into
11800 // something isel will recognize better. E.g.
11801 //
11802 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
11803 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
11804 //                     (extract_high (v2i64 (dup128 scalar)))))
11805 //
11806 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
11807                                        TargetLowering::DAGCombinerInfo &DCI,
11808                                        SelectionDAG &DAG) {
11809   if (DCI.isBeforeLegalizeOps())
11810     return SDValue();
11811 
11812   SDValue LHS = N->getOperand(1);
11813   SDValue RHS = N->getOperand(2);
11814   assert(LHS.getValueType().is64BitVector() &&
11815          RHS.getValueType().is64BitVector() &&
11816          "unexpected shape for long operation");
11817 
11818   // Either node could be a DUP, but it's not worth doing both of them (you'd
11819   // just as well use the non-high version) so look for a corresponding extract
11820   // operation on the other "wing".
11821   if (isEssentiallyExtractHighSubvector(LHS)) {
11822     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
11823     if (!RHS.getNode())
11824       return SDValue();
11825   } else if (isEssentiallyExtractHighSubvector(RHS)) {
11826     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
11827     if (!LHS.getNode())
11828       return SDValue();
11829   }
11830 
11831   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
11832                      N->getOperand(0), LHS, RHS);
11833 }
11834 
11835 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
11836   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
11837   unsigned ElemBits = ElemTy.getSizeInBits();
11838 
11839   int64_t ShiftAmount;
11840   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
11841     APInt SplatValue, SplatUndef;
11842     unsigned SplatBitSize;
11843     bool HasAnyUndefs;
11844     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11845                               HasAnyUndefs, ElemBits) ||
11846         SplatBitSize != ElemBits)
11847       return SDValue();
11848 
11849     ShiftAmount = SplatValue.getSExtValue();
11850   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
11851     ShiftAmount = CVN->getSExtValue();
11852   } else
11853     return SDValue();
11854 
11855   unsigned Opcode;
11856   bool IsRightShift;
11857   switch (IID) {
11858   default:
11859     llvm_unreachable("Unknown shift intrinsic");
11860   case Intrinsic::aarch64_neon_sqshl:
11861     Opcode = AArch64ISD::SQSHL_I;
11862     IsRightShift = false;
11863     break;
11864   case Intrinsic::aarch64_neon_uqshl:
11865     Opcode = AArch64ISD::UQSHL_I;
11866     IsRightShift = false;
11867     break;
11868   case Intrinsic::aarch64_neon_srshl:
11869     Opcode = AArch64ISD::SRSHR_I;
11870     IsRightShift = true;
11871     break;
11872   case Intrinsic::aarch64_neon_urshl:
11873     Opcode = AArch64ISD::URSHR_I;
11874     IsRightShift = true;
11875     break;
11876   case Intrinsic::aarch64_neon_sqshlu:
11877     Opcode = AArch64ISD::SQSHLU_I;
11878     IsRightShift = false;
11879     break;
11880   case Intrinsic::aarch64_neon_sshl:
11881   case Intrinsic::aarch64_neon_ushl:
11882     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11883     // left shift for positive shift amounts. Below, we only replace the current
11884     // node with VSHL, if this condition is met.
11885     Opcode = AArch64ISD::VSHL;
11886     IsRightShift = false;
11887     break;
11888   }
11889 
11890   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11891     SDLoc dl(N);
11892     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11893                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11894   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11895     SDLoc dl(N);
11896     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11897                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
11898   }
11899 
11900   return SDValue();
11901 }
11902 
11903 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11904 // the intrinsics must be legal and take an i32, this means there's almost
11905 // certainly going to be a zext in the DAG which we can eliminate.
11906 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11907   SDValue AndN = N->getOperand(2);
11908   if (AndN.getOpcode() != ISD::AND)
11909     return SDValue();
11910 
11911   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11912   if (!CMask || CMask->getZExtValue() != Mask)
11913     return SDValue();
11914 
11915   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11916                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11917 }
11918 
11919 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11920                                            SelectionDAG &DAG) {
11921   SDLoc dl(N);
11922   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11923                      DAG.getNode(Opc, dl,
11924                                  N->getOperand(1).getSimpleValueType(),
11925                                  N->getOperand(1)),
11926                      DAG.getConstant(0, dl, MVT::i64));
11927 }
11928 
11929 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11930                                     SelectionDAG &DAG) {
11931   SDLoc dl(N);
11932   LLVMContext &Ctx = *DAG.getContext();
11933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11934 
11935   EVT VT = N->getValueType(0);
11936   SDValue Pred = N->getOperand(1);
11937   SDValue Data = N->getOperand(2);
11938   EVT DataVT = Data.getValueType();
11939 
11940   if (DataVT.getVectorElementType().isScalarInteger() &&
11941       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11942     if (!TLI.isTypeLegal(DataVT))
11943       return SDValue();
11944 
11945     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11946       AArch64::NeonBitsPerVector / VT.getSizeInBits());
11947     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11948     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11949     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11950 
11951     return Result;
11952   }
11953 
11954   return SDValue();
11955 }
11956 
11957 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11958   SDLoc DL(N);
11959   SDValue Op1 = N->getOperand(1);
11960   SDValue Op2 = N->getOperand(2);
11961   EVT ScalarTy = Op1.getValueType();
11962 
11963   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11964     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11965     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11966   }
11967 
11968   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11969                      Op1, Op2);
11970 }
11971 
11972 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11973   SDLoc dl(N);
11974   SDValue Scalar = N->getOperand(3);
11975   EVT ScalarTy = Scalar.getValueType();
11976 
11977   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11978     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11979 
11980   SDValue Passthru = N->getOperand(1);
11981   SDValue Pred = N->getOperand(2);
11982   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
11983                      Pred, Scalar, Passthru);
11984 }
11985 
11986 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11987   SDLoc dl(N);
11988   LLVMContext &Ctx = *DAG.getContext();
11989   EVT VT = N->getValueType(0);
11990 
11991   assert(VT.isScalableVector() && "Expected a scalable vector.");
11992 
11993   // Current lowering only supports the SVE-ACLE types.
11994   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11995     return SDValue();
11996 
11997   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11998   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11999   EVT ByteVT =
12000       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
12001 
12002   // Convert everything to the domain of EXT (i.e bytes).
12003   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
12004   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
12005   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
12006                             DAG.getConstant(ElemSize, dl, MVT::i32));
12007 
12008   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
12009   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
12010 }
12011 
12012 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
12013                                         TargetLowering::DAGCombinerInfo &DCI,
12014                                         SelectionDAG &DAG) {
12015   if (DCI.isBeforeLegalize())
12016     return SDValue();
12017 
12018   SDValue Comparator = N->getOperand(3);
12019   if (Comparator.getOpcode() == AArch64ISD::DUP ||
12020       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
12021     unsigned IID = getIntrinsicID(N);
12022     EVT VT = N->getValueType(0);
12023     EVT CmpVT = N->getOperand(2).getValueType();
12024     SDValue Pred = N->getOperand(1);
12025     SDValue Imm;
12026     SDLoc DL(N);
12027 
12028     switch (IID) {
12029     default:
12030       llvm_unreachable("Called with wrong intrinsic!");
12031       break;
12032 
12033     // Signed comparisons
12034     case Intrinsic::aarch64_sve_cmpeq_wide:
12035     case Intrinsic::aarch64_sve_cmpne_wide:
12036     case Intrinsic::aarch64_sve_cmpge_wide:
12037     case Intrinsic::aarch64_sve_cmpgt_wide:
12038     case Intrinsic::aarch64_sve_cmplt_wide:
12039     case Intrinsic::aarch64_sve_cmple_wide: {
12040       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12041         int64_t ImmVal = CN->getSExtValue();
12042         if (ImmVal >= -16 && ImmVal <= 15)
12043           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12044         else
12045           return SDValue();
12046       }
12047       break;
12048     }
12049     // Unsigned comparisons
12050     case Intrinsic::aarch64_sve_cmphs_wide:
12051     case Intrinsic::aarch64_sve_cmphi_wide:
12052     case Intrinsic::aarch64_sve_cmplo_wide:
12053     case Intrinsic::aarch64_sve_cmpls_wide:  {
12054       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12055         uint64_t ImmVal = CN->getZExtValue();
12056         if (ImmVal <= 127)
12057           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12058         else
12059           return SDValue();
12060       }
12061       break;
12062     }
12063     }
12064 
12065     if (!Imm)
12066       return SDValue();
12067 
12068     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
12069     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
12070                        N->getOperand(2), Splat, DAG.getCondCode(CC));
12071   }
12072 
12073   return SDValue();
12074 }
12075 
12076 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
12077                         AArch64CC::CondCode Cond) {
12078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12079 
12080   SDLoc DL(Op);
12081   assert(Op.getValueType().isScalableVector() &&
12082          TLI.isTypeLegal(Op.getValueType()) &&
12083          "Expected legal scalable vector type!");
12084 
12085   // Ensure target specific opcodes are using legal type.
12086   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12087   SDValue TVal = DAG.getConstant(1, DL, OutVT);
12088   SDValue FVal = DAG.getConstant(0, DL, OutVT);
12089 
12090   // Set condition code (CC) flags.
12091   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
12092 
12093   // Convert CC to integer based on requested condition.
12094   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
12095   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
12096   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
12097   return DAG.getZExtOrTrunc(Res, DL, VT);
12098 }
12099 
12100 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
12101                                      SelectionDAG &DAG) {
12102   SDLoc DL(N);
12103 
12104   SDValue Pred = N->getOperand(1);
12105   SDValue VecToReduce = N->getOperand(2);
12106 
12107   EVT ReduceVT = VecToReduce.getValueType();
12108   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12109 
12110   // SVE reductions set the whole vector register with the first element
12111   // containing the reduction result, which we'll now extract.
12112   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12113   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12114                      Zero);
12115 }
12116 
12117 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
12118                                             SelectionDAG &DAG) {
12119   SDLoc DL(N);
12120 
12121   SDValue Pred = N->getOperand(1);
12122   SDValue InitVal = N->getOperand(2);
12123   SDValue VecToReduce = N->getOperand(3);
12124   EVT ReduceVT = VecToReduce.getValueType();
12125 
12126   // Ordered reductions use the first lane of the result vector as the
12127   // reduction's initial value.
12128   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12129   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
12130                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
12131 
12132   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
12133 
12134   // SVE reductions set the whole vector register with the first element
12135   // containing the reduction result, which we'll now extract.
12136   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12137                      Zero);
12138 }
12139 
12140 // If a merged operation has no inactive lanes we can relax it to a predicated
12141 // or unpredicated operation, which potentially allows better isel (perhaps
12142 // using immediate forms) or relaxing register reuse requirements.
12143 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
12144                                        SelectionDAG &DAG) {
12145   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
12146   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
12147   SDValue Pg = N->getOperand(1);
12148 
12149   // ISD way to specify an all active predicate.
12150   if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
12151       (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
12152     return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
12153                        N->getOperand(2), N->getOperand(3));
12154 
12155   // FUTURE: SplatVector(true)
12156   return SDValue();
12157 }
12158 
12159 static SDValue performIntrinsicCombine(SDNode *N,
12160                                        TargetLowering::DAGCombinerInfo &DCI,
12161                                        const AArch64Subtarget *Subtarget) {
12162   SelectionDAG &DAG = DCI.DAG;
12163   unsigned IID = getIntrinsicID(N);
12164   switch (IID) {
12165   default:
12166     break;
12167   case Intrinsic::aarch64_neon_vcvtfxs2fp:
12168   case Intrinsic::aarch64_neon_vcvtfxu2fp:
12169     return tryCombineFixedPointConvert(N, DCI, DAG);
12170   case Intrinsic::aarch64_neon_saddv:
12171     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
12172   case Intrinsic::aarch64_neon_uaddv:
12173     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
12174   case Intrinsic::aarch64_neon_sminv:
12175     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
12176   case Intrinsic::aarch64_neon_uminv:
12177     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
12178   case Intrinsic::aarch64_neon_smaxv:
12179     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
12180   case Intrinsic::aarch64_neon_umaxv:
12181     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
12182   case Intrinsic::aarch64_neon_fmax:
12183     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
12184                        N->getOperand(1), N->getOperand(2));
12185   case Intrinsic::aarch64_neon_fmin:
12186     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
12187                        N->getOperand(1), N->getOperand(2));
12188   case Intrinsic::aarch64_neon_fmaxnm:
12189     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
12190                        N->getOperand(1), N->getOperand(2));
12191   case Intrinsic::aarch64_neon_fminnm:
12192     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
12193                        N->getOperand(1), N->getOperand(2));
12194   case Intrinsic::aarch64_neon_smull:
12195   case Intrinsic::aarch64_neon_umull:
12196   case Intrinsic::aarch64_neon_pmull:
12197   case Intrinsic::aarch64_neon_sqdmull:
12198     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
12199   case Intrinsic::aarch64_neon_sqshl:
12200   case Intrinsic::aarch64_neon_uqshl:
12201   case Intrinsic::aarch64_neon_sqshlu:
12202   case Intrinsic::aarch64_neon_srshl:
12203   case Intrinsic::aarch64_neon_urshl:
12204   case Intrinsic::aarch64_neon_sshl:
12205   case Intrinsic::aarch64_neon_ushl:
12206     return tryCombineShiftImm(IID, N, DAG);
12207   case Intrinsic::aarch64_crc32b:
12208   case Intrinsic::aarch64_crc32cb:
12209     return tryCombineCRC32(0xff, N, DAG);
12210   case Intrinsic::aarch64_crc32h:
12211   case Intrinsic::aarch64_crc32ch:
12212     return tryCombineCRC32(0xffff, N, DAG);
12213   case Intrinsic::aarch64_sve_smaxv:
12214     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
12215   case Intrinsic::aarch64_sve_umaxv:
12216     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
12217   case Intrinsic::aarch64_sve_sminv:
12218     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
12219   case Intrinsic::aarch64_sve_uminv:
12220     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
12221   case Intrinsic::aarch64_sve_orv:
12222     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
12223   case Intrinsic::aarch64_sve_eorv:
12224     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
12225   case Intrinsic::aarch64_sve_andv:
12226     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
12227   case Intrinsic::aarch64_sve_index:
12228     return LowerSVEIntrinsicIndex(N, DAG);
12229   case Intrinsic::aarch64_sve_dup:
12230     return LowerSVEIntrinsicDUP(N, DAG);
12231   case Intrinsic::aarch64_sve_dup_x:
12232     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
12233                        N->getOperand(1));
12234   case Intrinsic::aarch64_sve_ext:
12235     return LowerSVEIntrinsicEXT(N, DAG);
12236   case Intrinsic::aarch64_sve_smin:
12237     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
12238   case Intrinsic::aarch64_sve_umin:
12239     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
12240   case Intrinsic::aarch64_sve_smax:
12241     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
12242   case Intrinsic::aarch64_sve_umax:
12243     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
12244   case Intrinsic::aarch64_sve_lsl:
12245     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
12246   case Intrinsic::aarch64_sve_lsr:
12247     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
12248   case Intrinsic::aarch64_sve_asr:
12249     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
12250   case Intrinsic::aarch64_sve_cmphs:
12251     if (!N->getOperand(2).getValueType().isFloatingPoint())
12252       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12253                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12254                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
12255     break;
12256   case Intrinsic::aarch64_sve_cmphi:
12257     if (!N->getOperand(2).getValueType().isFloatingPoint())
12258       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12259                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12260                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
12261     break;
12262   case Intrinsic::aarch64_sve_cmpge:
12263     if (!N->getOperand(2).getValueType().isFloatingPoint())
12264       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12265                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12266                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
12267     break;
12268   case Intrinsic::aarch64_sve_cmpgt:
12269     if (!N->getOperand(2).getValueType().isFloatingPoint())
12270       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12271                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12272                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12273     break;
12274   case Intrinsic::aarch64_sve_cmpeq:
12275     if (!N->getOperand(2).getValueType().isFloatingPoint())
12276       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12277                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12278                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12279     break;
12280   case Intrinsic::aarch64_sve_cmpne:
12281     if (!N->getOperand(2).getValueType().isFloatingPoint())
12282       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12283                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12284                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12285     break;
12286   case Intrinsic::aarch64_sve_fadda:
12287     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12288   case Intrinsic::aarch64_sve_faddv:
12289     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12290   case Intrinsic::aarch64_sve_fmaxnmv:
12291     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12292   case Intrinsic::aarch64_sve_fmaxv:
12293     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12294   case Intrinsic::aarch64_sve_fminnmv:
12295     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12296   case Intrinsic::aarch64_sve_fminv:
12297     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12298   case Intrinsic::aarch64_sve_sel:
12299     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12300                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12301   case Intrinsic::aarch64_sve_cmpeq_wide:
12302     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12303   case Intrinsic::aarch64_sve_cmpne_wide:
12304     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12305   case Intrinsic::aarch64_sve_cmpge_wide:
12306     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12307   case Intrinsic::aarch64_sve_cmpgt_wide:
12308     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12309   case Intrinsic::aarch64_sve_cmplt_wide:
12310     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12311   case Intrinsic::aarch64_sve_cmple_wide:
12312     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12313   case Intrinsic::aarch64_sve_cmphs_wide:
12314     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12315   case Intrinsic::aarch64_sve_cmphi_wide:
12316     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12317   case Intrinsic::aarch64_sve_cmplo_wide:
12318     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12319   case Intrinsic::aarch64_sve_cmpls_wide:
12320     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12321   case Intrinsic::aarch64_sve_ptest_any:
12322     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12323                     AArch64CC::ANY_ACTIVE);
12324   case Intrinsic::aarch64_sve_ptest_first:
12325     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12326                     AArch64CC::FIRST_ACTIVE);
12327   case Intrinsic::aarch64_sve_ptest_last:
12328     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12329                     AArch64CC::LAST_ACTIVE);
12330   }
12331   return SDValue();
12332 }
12333 
12334 static SDValue performExtendCombine(SDNode *N,
12335                                     TargetLowering::DAGCombinerInfo &DCI,
12336                                     SelectionDAG &DAG) {
12337   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12338   // we can convert that DUP into another extract_high (of a bigger DUP), which
12339   // helps the backend to decide that an sabdl2 would be useful, saving a real
12340   // extract_high operation.
12341   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12342       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
12343     SDNode *ABDNode = N->getOperand(0).getNode();
12344     unsigned IID = getIntrinsicID(ABDNode);
12345     if (IID == Intrinsic::aarch64_neon_sabd ||
12346         IID == Intrinsic::aarch64_neon_uabd) {
12347       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
12348       if (!NewABD.getNode())
12349         return SDValue();
12350 
12351       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
12352                          NewABD);
12353     }
12354   }
12355 
12356   // This is effectively a custom type legalization for AArch64.
12357   //
12358   // Type legalization will split an extend of a small, legal, type to a larger
12359   // illegal type by first splitting the destination type, often creating
12360   // illegal source types, which then get legalized in isel-confusing ways,
12361   // leading to really terrible codegen. E.g.,
12362   //   %result = v8i32 sext v8i8 %value
12363   // becomes
12364   //   %losrc = extract_subreg %value, ...
12365   //   %hisrc = extract_subreg %value, ...
12366   //   %lo = v4i32 sext v4i8 %losrc
12367   //   %hi = v4i32 sext v4i8 %hisrc
12368   // Things go rapidly downhill from there.
12369   //
12370   // For AArch64, the [sz]ext vector instructions can only go up one element
12371   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
12372   // take two instructions.
12373   //
12374   // This implies that the most efficient way to do the extend from v8i8
12375   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
12376   // the normal splitting to happen for the v8i16->v8i32.
12377 
12378   // This is pre-legalization to catch some cases where the default
12379   // type legalization will create ill-tempered code.
12380   if (!DCI.isBeforeLegalizeOps())
12381     return SDValue();
12382 
12383   // We're only interested in cleaning things up for non-legal vector types
12384   // here. If both the source and destination are legal, things will just
12385   // work naturally without any fiddling.
12386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12387   EVT ResVT = N->getValueType(0);
12388   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
12389     return SDValue();
12390   // If the vector type isn't a simple VT, it's beyond the scope of what
12391   // we're  worried about here. Let legalization do its thing and hope for
12392   // the best.
12393   SDValue Src = N->getOperand(0);
12394   EVT SrcVT = Src->getValueType(0);
12395   if (!ResVT.isSimple() || !SrcVT.isSimple())
12396     return SDValue();
12397 
12398   // If the source VT is a 64-bit fixed or scalable vector, we can play games
12399   // and get the better results we want.
12400   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
12401     return SDValue();
12402 
12403   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
12404   ElementCount SrcEC = SrcVT.getVectorElementCount();
12405   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
12406   SDLoc DL(N);
12407   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
12408 
12409   // Now split the rest of the operation into two halves, each with a 64
12410   // bit source.
12411   EVT LoVT, HiVT;
12412   SDValue Lo, Hi;
12413   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
12414 
12415   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
12416                                LoVT.getVectorElementCount());
12417   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12418                    DAG.getConstant(0, DL, MVT::i64));
12419   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12420                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
12421   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
12422   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
12423 
12424   // Now combine the parts back together so we still have a single result
12425   // like the combiner expects.
12426   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
12427 }
12428 
12429 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
12430                                SDValue SplatVal, unsigned NumVecElts) {
12431   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
12432   unsigned OrigAlignment = St.getAlignment();
12433   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
12434 
12435   // Create scalar stores. This is at least as good as the code sequence for a
12436   // split unaligned store which is a dup.s, ext.b, and two stores.
12437   // Most of the time the three stores should be replaced by store pair
12438   // instructions (stp).
12439   SDLoc DL(&St);
12440   SDValue BasePtr = St.getBasePtr();
12441   uint64_t BaseOffset = 0;
12442 
12443   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
12444   SDValue NewST1 =
12445       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
12446                    OrigAlignment, St.getMemOperand()->getFlags());
12447 
12448   // As this in ISel, we will not merge this add which may degrade results.
12449   if (BasePtr->getOpcode() == ISD::ADD &&
12450       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
12451     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
12452     BasePtr = BasePtr->getOperand(0);
12453   }
12454 
12455   unsigned Offset = EltOffset;
12456   while (--NumVecElts) {
12457     unsigned Alignment = MinAlign(OrigAlignment, Offset);
12458     SDValue OffsetPtr =
12459         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12460                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
12461     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
12462                           PtrInfo.getWithOffset(Offset), Alignment,
12463                           St.getMemOperand()->getFlags());
12464     Offset += EltOffset;
12465   }
12466   return NewST1;
12467 }
12468 
12469 // Returns an SVE type that ContentTy can be trivially sign or zero extended
12470 // into.
12471 static MVT getSVEContainerType(EVT ContentTy) {
12472   assert(ContentTy.isSimple() && "No SVE containers for extended types");
12473 
12474   switch (ContentTy.getSimpleVT().SimpleTy) {
12475   default:
12476     llvm_unreachable("No known SVE container for this MVT type");
12477   case MVT::nxv2i8:
12478   case MVT::nxv2i16:
12479   case MVT::nxv2i32:
12480   case MVT::nxv2i64:
12481   case MVT::nxv2f32:
12482   case MVT::nxv2f64:
12483     return MVT::nxv2i64;
12484   case MVT::nxv4i8:
12485   case MVT::nxv4i16:
12486   case MVT::nxv4i32:
12487   case MVT::nxv4f32:
12488     return MVT::nxv4i32;
12489   case MVT::nxv8i8:
12490   case MVT::nxv8i16:
12491   case MVT::nxv8f16:
12492   case MVT::nxv8bf16:
12493     return MVT::nxv8i16;
12494   case MVT::nxv16i8:
12495     return MVT::nxv16i8;
12496   }
12497 }
12498 
12499 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
12500   SDLoc DL(N);
12501   EVT VT = N->getValueType(0);
12502 
12503   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12504     return SDValue();
12505 
12506   EVT ContainerVT = VT;
12507   if (ContainerVT.isInteger())
12508     ContainerVT = getSVEContainerType(ContainerVT);
12509 
12510   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
12511   SDValue Ops[] = { N->getOperand(0), // Chain
12512                     N->getOperand(2), // Pg
12513                     N->getOperand(3), // Base
12514                     DAG.getValueType(VT) };
12515 
12516   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
12517   SDValue LoadChain = SDValue(Load.getNode(), 1);
12518 
12519   if (ContainerVT.isInteger() && (VT != ContainerVT))
12520     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
12521 
12522   return DAG.getMergeValues({ Load, LoadChain }, DL);
12523 }
12524 
12525 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
12526   SDLoc DL(N);
12527   EVT VT = N->getValueType(0);
12528   EVT PtrTy = N->getOperand(3).getValueType();
12529 
12530   if (VT == MVT::nxv8bf16 &&
12531       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12532     return SDValue();
12533 
12534   EVT LoadVT = VT;
12535   if (VT.isFloatingPoint())
12536     LoadVT = VT.changeTypeToInteger();
12537 
12538   auto *MINode = cast<MemIntrinsicSDNode>(N);
12539   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
12540   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
12541                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
12542                                 MINode->getOperand(2), PassThru,
12543                                 MINode->getMemoryVT(), MINode->getMemOperand(),
12544                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
12545 
12546    if (VT.isFloatingPoint()) {
12547      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
12548      return DAG.getMergeValues(Ops, DL);
12549    }
12550 
12551   return L;
12552 }
12553 
12554 template <unsigned Opcode>
12555 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
12556   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
12557                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
12558                 "Unsupported opcode.");
12559   SDLoc DL(N);
12560   EVT VT = N->getValueType(0);
12561   if (VT == MVT::nxv8bf16 &&
12562       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12563     return SDValue();
12564 
12565   EVT LoadVT = VT;
12566   if (VT.isFloatingPoint())
12567     LoadVT = VT.changeTypeToInteger();
12568 
12569   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
12570   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
12571   SDValue LoadChain = SDValue(Load.getNode(), 1);
12572 
12573   if (VT.isFloatingPoint())
12574     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
12575 
12576   return DAG.getMergeValues({Load, LoadChain}, DL);
12577 }
12578 
12579 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
12580   SDLoc DL(N);
12581   SDValue Data = N->getOperand(2);
12582   EVT DataVT = Data.getValueType();
12583   EVT HwSrcVt = getSVEContainerType(DataVT);
12584   SDValue InputVT = DAG.getValueType(DataVT);
12585 
12586   if (DataVT == MVT::nxv8bf16 &&
12587       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12588     return SDValue();
12589 
12590   if (DataVT.isFloatingPoint())
12591     InputVT = DAG.getValueType(HwSrcVt);
12592 
12593   SDValue SrcNew;
12594   if (Data.getValueType().isFloatingPoint())
12595     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
12596   else
12597     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
12598 
12599   SDValue Ops[] = { N->getOperand(0), // Chain
12600                     SrcNew,
12601                     N->getOperand(4), // Base
12602                     N->getOperand(3), // Pg
12603                     InputVT
12604                   };
12605 
12606   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
12607 }
12608 
12609 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
12610   SDLoc DL(N);
12611 
12612   SDValue Data = N->getOperand(2);
12613   EVT DataVT = Data.getValueType();
12614   EVT PtrTy = N->getOperand(4).getValueType();
12615 
12616   if (DataVT == MVT::nxv8bf16 &&
12617       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12618     return SDValue();
12619 
12620   if (DataVT.isFloatingPoint())
12621     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
12622 
12623   auto *MINode = cast<MemIntrinsicSDNode>(N);
12624   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
12625                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
12626                             MINode->getMemoryVT(), MINode->getMemOperand(),
12627                             ISD::UNINDEXED, false, false);
12628 }
12629 
12630 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
12631 /// load store optimizer pass will merge them to store pair stores.  This should
12632 /// be better than a movi to create the vector zero followed by a vector store
12633 /// if the zero constant is not re-used, since one instructions and one register
12634 /// live range will be removed.
12635 ///
12636 /// For example, the final generated code should be:
12637 ///
12638 ///   stp xzr, xzr, [x0]
12639 ///
12640 /// instead of:
12641 ///
12642 ///   movi v0.2d, #0
12643 ///   str q0, [x0]
12644 ///
12645 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12646   SDValue StVal = St.getValue();
12647   EVT VT = StVal.getValueType();
12648 
12649   // Avoid scalarizing zero splat stores for scalable vectors.
12650   if (VT.isScalableVector())
12651     return SDValue();
12652 
12653   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
12654   // 2, 3 or 4 i32 elements.
12655   int NumVecElts = VT.getVectorNumElements();
12656   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
12657          VT.getVectorElementType().getSizeInBits() == 64) ||
12658         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
12659          VT.getVectorElementType().getSizeInBits() == 32)))
12660     return SDValue();
12661 
12662   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
12663     return SDValue();
12664 
12665   // If the zero constant has more than one use then the vector store could be
12666   // better since the constant mov will be amortized and stp q instructions
12667   // should be able to be formed.
12668   if (!StVal.hasOneUse())
12669     return SDValue();
12670 
12671   // If the store is truncating then it's going down to i16 or smaller, which
12672   // means it can be implemented in a single store anyway.
12673   if (St.isTruncatingStore())
12674     return SDValue();
12675 
12676   // If the immediate offset of the address operand is too large for the stp
12677   // instruction, then bail out.
12678   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
12679     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
12680     if (Offset < -512 || Offset > 504)
12681       return SDValue();
12682   }
12683 
12684   for (int I = 0; I < NumVecElts; ++I) {
12685     SDValue EltVal = StVal.getOperand(I);
12686     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
12687       return SDValue();
12688   }
12689 
12690   // Use a CopyFromReg WZR/XZR here to prevent
12691   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
12692   SDLoc DL(&St);
12693   unsigned ZeroReg;
12694   EVT ZeroVT;
12695   if (VT.getVectorElementType().getSizeInBits() == 32) {
12696     ZeroReg = AArch64::WZR;
12697     ZeroVT = MVT::i32;
12698   } else {
12699     ZeroReg = AArch64::XZR;
12700     ZeroVT = MVT::i64;
12701   }
12702   SDValue SplatVal =
12703       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
12704   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12705 }
12706 
12707 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
12708 /// value. The load store optimizer pass will merge them to store pair stores.
12709 /// This has better performance than a splat of the scalar followed by a split
12710 /// vector store. Even if the stores are not merged it is four stores vs a dup,
12711 /// followed by an ext.b and two stores.
12712 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12713   SDValue StVal = St.getValue();
12714   EVT VT = StVal.getValueType();
12715 
12716   // Don't replace floating point stores, they possibly won't be transformed to
12717   // stp because of the store pair suppress pass.
12718   if (VT.isFloatingPoint())
12719     return SDValue();
12720 
12721   // We can express a splat as store pair(s) for 2 or 4 elements.
12722   unsigned NumVecElts = VT.getVectorNumElements();
12723   if (NumVecElts != 4 && NumVecElts != 2)
12724     return SDValue();
12725 
12726   // If the store is truncating then it's going down to i16 or smaller, which
12727   // means it can be implemented in a single store anyway.
12728   if (St.isTruncatingStore())
12729     return SDValue();
12730 
12731   // Check that this is a splat.
12732   // Make sure that each of the relevant vector element locations are inserted
12733   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
12734   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
12735   SDValue SplatVal;
12736   for (unsigned I = 0; I < NumVecElts; ++I) {
12737     // Check for insert vector elements.
12738     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
12739       return SDValue();
12740 
12741     // Check that same value is inserted at each vector element.
12742     if (I == 0)
12743       SplatVal = StVal.getOperand(1);
12744     else if (StVal.getOperand(1) != SplatVal)
12745       return SDValue();
12746 
12747     // Check insert element index.
12748     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
12749     if (!CIndex)
12750       return SDValue();
12751     uint64_t IndexVal = CIndex->getZExtValue();
12752     if (IndexVal >= NumVecElts)
12753       return SDValue();
12754     IndexNotInserted.reset(IndexVal);
12755 
12756     StVal = StVal.getOperand(0);
12757   }
12758   // Check that all vector element locations were inserted to.
12759   if (IndexNotInserted.any())
12760       return SDValue();
12761 
12762   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12763 }
12764 
12765 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12766                            SelectionDAG &DAG,
12767                            const AArch64Subtarget *Subtarget) {
12768 
12769   StoreSDNode *S = cast<StoreSDNode>(N);
12770   if (S->isVolatile() || S->isIndexed())
12771     return SDValue();
12772 
12773   SDValue StVal = S->getValue();
12774   EVT VT = StVal.getValueType();
12775 
12776   if (!VT.isFixedLengthVector())
12777     return SDValue();
12778 
12779   // If we get a splat of zeros, convert this vector store to a store of
12780   // scalars. They will be merged into store pairs of xzr thereby removing one
12781   // instruction and one register.
12782   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
12783     return ReplacedZeroSplat;
12784 
12785   // FIXME: The logic for deciding if an unaligned store should be split should
12786   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
12787   // a call to that function here.
12788 
12789   if (!Subtarget->isMisaligned128StoreSlow())
12790     return SDValue();
12791 
12792   // Don't split at -Oz.
12793   if (DAG.getMachineFunction().getFunction().hasMinSize())
12794     return SDValue();
12795 
12796   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
12797   // those up regresses performance on micro-benchmarks and olden/bh.
12798   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
12799     return SDValue();
12800 
12801   // Split unaligned 16B stores. They are terrible for performance.
12802   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
12803   // extensions can use this to mark that it does not want splitting to happen
12804   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
12805   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
12806   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
12807       S->getAlignment() <= 2)
12808     return SDValue();
12809 
12810   // If we get a splat of a scalar convert this vector store to a store of
12811   // scalars. They will be merged into store pairs thereby removing two
12812   // instructions.
12813   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
12814     return ReplacedSplat;
12815 
12816   SDLoc DL(S);
12817 
12818   // Split VT into two.
12819   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12820   unsigned NumElts = HalfVT.getVectorNumElements();
12821   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12822                                    DAG.getConstant(0, DL, MVT::i64));
12823   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12824                                    DAG.getConstant(NumElts, DL, MVT::i64));
12825   SDValue BasePtr = S->getBasePtr();
12826   SDValue NewST1 =
12827       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
12828                    S->getAlignment(), S->getMemOperand()->getFlags());
12829   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12830                                   DAG.getConstant(8, DL, MVT::i64));
12831   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
12832                       S->getPointerInfo(), S->getAlignment(),
12833                       S->getMemOperand()->getFlags());
12834 }
12835 
12836 /// Target-specific DAG combine function for post-increment LD1 (lane) and
12837 /// post-increment LD1R.
12838 static SDValue performPostLD1Combine(SDNode *N,
12839                                      TargetLowering::DAGCombinerInfo &DCI,
12840                                      bool IsLaneOp) {
12841   if (DCI.isBeforeLegalizeOps())
12842     return SDValue();
12843 
12844   SelectionDAG &DAG = DCI.DAG;
12845   EVT VT = N->getValueType(0);
12846 
12847   if (VT.isScalableVector())
12848     return SDValue();
12849 
12850   unsigned LoadIdx = IsLaneOp ? 1 : 0;
12851   SDNode *LD = N->getOperand(LoadIdx).getNode();
12852   // If it is not LOAD, can not do such combine.
12853   if (LD->getOpcode() != ISD::LOAD)
12854     return SDValue();
12855 
12856   // The vector lane must be a constant in the LD1LANE opcode.
12857   SDValue Lane;
12858   if (IsLaneOp) {
12859     Lane = N->getOperand(2);
12860     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
12861     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
12862       return SDValue();
12863   }
12864 
12865   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
12866   EVT MemVT = LoadSDN->getMemoryVT();
12867   // Check if memory operand is the same type as the vector element.
12868   if (MemVT != VT.getVectorElementType())
12869     return SDValue();
12870 
12871   // Check if there are other uses. If so, do not combine as it will introduce
12872   // an extra load.
12873   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
12874        ++UI) {
12875     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
12876       continue;
12877     if (*UI != N)
12878       return SDValue();
12879   }
12880 
12881   SDValue Addr = LD->getOperand(1);
12882   SDValue Vector = N->getOperand(0);
12883   // Search for a use of the address operand that is an increment.
12884   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
12885        Addr.getNode()->use_end(); UI != UE; ++UI) {
12886     SDNode *User = *UI;
12887     if (User->getOpcode() != ISD::ADD
12888         || UI.getUse().getResNo() != Addr.getResNo())
12889       continue;
12890 
12891     // If the increment is a constant, it must match the memory ref size.
12892     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12893     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12894       uint32_t IncVal = CInc->getZExtValue();
12895       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
12896       if (IncVal != NumBytes)
12897         continue;
12898       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12899     }
12900 
12901     // To avoid cycle construction make sure that neither the load nor the add
12902     // are predecessors to each other or the Vector.
12903     SmallPtrSet<const SDNode *, 32> Visited;
12904     SmallVector<const SDNode *, 16> Worklist;
12905     Visited.insert(Addr.getNode());
12906     Worklist.push_back(User);
12907     Worklist.push_back(LD);
12908     Worklist.push_back(Vector.getNode());
12909     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
12910         SDNode::hasPredecessorHelper(User, Visited, Worklist))
12911       continue;
12912 
12913     SmallVector<SDValue, 8> Ops;
12914     Ops.push_back(LD->getOperand(0));  // Chain
12915     if (IsLaneOp) {
12916       Ops.push_back(Vector);           // The vector to be inserted
12917       Ops.push_back(Lane);             // The lane to be inserted in the vector
12918     }
12919     Ops.push_back(Addr);
12920     Ops.push_back(Inc);
12921 
12922     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
12923     SDVTList SDTys = DAG.getVTList(Tys);
12924     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
12925     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
12926                                            MemVT,
12927                                            LoadSDN->getMemOperand());
12928 
12929     // Update the uses.
12930     SDValue NewResults[] = {
12931         SDValue(LD, 0),            // The result of load
12932         SDValue(UpdN.getNode(), 2) // Chain
12933     };
12934     DCI.CombineTo(LD, NewResults);
12935     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
12936     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
12937 
12938     break;
12939   }
12940   return SDValue();
12941 }
12942 
12943 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
12944 /// address translation.
12945 static bool performTBISimplification(SDValue Addr,
12946                                      TargetLowering::DAGCombinerInfo &DCI,
12947                                      SelectionDAG &DAG) {
12948   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
12949   KnownBits Known;
12950   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12951                                         !DCI.isBeforeLegalizeOps());
12952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12953   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
12954     DCI.CommitTargetLoweringOpt(TLO);
12955     return true;
12956   }
12957   return false;
12958 }
12959 
12960 static SDValue performSTORECombine(SDNode *N,
12961                                    TargetLowering::DAGCombinerInfo &DCI,
12962                                    SelectionDAG &DAG,
12963                                    const AArch64Subtarget *Subtarget) {
12964   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
12965     return Split;
12966 
12967   if (Subtarget->supportsAddressTopByteIgnored() &&
12968       performTBISimplification(N->getOperand(2), DCI, DAG))
12969     return SDValue(N, 0);
12970 
12971   return SDValue();
12972 }
12973 
12974 
12975 /// Target-specific DAG combine function for NEON load/store intrinsics
12976 /// to merge base address updates.
12977 static SDValue performNEONPostLDSTCombine(SDNode *N,
12978                                           TargetLowering::DAGCombinerInfo &DCI,
12979                                           SelectionDAG &DAG) {
12980   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12981     return SDValue();
12982 
12983   unsigned AddrOpIdx = N->getNumOperands() - 1;
12984   SDValue Addr = N->getOperand(AddrOpIdx);
12985 
12986   // Search for a use of the address operand that is an increment.
12987   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12988        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12989     SDNode *User = *UI;
12990     if (User->getOpcode() != ISD::ADD ||
12991         UI.getUse().getResNo() != Addr.getResNo())
12992       continue;
12993 
12994     // Check that the add is independent of the load/store.  Otherwise, folding
12995     // it would create a cycle.
12996     SmallPtrSet<const SDNode *, 32> Visited;
12997     SmallVector<const SDNode *, 16> Worklist;
12998     Visited.insert(Addr.getNode());
12999     Worklist.push_back(N);
13000     Worklist.push_back(User);
13001     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13002         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13003       continue;
13004 
13005     // Find the new opcode for the updating load/store.
13006     bool IsStore = false;
13007     bool IsLaneOp = false;
13008     bool IsDupOp = false;
13009     unsigned NewOpc = 0;
13010     unsigned NumVecs = 0;
13011     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13012     switch (IntNo) {
13013     default: llvm_unreachable("unexpected intrinsic for Neon base update");
13014     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
13015       NumVecs = 2; break;
13016     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
13017       NumVecs = 3; break;
13018     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
13019       NumVecs = 4; break;
13020     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
13021       NumVecs = 2; IsStore = true; break;
13022     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
13023       NumVecs = 3; IsStore = true; break;
13024     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
13025       NumVecs = 4; IsStore = true; break;
13026     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
13027       NumVecs = 2; break;
13028     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
13029       NumVecs = 3; break;
13030     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
13031       NumVecs = 4; break;
13032     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
13033       NumVecs = 2; IsStore = true; break;
13034     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
13035       NumVecs = 3; IsStore = true; break;
13036     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
13037       NumVecs = 4; IsStore = true; break;
13038     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
13039       NumVecs = 2; IsDupOp = true; break;
13040     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
13041       NumVecs = 3; IsDupOp = true; break;
13042     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
13043       NumVecs = 4; IsDupOp = true; break;
13044     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
13045       NumVecs = 2; IsLaneOp = true; break;
13046     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
13047       NumVecs = 3; IsLaneOp = true; break;
13048     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
13049       NumVecs = 4; IsLaneOp = true; break;
13050     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
13051       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
13052     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
13053       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
13054     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
13055       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
13056     }
13057 
13058     EVT VecTy;
13059     if (IsStore)
13060       VecTy = N->getOperand(2).getValueType();
13061     else
13062       VecTy = N->getValueType(0);
13063 
13064     // If the increment is a constant, it must match the memory ref size.
13065     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13066     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13067       uint32_t IncVal = CInc->getZExtValue();
13068       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13069       if (IsLaneOp || IsDupOp)
13070         NumBytes /= VecTy.getVectorNumElements();
13071       if (IncVal != NumBytes)
13072         continue;
13073       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13074     }
13075     SmallVector<SDValue, 8> Ops;
13076     Ops.push_back(N->getOperand(0)); // Incoming chain
13077     // Load lane and store have vector list as input.
13078     if (IsLaneOp || IsStore)
13079       for (unsigned i = 2; i < AddrOpIdx; ++i)
13080         Ops.push_back(N->getOperand(i));
13081     Ops.push_back(Addr); // Base register
13082     Ops.push_back(Inc);
13083 
13084     // Return Types.
13085     EVT Tys[6];
13086     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
13087     unsigned n;
13088     for (n = 0; n < NumResultVecs; ++n)
13089       Tys[n] = VecTy;
13090     Tys[n++] = MVT::i64;  // Type of write back register
13091     Tys[n] = MVT::Other;  // Type of the chain
13092     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13093 
13094     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
13095     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
13096                                            MemInt->getMemoryVT(),
13097                                            MemInt->getMemOperand());
13098 
13099     // Update the uses.
13100     std::vector<SDValue> NewResults;
13101     for (unsigned i = 0; i < NumResultVecs; ++i) {
13102       NewResults.push_back(SDValue(UpdN.getNode(), i));
13103     }
13104     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
13105     DCI.CombineTo(N, NewResults);
13106     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13107 
13108     break;
13109   }
13110   return SDValue();
13111 }
13112 
13113 // Checks to see if the value is the prescribed width and returns information
13114 // about its extension mode.
13115 static
13116 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
13117   ExtType = ISD::NON_EXTLOAD;
13118   switch(V.getNode()->getOpcode()) {
13119   default:
13120     return false;
13121   case ISD::LOAD: {
13122     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
13123     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
13124        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
13125       ExtType = LoadNode->getExtensionType();
13126       return true;
13127     }
13128     return false;
13129   }
13130   case ISD::AssertSext: {
13131     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13132     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13133        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13134       ExtType = ISD::SEXTLOAD;
13135       return true;
13136     }
13137     return false;
13138   }
13139   case ISD::AssertZext: {
13140     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13141     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13142        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13143       ExtType = ISD::ZEXTLOAD;
13144       return true;
13145     }
13146     return false;
13147   }
13148   case ISD::Constant:
13149   case ISD::TargetConstant: {
13150     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
13151            1LL << (width - 1);
13152   }
13153   }
13154 
13155   return true;
13156 }
13157 
13158 // This function does a whole lot of voodoo to determine if the tests are
13159 // equivalent without and with a mask. Essentially what happens is that given a
13160 // DAG resembling:
13161 //
13162 //  +-------------+ +-------------+ +-------------+ +-------------+
13163 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
13164 //  +-------------+ +-------------+ +-------------+ +-------------+
13165 //           |           |           |               |
13166 //           V           V           |    +----------+
13167 //          +-------------+  +----+  |    |
13168 //          |     ADD     |  |0xff|  |    |
13169 //          +-------------+  +----+  |    |
13170 //                  |           |    |    |
13171 //                  V           V    |    |
13172 //                 +-------------+   |    |
13173 //                 |     AND     |   |    |
13174 //                 +-------------+   |    |
13175 //                      |            |    |
13176 //                      +-----+      |    |
13177 //                            |      |    |
13178 //                            V      V    V
13179 //                           +-------------+
13180 //                           |     CMP     |
13181 //                           +-------------+
13182 //
13183 // The AND node may be safely removed for some combinations of inputs. In
13184 // particular we need to take into account the extension type of the Input,
13185 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
13186 // width of the input (this can work for any width inputs, the above graph is
13187 // specific to 8 bits.
13188 //
13189 // The specific equations were worked out by generating output tables for each
13190 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
13191 // problem was simplified by working with 4 bit inputs, which means we only
13192 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
13193 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
13194 // patterns present in both extensions (0,7). For every distinct set of
13195 // AddConstant and CompConstants bit patterns we can consider the masked and
13196 // unmasked versions to be equivalent if the result of this function is true for
13197 // all 16 distinct bit patterns of for the current extension type of Input (w0).
13198 //
13199 //   sub      w8, w0, w1
13200 //   and      w10, w8, #0x0f
13201 //   cmp      w8, w2
13202 //   cset     w9, AArch64CC
13203 //   cmp      w10, w2
13204 //   cset     w11, AArch64CC
13205 //   cmp      w9, w11
13206 //   cset     w0, eq
13207 //   ret
13208 //
13209 // Since the above function shows when the outputs are equivalent it defines
13210 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
13211 // would be expensive to run during compiles. The equations below were written
13212 // in a test harness that confirmed they gave equivalent outputs to the above
13213 // for all inputs function, so they can be used determine if the removal is
13214 // legal instead.
13215 //
13216 // isEquivalentMaskless() is the code for testing if the AND can be removed
13217 // factored out of the DAG recognition as the DAG can take several forms.
13218 
13219 static bool isEquivalentMaskless(unsigned CC, unsigned width,
13220                                  ISD::LoadExtType ExtType, int AddConstant,
13221                                  int CompConstant) {
13222   // By being careful about our equations and only writing the in term
13223   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
13224   // make them generally applicable to all bit widths.
13225   int MaxUInt = (1 << width);
13226 
13227   // For the purposes of these comparisons sign extending the type is
13228   // equivalent to zero extending the add and displacing it by half the integer
13229   // width. Provided we are careful and make sure our equations are valid over
13230   // the whole range we can just adjust the input and avoid writing equations
13231   // for sign extended inputs.
13232   if (ExtType == ISD::SEXTLOAD)
13233     AddConstant -= (1 << (width-1));
13234 
13235   switch(CC) {
13236   case AArch64CC::LE:
13237   case AArch64CC::GT:
13238     if ((AddConstant == 0) ||
13239         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
13240         (AddConstant >= 0 && CompConstant < 0) ||
13241         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
13242       return true;
13243     break;
13244   case AArch64CC::LT:
13245   case AArch64CC::GE:
13246     if ((AddConstant == 0) ||
13247         (AddConstant >= 0 && CompConstant <= 0) ||
13248         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
13249       return true;
13250     break;
13251   case AArch64CC::HI:
13252   case AArch64CC::LS:
13253     if ((AddConstant >= 0 && CompConstant < 0) ||
13254        (AddConstant <= 0 && CompConstant >= -1 &&
13255         CompConstant < AddConstant + MaxUInt))
13256       return true;
13257    break;
13258   case AArch64CC::PL:
13259   case AArch64CC::MI:
13260     if ((AddConstant == 0) ||
13261         (AddConstant > 0 && CompConstant <= 0) ||
13262         (AddConstant < 0 && CompConstant <= AddConstant))
13263       return true;
13264     break;
13265   case AArch64CC::LO:
13266   case AArch64CC::HS:
13267     if ((AddConstant >= 0 && CompConstant <= 0) ||
13268         (AddConstant <= 0 && CompConstant >= 0 &&
13269          CompConstant <= AddConstant + MaxUInt))
13270       return true;
13271     break;
13272   case AArch64CC::EQ:
13273   case AArch64CC::NE:
13274     if ((AddConstant > 0 && CompConstant < 0) ||
13275         (AddConstant < 0 && CompConstant >= 0 &&
13276          CompConstant < AddConstant + MaxUInt) ||
13277         (AddConstant >= 0 && CompConstant >= 0 &&
13278          CompConstant >= AddConstant) ||
13279         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13280       return true;
13281     break;
13282   case AArch64CC::VS:
13283   case AArch64CC::VC:
13284   case AArch64CC::AL:
13285   case AArch64CC::NV:
13286     return true;
13287   case AArch64CC::Invalid:
13288     break;
13289   }
13290 
13291   return false;
13292 }
13293 
13294 static
13295 SDValue performCONDCombine(SDNode *N,
13296                            TargetLowering::DAGCombinerInfo &DCI,
13297                            SelectionDAG &DAG, unsigned CCIndex,
13298                            unsigned CmpIndex) {
13299   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13300   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13301   unsigned CondOpcode = SubsNode->getOpcode();
13302 
13303   if (CondOpcode != AArch64ISD::SUBS)
13304     return SDValue();
13305 
13306   // There is a SUBS feeding this condition. Is it fed by a mask we can
13307   // use?
13308 
13309   SDNode *AndNode = SubsNode->getOperand(0).getNode();
13310   unsigned MaskBits = 0;
13311 
13312   if (AndNode->getOpcode() != ISD::AND)
13313     return SDValue();
13314 
13315   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13316     uint32_t CNV = CN->getZExtValue();
13317     if (CNV == 255)
13318       MaskBits = 8;
13319     else if (CNV == 65535)
13320       MaskBits = 16;
13321   }
13322 
13323   if (!MaskBits)
13324     return SDValue();
13325 
13326   SDValue AddValue = AndNode->getOperand(0);
13327 
13328   if (AddValue.getOpcode() != ISD::ADD)
13329     return SDValue();
13330 
13331   // The basic dag structure is correct, grab the inputs and validate them.
13332 
13333   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
13334   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
13335   SDValue SubsInputValue = SubsNode->getOperand(1);
13336 
13337   // The mask is present and the provenance of all the values is a smaller type,
13338   // lets see if the mask is superfluous.
13339 
13340   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
13341       !isa<ConstantSDNode>(SubsInputValue.getNode()))
13342     return SDValue();
13343 
13344   ISD::LoadExtType ExtType;
13345 
13346   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
13347       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
13348       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
13349     return SDValue();
13350 
13351   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
13352                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
13353                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
13354     return SDValue();
13355 
13356   // The AND is not necessary, remove it.
13357 
13358   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
13359                                SubsNode->getValueType(1));
13360   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
13361 
13362   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
13363   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
13364 
13365   return SDValue(N, 0);
13366 }
13367 
13368 // Optimize compare with zero and branch.
13369 static SDValue performBRCONDCombine(SDNode *N,
13370                                     TargetLowering::DAGCombinerInfo &DCI,
13371                                     SelectionDAG &DAG) {
13372   MachineFunction &MF = DAG.getMachineFunction();
13373   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
13374   // will not be produced, as they are conditional branch instructions that do
13375   // not set flags.
13376   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
13377     return SDValue();
13378 
13379   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
13380     N = NV.getNode();
13381   SDValue Chain = N->getOperand(0);
13382   SDValue Dest = N->getOperand(1);
13383   SDValue CCVal = N->getOperand(2);
13384   SDValue Cmp = N->getOperand(3);
13385 
13386   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
13387   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
13388   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
13389     return SDValue();
13390 
13391   unsigned CmpOpc = Cmp.getOpcode();
13392   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
13393     return SDValue();
13394 
13395   // Only attempt folding if there is only one use of the flag and no use of the
13396   // value.
13397   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
13398     return SDValue();
13399 
13400   SDValue LHS = Cmp.getOperand(0);
13401   SDValue RHS = Cmp.getOperand(1);
13402 
13403   assert(LHS.getValueType() == RHS.getValueType() &&
13404          "Expected the value type to be the same for both operands!");
13405   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
13406     return SDValue();
13407 
13408   if (isNullConstant(LHS))
13409     std::swap(LHS, RHS);
13410 
13411   if (!isNullConstant(RHS))
13412     return SDValue();
13413 
13414   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
13415       LHS.getOpcode() == ISD::SRL)
13416     return SDValue();
13417 
13418   // Fold the compare into the branch instruction.
13419   SDValue BR;
13420   if (CC == AArch64CC::EQ)
13421     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13422   else
13423     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13424 
13425   // Do not add new nodes to DAG combiner worklist.
13426   DCI.CombineTo(N, BR, false);
13427 
13428   return SDValue();
13429 }
13430 
13431 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
13432 // as well as whether the test should be inverted.  This code is required to
13433 // catch these cases (as opposed to standard dag combines) because
13434 // AArch64ISD::TBZ is matched during legalization.
13435 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
13436                                  SelectionDAG &DAG) {
13437 
13438   if (!Op->hasOneUse())
13439     return Op;
13440 
13441   // We don't handle undef/constant-fold cases below, as they should have
13442   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
13443   // etc.)
13444 
13445   // (tbz (trunc x), b) -> (tbz x, b)
13446   // This case is just here to enable more of the below cases to be caught.
13447   if (Op->getOpcode() == ISD::TRUNCATE &&
13448       Bit < Op->getValueType(0).getSizeInBits()) {
13449     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13450   }
13451 
13452   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
13453   if (Op->getOpcode() == ISD::ANY_EXTEND &&
13454       Bit < Op->getOperand(0).getValueSizeInBits()) {
13455     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13456   }
13457 
13458   if (Op->getNumOperands() != 2)
13459     return Op;
13460 
13461   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13462   if (!C)
13463     return Op;
13464 
13465   switch (Op->getOpcode()) {
13466   default:
13467     return Op;
13468 
13469   // (tbz (and x, m), b) -> (tbz x, b)
13470   case ISD::AND:
13471     if ((C->getZExtValue() >> Bit) & 1)
13472       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13473     return Op;
13474 
13475   // (tbz (shl x, c), b) -> (tbz x, b-c)
13476   case ISD::SHL:
13477     if (C->getZExtValue() <= Bit &&
13478         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13479       Bit = Bit - C->getZExtValue();
13480       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13481     }
13482     return Op;
13483 
13484   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
13485   case ISD::SRA:
13486     Bit = Bit + C->getZExtValue();
13487     if (Bit >= Op->getValueType(0).getSizeInBits())
13488       Bit = Op->getValueType(0).getSizeInBits() - 1;
13489     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13490 
13491   // (tbz (srl x, c), b) -> (tbz x, b+c)
13492   case ISD::SRL:
13493     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13494       Bit = Bit + C->getZExtValue();
13495       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13496     }
13497     return Op;
13498 
13499   // (tbz (xor x, -1), b) -> (tbnz x, b)
13500   case ISD::XOR:
13501     if ((C->getZExtValue() >> Bit) & 1)
13502       Invert = !Invert;
13503     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13504   }
13505 }
13506 
13507 // Optimize test single bit zero/non-zero and branch.
13508 static SDValue performTBZCombine(SDNode *N,
13509                                  TargetLowering::DAGCombinerInfo &DCI,
13510                                  SelectionDAG &DAG) {
13511   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13512   bool Invert = false;
13513   SDValue TestSrc = N->getOperand(1);
13514   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
13515 
13516   if (TestSrc == NewTestSrc)
13517     return SDValue();
13518 
13519   unsigned NewOpc = N->getOpcode();
13520   if (Invert) {
13521     if (NewOpc == AArch64ISD::TBZ)
13522       NewOpc = AArch64ISD::TBNZ;
13523     else {
13524       assert(NewOpc == AArch64ISD::TBNZ);
13525       NewOpc = AArch64ISD::TBZ;
13526     }
13527   }
13528 
13529   SDLoc DL(N);
13530   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
13531                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
13532 }
13533 
13534 // vselect (v1i1 setcc) ->
13535 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
13536 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
13537 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
13538 // such VSELECT.
13539 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
13540   SDValue N0 = N->getOperand(0);
13541   EVT CCVT = N0.getValueType();
13542 
13543   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
13544       CCVT.getVectorElementType() != MVT::i1)
13545     return SDValue();
13546 
13547   EVT ResVT = N->getValueType(0);
13548   EVT CmpVT = N0.getOperand(0).getValueType();
13549   // Only combine when the result type is of the same size as the compared
13550   // operands.
13551   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
13552     return SDValue();
13553 
13554   SDValue IfTrue = N->getOperand(1);
13555   SDValue IfFalse = N->getOperand(2);
13556   SDValue SetCC =
13557       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
13558                    N0.getOperand(0), N0.getOperand(1),
13559                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
13560   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
13561                      IfTrue, IfFalse);
13562 }
13563 
13564 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
13565 /// the compare-mask instructions rather than going via NZCV, even if LHS and
13566 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
13567 /// with a vector one followed by a DUP shuffle on the result.
13568 static SDValue performSelectCombine(SDNode *N,
13569                                     TargetLowering::DAGCombinerInfo &DCI) {
13570   SelectionDAG &DAG = DCI.DAG;
13571   SDValue N0 = N->getOperand(0);
13572   EVT ResVT = N->getValueType(0);
13573 
13574   if (N0.getOpcode() != ISD::SETCC)
13575     return SDValue();
13576 
13577   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
13578   // scalar SetCCResultType. We also don't expect vectors, because we assume
13579   // that selects fed by vector SETCCs are canonicalized to VSELECT.
13580   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
13581          "Scalar-SETCC feeding SELECT has unexpected result type!");
13582 
13583   // If NumMaskElts == 0, the comparison is larger than select result. The
13584   // largest real NEON comparison is 64-bits per lane, which means the result is
13585   // at most 32-bits and an illegal vector. Just bail out for now.
13586   EVT SrcVT = N0.getOperand(0).getValueType();
13587 
13588   // Don't try to do this optimization when the setcc itself has i1 operands.
13589   // There are no legal vectors of i1, so this would be pointless.
13590   if (SrcVT == MVT::i1)
13591     return SDValue();
13592 
13593   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
13594   if (!ResVT.isVector() || NumMaskElts == 0)
13595     return SDValue();
13596 
13597   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
13598   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
13599 
13600   // Also bail out if the vector CCVT isn't the same size as ResVT.
13601   // This can happen if the SETCC operand size doesn't divide the ResVT size
13602   // (e.g., f64 vs v3f32).
13603   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
13604     return SDValue();
13605 
13606   // Make sure we didn't create illegal types, if we're not supposed to.
13607   assert(DCI.isBeforeLegalize() ||
13608          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
13609 
13610   // First perform a vector comparison, where lane 0 is the one we're interested
13611   // in.
13612   SDLoc DL(N0);
13613   SDValue LHS =
13614       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
13615   SDValue RHS =
13616       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
13617   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
13618 
13619   // Now duplicate the comparison mask we want across all other lanes.
13620   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
13621   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
13622   Mask = DAG.getNode(ISD::BITCAST, DL,
13623                      ResVT.changeVectorElementTypeToInteger(), Mask);
13624 
13625   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
13626 }
13627 
13628 /// Get rid of unnecessary NVCASTs (that don't change the type).
13629 static SDValue performNVCASTCombine(SDNode *N) {
13630   if (N->getValueType(0) == N->getOperand(0).getValueType())
13631     return N->getOperand(0);
13632 
13633   return SDValue();
13634 }
13635 
13636 // If all users of the globaladdr are of the form (globaladdr + constant), find
13637 // the smallest constant, fold it into the globaladdr's offset and rewrite the
13638 // globaladdr as (globaladdr + constant) - constant.
13639 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
13640                                            const AArch64Subtarget *Subtarget,
13641                                            const TargetMachine &TM) {
13642   auto *GN = cast<GlobalAddressSDNode>(N);
13643   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
13644       AArch64II::MO_NO_FLAG)
13645     return SDValue();
13646 
13647   uint64_t MinOffset = -1ull;
13648   for (SDNode *N : GN->uses()) {
13649     if (N->getOpcode() != ISD::ADD)
13650       return SDValue();
13651     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
13652     if (!C)
13653       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13654     if (!C)
13655       return SDValue();
13656     MinOffset = std::min(MinOffset, C->getZExtValue());
13657   }
13658   uint64_t Offset = MinOffset + GN->getOffset();
13659 
13660   // Require that the new offset is larger than the existing one. Otherwise, we
13661   // can end up oscillating between two possible DAGs, for example,
13662   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
13663   if (Offset <= uint64_t(GN->getOffset()))
13664     return SDValue();
13665 
13666   // Check whether folding this offset is legal. It must not go out of bounds of
13667   // the referenced object to avoid violating the code model, and must be
13668   // smaller than 2^21 because this is the largest offset expressible in all
13669   // object formats.
13670   //
13671   // This check also prevents us from folding negative offsets, which will end
13672   // up being treated in the same way as large positive ones. They could also
13673   // cause code model violations, and aren't really common enough to matter.
13674   if (Offset >= (1 << 21))
13675     return SDValue();
13676 
13677   const GlobalValue *GV = GN->getGlobal();
13678   Type *T = GV->getValueType();
13679   if (!T->isSized() ||
13680       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
13681     return SDValue();
13682 
13683   SDLoc DL(GN);
13684   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
13685   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
13686                      DAG.getConstant(MinOffset, DL, MVT::i64));
13687 }
13688 
13689 // Turns the vector of indices into a vector of byte offstes by scaling Offset
13690 // by (BitWidth / 8).
13691 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
13692                                           SDLoc DL, unsigned BitWidth) {
13693   assert(Offset.getValueType().isScalableVector() &&
13694          "This method is only for scalable vectors of offsets");
13695 
13696   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
13697   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
13698 
13699   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
13700 }
13701 
13702 /// Check if the value of \p OffsetInBytes can be used as an immediate for
13703 /// the gather load/prefetch and scatter store instructions with vector base and
13704 /// immediate offset addressing mode:
13705 ///
13706 ///      [<Zn>.[S|D]{, #<imm>}]
13707 ///
13708 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13709 
13710 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
13711                                                   unsigned ScalarSizeInBytes) {
13712   // The immediate is not a multiple of the scalar size.
13713   if (OffsetInBytes % ScalarSizeInBytes)
13714     return false;
13715 
13716   // The immediate is out of range.
13717   if (OffsetInBytes / ScalarSizeInBytes > 31)
13718     return false;
13719 
13720   return true;
13721 }
13722 
13723 /// Check if the value of \p Offset represents a valid immediate for the SVE
13724 /// gather load/prefetch and scatter store instructiona with vector base and
13725 /// immediate offset addressing mode:
13726 ///
13727 ///      [<Zn>.[S|D]{, #<imm>}]
13728 ///
13729 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13730 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
13731                                            unsigned ScalarSizeInBytes) {
13732   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
13733   return OffsetConst && isValidImmForSVEVecImmAddrMode(
13734                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
13735 }
13736 
13737 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
13738                                           unsigned Opcode,
13739                                           bool OnlyPackedOffsets = true) {
13740   const SDValue Src = N->getOperand(2);
13741   const EVT SrcVT = Src->getValueType(0);
13742   assert(SrcVT.isScalableVector() &&
13743          "Scatter stores are only possible for SVE vectors");
13744 
13745   SDLoc DL(N);
13746   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
13747 
13748   // Make sure that source data will fit into an SVE register
13749   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13750     return SDValue();
13751 
13752   // For FPs, ACLE only supports _packed_ single and double precision types.
13753   if (SrcElVT.isFloatingPoint())
13754     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
13755       return SDValue();
13756 
13757   // Depending on the addressing mode, this is either a pointer or a vector of
13758   // pointers (that fits into one register)
13759   SDValue Base = N->getOperand(4);
13760   // Depending on the addressing mode, this is either a single offset or a
13761   // vector of offsets  (that fits into one register)
13762   SDValue Offset = N->getOperand(5);
13763 
13764   // For "scalar + vector of indices", just scale the indices. This only
13765   // applies to non-temporal scatters because there's no instruction that takes
13766   // indicies.
13767   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
13768     Offset =
13769         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
13770     Opcode = AArch64ISD::SSTNT1_PRED;
13771   }
13772 
13773   // In the case of non-temporal gather loads there's only one SVE instruction
13774   // per data-size: "scalar + vector", i.e.
13775   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13776   // Since we do have intrinsics that allow the arguments to be in a different
13777   // order, we may need to swap them to match the spec.
13778   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
13779     std::swap(Base, Offset);
13780 
13781   // SST1_IMM requires that the offset is an immediate that is:
13782   //    * a multiple of #SizeInBytes,
13783   //    * in the range [0, 31 x #SizeInBytes],
13784   // where #SizeInBytes is the size in bytes of the stored items. For
13785   // immediates outside that range and non-immediate scalar offsets use SST1 or
13786   // SST1_UXTW instead.
13787   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
13788     if (!isValidImmForSVEVecImmAddrMode(Offset,
13789                                         SrcVT.getScalarSizeInBits() / 8)) {
13790       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13791         Opcode = AArch64ISD::SST1_UXTW_PRED;
13792       else
13793         Opcode = AArch64ISD::SST1_PRED;
13794 
13795       std::swap(Base, Offset);
13796     }
13797   }
13798 
13799   auto &TLI = DAG.getTargetLoweringInfo();
13800   if (!TLI.isTypeLegal(Base.getValueType()))
13801     return SDValue();
13802 
13803   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
13804   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13805   // nxv2i64. Legalize accordingly.
13806   if (!OnlyPackedOffsets &&
13807       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13808     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13809 
13810   if (!TLI.isTypeLegal(Offset.getValueType()))
13811     return SDValue();
13812 
13813   // Source value type that is representable in hardware
13814   EVT HwSrcVt = getSVEContainerType(SrcVT);
13815 
13816   // Keep the original type of the input data to store - this is needed to be
13817   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
13818   // FP values we want the integer equivalent, so just use HwSrcVt.
13819   SDValue InputVT = DAG.getValueType(SrcVT);
13820   if (SrcVT.isFloatingPoint())
13821     InputVT = DAG.getValueType(HwSrcVt);
13822 
13823   SDVTList VTs = DAG.getVTList(MVT::Other);
13824   SDValue SrcNew;
13825 
13826   if (Src.getValueType().isFloatingPoint())
13827     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
13828   else
13829     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
13830 
13831   SDValue Ops[] = {N->getOperand(0), // Chain
13832                    SrcNew,
13833                    N->getOperand(3), // Pg
13834                    Base,
13835                    Offset,
13836                    InputVT};
13837 
13838   return DAG.getNode(Opcode, DL, VTs, Ops);
13839 }
13840 
13841 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
13842                                         unsigned Opcode,
13843                                         bool OnlyPackedOffsets = true) {
13844   const EVT RetVT = N->getValueType(0);
13845   assert(RetVT.isScalableVector() &&
13846          "Gather loads are only possible for SVE vectors");
13847 
13848   SDLoc DL(N);
13849 
13850   // Make sure that the loaded data will fit into an SVE register
13851   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13852     return SDValue();
13853 
13854   // Depending on the addressing mode, this is either a pointer or a vector of
13855   // pointers (that fits into one register)
13856   SDValue Base = N->getOperand(3);
13857   // Depending on the addressing mode, this is either a single offset or a
13858   // vector of offsets  (that fits into one register)
13859   SDValue Offset = N->getOperand(4);
13860 
13861   // For "scalar + vector of indices", just scale the indices. This only
13862   // applies to non-temporal gathers because there's no instruction that takes
13863   // indicies.
13864   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
13865     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
13866                                         RetVT.getScalarSizeInBits());
13867     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
13868   }
13869 
13870   // In the case of non-temporal gather loads there's only one SVE instruction
13871   // per data-size: "scalar + vector", i.e.
13872   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13873   // Since we do have intrinsics that allow the arguments to be in a different
13874   // order, we may need to swap them to match the spec.
13875   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
13876       Offset.getValueType().isVector())
13877     std::swap(Base, Offset);
13878 
13879   // GLD{FF}1_IMM requires that the offset is an immediate that is:
13880   //    * a multiple of #SizeInBytes,
13881   //    * in the range [0, 31 x #SizeInBytes],
13882   // where #SizeInBytes is the size in bytes of the loaded items. For
13883   // immediates outside that range and non-immediate scalar offsets use
13884   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
13885   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
13886       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
13887     if (!isValidImmForSVEVecImmAddrMode(Offset,
13888                                         RetVT.getScalarSizeInBits() / 8)) {
13889       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13890         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13891                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
13892                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
13893       else
13894         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13895                      ? AArch64ISD::GLD1_MERGE_ZERO
13896                      : AArch64ISD::GLDFF1_MERGE_ZERO;
13897 
13898       std::swap(Base, Offset);
13899     }
13900   }
13901 
13902   auto &TLI = DAG.getTargetLoweringInfo();
13903   if (!TLI.isTypeLegal(Base.getValueType()))
13904     return SDValue();
13905 
13906   // Some gather load variants allow unpacked offsets, but only as nxv2i32
13907   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13908   // nxv2i64. Legalize accordingly.
13909   if (!OnlyPackedOffsets &&
13910       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13911     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13912 
13913   // Return value type that is representable in hardware
13914   EVT HwRetVt = getSVEContainerType(RetVT);
13915 
13916   // Keep the original output value type around - this is needed to be able to
13917   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
13918   // values we want the integer equivalent, so just use HwRetVT.
13919   SDValue OutVT = DAG.getValueType(RetVT);
13920   if (RetVT.isFloatingPoint())
13921     OutVT = DAG.getValueType(HwRetVt);
13922 
13923   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
13924   SDValue Ops[] = {N->getOperand(0), // Chain
13925                    N->getOperand(2), // Pg
13926                    Base, Offset, OutVT};
13927 
13928   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
13929   SDValue LoadChain = SDValue(Load.getNode(), 1);
13930 
13931   if (RetVT.isInteger() && (RetVT != HwRetVt))
13932     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
13933 
13934   // If the original return value was FP, bitcast accordingly. Doing it here
13935   // means that we can avoid adding TableGen patterns for FPs.
13936   if (RetVT.isFloatingPoint())
13937     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
13938 
13939   return DAG.getMergeValues({Load, LoadChain}, DL);
13940 }
13941 
13942 static SDValue
13943 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13944                               SelectionDAG &DAG) {
13945   if (DCI.isBeforeLegalizeOps())
13946     return SDValue();
13947 
13948   SDLoc DL(N);
13949   SDValue Src = N->getOperand(0);
13950   unsigned Opc = Src->getOpcode();
13951 
13952   // Sign extend of an unsigned unpack -> signed unpack
13953   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13954 
13955     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
13956                                                : AArch64ISD::SUNPKLO;
13957 
13958     // Push the sign extend to the operand of the unpack
13959     // This is necessary where, for example, the operand of the unpack
13960     // is another unpack:
13961     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
13962     // ->
13963     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
13964     // ->
13965     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
13966     SDValue ExtOp = Src->getOperand(0);
13967     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
13968     EVT EltTy = VT.getVectorElementType();
13969     (void)EltTy;
13970 
13971     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
13972            "Sign extending from an invalid type");
13973 
13974     EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13975                                  VT.getVectorElementType(),
13976                                  VT.getVectorElementCount() * 2);
13977 
13978     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
13979                               ExtOp, DAG.getValueType(ExtVT));
13980 
13981     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
13982   }
13983 
13984   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
13985   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
13986   unsigned NewOpc;
13987   unsigned MemVTOpNum = 4;
13988   switch (Opc) {
13989   case AArch64ISD::LD1_MERGE_ZERO:
13990     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
13991     MemVTOpNum = 3;
13992     break;
13993   case AArch64ISD::LDNF1_MERGE_ZERO:
13994     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
13995     MemVTOpNum = 3;
13996     break;
13997   case AArch64ISD::LDFF1_MERGE_ZERO:
13998     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
13999     MemVTOpNum = 3;
14000     break;
14001   case AArch64ISD::GLD1_MERGE_ZERO:
14002     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
14003     break;
14004   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
14005     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
14006     break;
14007   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
14008     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
14009     break;
14010   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
14011     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
14012     break;
14013   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
14014     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
14015     break;
14016   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
14017     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
14018     break;
14019   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
14020     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
14021     break;
14022   case AArch64ISD::GLDFF1_MERGE_ZERO:
14023     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
14024     break;
14025   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
14026     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
14027     break;
14028   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
14029     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
14030     break;
14031   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
14032     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
14033     break;
14034   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
14035     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
14036     break;
14037   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
14038     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
14039     break;
14040   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
14041     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
14042     break;
14043   case AArch64ISD::GLDNT1_MERGE_ZERO:
14044     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
14045     break;
14046   default:
14047     return SDValue();
14048   }
14049 
14050   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
14051   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
14052 
14053   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
14054     return SDValue();
14055 
14056   EVT DstVT = N->getValueType(0);
14057   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
14058 
14059   SmallVector<SDValue, 5> Ops;
14060   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
14061     Ops.push_back(Src->getOperand(I));
14062 
14063   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
14064   DCI.CombineTo(N, ExtLoad);
14065   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
14066 
14067   // Return N so it doesn't get rechecked
14068   return SDValue(N, 0);
14069 }
14070 
14071 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
14072 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
14073 /// != nxv2i32) do not need legalization.
14074 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
14075   const unsigned OffsetPos = 4;
14076   SDValue Offset = N->getOperand(OffsetPos);
14077 
14078   // Not an unpacked vector, bail out.
14079   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
14080     return SDValue();
14081 
14082   // Extend the unpacked offset vector to 64-bit lanes.
14083   SDLoc DL(N);
14084   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
14085   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14086   // Replace the offset operand with the 64-bit one.
14087   Ops[OffsetPos] = Offset;
14088 
14089   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14090 }
14091 
14092 /// Combines a node carrying the intrinsic
14093 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
14094 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
14095 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
14096 /// sve gather prefetch instruction with vector plus immediate addressing mode.
14097 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
14098                                                unsigned ScalarSizeInBytes) {
14099   const unsigned ImmPos = 4, OffsetPos = 3;
14100   // No need to combine the node if the immediate is valid...
14101   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
14102     return SDValue();
14103 
14104   // ...otherwise swap the offset base with the offset...
14105   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14106   std::swap(Ops[ImmPos], Ops[OffsetPos]);
14107   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
14108   // `aarch64_sve_prfb_gather_uxtw_index`.
14109   SDLoc DL(N);
14110   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
14111                            MVT::i64);
14112 
14113   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14114 }
14115 
14116 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
14117                                                  DAGCombinerInfo &DCI) const {
14118   SelectionDAG &DAG = DCI.DAG;
14119   switch (N->getOpcode()) {
14120   default:
14121     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
14122     break;
14123   case ISD::ADD:
14124   case ISD::SUB:
14125     return performAddSubLongCombine(N, DCI, DAG);
14126   case ISD::XOR:
14127     return performXorCombine(N, DAG, DCI, Subtarget);
14128   case ISD::MUL:
14129     return performMulCombine(N, DAG, DCI, Subtarget);
14130   case ISD::SINT_TO_FP:
14131   case ISD::UINT_TO_FP:
14132     return performIntToFpCombine(N, DAG, Subtarget);
14133   case ISD::FP_TO_SINT:
14134   case ISD::FP_TO_UINT:
14135     return performFpToIntCombine(N, DAG, DCI, Subtarget);
14136   case ISD::FDIV:
14137     return performFDivCombine(N, DAG, DCI, Subtarget);
14138   case ISD::OR:
14139     return performORCombine(N, DCI, Subtarget);
14140   case ISD::AND:
14141     return performANDCombine(N, DCI);
14142   case ISD::SRL:
14143     return performSRLCombine(N, DCI);
14144   case ISD::INTRINSIC_WO_CHAIN:
14145     return performIntrinsicCombine(N, DCI, Subtarget);
14146   case ISD::ANY_EXTEND:
14147   case ISD::ZERO_EXTEND:
14148   case ISD::SIGN_EXTEND:
14149     return performExtendCombine(N, DCI, DAG);
14150   case ISD::SIGN_EXTEND_INREG:
14151     return performSignExtendInRegCombine(N, DCI, DAG);
14152   case ISD::TRUNCATE:
14153     return performVectorTruncateCombine(N, DCI, DAG);
14154   case ISD::CONCAT_VECTORS:
14155     return performConcatVectorsCombine(N, DCI, DAG);
14156   case ISD::SELECT:
14157     return performSelectCombine(N, DCI);
14158   case ISD::VSELECT:
14159     return performVSelectCombine(N, DCI.DAG);
14160   case ISD::LOAD:
14161     if (performTBISimplification(N->getOperand(1), DCI, DAG))
14162       return SDValue(N, 0);
14163     break;
14164   case ISD::STORE:
14165     return performSTORECombine(N, DCI, DAG, Subtarget);
14166   case AArch64ISD::BRCOND:
14167     return performBRCONDCombine(N, DCI, DAG);
14168   case AArch64ISD::TBNZ:
14169   case AArch64ISD::TBZ:
14170     return performTBZCombine(N, DCI, DAG);
14171   case AArch64ISD::CSEL:
14172     return performCONDCombine(N, DCI, DAG, 2, 3);
14173   case AArch64ISD::DUP:
14174     return performPostLD1Combine(N, DCI, false);
14175   case AArch64ISD::NVCAST:
14176     return performNVCASTCombine(N);
14177   case ISD::INSERT_VECTOR_ELT:
14178     return performPostLD1Combine(N, DCI, true);
14179   case ISD::INTRINSIC_VOID:
14180   case ISD::INTRINSIC_W_CHAIN:
14181     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14182     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
14183       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
14184     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
14185       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
14186     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
14187       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
14188     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
14189       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
14190     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
14191     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
14192     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
14193     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
14194     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
14195     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
14196     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
14197     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
14198       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
14199     case Intrinsic::aarch64_neon_ld2:
14200     case Intrinsic::aarch64_neon_ld3:
14201     case Intrinsic::aarch64_neon_ld4:
14202     case Intrinsic::aarch64_neon_ld1x2:
14203     case Intrinsic::aarch64_neon_ld1x3:
14204     case Intrinsic::aarch64_neon_ld1x4:
14205     case Intrinsic::aarch64_neon_ld2lane:
14206     case Intrinsic::aarch64_neon_ld3lane:
14207     case Intrinsic::aarch64_neon_ld4lane:
14208     case Intrinsic::aarch64_neon_ld2r:
14209     case Intrinsic::aarch64_neon_ld3r:
14210     case Intrinsic::aarch64_neon_ld4r:
14211     case Intrinsic::aarch64_neon_st2:
14212     case Intrinsic::aarch64_neon_st3:
14213     case Intrinsic::aarch64_neon_st4:
14214     case Intrinsic::aarch64_neon_st1x2:
14215     case Intrinsic::aarch64_neon_st1x3:
14216     case Intrinsic::aarch64_neon_st1x4:
14217     case Intrinsic::aarch64_neon_st2lane:
14218     case Intrinsic::aarch64_neon_st3lane:
14219     case Intrinsic::aarch64_neon_st4lane:
14220       return performNEONPostLDSTCombine(N, DCI, DAG);
14221     case Intrinsic::aarch64_sve_ldnt1:
14222       return performLDNT1Combine(N, DAG);
14223     case Intrinsic::aarch64_sve_ld1rq:
14224       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
14225     case Intrinsic::aarch64_sve_ld1ro:
14226       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
14227     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
14228       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14229     case Intrinsic::aarch64_sve_ldnt1_gather:
14230       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14231     case Intrinsic::aarch64_sve_ldnt1_gather_index:
14232       return performGatherLoadCombine(N, DAG,
14233                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
14234     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
14235       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
14236     case Intrinsic::aarch64_sve_ld1:
14237       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
14238     case Intrinsic::aarch64_sve_ldnf1:
14239       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
14240     case Intrinsic::aarch64_sve_ldff1:
14241       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
14242     case Intrinsic::aarch64_sve_st1:
14243       return performST1Combine(N, DAG);
14244     case Intrinsic::aarch64_sve_stnt1:
14245       return performSTNT1Combine(N, DAG);
14246     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
14247       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14248     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
14249       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14250     case Intrinsic::aarch64_sve_stnt1_scatter:
14251       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
14252     case Intrinsic::aarch64_sve_stnt1_scatter_index:
14253       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
14254     case Intrinsic::aarch64_sve_ld1_gather:
14255       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
14256     case Intrinsic::aarch64_sve_ld1_gather_index:
14257       return performGatherLoadCombine(N, DAG,
14258                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
14259     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
14260       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
14261                                       /*OnlyPackedOffsets=*/false);
14262     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
14263       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
14264                                       /*OnlyPackedOffsets=*/false);
14265     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
14266       return performGatherLoadCombine(N, DAG,
14267                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
14268                                       /*OnlyPackedOffsets=*/false);
14269     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
14270       return performGatherLoadCombine(N, DAG,
14271                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
14272                                       /*OnlyPackedOffsets=*/false);
14273     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
14274       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14275     case Intrinsic::aarch64_sve_ldff1_gather:
14276       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14277     case Intrinsic::aarch64_sve_ldff1_gather_index:
14278       return performGatherLoadCombine(N, DAG,
14279                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14280     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14281       return performGatherLoadCombine(N, DAG,
14282                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14283                                       /*OnlyPackedOffsets=*/false);
14284     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14285       return performGatherLoadCombine(N, DAG,
14286                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14287                                       /*OnlyPackedOffsets=*/false);
14288     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14289       return performGatherLoadCombine(N, DAG,
14290                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14291                                       /*OnlyPackedOffsets=*/false);
14292     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14293       return performGatherLoadCombine(N, DAG,
14294                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14295                                       /*OnlyPackedOffsets=*/false);
14296     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14297       return performGatherLoadCombine(N, DAG,
14298                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14299     case Intrinsic::aarch64_sve_st1_scatter:
14300       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14301     case Intrinsic::aarch64_sve_st1_scatter_index:
14302       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14303     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14304       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14305                                         /*OnlyPackedOffsets=*/false);
14306     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14307       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14308                                         /*OnlyPackedOffsets=*/false);
14309     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14310       return performScatterStoreCombine(N, DAG,
14311                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
14312                                         /*OnlyPackedOffsets=*/false);
14313     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14314       return performScatterStoreCombine(N, DAG,
14315                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
14316                                         /*OnlyPackedOffsets=*/false);
14317     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14318       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14319     case Intrinsic::aarch64_sve_tuple_get: {
14320       SDLoc DL(N);
14321       SDValue Chain = N->getOperand(0);
14322       SDValue Src1 = N->getOperand(2);
14323       SDValue Idx = N->getOperand(3);
14324 
14325       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14326       EVT ResVT = N->getValueType(0);
14327       uint64_t NumLanes = ResVT.getVectorElementCount().Min;
14328       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
14329       SDValue Val =
14330           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
14331       return DAG.getMergeValues({Val, Chain}, DL);
14332     }
14333     case Intrinsic::aarch64_sve_tuple_set: {
14334       SDLoc DL(N);
14335       SDValue Chain = N->getOperand(0);
14336       SDValue Tuple = N->getOperand(2);
14337       SDValue Idx = N->getOperand(3);
14338       SDValue Vec = N->getOperand(4);
14339 
14340       EVT TupleVT = Tuple.getValueType();
14341       uint64_t TupleLanes = TupleVT.getVectorElementCount().Min;
14342 
14343       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14344       uint64_t NumLanes = Vec.getValueType().getVectorElementCount().Min;
14345 
14346       if ((TupleLanes % NumLanes) != 0)
14347         report_fatal_error("invalid tuple vector!");
14348 
14349       uint64_t NumVecs = TupleLanes / NumLanes;
14350 
14351       SmallVector<SDValue, 4> Opnds;
14352       for (unsigned I = 0; I < NumVecs; ++I) {
14353         if (I == IdxConst)
14354           Opnds.push_back(Vec);
14355         else {
14356           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
14357           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
14358                                       Vec.getValueType(), Tuple, ExtIdx));
14359         }
14360       }
14361       SDValue Concat =
14362           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
14363       return DAG.getMergeValues({Concat, Chain}, DL);
14364     }
14365     case Intrinsic::aarch64_sve_tuple_create2:
14366     case Intrinsic::aarch64_sve_tuple_create3:
14367     case Intrinsic::aarch64_sve_tuple_create4: {
14368       SDLoc DL(N);
14369       SDValue Chain = N->getOperand(0);
14370 
14371       SmallVector<SDValue, 4> Opnds;
14372       for (unsigned I = 2; I < N->getNumOperands(); ++I)
14373         Opnds.push_back(N->getOperand(I));
14374 
14375       EVT VT = Opnds[0].getValueType();
14376       EVT EltVT = VT.getVectorElementType();
14377       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
14378                                     VT.getVectorElementCount() *
14379                                         (N->getNumOperands() - 2));
14380       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
14381       return DAG.getMergeValues({Concat, Chain}, DL);
14382     }
14383     case Intrinsic::aarch64_sve_ld2:
14384     case Intrinsic::aarch64_sve_ld3:
14385     case Intrinsic::aarch64_sve_ld4: {
14386       SDLoc DL(N);
14387       SDValue Chain = N->getOperand(0);
14388       SDValue Mask = N->getOperand(2);
14389       SDValue BasePtr = N->getOperand(3);
14390       SDValue LoadOps[] = {Chain, Mask, BasePtr};
14391       unsigned IntrinsicID =
14392           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14393       SDValue Result =
14394           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
14395       return DAG.getMergeValues({Result, Chain}, DL);
14396     }
14397     default:
14398       break;
14399     }
14400     break;
14401   case ISD::GlobalAddress:
14402     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
14403   }
14404   return SDValue();
14405 }
14406 
14407 // Check if the return value is used as only a return value, as otherwise
14408 // we can't perform a tail-call. In particular, we need to check for
14409 // target ISD nodes that are returns and any other "odd" constructs
14410 // that the generic analysis code won't necessarily catch.
14411 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
14412                                                SDValue &Chain) const {
14413   if (N->getNumValues() != 1)
14414     return false;
14415   if (!N->hasNUsesOfValue(1, 0))
14416     return false;
14417 
14418   SDValue TCChain = Chain;
14419   SDNode *Copy = *N->use_begin();
14420   if (Copy->getOpcode() == ISD::CopyToReg) {
14421     // If the copy has a glue operand, we conservatively assume it isn't safe to
14422     // perform a tail call.
14423     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
14424         MVT::Glue)
14425       return false;
14426     TCChain = Copy->getOperand(0);
14427   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
14428     return false;
14429 
14430   bool HasRet = false;
14431   for (SDNode *Node : Copy->uses()) {
14432     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
14433       return false;
14434     HasRet = true;
14435   }
14436 
14437   if (!HasRet)
14438     return false;
14439 
14440   Chain = TCChain;
14441   return true;
14442 }
14443 
14444 // Return whether the an instruction can potentially be optimized to a tail
14445 // call. This will cause the optimizers to attempt to move, or duplicate,
14446 // return instructions to help enable tail call optimizations for this
14447 // instruction.
14448 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14449   return CI->isTailCall();
14450 }
14451 
14452 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
14453                                                    SDValue &Offset,
14454                                                    ISD::MemIndexedMode &AM,
14455                                                    bool &IsInc,
14456                                                    SelectionDAG &DAG) const {
14457   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
14458     return false;
14459 
14460   Base = Op->getOperand(0);
14461   // All of the indexed addressing mode instructions take a signed
14462   // 9 bit immediate offset.
14463   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
14464     int64_t RHSC = RHS->getSExtValue();
14465     if (Op->getOpcode() == ISD::SUB)
14466       RHSC = -(uint64_t)RHSC;
14467     if (!isInt<9>(RHSC))
14468       return false;
14469     IsInc = (Op->getOpcode() == ISD::ADD);
14470     Offset = Op->getOperand(1);
14471     return true;
14472   }
14473   return false;
14474 }
14475 
14476 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14477                                                       SDValue &Offset,
14478                                                       ISD::MemIndexedMode &AM,
14479                                                       SelectionDAG &DAG) const {
14480   EVT VT;
14481   SDValue Ptr;
14482   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14483     VT = LD->getMemoryVT();
14484     Ptr = LD->getBasePtr();
14485   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14486     VT = ST->getMemoryVT();
14487     Ptr = ST->getBasePtr();
14488   } else
14489     return false;
14490 
14491   bool IsInc;
14492   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
14493     return false;
14494   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
14495   return true;
14496 }
14497 
14498 bool AArch64TargetLowering::getPostIndexedAddressParts(
14499     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
14500     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
14501   EVT VT;
14502   SDValue Ptr;
14503   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14504     VT = LD->getMemoryVT();
14505     Ptr = LD->getBasePtr();
14506   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14507     VT = ST->getMemoryVT();
14508     Ptr = ST->getBasePtr();
14509   } else
14510     return false;
14511 
14512   bool IsInc;
14513   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
14514     return false;
14515   // Post-indexing updates the base, so it's not a valid transform
14516   // if that's not the same as the load's pointer.
14517   if (Ptr != Base)
14518     return false;
14519   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
14520   return true;
14521 }
14522 
14523 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
14524                                   SelectionDAG &DAG) {
14525   SDLoc DL(N);
14526   SDValue Op = N->getOperand(0);
14527 
14528   if (N->getValueType(0) != MVT::i16 ||
14529       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
14530     return;
14531 
14532   Op = SDValue(
14533       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
14534                          DAG.getUNDEF(MVT::i32), Op,
14535                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
14536       0);
14537   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
14538   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
14539 }
14540 
14541 static void ReplaceReductionResults(SDNode *N,
14542                                     SmallVectorImpl<SDValue> &Results,
14543                                     SelectionDAG &DAG, unsigned InterOp,
14544                                     unsigned AcrossOp) {
14545   EVT LoVT, HiVT;
14546   SDValue Lo, Hi;
14547   SDLoc dl(N);
14548   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
14549   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
14550   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
14551   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
14552   Results.push_back(SplitVal);
14553 }
14554 
14555 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
14556   SDLoc DL(N);
14557   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
14558   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
14559                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
14560                                        DAG.getConstant(64, DL, MVT::i64)));
14561   return std::make_pair(Lo, Hi);
14562 }
14563 
14564 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
14565     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14566   SDValue In = N->getOperand(0);
14567   EVT InVT = In.getValueType();
14568 
14569   // Common code will handle these just fine.
14570   if (!InVT.isScalableVector() || !InVT.isInteger())
14571     return;
14572 
14573   SDLoc DL(N);
14574   EVT VT = N->getValueType(0);
14575 
14576   // The following checks bail if this is not a halving operation.
14577 
14578   ElementCount ResEC = VT.getVectorElementCount();
14579 
14580   if (InVT.getVectorElementCount().Min != (ResEC.Min * 2))
14581     return;
14582 
14583   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
14584   if (!CIndex)
14585     return;
14586 
14587   unsigned Index = CIndex->getZExtValue();
14588   if ((Index != 0) && (Index != ResEC.Min))
14589     return;
14590 
14591   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
14592   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
14593 
14594   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
14595   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
14596 }
14597 
14598 // Create an even/odd pair of X registers holding integer value V.
14599 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
14600   SDLoc dl(V.getNode());
14601   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
14602   SDValue VHi = DAG.getAnyExtOrTrunc(
14603       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
14604       dl, MVT::i64);
14605   if (DAG.getDataLayout().isBigEndian())
14606     std::swap (VLo, VHi);
14607   SDValue RegClass =
14608       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
14609   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
14610   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
14611   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
14612   return SDValue(
14613       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
14614 }
14615 
14616 static void ReplaceCMP_SWAP_128Results(SDNode *N,
14617                                        SmallVectorImpl<SDValue> &Results,
14618                                        SelectionDAG &DAG,
14619                                        const AArch64Subtarget *Subtarget) {
14620   assert(N->getValueType(0) == MVT::i128 &&
14621          "AtomicCmpSwap on types less than 128 should be legal");
14622 
14623   if (Subtarget->hasLSE()) {
14624     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
14625     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
14626     SDValue Ops[] = {
14627         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
14628         createGPRPairNode(DAG, N->getOperand(3)), // Store value
14629         N->getOperand(1), // Ptr
14630         N->getOperand(0), // Chain in
14631     };
14632 
14633     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14634 
14635     unsigned Opcode;
14636     switch (MemOp->getOrdering()) {
14637     case AtomicOrdering::Monotonic:
14638       Opcode = AArch64::CASPX;
14639       break;
14640     case AtomicOrdering::Acquire:
14641       Opcode = AArch64::CASPAX;
14642       break;
14643     case AtomicOrdering::Release:
14644       Opcode = AArch64::CASPLX;
14645       break;
14646     case AtomicOrdering::AcquireRelease:
14647     case AtomicOrdering::SequentiallyConsistent:
14648       Opcode = AArch64::CASPALX;
14649       break;
14650     default:
14651       llvm_unreachable("Unexpected ordering!");
14652     }
14653 
14654     MachineSDNode *CmpSwap = DAG.getMachineNode(
14655         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
14656     DAG.setNodeMemRefs(CmpSwap, {MemOp});
14657 
14658     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
14659     if (DAG.getDataLayout().isBigEndian())
14660       std::swap(SubReg1, SubReg2);
14661     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
14662                                             SDValue(CmpSwap, 0));
14663     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
14664                                             SDValue(CmpSwap, 0));
14665     Results.push_back(
14666         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
14667     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
14668     return;
14669   }
14670 
14671   auto Desired = splitInt128(N->getOperand(2), DAG);
14672   auto New = splitInt128(N->getOperand(3), DAG);
14673   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
14674                    New.first,        New.second,    N->getOperand(0)};
14675   SDNode *CmpSwap = DAG.getMachineNode(
14676       AArch64::CMP_SWAP_128, SDLoc(N),
14677       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
14678 
14679   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14680   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
14681 
14682   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14683                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
14684   Results.push_back(SDValue(CmpSwap, 3));
14685 }
14686 
14687 void AArch64TargetLowering::ReplaceNodeResults(
14688     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14689   switch (N->getOpcode()) {
14690   default:
14691     llvm_unreachable("Don't know how to custom expand this");
14692   case ISD::BITCAST:
14693     ReplaceBITCASTResults(N, Results, DAG);
14694     return;
14695   case ISD::VECREDUCE_ADD:
14696   case ISD::VECREDUCE_SMAX:
14697   case ISD::VECREDUCE_SMIN:
14698   case ISD::VECREDUCE_UMAX:
14699   case ISD::VECREDUCE_UMIN:
14700     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
14701     return;
14702 
14703   case ISD::CTPOP:
14704     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
14705     return;
14706   case AArch64ISD::SADDV:
14707     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
14708     return;
14709   case AArch64ISD::UADDV:
14710     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
14711     return;
14712   case AArch64ISD::SMINV:
14713     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
14714     return;
14715   case AArch64ISD::UMINV:
14716     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
14717     return;
14718   case AArch64ISD::SMAXV:
14719     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
14720     return;
14721   case AArch64ISD::UMAXV:
14722     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
14723     return;
14724   case ISD::FP_TO_UINT:
14725   case ISD::FP_TO_SINT:
14726     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
14727     // Let normal code take care of it by not adding anything to Results.
14728     return;
14729   case ISD::ATOMIC_CMP_SWAP:
14730     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
14731     return;
14732   case ISD::LOAD: {
14733     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
14734            "unexpected load's value type");
14735     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
14736     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
14737       // Non-volatile loads are optimized later in AArch64's load/store
14738       // optimizer.
14739       return;
14740     }
14741 
14742     SDValue Result = DAG.getMemIntrinsicNode(
14743         AArch64ISD::LDP, SDLoc(N),
14744         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
14745         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
14746         LoadNode->getMemOperand());
14747 
14748     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14749                                Result.getValue(0), Result.getValue(1));
14750     Results.append({Pair, Result.getValue(2) /* Chain */});
14751     return;
14752   }
14753   case ISD::EXTRACT_SUBVECTOR:
14754     ReplaceExtractSubVectorResults(N, Results, DAG);
14755     return;
14756   case ISD::INTRINSIC_WO_CHAIN: {
14757     EVT VT = N->getValueType(0);
14758     assert((VT == MVT::i8 || VT == MVT::i16) &&
14759            "custom lowering for unexpected type");
14760 
14761     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
14762     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14763     switch (IntID) {
14764     default:
14765       return;
14766     case Intrinsic::aarch64_sve_clasta_n: {
14767       SDLoc DL(N);
14768       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14769       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
14770                            N->getOperand(1), Op2, N->getOperand(3));
14771       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14772       return;
14773     }
14774     case Intrinsic::aarch64_sve_clastb_n: {
14775       SDLoc DL(N);
14776       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14777       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
14778                            N->getOperand(1), Op2, N->getOperand(3));
14779       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14780       return;
14781     }
14782     case Intrinsic::aarch64_sve_lasta: {
14783       SDLoc DL(N);
14784       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
14785                            N->getOperand(1), N->getOperand(2));
14786       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14787       return;
14788     }
14789     case Intrinsic::aarch64_sve_lastb: {
14790       SDLoc DL(N);
14791       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
14792                            N->getOperand(1), N->getOperand(2));
14793       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14794       return;
14795     }
14796     }
14797   }
14798   }
14799 }
14800 
14801 bool AArch64TargetLowering::useLoadStackGuardNode() const {
14802   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
14803     return TargetLowering::useLoadStackGuardNode();
14804   return true;
14805 }
14806 
14807 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
14808   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
14809   // reciprocal if there are three or more FDIVs.
14810   return 3;
14811 }
14812 
14813 TargetLoweringBase::LegalizeTypeAction
14814 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
14815   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
14816   // v4i16, v2i32 instead of to promote.
14817   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
14818       VT == MVT::v1f32)
14819     return TypeWidenVector;
14820 
14821   return TargetLoweringBase::getPreferredVectorAction(VT);
14822 }
14823 
14824 // Loads and stores less than 128-bits are already atomic; ones above that
14825 // are doomed anyway, so defer to the default libcall and blame the OS when
14826 // things go wrong.
14827 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14828   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14829   return Size == 128;
14830 }
14831 
14832 // Loads and stores less than 128-bits are already atomic; ones above that
14833 // are doomed anyway, so defer to the default libcall and blame the OS when
14834 // things go wrong.
14835 TargetLowering::AtomicExpansionKind
14836 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14837   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14838   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
14839 }
14840 
14841 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
14842 TargetLowering::AtomicExpansionKind
14843 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14844   if (AI->isFloatingPointOperation())
14845     return AtomicExpansionKind::CmpXChg;
14846 
14847   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14848   if (Size > 128) return AtomicExpansionKind::None;
14849   // Nand not supported in LSE.
14850   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
14851   // Leave 128 bits to LLSC.
14852   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
14853 }
14854 
14855 TargetLowering::AtomicExpansionKind
14856 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
14857     AtomicCmpXchgInst *AI) const {
14858   // If subtarget has LSE, leave cmpxchg intact for codegen.
14859   if (Subtarget->hasLSE())
14860     return AtomicExpansionKind::None;
14861   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14862   // implement cmpxchg without spilling. If the address being exchanged is also
14863   // on the stack and close enough to the spill slot, this can lead to a
14864   // situation where the monitor always gets cleared and the atomic operation
14865   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14866   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
14867     return AtomicExpansionKind::None;
14868   return AtomicExpansionKind::LLSC;
14869 }
14870 
14871 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14872                                              AtomicOrdering Ord) const {
14873   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14874   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14875   bool IsAcquire = isAcquireOrStronger(Ord);
14876 
14877   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
14878   // intrinsic must return {i64, i64} and we have to recombine them into a
14879   // single i128 here.
14880   if (ValTy->getPrimitiveSizeInBits() == 128) {
14881     Intrinsic::ID Int =
14882         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
14883     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
14884 
14885     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14886     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
14887 
14888     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14889     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14890     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14891     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14892     return Builder.CreateOr(
14893         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
14894   }
14895 
14896   Type *Tys[] = { Addr->getType() };
14897   Intrinsic::ID Int =
14898       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
14899   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
14900 
14901   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
14902 
14903   const DataLayout &DL = M->getDataLayout();
14904   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
14905   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
14906 
14907   return Builder.CreateBitCast(Trunc, EltTy);
14908 }
14909 
14910 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14911     IRBuilder<> &Builder) const {
14912   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14913   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
14914 }
14915 
14916 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
14917                                                    Value *Val, Value *Addr,
14918                                                    AtomicOrdering Ord) const {
14919   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14920   bool IsRelease = isReleaseOrStronger(Ord);
14921 
14922   // Since the intrinsics must have legal type, the i128 intrinsics take two
14923   // parameters: "i64, i64". We must marshal Val into the appropriate form
14924   // before the call.
14925   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
14926     Intrinsic::ID Int =
14927         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
14928     Function *Stxr = Intrinsic::getDeclaration(M, Int);
14929     Type *Int64Ty = Type::getInt64Ty(M->getContext());
14930 
14931     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
14932     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
14933     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14934     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
14935   }
14936 
14937   Intrinsic::ID Int =
14938       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
14939   Type *Tys[] = { Addr->getType() };
14940   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
14941 
14942   const DataLayout &DL = M->getDataLayout();
14943   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
14944   Val = Builder.CreateBitCast(Val, IntValTy);
14945 
14946   return Builder.CreateCall(Stxr,
14947                             {Builder.CreateZExtOrBitCast(
14948                                  Val, Stxr->getFunctionType()->getParamType(0)),
14949                              Addr});
14950 }
14951 
14952 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
14953     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14954   return Ty->isArrayTy();
14955 }
14956 
14957 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
14958                                                             EVT) const {
14959   return false;
14960 }
14961 
14962 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
14963   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
14964   Function *ThreadPointerFunc =
14965       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
14966   return IRB.CreatePointerCast(
14967       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
14968                              Offset),
14969       IRB.getInt8PtrTy()->getPointerTo(0));
14970 }
14971 
14972 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
14973   // Android provides a fixed TLS slot for the stack cookie. See the definition
14974   // of TLS_SLOT_STACK_GUARD in
14975   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14976   if (Subtarget->isTargetAndroid())
14977     return UseTlsOffset(IRB, 0x28);
14978 
14979   // Fuchsia is similar.
14980   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
14981   if (Subtarget->isTargetFuchsia())
14982     return UseTlsOffset(IRB, -0x10);
14983 
14984   return TargetLowering::getIRStackGuard(IRB);
14985 }
14986 
14987 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
14988   // MSVC CRT provides functionalities for stack protection.
14989   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
14990     // MSVC CRT has a global variable holding security cookie.
14991     M.getOrInsertGlobal("__security_cookie",
14992                         Type::getInt8PtrTy(M.getContext()));
14993 
14994     // MSVC CRT has a function to validate security cookie.
14995     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
14996         "__security_check_cookie", Type::getVoidTy(M.getContext()),
14997         Type::getInt8PtrTy(M.getContext()));
14998     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
14999       F->setCallingConv(CallingConv::Win64);
15000       F->addAttribute(1, Attribute::AttrKind::InReg);
15001     }
15002     return;
15003   }
15004   TargetLowering::insertSSPDeclarations(M);
15005 }
15006 
15007 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
15008   // MSVC CRT has a global variable holding security cookie.
15009   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15010     return M.getGlobalVariable("__security_cookie");
15011   return TargetLowering::getSDagStackGuard(M);
15012 }
15013 
15014 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
15015   // MSVC CRT has a function to validate security cookie.
15016   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15017     return M.getFunction("__security_check_cookie");
15018   return TargetLowering::getSSPStackGuardCheck(M);
15019 }
15020 
15021 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
15022   // Android provides a fixed TLS slot for the SafeStack pointer. See the
15023   // definition of TLS_SLOT_SAFESTACK in
15024   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15025   if (Subtarget->isTargetAndroid())
15026     return UseTlsOffset(IRB, 0x48);
15027 
15028   // Fuchsia is similar.
15029   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
15030   if (Subtarget->isTargetFuchsia())
15031     return UseTlsOffset(IRB, -0x8);
15032 
15033   return TargetLowering::getSafeStackPointerLocation(IRB);
15034 }
15035 
15036 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
15037     const Instruction &AndI) const {
15038   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
15039   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
15040   // may be beneficial to sink in other cases, but we would have to check that
15041   // the cmp would not get folded into the br to form a cbz for these to be
15042   // beneficial.
15043   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
15044   if (!Mask)
15045     return false;
15046   return Mask->getValue().isPowerOf2();
15047 }
15048 
15049 bool AArch64TargetLowering::
15050     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15051         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
15052         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
15053         SelectionDAG &DAG) const {
15054   // Does baseline recommend not to perform the fold by default?
15055   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15056           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
15057     return false;
15058   // Else, if this is a vector shift, prefer 'shl'.
15059   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
15060 }
15061 
15062 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
15063                                               SDNode *N) const {
15064   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15065       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
15066     return false;
15067   return true;
15068 }
15069 
15070 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15071   // Update IsSplitCSR in AArch64unctionInfo.
15072   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
15073   AFI->setIsSplitCSR(true);
15074 }
15075 
15076 void AArch64TargetLowering::insertCopiesSplitCSR(
15077     MachineBasicBlock *Entry,
15078     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15079   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
15080   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15081   if (!IStart)
15082     return;
15083 
15084   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15085   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15086   MachineBasicBlock::iterator MBBI = Entry->begin();
15087   for (const MCPhysReg *I = IStart; *I; ++I) {
15088     const TargetRegisterClass *RC = nullptr;
15089     if (AArch64::GPR64RegClass.contains(*I))
15090       RC = &AArch64::GPR64RegClass;
15091     else if (AArch64::FPR64RegClass.contains(*I))
15092       RC = &AArch64::FPR64RegClass;
15093     else
15094       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15095 
15096     Register NewVR = MRI->createVirtualRegister(RC);
15097     // Create copy from CSR to a virtual register.
15098     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15099     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15100     // nounwind. If we want to generalize this later, we may need to emit
15101     // CFI pseudo-instructions.
15102     assert(Entry->getParent()->getFunction().hasFnAttribute(
15103                Attribute::NoUnwind) &&
15104            "Function should be nounwind in insertCopiesSplitCSR!");
15105     Entry->addLiveIn(*I);
15106     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15107         .addReg(*I);
15108 
15109     // Insert the copy-back instructions right before the terminator.
15110     for (auto *Exit : Exits)
15111       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15112               TII->get(TargetOpcode::COPY), *I)
15113           .addReg(NewVR);
15114   }
15115 }
15116 
15117 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
15118   // Integer division on AArch64 is expensive. However, when aggressively
15119   // optimizing for code size, we prefer to use a div instruction, as it is
15120   // usually smaller than the alternative sequence.
15121   // The exception to this is vector division. Since AArch64 doesn't have vector
15122   // integer division, leaving the division as-is is a loss even in terms of
15123   // size, because it will have to be scalarized, while the alternative code
15124   // sequence can be performed in vector form.
15125   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
15126   return OptSize && !VT.isVector();
15127 }
15128 
15129 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
15130   // We want inc-of-add for scalars and sub-of-not for vectors.
15131   return VT.isScalarInteger();
15132 }
15133 
15134 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
15135   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
15136 }
15137 
15138 unsigned
15139 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
15140   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
15141     return getPointerTy(DL).getSizeInBits();
15142 
15143   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
15144 }
15145 
15146 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
15147   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15148   TargetLoweringBase::finalizeLowering(MF);
15149 }
15150 
15151 // Unlike X86, we let frame lowering assign offsets to all catch objects.
15152 bool AArch64TargetLowering::needsFixedCatchObjects() const {
15153   return false;
15154 }
15155 
15156 bool AArch64TargetLowering::shouldLocalize(
15157     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
15158   switch (MI.getOpcode()) {
15159   case TargetOpcode::G_GLOBAL_VALUE: {
15160     // On Darwin, TLS global vars get selected into function calls, which
15161     // we don't want localized, as they can get moved into the middle of a
15162     // another call sequence.
15163     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
15164     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
15165       return false;
15166     break;
15167   }
15168   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
15169   // localizable.
15170   case AArch64::ADRP:
15171   case AArch64::G_ADD_LOW:
15172     return true;
15173   default:
15174     break;
15175   }
15176   return TargetLoweringBase::shouldLocalize(MI, TTI);
15177 }
15178 
15179 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
15180   if (isa<ScalableVectorType>(Inst.getType()))
15181     return true;
15182 
15183   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
15184     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
15185       return true;
15186 
15187   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
15188     if (isa<ScalableVectorType>(AI->getAllocatedType()))
15189       return true;
15190   }
15191 
15192   return false;
15193 }
15194 
15195 // Return the largest legal scalable vector type that matches VT's element type.
15196 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
15197   assert(VT.isFixedLengthVector() &&
15198          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15199          "Expected legal fixed length vector!");
15200   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15201   default:
15202     llvm_unreachable("unexpected element type for SVE container");
15203   case MVT::i8:
15204     return EVT(MVT::nxv16i8);
15205   case MVT::i16:
15206     return EVT(MVT::nxv8i16);
15207   case MVT::i32:
15208     return EVT(MVT::nxv4i32);
15209   case MVT::i64:
15210     return EVT(MVT::nxv2i64);
15211   case MVT::f16:
15212     return EVT(MVT::nxv8f16);
15213   case MVT::f32:
15214     return EVT(MVT::nxv4f32);
15215   case MVT::f64:
15216     return EVT(MVT::nxv2f64);
15217   }
15218 }
15219 
15220 // Return a PTRUE with active lanes corresponding to the extent of VT.
15221 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
15222                                                 EVT VT) {
15223   assert(VT.isFixedLengthVector() &&
15224          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15225          "Expected legal fixed length vector!");
15226 
15227   int PgPattern;
15228   switch (VT.getVectorNumElements()) {
15229   default:
15230     llvm_unreachable("unexpected element count for SVE predicate");
15231   case 1:
15232     PgPattern = AArch64SVEPredPattern::vl1;
15233     break;
15234   case 2:
15235     PgPattern = AArch64SVEPredPattern::vl2;
15236     break;
15237   case 4:
15238     PgPattern = AArch64SVEPredPattern::vl4;
15239     break;
15240   case 8:
15241     PgPattern = AArch64SVEPredPattern::vl8;
15242     break;
15243   case 16:
15244     PgPattern = AArch64SVEPredPattern::vl16;
15245     break;
15246   case 32:
15247     PgPattern = AArch64SVEPredPattern::vl32;
15248     break;
15249   case 64:
15250     PgPattern = AArch64SVEPredPattern::vl64;
15251     break;
15252   case 128:
15253     PgPattern = AArch64SVEPredPattern::vl128;
15254     break;
15255   case 256:
15256     PgPattern = AArch64SVEPredPattern::vl256;
15257     break;
15258   }
15259 
15260   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
15261   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
15262   // variants of instructions when available.
15263 
15264   MVT MaskVT;
15265   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15266   default:
15267     llvm_unreachable("unexpected element type for SVE predicate");
15268   case MVT::i8:
15269     MaskVT = MVT::nxv16i1;
15270     break;
15271   case MVT::i16:
15272   case MVT::f16:
15273     MaskVT = MVT::nxv8i1;
15274     break;
15275   case MVT::i32:
15276   case MVT::f32:
15277     MaskVT = MVT::nxv4i1;
15278     break;
15279   case MVT::i64:
15280   case MVT::f64:
15281     MaskVT = MVT::nxv2i1;
15282     break;
15283   }
15284 
15285   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15286                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15287 }
15288 
15289 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15290                                              EVT VT) {
15291   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15292          "Expected legal scalable vector!");
15293   auto PredTy = VT.changeVectorElementType(MVT::i1);
15294   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15295 }
15296 
15297 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15298   if (VT.isFixedLengthVector())
15299     return getPredicateForFixedLengthVector(DAG, DL, VT);
15300 
15301   return getPredicateForScalableVector(DAG, DL, VT);
15302 }
15303 
15304 // Grow V to consume an entire SVE register.
15305 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15306   assert(VT.isScalableVector() &&
15307          "Expected to convert into a scalable vector!");
15308   assert(V.getValueType().isFixedLengthVector() &&
15309          "Expected a fixed length vector operand!");
15310   SDLoc DL(V);
15311   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15312   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
15313 }
15314 
15315 // Shrink V so it's just big enough to maintain a VT's worth of data.
15316 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15317   assert(VT.isFixedLengthVector() &&
15318          "Expected to convert into a fixed length vector!");
15319   assert(V.getValueType().isScalableVector() &&
15320          "Expected a scalable vector operand!");
15321   SDLoc DL(V);
15322   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15323   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
15324 }
15325 
15326 // Convert all fixed length vector loads larger than NEON to masked_loads.
15327 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
15328     SDValue Op, SelectionDAG &DAG) const {
15329   auto Load = cast<LoadSDNode>(Op);
15330 
15331   SDLoc DL(Op);
15332   EVT VT = Op.getValueType();
15333   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15334 
15335   auto NewLoad = DAG.getMaskedLoad(
15336       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
15337       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
15338       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
15339       Load->getExtensionType());
15340 
15341   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
15342   SDValue MergedValues[2] = {Result, Load->getChain()};
15343   return DAG.getMergeValues(MergedValues, DL);
15344 }
15345 
15346 // Convert all fixed length vector stores larger than NEON to masked_stores.
15347 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
15348     SDValue Op, SelectionDAG &DAG) const {
15349   auto Store = cast<StoreSDNode>(Op);
15350 
15351   SDLoc DL(Op);
15352   EVT VT = Store->getValue().getValueType();
15353   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15354 
15355   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
15356   return DAG.getMaskedStore(
15357       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
15358       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
15359       Store->getMemOperand(), Store->getAddressingMode(),
15360       Store->isTruncatingStore());
15361 }
15362 
15363 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
15364     SDValue Op, SelectionDAG &DAG) const {
15365   SDLoc dl(Op);
15366   EVT VT = Op.getValueType();
15367   EVT EltVT = VT.getVectorElementType();
15368 
15369   bool Signed = Op.getOpcode() == ISD::SDIV;
15370   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
15371 
15372   // Scalable vector i32/i64 DIV is supported.
15373   if (EltVT == MVT::i32 || EltVT == MVT::i64)
15374     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
15375 
15376   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
15377   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15378   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
15379   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
15380   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
15381 
15382   // Convert the operands to scalable vectors.
15383   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
15384   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
15385 
15386   // Extend the scalable operands.
15387   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
15388   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
15389   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
15390   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
15391   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
15392   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
15393 
15394   // Convert back to fixed vectors so the DIV can be further lowered.
15395   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
15396   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
15397   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
15398   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
15399   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
15400                                  Op0Lo, Op1Lo);
15401   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
15402                                  Op0Hi, Op1Hi);
15403 
15404   // Convert again to scalable vectors to truncate.
15405   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
15406   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
15407   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
15408                                        ResultLo, ResultHi);
15409 
15410   return convertFromScalableVector(DAG, VT, ScalableResult);
15411 }
15412 
15413 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
15414     SDValue Op, SelectionDAG &DAG) const {
15415   EVT VT = Op.getValueType();
15416   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
15417 
15418   SDLoc DL(Op);
15419   SDValue Val = Op.getOperand(0);
15420   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
15421   Val = convertToScalableVector(DAG, ContainerVT, Val);
15422 
15423   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
15424   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
15425 
15426   // Repeatedly unpack Val until the result is of the desired element type.
15427   switch (ContainerVT.getSimpleVT().SimpleTy) {
15428   default:
15429     llvm_unreachable("unimplemented container type");
15430   case MVT::nxv16i8:
15431     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
15432     if (VT.getVectorElementType() == MVT::i16)
15433       break;
15434     LLVM_FALLTHROUGH;
15435   case MVT::nxv8i16:
15436     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
15437     if (VT.getVectorElementType() == MVT::i32)
15438       break;
15439     LLVM_FALLTHROUGH;
15440   case MVT::nxv4i32:
15441     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
15442     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
15443     break;
15444   }
15445 
15446   return convertFromScalableVector(DAG, VT, Val);
15447 }
15448 
15449 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
15450     SDValue Op, SelectionDAG &DAG) const {
15451   EVT VT = Op.getValueType();
15452   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
15453 
15454   SDLoc DL(Op);
15455   SDValue Val = Op.getOperand(0);
15456   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
15457   Val = convertToScalableVector(DAG, ContainerVT, Val);
15458 
15459   // Repeatedly truncate Val until the result is of the desired element type.
15460   switch (ContainerVT.getSimpleVT().SimpleTy) {
15461   default:
15462     llvm_unreachable("unimplemented container type");
15463   case MVT::nxv2i64:
15464     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
15465     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
15466     if (VT.getVectorElementType() == MVT::i32)
15467       break;
15468     LLVM_FALLTHROUGH;
15469   case MVT::nxv4i32:
15470     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
15471     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
15472     if (VT.getVectorElementType() == MVT::i16)
15473       break;
15474     LLVM_FALLTHROUGH;
15475   case MVT::nxv8i16:
15476     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
15477     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
15478     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
15479     break;
15480   }
15481 
15482   return convertFromScalableVector(DAG, VT, Val);
15483 }
15484 
15485 // Convert vector operation 'Op' to an equivalent predicated operation whereby
15486 // the original operation's type is used to construct a suitable predicate.
15487 // NOTE: The results for inactive lanes are undefined.
15488 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
15489                                                    SelectionDAG &DAG,
15490                                                    unsigned NewOp,
15491                                                    bool OverrideNEON) const {
15492   EVT VT = Op.getValueType();
15493   SDLoc DL(Op);
15494   auto Pg = getPredicateForVector(DAG, DL, VT);
15495 
15496   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
15497     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15498 
15499     // Create list of operands by converting existing ones to scalable types.
15500     SmallVector<SDValue, 4> Operands = {Pg};
15501     for (const SDValue &V : Op->op_values()) {
15502       if (isa<CondCodeSDNode>(V)) {
15503         Operands.push_back(V);
15504         continue;
15505       }
15506 
15507       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
15508         EVT VTArg = VTNode->getVT().getVectorElementType();
15509         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
15510         Operands.push_back(DAG.getValueType(NewVTArg));
15511         continue;
15512       }
15513 
15514       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
15515              "Only fixed length vectors are supported!");
15516       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
15517     }
15518 
15519     if (isMergePassthruOpcode(NewOp))
15520       Operands.push_back(DAG.getUNDEF(ContainerVT));
15521 
15522     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
15523     return convertFromScalableVector(DAG, VT, ScalableRes);
15524   }
15525 
15526   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
15527 
15528   SmallVector<SDValue, 4> Operands = {Pg};
15529   for (const SDValue &V : Op->op_values()) {
15530     assert((isa<CondCodeSDNode>(V) || V.getValueType().isScalableVector()) &&
15531            "Only scalable vectors are supported!");
15532     Operands.push_back(V);
15533   }
15534 
15535   if (isMergePassthruOpcode(NewOp))
15536     Operands.push_back(DAG.getUNDEF(VT));
15537 
15538   return DAG.getNode(NewOp, DL, VT, Operands);
15539 }
15540 
15541 // If a fixed length vector operation has no side effects when applied to
15542 // undefined elements, we can safely use scalable vectors to perform the same
15543 // operation without needing to worry about predication.
15544 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
15545                                                  SelectionDAG &DAG) const {
15546   EVT VT = Op.getValueType();
15547   assert(useSVEForFixedLengthVectorVT(VT) &&
15548          "Only expected to lower fixed length vector operation!");
15549   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15550 
15551   // Create list of operands by converting existing ones to scalable types.
15552   SmallVector<SDValue, 4> Ops;
15553   for (const SDValue &V : Op->op_values()) {
15554     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
15555 
15556     // Pass through non-vector operands.
15557     if (!V.getValueType().isVector()) {
15558       Ops.push_back(V);
15559       continue;
15560     }
15561 
15562     // "cast" fixed length vector to a scalable vector.
15563     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
15564            "Only fixed length vectors are supported!");
15565     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
15566   }
15567 
15568   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
15569   return convertFromScalableVector(DAG, VT, ScalableRes);
15570 }
15571 
15572 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
15573     SDValue Op, SelectionDAG &DAG) const {
15574   SDLoc DL(Op);
15575   EVT InVT = Op.getOperand(0).getValueType();
15576   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
15577 
15578   assert(useSVEForFixedLengthVectorVT(InVT) &&
15579          "Only expected to lower fixed length vector operation!");
15580   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
15581          "Expected integer result of the same bit length as the inputs!");
15582 
15583   // Expand floating point vector comparisons.
15584   if (InVT.isFloatingPoint())
15585     return SDValue();
15586 
15587   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
15588   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
15589   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
15590 
15591   EVT CmpVT = Pg.getValueType();
15592   SmallVector<SDValue, 4> CmpOps = {Pg, Op1, Op2, Op.getOperand(2)};
15593   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT, CmpOps);
15594 
15595   EVT PromoteVT = ContainerVT.changeTypeToInteger();
15596   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
15597   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
15598 }
15599