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 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
132                                              const AArch64Subtarget &STI)
133     : TargetLowering(TM), Subtarget(&STI) {
134   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
135   // we have to make something up. Arbitrarily, choose ZeroOrOne.
136   setBooleanContents(ZeroOrOneBooleanContent);
137   // When comparing vectors the result sets the different elements in the
138   // vector to all-one or all-zero.
139   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
140 
141   // Set up the register classes.
142   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
143   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
144 
145   if (Subtarget->hasFPARMv8()) {
146     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
147     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
148     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
149     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
150     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
151   }
152 
153   if (Subtarget->hasNEON()) {
154     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
155     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
156     // Someone set us up the NEON.
157     addDRTypeForNEON(MVT::v2f32);
158     addDRTypeForNEON(MVT::v8i8);
159     addDRTypeForNEON(MVT::v4i16);
160     addDRTypeForNEON(MVT::v2i32);
161     addDRTypeForNEON(MVT::v1i64);
162     addDRTypeForNEON(MVT::v1f64);
163     addDRTypeForNEON(MVT::v4f16);
164     addDRTypeForNEON(MVT::v4bf16);
165 
166     addQRTypeForNEON(MVT::v4f32);
167     addQRTypeForNEON(MVT::v2f64);
168     addQRTypeForNEON(MVT::v16i8);
169     addQRTypeForNEON(MVT::v8i16);
170     addQRTypeForNEON(MVT::v4i32);
171     addQRTypeForNEON(MVT::v2i64);
172     addQRTypeForNEON(MVT::v8f16);
173     addQRTypeForNEON(MVT::v8bf16);
174   }
175 
176   if (Subtarget->hasSVE()) {
177     // Add legal sve predicate types
178     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
179     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
180     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
181     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
182 
183     // Add legal sve data types
184     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
185     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
186     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
187     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
188 
189     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
190     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
191     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
192     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
193     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
194     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
195 
196     if (Subtarget->hasBF16()) {
197       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
198       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
199       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
200     }
201 
202     if (useSVEForFixedLengthVectors()) {
203       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
204         if (useSVEForFixedLengthVectorVT(VT))
205           addRegisterClass(VT, &AArch64::ZPRRegClass);
206 
207       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
208         if (useSVEForFixedLengthVectorVT(VT))
209           addRegisterClass(VT, &AArch64::ZPRRegClass);
210     }
211 
212     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
213       setOperationAction(ISD::SADDSAT, VT, Legal);
214       setOperationAction(ISD::UADDSAT, VT, Legal);
215       setOperationAction(ISD::SSUBSAT, VT, Legal);
216       setOperationAction(ISD::USUBSAT, VT, Legal);
217       setOperationAction(ISD::UREM, VT, Expand);
218       setOperationAction(ISD::SREM, VT, Expand);
219       setOperationAction(ISD::SDIVREM, VT, Expand);
220       setOperationAction(ISD::UDIVREM, VT, Expand);
221     }
222 
223     for (auto VT :
224          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
225            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
226       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
227 
228     for (auto VT :
229          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
230            MVT::nxv2f64 }) {
231       setCondCodeAction(ISD::SETO, VT, Expand);
232       setCondCodeAction(ISD::SETOLT, VT, Expand);
233       setCondCodeAction(ISD::SETOLE, VT, Expand);
234       setCondCodeAction(ISD::SETULT, VT, Expand);
235       setCondCodeAction(ISD::SETULE, VT, Expand);
236       setCondCodeAction(ISD::SETUGE, VT, Expand);
237       setCondCodeAction(ISD::SETUGT, VT, Expand);
238       setCondCodeAction(ISD::SETUEQ, VT, Expand);
239       setCondCodeAction(ISD::SETUNE, VT, Expand);
240     }
241   }
242 
243   // Compute derived properties from the register classes
244   computeRegisterProperties(Subtarget->getRegisterInfo());
245 
246   // Provide all sorts of operation actions
247   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
248   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
249   setOperationAction(ISD::SETCC, MVT::i32, Custom);
250   setOperationAction(ISD::SETCC, MVT::i64, Custom);
251   setOperationAction(ISD::SETCC, MVT::f16, Custom);
252   setOperationAction(ISD::SETCC, MVT::f32, Custom);
253   setOperationAction(ISD::SETCC, MVT::f64, Custom);
254   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
255   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
256   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
257   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
258   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
259   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
260   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
261   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
262   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
263   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
264   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
265   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
266   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
267   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
268   setOperationAction(ISD::SELECT, MVT::i32, Custom);
269   setOperationAction(ISD::SELECT, MVT::i64, Custom);
270   setOperationAction(ISD::SELECT, MVT::f16, Custom);
271   setOperationAction(ISD::SELECT, MVT::f32, Custom);
272   setOperationAction(ISD::SELECT, MVT::f64, Custom);
273   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
274   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
275   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
276   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
277   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
278   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
279   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
284 
285   setOperationAction(ISD::FREM, MVT::f32, Expand);
286   setOperationAction(ISD::FREM, MVT::f64, Expand);
287   setOperationAction(ISD::FREM, MVT::f80, Expand);
288 
289   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
290 
291   // Custom lowering hooks are needed for XOR
292   // to fold it into CSINC/CSINV.
293   setOperationAction(ISD::XOR, MVT::i32, Custom);
294   setOperationAction(ISD::XOR, MVT::i64, Custom);
295 
296   // Virtually no operation on f128 is legal, but LLVM can't expand them when
297   // there's a valid register class, so we need custom operations in most cases.
298   setOperationAction(ISD::FABS, MVT::f128, Expand);
299   setOperationAction(ISD::FADD, MVT::f128, Custom);
300   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
301   setOperationAction(ISD::FCOS, MVT::f128, Expand);
302   setOperationAction(ISD::FDIV, MVT::f128, Custom);
303   setOperationAction(ISD::FMA, MVT::f128, Expand);
304   setOperationAction(ISD::FMUL, MVT::f128, Custom);
305   setOperationAction(ISD::FNEG, MVT::f128, Expand);
306   setOperationAction(ISD::FPOW, MVT::f128, Expand);
307   setOperationAction(ISD::FREM, MVT::f128, Expand);
308   setOperationAction(ISD::FRINT, MVT::f128, Expand);
309   setOperationAction(ISD::FSIN, MVT::f128, Expand);
310   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
311   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
312   setOperationAction(ISD::FSUB, MVT::f128, Custom);
313   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
314   setOperationAction(ISD::SETCC, MVT::f128, Custom);
315   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
316   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
317   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
318   setOperationAction(ISD::SELECT, MVT::f128, Custom);
319   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
320   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
321 
322   // Lowering for many of the conversions is actually specified by the non-f128
323   // type. The LowerXXX function will be trivial when f128 isn't involved.
324   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
325   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
326   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
327   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
328   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
329   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
330   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
331   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
332   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
333   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
334   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
335   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
336   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
337   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
338   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
339   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
340   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
341   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
342   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
343   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
344   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
345   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
346   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
347   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
348   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
349   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
350   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
351   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
352 
353   // Variable arguments.
354   setOperationAction(ISD::VASTART, MVT::Other, Custom);
355   setOperationAction(ISD::VAARG, MVT::Other, Custom);
356   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
357   setOperationAction(ISD::VAEND, MVT::Other, Expand);
358 
359   // Variable-sized objects.
360   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
361   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
362 
363   if (Subtarget->isTargetWindows())
364     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
365   else
366     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
367 
368   // Constant pool entries
369   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
370 
371   // BlockAddress
372   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
373 
374   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
375   setOperationAction(ISD::ADDC, MVT::i32, Custom);
376   setOperationAction(ISD::ADDE, MVT::i32, Custom);
377   setOperationAction(ISD::SUBC, MVT::i32, Custom);
378   setOperationAction(ISD::SUBE, MVT::i32, Custom);
379   setOperationAction(ISD::ADDC, MVT::i64, Custom);
380   setOperationAction(ISD::ADDE, MVT::i64, Custom);
381   setOperationAction(ISD::SUBC, MVT::i64, Custom);
382   setOperationAction(ISD::SUBE, MVT::i64, Custom);
383 
384   // AArch64 lacks both left-rotate and popcount instructions.
385   setOperationAction(ISD::ROTL, MVT::i32, Expand);
386   setOperationAction(ISD::ROTL, MVT::i64, Expand);
387   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
388     setOperationAction(ISD::ROTL, VT, Expand);
389     setOperationAction(ISD::ROTR, VT, Expand);
390   }
391 
392   // AArch64 doesn't have i32 MULH{S|U}.
393   setOperationAction(ISD::MULHU, MVT::i32, Expand);
394   setOperationAction(ISD::MULHS, MVT::i32, Expand);
395 
396   // AArch64 doesn't have {U|S}MUL_LOHI.
397   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
398   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
399 
400   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
401   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
402   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
403 
404   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
405   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
406   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
407     setOperationAction(ISD::SDIVREM, VT, Expand);
408     setOperationAction(ISD::UDIVREM, VT, Expand);
409   }
410   setOperationAction(ISD::SREM, MVT::i32, Expand);
411   setOperationAction(ISD::SREM, MVT::i64, Expand);
412   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
413   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
414   setOperationAction(ISD::UREM, MVT::i32, Expand);
415   setOperationAction(ISD::UREM, MVT::i64, Expand);
416 
417   // Custom lower Add/Sub/Mul with overflow.
418   setOperationAction(ISD::SADDO, MVT::i32, Custom);
419   setOperationAction(ISD::SADDO, MVT::i64, Custom);
420   setOperationAction(ISD::UADDO, MVT::i32, Custom);
421   setOperationAction(ISD::UADDO, MVT::i64, Custom);
422   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
423   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
424   setOperationAction(ISD::USUBO, MVT::i32, Custom);
425   setOperationAction(ISD::USUBO, MVT::i64, Custom);
426   setOperationAction(ISD::SMULO, MVT::i32, Custom);
427   setOperationAction(ISD::SMULO, MVT::i64, Custom);
428   setOperationAction(ISD::UMULO, MVT::i32, Custom);
429   setOperationAction(ISD::UMULO, MVT::i64, Custom);
430 
431   setOperationAction(ISD::FSIN, MVT::f32, Expand);
432   setOperationAction(ISD::FSIN, MVT::f64, Expand);
433   setOperationAction(ISD::FCOS, MVT::f32, Expand);
434   setOperationAction(ISD::FCOS, MVT::f64, Expand);
435   setOperationAction(ISD::FPOW, MVT::f32, Expand);
436   setOperationAction(ISD::FPOW, MVT::f64, Expand);
437   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439   if (Subtarget->hasFullFP16())
440     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
441   else
442     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
443 
444   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
445   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
446   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
447   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
448   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
449   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
450   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
451   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
452   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
453   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
454   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
455   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
456   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
457   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
458   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
459   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
460   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
461   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
462   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
463   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
464   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
465   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
466   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
467   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
468   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
469   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
470   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
471   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
472   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
473   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
474   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
475   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
476   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
477 
478   if (!Subtarget->hasFullFP16()) {
479     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
480     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
481     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
482     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
483     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
484     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
485     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
486     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
487     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
488     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
489     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
490     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
491     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
492     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
493     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
494     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
495     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
496     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
497     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
498     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
499     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
500     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
501 
502     // promote v4f16 to v4f32 when that is known to be safe.
503     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
504     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
505     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
506     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
507     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
508     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
509     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
510     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
511 
512     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
513     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
514     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
515     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
516     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
517     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
518     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
519     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
520     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
521     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
522     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
523     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
524     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
525     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
526     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
527 
528     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
529     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
530     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
531     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
532     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
533     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
534     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
535     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
536     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
537     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
538     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
539     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
540     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
541     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
542     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
543     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
544     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
545     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
546     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
547     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
548   }
549 
550   // AArch64 has implementations of a lot of rounding-like FP operations.
551   for (MVT Ty : {MVT::f32, MVT::f64}) {
552     setOperationAction(ISD::FFLOOR, Ty, Legal);
553     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
554     setOperationAction(ISD::FCEIL, Ty, Legal);
555     setOperationAction(ISD::FRINT, Ty, Legal);
556     setOperationAction(ISD::FTRUNC, Ty, Legal);
557     setOperationAction(ISD::FROUND, Ty, Legal);
558     setOperationAction(ISD::FMINNUM, Ty, Legal);
559     setOperationAction(ISD::FMAXNUM, Ty, Legal);
560     setOperationAction(ISD::FMINIMUM, Ty, Legal);
561     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
562     setOperationAction(ISD::LROUND, Ty, Legal);
563     setOperationAction(ISD::LLROUND, Ty, Legal);
564     setOperationAction(ISD::LRINT, Ty, Legal);
565     setOperationAction(ISD::LLRINT, Ty, Legal);
566   }
567 
568   if (Subtarget->hasFullFP16()) {
569     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
570     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
571     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
572     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
573     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
574     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
575     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
576     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
577     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
578     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
579   }
580 
581   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
582 
583   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
584 
585   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
586   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
587   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
588   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
589   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
590 
591   // 128-bit loads and stores can be done without expanding
592   setOperationAction(ISD::LOAD, MVT::i128, Custom);
593   setOperationAction(ISD::STORE, MVT::i128, Custom);
594 
595   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
596   // custom lowering, as there are no un-paired non-temporal stores and
597   // legalization will break up 256 bit inputs.
598   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
599   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
600   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
601   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
602   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
603   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
604   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
605 
606   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
607   // This requires the Performance Monitors extension.
608   if (Subtarget->hasPerfMon())
609     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
610 
611   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
612       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
613     // Issue __sincos_stret if available.
614     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
615     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
616   } else {
617     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
618     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
619   }
620 
621   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
622     // MSVCRT doesn't have powi; fall back to pow
623     setLibcallName(RTLIB::POWI_F32, nullptr);
624     setLibcallName(RTLIB::POWI_F64, nullptr);
625   }
626 
627   // Make floating-point constants legal for the large code model, so they don't
628   // become loads from the constant pool.
629   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
630     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
631     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
632   }
633 
634   // AArch64 does not have floating-point extending loads, i1 sign-extending
635   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
636   for (MVT VT : MVT::fp_valuetypes()) {
637     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
638     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
639     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
640     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
641   }
642   for (MVT VT : MVT::integer_valuetypes())
643     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
644 
645   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
646   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
647   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
648   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
649   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
650   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
651   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
652 
653   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
654   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
655   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
656 
657   // Indexed loads and stores are supported.
658   for (unsigned im = (unsigned)ISD::PRE_INC;
659        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
660     setIndexedLoadAction(im, MVT::i8, Legal);
661     setIndexedLoadAction(im, MVT::i16, Legal);
662     setIndexedLoadAction(im, MVT::i32, Legal);
663     setIndexedLoadAction(im, MVT::i64, Legal);
664     setIndexedLoadAction(im, MVT::f64, Legal);
665     setIndexedLoadAction(im, MVT::f32, Legal);
666     setIndexedLoadAction(im, MVT::f16, Legal);
667     setIndexedLoadAction(im, MVT::bf16, Legal);
668     setIndexedStoreAction(im, MVT::i8, Legal);
669     setIndexedStoreAction(im, MVT::i16, Legal);
670     setIndexedStoreAction(im, MVT::i32, Legal);
671     setIndexedStoreAction(im, MVT::i64, Legal);
672     setIndexedStoreAction(im, MVT::f64, Legal);
673     setIndexedStoreAction(im, MVT::f32, Legal);
674     setIndexedStoreAction(im, MVT::f16, Legal);
675     setIndexedStoreAction(im, MVT::bf16, Legal);
676   }
677 
678   // Trap.
679   setOperationAction(ISD::TRAP, MVT::Other, Legal);
680   if (Subtarget->isTargetWindows())
681     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
682 
683   // We combine OR nodes for bitfield operations.
684   setTargetDAGCombine(ISD::OR);
685   // Try to create BICs for vector ANDs.
686   setTargetDAGCombine(ISD::AND);
687 
688   // Vector add and sub nodes may conceal a high-half opportunity.
689   // Also, try to fold ADD into CSINC/CSINV..
690   setTargetDAGCombine(ISD::ADD);
691   setTargetDAGCombine(ISD::SUB);
692   setTargetDAGCombine(ISD::SRL);
693   setTargetDAGCombine(ISD::XOR);
694   setTargetDAGCombine(ISD::SINT_TO_FP);
695   setTargetDAGCombine(ISD::UINT_TO_FP);
696 
697   setTargetDAGCombine(ISD::FP_TO_SINT);
698   setTargetDAGCombine(ISD::FP_TO_UINT);
699   setTargetDAGCombine(ISD::FDIV);
700 
701   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
702 
703   setTargetDAGCombine(ISD::ANY_EXTEND);
704   setTargetDAGCombine(ISD::ZERO_EXTEND);
705   setTargetDAGCombine(ISD::SIGN_EXTEND);
706   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
707   setTargetDAGCombine(ISD::CONCAT_VECTORS);
708   setTargetDAGCombine(ISD::STORE);
709   if (Subtarget->supportsAddressTopByteIgnored())
710     setTargetDAGCombine(ISD::LOAD);
711 
712   setTargetDAGCombine(ISD::MUL);
713 
714   setTargetDAGCombine(ISD::SELECT);
715   setTargetDAGCombine(ISD::VSELECT);
716 
717   setTargetDAGCombine(ISD::INTRINSIC_VOID);
718   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
719   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
720 
721   setTargetDAGCombine(ISD::GlobalAddress);
722 
723   // In case of strict alignment, avoid an excessive number of byte wide stores.
724   MaxStoresPerMemsetOptSize = 8;
725   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
726                        ? MaxStoresPerMemsetOptSize : 32;
727 
728   MaxGluedStoresPerMemcpy = 4;
729   MaxStoresPerMemcpyOptSize = 4;
730   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
731                        ? MaxStoresPerMemcpyOptSize : 16;
732 
733   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
734 
735   MaxLoadsPerMemcmpOptSize = 4;
736   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
737                       ? MaxLoadsPerMemcmpOptSize : 8;
738 
739   setStackPointerRegisterToSaveRestore(AArch64::SP);
740 
741   setSchedulingPreference(Sched::Hybrid);
742 
743   EnableExtLdPromotion = true;
744 
745   // Set required alignment.
746   setMinFunctionAlignment(Align(4));
747   // Set preferred alignments.
748   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
749   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
750 
751   // Only change the limit for entries in a jump table if specified by
752   // the sub target, but not at the command line.
753   unsigned MaxJT = STI.getMaximumJumpTableSize();
754   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
755     setMaximumJumpTableSize(MaxJT);
756 
757   setHasExtractBitsInsn(true);
758 
759   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
760 
761   if (Subtarget->hasNEON()) {
762     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
763     // silliness like this:
764     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
765     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
766     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
767     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
768     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
769     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
770     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
771     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
772     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
774     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
775     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
776     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
777     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
778     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
779     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
780     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
781     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
782     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
783     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
784     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
785     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
786     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
787     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
788     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
789 
790     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
791     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
792     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
793     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
794     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
795 
796     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
797 
798     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
799     // elements smaller than i32, so promote the input to i32 first.
800     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
801     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
802     // i8 vector elements also need promotion to i32 for v8i8
803     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
804     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
805     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
806     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
807     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
808     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
809     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
810     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
811     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
812     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
813     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
814 
815     if (Subtarget->hasFullFP16()) {
816       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
817       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
818       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
819       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
820     } else {
821       // when AArch64 doesn't have fullfp16 support, promote the input
822       // to i32 first.
823       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
824       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
825       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
826       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
827     }
828 
829     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
830     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
831 
832     // AArch64 doesn't have MUL.2d:
833     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
834     // Custom handling for some quad-vector types to detect MULL.
835     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
836     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
837     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
838 
839     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
840                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
841       // Vector reductions
842       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
843       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
844       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
845       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
846       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
847 
848       // Saturates
849       setOperationAction(ISD::SADDSAT, VT, Legal);
850       setOperationAction(ISD::UADDSAT, VT, Legal);
851       setOperationAction(ISD::SSUBSAT, VT, Legal);
852       setOperationAction(ISD::USUBSAT, VT, Legal);
853 
854       setOperationAction(ISD::TRUNCATE, VT, Custom);
855     }
856     for (MVT VT : { MVT::v4f16, MVT::v2f32,
857                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
858       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
859       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
860     }
861 
862     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
863     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
864     // Likewise, narrowing and extending vector loads/stores aren't handled
865     // directly.
866     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
867       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
868 
869       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
870         setOperationAction(ISD::MULHS, VT, Legal);
871         setOperationAction(ISD::MULHU, VT, Legal);
872       } else {
873         setOperationAction(ISD::MULHS, VT, Expand);
874         setOperationAction(ISD::MULHU, VT, Expand);
875       }
876       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
877       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
878 
879       setOperationAction(ISD::BSWAP, VT, Expand);
880       setOperationAction(ISD::CTTZ, VT, Expand);
881 
882       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
883         setTruncStoreAction(VT, InnerVT, Expand);
884         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
885         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
886         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
887       }
888     }
889 
890     // AArch64 has implementations of a lot of rounding-like FP operations.
891     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
892       setOperationAction(ISD::FFLOOR, Ty, Legal);
893       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
894       setOperationAction(ISD::FCEIL, Ty, Legal);
895       setOperationAction(ISD::FRINT, Ty, Legal);
896       setOperationAction(ISD::FTRUNC, Ty, Legal);
897       setOperationAction(ISD::FROUND, Ty, Legal);
898     }
899 
900     if (Subtarget->hasFullFP16()) {
901       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
902         setOperationAction(ISD::FFLOOR, Ty, Legal);
903         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
904         setOperationAction(ISD::FCEIL, Ty, Legal);
905         setOperationAction(ISD::FRINT, Ty, Legal);
906         setOperationAction(ISD::FTRUNC, Ty, Legal);
907         setOperationAction(ISD::FROUND, Ty, Legal);
908       }
909     }
910 
911     if (Subtarget->hasSVE())
912       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
913 
914     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
915   }
916 
917   if (Subtarget->hasSVE()) {
918     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
919     // splat of 0 or undef) once vector selects supported in SVE codegen. See
920     // D68877 for more details.
921     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
922       if (isTypeLegal(VT)) {
923         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
924         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
925         setOperationAction(ISD::SELECT, VT, Custom);
926         setOperationAction(ISD::SDIV, VT, Custom);
927         setOperationAction(ISD::UDIV, VT, Custom);
928         setOperationAction(ISD::SMIN, VT, Custom);
929         setOperationAction(ISD::UMIN, VT, Custom);
930         setOperationAction(ISD::SMAX, VT, Custom);
931         setOperationAction(ISD::UMAX, VT, Custom);
932         setOperationAction(ISD::SHL, VT, Custom);
933         setOperationAction(ISD::SRL, VT, Custom);
934         setOperationAction(ISD::SRA, VT, Custom);
935         if (VT.getScalarType() == MVT::i1)
936           setOperationAction(ISD::SETCC, VT, Custom);
937       }
938     }
939 
940     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32})
941       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
942 
943     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
944     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
945 
946     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
947       if (isTypeLegal(VT)) {
948         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
949         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
950         setOperationAction(ISD::SELECT, VT, Custom);
951         setOperationAction(ISD::FMA, VT, Custom);
952       }
953     }
954 
955     // NOTE: Currently this has to happen after computeRegisterProperties rather
956     // than the preferred option of combining it with the addRegisterClass call.
957     if (useSVEForFixedLengthVectors()) {
958       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
959         if (useSVEForFixedLengthVectorVT(VT))
960           addTypeForFixedLengthSVE(VT);
961       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
962         if (useSVEForFixedLengthVectorVT(VT))
963           addTypeForFixedLengthSVE(VT);
964 
965       // 64bit results can mean a bigger than NEON input.
966       for (auto VT : {MVT::v8i8, MVT::v4i16})
967         setOperationAction(ISD::TRUNCATE, VT, Custom);
968       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
969 
970       // 128bit results imply a bigger than NEON input.
971       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
972         setOperationAction(ISD::TRUNCATE, VT, Custom);
973       for (auto VT : {MVT::v8f16, MVT::v4f32})
974         setOperationAction(ISD::FP_ROUND, VT, Expand);
975     }
976   }
977 
978   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
979 }
980 
981 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
982   assert(VT.isVector() && "VT should be a vector type");
983 
984   if (VT.isFloatingPoint()) {
985     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
986     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
987     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
988   }
989 
990   // Mark vector float intrinsics as expand.
991   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
992     setOperationAction(ISD::FSIN, VT, Expand);
993     setOperationAction(ISD::FCOS, VT, Expand);
994     setOperationAction(ISD::FPOW, VT, Expand);
995     setOperationAction(ISD::FLOG, VT, Expand);
996     setOperationAction(ISD::FLOG2, VT, Expand);
997     setOperationAction(ISD::FLOG10, VT, Expand);
998     setOperationAction(ISD::FEXP, VT, Expand);
999     setOperationAction(ISD::FEXP2, VT, Expand);
1000 
1001     // But we do support custom-lowering for FCOPYSIGN.
1002     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1003   }
1004 
1005   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1006   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1007   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1008   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1009   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1010   setOperationAction(ISD::SRA, VT, Custom);
1011   setOperationAction(ISD::SRL, VT, Custom);
1012   setOperationAction(ISD::SHL, VT, Custom);
1013   setOperationAction(ISD::OR, VT, Custom);
1014   setOperationAction(ISD::SETCC, VT, Custom);
1015   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1016 
1017   setOperationAction(ISD::SELECT, VT, Expand);
1018   setOperationAction(ISD::SELECT_CC, VT, Expand);
1019   setOperationAction(ISD::VSELECT, VT, Expand);
1020   for (MVT InnerVT : MVT::all_valuetypes())
1021     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1022 
1023   // CNT supports only B element sizes, then use UADDLP to widen.
1024   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1025     setOperationAction(ISD::CTPOP, VT, Custom);
1026 
1027   setOperationAction(ISD::UDIV, VT, Expand);
1028   setOperationAction(ISD::SDIV, VT, Expand);
1029   setOperationAction(ISD::UREM, VT, Expand);
1030   setOperationAction(ISD::SREM, VT, Expand);
1031   setOperationAction(ISD::FREM, VT, Expand);
1032 
1033   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1034   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1035 
1036   if (!VT.isFloatingPoint())
1037     setOperationAction(ISD::ABS, VT, Legal);
1038 
1039   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1040   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1041     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1042       setOperationAction(Opcode, VT, Legal);
1043 
1044   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1045   if (VT.isFloatingPoint() &&
1046       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1047     for (unsigned Opcode :
1048          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1049       setOperationAction(Opcode, VT, Legal);
1050 
1051   if (Subtarget->isLittleEndian()) {
1052     for (unsigned im = (unsigned)ISD::PRE_INC;
1053          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1054       setIndexedLoadAction(im, VT, Legal);
1055       setIndexedStoreAction(im, VT, Legal);
1056     }
1057   }
1058 }
1059 
1060 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1061   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1062 
1063   // By default everything must be expanded.
1064   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1065     setOperationAction(Op, VT, Expand);
1066 
1067   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1068   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1069 
1070   // Lower fixed length vector operations to scalable equivalents.
1071   setOperationAction(ISD::ADD, VT, Custom);
1072   setOperationAction(ISD::FADD, VT, Custom);
1073   setOperationAction(ISD::LOAD, VT, Custom);
1074   setOperationAction(ISD::STORE, VT, Custom);
1075   setOperationAction(ISD::TRUNCATE, VT, Custom);
1076 }
1077 
1078 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1079   addRegisterClass(VT, &AArch64::FPR64RegClass);
1080   addTypeForNEON(VT, MVT::v2i32);
1081 }
1082 
1083 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1084   addRegisterClass(VT, &AArch64::FPR128RegClass);
1085   addTypeForNEON(VT, MVT::v4i32);
1086 }
1087 
1088 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1089                                               LLVMContext &C, EVT VT) const {
1090   if (!VT.isVector())
1091     return MVT::i32;
1092   if (VT.isScalableVector())
1093     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1094   return VT.changeVectorElementTypeToInteger();
1095 }
1096 
1097 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1098                                const APInt &Demanded,
1099                                TargetLowering::TargetLoweringOpt &TLO,
1100                                unsigned NewOpc) {
1101   uint64_t OldImm = Imm, NewImm, Enc;
1102   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1103 
1104   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1105   // bimm64.
1106   if (Imm == 0 || Imm == Mask ||
1107       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1108     return false;
1109 
1110   unsigned EltSize = Size;
1111   uint64_t DemandedBits = Demanded.getZExtValue();
1112 
1113   // Clear bits that are not demanded.
1114   Imm &= DemandedBits;
1115 
1116   while (true) {
1117     // The goal here is to set the non-demanded bits in a way that minimizes
1118     // the number of switching between 0 and 1. In order to achieve this goal,
1119     // we set the non-demanded bits to the value of the preceding demanded bits.
1120     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1121     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1122     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1123     // The final result is 0b11000011.
1124     uint64_t NonDemandedBits = ~DemandedBits;
1125     uint64_t InvertedImm = ~Imm & DemandedBits;
1126     uint64_t RotatedImm =
1127         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1128         NonDemandedBits;
1129     uint64_t Sum = RotatedImm + NonDemandedBits;
1130     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1131     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1132     NewImm = (Imm | Ones) & Mask;
1133 
1134     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1135     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1136     // we halve the element size and continue the search.
1137     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1138       break;
1139 
1140     // We cannot shrink the element size any further if it is 2-bits.
1141     if (EltSize == 2)
1142       return false;
1143 
1144     EltSize /= 2;
1145     Mask >>= EltSize;
1146     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1147 
1148     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1149     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1150       return false;
1151 
1152     // Merge the upper and lower halves of Imm and DemandedBits.
1153     Imm |= Hi;
1154     DemandedBits |= DemandedBitsHi;
1155   }
1156 
1157   ++NumOptimizedImms;
1158 
1159   // Replicate the element across the register width.
1160   while (EltSize < Size) {
1161     NewImm |= NewImm << EltSize;
1162     EltSize *= 2;
1163   }
1164 
1165   (void)OldImm;
1166   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1167          "demanded bits should never be altered");
1168   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1169 
1170   // Create the new constant immediate node.
1171   EVT VT = Op.getValueType();
1172   SDLoc DL(Op);
1173   SDValue New;
1174 
1175   // If the new constant immediate is all-zeros or all-ones, let the target
1176   // independent DAG combine optimize this node.
1177   if (NewImm == 0 || NewImm == OrigMask) {
1178     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1179                           TLO.DAG.getConstant(NewImm, DL, VT));
1180   // Otherwise, create a machine node so that target independent DAG combine
1181   // doesn't undo this optimization.
1182   } else {
1183     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1184     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1185     New = SDValue(
1186         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1187   }
1188 
1189   return TLO.CombineTo(Op, New);
1190 }
1191 
1192 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1193     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1194     TargetLoweringOpt &TLO) const {
1195   // Delay this optimization to as late as possible.
1196   if (!TLO.LegalOps)
1197     return false;
1198 
1199   if (!EnableOptimizeLogicalImm)
1200     return false;
1201 
1202   EVT VT = Op.getValueType();
1203   if (VT.isVector())
1204     return false;
1205 
1206   unsigned Size = VT.getSizeInBits();
1207   assert((Size == 32 || Size == 64) &&
1208          "i32 or i64 is expected after legalization.");
1209 
1210   // Exit early if we demand all bits.
1211   if (DemandedBits.countPopulation() == Size)
1212     return false;
1213 
1214   unsigned NewOpc;
1215   switch (Op.getOpcode()) {
1216   default:
1217     return false;
1218   case ISD::AND:
1219     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1220     break;
1221   case ISD::OR:
1222     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1223     break;
1224   case ISD::XOR:
1225     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1226     break;
1227   }
1228   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1229   if (!C)
1230     return false;
1231   uint64_t Imm = C->getZExtValue();
1232   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1233 }
1234 
1235 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1236 /// Mask are known to be either zero or one and return them Known.
1237 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1238     const SDValue Op, KnownBits &Known,
1239     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1240   switch (Op.getOpcode()) {
1241   default:
1242     break;
1243   case AArch64ISD::CSEL: {
1244     KnownBits Known2;
1245     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1246     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1247     Known.Zero &= Known2.Zero;
1248     Known.One &= Known2.One;
1249     break;
1250   }
1251   case AArch64ISD::LOADgot:
1252   case AArch64ISD::ADDlow: {
1253     if (!Subtarget->isTargetILP32())
1254       break;
1255     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1256     Known.Zero = APInt::getHighBitsSet(64, 32);
1257     break;
1258   }
1259   case ISD::INTRINSIC_W_CHAIN: {
1260     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1261     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1262     switch (IntID) {
1263     default: return;
1264     case Intrinsic::aarch64_ldaxr:
1265     case Intrinsic::aarch64_ldxr: {
1266       unsigned BitWidth = Known.getBitWidth();
1267       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1268       unsigned MemBits = VT.getScalarSizeInBits();
1269       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1270       return;
1271     }
1272     }
1273     break;
1274   }
1275   case ISD::INTRINSIC_WO_CHAIN:
1276   case ISD::INTRINSIC_VOID: {
1277     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1278     switch (IntNo) {
1279     default:
1280       break;
1281     case Intrinsic::aarch64_neon_umaxv:
1282     case Intrinsic::aarch64_neon_uminv: {
1283       // Figure out the datatype of the vector operand. The UMINV instruction
1284       // will zero extend the result, so we can mark as known zero all the
1285       // bits larger than the element datatype. 32-bit or larget doesn't need
1286       // this as those are legal types and will be handled by isel directly.
1287       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1288       unsigned BitWidth = Known.getBitWidth();
1289       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1290         assert(BitWidth >= 8 && "Unexpected width!");
1291         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1292         Known.Zero |= Mask;
1293       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1294         assert(BitWidth >= 16 && "Unexpected width!");
1295         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1296         Known.Zero |= Mask;
1297       }
1298       break;
1299     } break;
1300     }
1301   }
1302   }
1303 }
1304 
1305 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1306                                                   EVT) const {
1307   return MVT::i64;
1308 }
1309 
1310 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1311     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1312     bool *Fast) const {
1313   if (Subtarget->requiresStrictAlign())
1314     return false;
1315 
1316   if (Fast) {
1317     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1318     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1319             // See comments in performSTORECombine() for more details about
1320             // these conditions.
1321 
1322             // Code that uses clang vector extensions can mark that it
1323             // wants unaligned accesses to be treated as fast by
1324             // underspecifying alignment to be 1 or 2.
1325             Align <= 2 ||
1326 
1327             // Disregard v2i64. Memcpy lowering produces those and splitting
1328             // them regresses performance on micro-benchmarks and olden/bh.
1329             VT == MVT::v2i64;
1330   }
1331   return true;
1332 }
1333 
1334 // Same as above but handling LLTs instead.
1335 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1336     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1337     bool *Fast) const {
1338   if (Subtarget->requiresStrictAlign())
1339     return false;
1340 
1341   if (Fast) {
1342     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1343     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1344             Ty.getSizeInBytes() != 16 ||
1345             // See comments in performSTORECombine() for more details about
1346             // these conditions.
1347 
1348             // Code that uses clang vector extensions can mark that it
1349             // wants unaligned accesses to be treated as fast by
1350             // underspecifying alignment to be 1 or 2.
1351             Alignment <= 2 ||
1352 
1353             // Disregard v2i64. Memcpy lowering produces those and splitting
1354             // them regresses performance on micro-benchmarks and olden/bh.
1355             Ty == LLT::vector(2, 64);
1356   }
1357   return true;
1358 }
1359 
1360 FastISel *
1361 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1362                                       const TargetLibraryInfo *libInfo) const {
1363   return AArch64::createFastISel(funcInfo, libInfo);
1364 }
1365 
1366 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1367 #define MAKE_CASE(V)                                                           \
1368   case V:                                                                      \
1369     return #V;
1370   switch ((AArch64ISD::NodeType)Opcode) {
1371   case AArch64ISD::FIRST_NUMBER:
1372     break;
1373     MAKE_CASE(AArch64ISD::CALL)
1374     MAKE_CASE(AArch64ISD::ADRP)
1375     MAKE_CASE(AArch64ISD::ADR)
1376     MAKE_CASE(AArch64ISD::ADDlow)
1377     MAKE_CASE(AArch64ISD::LOADgot)
1378     MAKE_CASE(AArch64ISD::RET_FLAG)
1379     MAKE_CASE(AArch64ISD::BRCOND)
1380     MAKE_CASE(AArch64ISD::CSEL)
1381     MAKE_CASE(AArch64ISD::FCSEL)
1382     MAKE_CASE(AArch64ISD::CSINV)
1383     MAKE_CASE(AArch64ISD::CSNEG)
1384     MAKE_CASE(AArch64ISD::CSINC)
1385     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1386     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1387     MAKE_CASE(AArch64ISD::ADD_PRED)
1388     MAKE_CASE(AArch64ISD::SDIV_PRED)
1389     MAKE_CASE(AArch64ISD::UDIV_PRED)
1390     MAKE_CASE(AArch64ISD::SMIN_MERGE_OP1)
1391     MAKE_CASE(AArch64ISD::UMIN_MERGE_OP1)
1392     MAKE_CASE(AArch64ISD::SMAX_MERGE_OP1)
1393     MAKE_CASE(AArch64ISD::UMAX_MERGE_OP1)
1394     MAKE_CASE(AArch64ISD::SHL_MERGE_OP1)
1395     MAKE_CASE(AArch64ISD::SRL_MERGE_OP1)
1396     MAKE_CASE(AArch64ISD::SRA_MERGE_OP1)
1397     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1398     MAKE_CASE(AArch64ISD::ADC)
1399     MAKE_CASE(AArch64ISD::SBC)
1400     MAKE_CASE(AArch64ISD::ADDS)
1401     MAKE_CASE(AArch64ISD::SUBS)
1402     MAKE_CASE(AArch64ISD::ADCS)
1403     MAKE_CASE(AArch64ISD::SBCS)
1404     MAKE_CASE(AArch64ISD::ANDS)
1405     MAKE_CASE(AArch64ISD::CCMP)
1406     MAKE_CASE(AArch64ISD::CCMN)
1407     MAKE_CASE(AArch64ISD::FCCMP)
1408     MAKE_CASE(AArch64ISD::FCMP)
1409     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1410     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1411     MAKE_CASE(AArch64ISD::DUP)
1412     MAKE_CASE(AArch64ISD::DUPLANE8)
1413     MAKE_CASE(AArch64ISD::DUPLANE16)
1414     MAKE_CASE(AArch64ISD::DUPLANE32)
1415     MAKE_CASE(AArch64ISD::DUPLANE64)
1416     MAKE_CASE(AArch64ISD::MOVI)
1417     MAKE_CASE(AArch64ISD::MOVIshift)
1418     MAKE_CASE(AArch64ISD::MOVIedit)
1419     MAKE_CASE(AArch64ISD::MOVImsl)
1420     MAKE_CASE(AArch64ISD::FMOV)
1421     MAKE_CASE(AArch64ISD::MVNIshift)
1422     MAKE_CASE(AArch64ISD::MVNImsl)
1423     MAKE_CASE(AArch64ISD::BICi)
1424     MAKE_CASE(AArch64ISD::ORRi)
1425     MAKE_CASE(AArch64ISD::BSP)
1426     MAKE_CASE(AArch64ISD::NEG)
1427     MAKE_CASE(AArch64ISD::EXTR)
1428     MAKE_CASE(AArch64ISD::ZIP1)
1429     MAKE_CASE(AArch64ISD::ZIP2)
1430     MAKE_CASE(AArch64ISD::UZP1)
1431     MAKE_CASE(AArch64ISD::UZP2)
1432     MAKE_CASE(AArch64ISD::TRN1)
1433     MAKE_CASE(AArch64ISD::TRN2)
1434     MAKE_CASE(AArch64ISD::REV16)
1435     MAKE_CASE(AArch64ISD::REV32)
1436     MAKE_CASE(AArch64ISD::REV64)
1437     MAKE_CASE(AArch64ISD::EXT)
1438     MAKE_CASE(AArch64ISD::VSHL)
1439     MAKE_CASE(AArch64ISD::VLSHR)
1440     MAKE_CASE(AArch64ISD::VASHR)
1441     MAKE_CASE(AArch64ISD::VSLI)
1442     MAKE_CASE(AArch64ISD::VSRI)
1443     MAKE_CASE(AArch64ISD::CMEQ)
1444     MAKE_CASE(AArch64ISD::CMGE)
1445     MAKE_CASE(AArch64ISD::CMGT)
1446     MAKE_CASE(AArch64ISD::CMHI)
1447     MAKE_CASE(AArch64ISD::CMHS)
1448     MAKE_CASE(AArch64ISD::FCMEQ)
1449     MAKE_CASE(AArch64ISD::FCMGE)
1450     MAKE_CASE(AArch64ISD::FCMGT)
1451     MAKE_CASE(AArch64ISD::CMEQz)
1452     MAKE_CASE(AArch64ISD::CMGEz)
1453     MAKE_CASE(AArch64ISD::CMGTz)
1454     MAKE_CASE(AArch64ISD::CMLEz)
1455     MAKE_CASE(AArch64ISD::CMLTz)
1456     MAKE_CASE(AArch64ISD::FCMEQz)
1457     MAKE_CASE(AArch64ISD::FCMGEz)
1458     MAKE_CASE(AArch64ISD::FCMGTz)
1459     MAKE_CASE(AArch64ISD::FCMLEz)
1460     MAKE_CASE(AArch64ISD::FCMLTz)
1461     MAKE_CASE(AArch64ISD::SADDV)
1462     MAKE_CASE(AArch64ISD::UADDV)
1463     MAKE_CASE(AArch64ISD::SRHADD)
1464     MAKE_CASE(AArch64ISD::URHADD)
1465     MAKE_CASE(AArch64ISD::SMINV)
1466     MAKE_CASE(AArch64ISD::UMINV)
1467     MAKE_CASE(AArch64ISD::SMAXV)
1468     MAKE_CASE(AArch64ISD::UMAXV)
1469     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1470     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1471     MAKE_CASE(AArch64ISD::SMINV_PRED)
1472     MAKE_CASE(AArch64ISD::UMINV_PRED)
1473     MAKE_CASE(AArch64ISD::ORV_PRED)
1474     MAKE_CASE(AArch64ISD::EORV_PRED)
1475     MAKE_CASE(AArch64ISD::ANDV_PRED)
1476     MAKE_CASE(AArch64ISD::CLASTA_N)
1477     MAKE_CASE(AArch64ISD::CLASTB_N)
1478     MAKE_CASE(AArch64ISD::LASTA)
1479     MAKE_CASE(AArch64ISD::LASTB)
1480     MAKE_CASE(AArch64ISD::REV)
1481     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1482     MAKE_CASE(AArch64ISD::TBL)
1483     MAKE_CASE(AArch64ISD::FADD_PRED)
1484     MAKE_CASE(AArch64ISD::FADDA_PRED)
1485     MAKE_CASE(AArch64ISD::FADDV_PRED)
1486     MAKE_CASE(AArch64ISD::FMA_PRED)
1487     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1488     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1489     MAKE_CASE(AArch64ISD::FMINV_PRED)
1490     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1491     MAKE_CASE(AArch64ISD::NOT)
1492     MAKE_CASE(AArch64ISD::BIT)
1493     MAKE_CASE(AArch64ISD::CBZ)
1494     MAKE_CASE(AArch64ISD::CBNZ)
1495     MAKE_CASE(AArch64ISD::TBZ)
1496     MAKE_CASE(AArch64ISD::TBNZ)
1497     MAKE_CASE(AArch64ISD::TC_RETURN)
1498     MAKE_CASE(AArch64ISD::PREFETCH)
1499     MAKE_CASE(AArch64ISD::SITOF)
1500     MAKE_CASE(AArch64ISD::UITOF)
1501     MAKE_CASE(AArch64ISD::NVCAST)
1502     MAKE_CASE(AArch64ISD::SQSHL_I)
1503     MAKE_CASE(AArch64ISD::UQSHL_I)
1504     MAKE_CASE(AArch64ISD::SRSHR_I)
1505     MAKE_CASE(AArch64ISD::URSHR_I)
1506     MAKE_CASE(AArch64ISD::SQSHLU_I)
1507     MAKE_CASE(AArch64ISD::WrapperLarge)
1508     MAKE_CASE(AArch64ISD::LD2post)
1509     MAKE_CASE(AArch64ISD::LD3post)
1510     MAKE_CASE(AArch64ISD::LD4post)
1511     MAKE_CASE(AArch64ISD::ST2post)
1512     MAKE_CASE(AArch64ISD::ST3post)
1513     MAKE_CASE(AArch64ISD::ST4post)
1514     MAKE_CASE(AArch64ISD::LD1x2post)
1515     MAKE_CASE(AArch64ISD::LD1x3post)
1516     MAKE_CASE(AArch64ISD::LD1x4post)
1517     MAKE_CASE(AArch64ISD::ST1x2post)
1518     MAKE_CASE(AArch64ISD::ST1x3post)
1519     MAKE_CASE(AArch64ISD::ST1x4post)
1520     MAKE_CASE(AArch64ISD::LD1DUPpost)
1521     MAKE_CASE(AArch64ISD::LD2DUPpost)
1522     MAKE_CASE(AArch64ISD::LD3DUPpost)
1523     MAKE_CASE(AArch64ISD::LD4DUPpost)
1524     MAKE_CASE(AArch64ISD::LD1LANEpost)
1525     MAKE_CASE(AArch64ISD::LD2LANEpost)
1526     MAKE_CASE(AArch64ISD::LD3LANEpost)
1527     MAKE_CASE(AArch64ISD::LD4LANEpost)
1528     MAKE_CASE(AArch64ISD::ST2LANEpost)
1529     MAKE_CASE(AArch64ISD::ST3LANEpost)
1530     MAKE_CASE(AArch64ISD::ST4LANEpost)
1531     MAKE_CASE(AArch64ISD::SMULL)
1532     MAKE_CASE(AArch64ISD::UMULL)
1533     MAKE_CASE(AArch64ISD::FRECPE)
1534     MAKE_CASE(AArch64ISD::FRECPS)
1535     MAKE_CASE(AArch64ISD::FRSQRTE)
1536     MAKE_CASE(AArch64ISD::FRSQRTS)
1537     MAKE_CASE(AArch64ISD::STG)
1538     MAKE_CASE(AArch64ISD::STZG)
1539     MAKE_CASE(AArch64ISD::ST2G)
1540     MAKE_CASE(AArch64ISD::STZ2G)
1541     MAKE_CASE(AArch64ISD::SUNPKHI)
1542     MAKE_CASE(AArch64ISD::SUNPKLO)
1543     MAKE_CASE(AArch64ISD::UUNPKHI)
1544     MAKE_CASE(AArch64ISD::UUNPKLO)
1545     MAKE_CASE(AArch64ISD::INSR)
1546     MAKE_CASE(AArch64ISD::PTEST)
1547     MAKE_CASE(AArch64ISD::PTRUE)
1548     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1549     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1550     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1551     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1552     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1553     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1554     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1555     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1556     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1557     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1558     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1559     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1560     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1561     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1562     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1563     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1564     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1565     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1566     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1567     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1568     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1569     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1570     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1571     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1572     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1573     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1574     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1575     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1576     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1577     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1578     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1579     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1580     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1581     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1582     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1583     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1584     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1585     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1586     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1587     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1588     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1589     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1590     MAKE_CASE(AArch64ISD::ST1_PRED)
1591     MAKE_CASE(AArch64ISD::SST1_PRED)
1592     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1593     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1594     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1595     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1596     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1597     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1598     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1599     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1600     MAKE_CASE(AArch64ISD::LDP)
1601     MAKE_CASE(AArch64ISD::STP)
1602     MAKE_CASE(AArch64ISD::STNP)
1603     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1604     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1605   }
1606 #undef MAKE_CASE
1607   return nullptr;
1608 }
1609 
1610 MachineBasicBlock *
1611 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1612                                     MachineBasicBlock *MBB) const {
1613   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1614   // phi node:
1615 
1616   // OrigBB:
1617   //     [... previous instrs leading to comparison ...]
1618   //     b.ne TrueBB
1619   //     b EndBB
1620   // TrueBB:
1621   //     ; Fallthrough
1622   // EndBB:
1623   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1624 
1625   MachineFunction *MF = MBB->getParent();
1626   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1627   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1628   DebugLoc DL = MI.getDebugLoc();
1629   MachineFunction::iterator It = ++MBB->getIterator();
1630 
1631   Register DestReg = MI.getOperand(0).getReg();
1632   Register IfTrueReg = MI.getOperand(1).getReg();
1633   Register IfFalseReg = MI.getOperand(2).getReg();
1634   unsigned CondCode = MI.getOperand(3).getImm();
1635   bool NZCVKilled = MI.getOperand(4).isKill();
1636 
1637   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1638   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1639   MF->insert(It, TrueBB);
1640   MF->insert(It, EndBB);
1641 
1642   // Transfer rest of current basic-block to EndBB
1643   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1644                 MBB->end());
1645   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1646 
1647   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1648   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1649   MBB->addSuccessor(TrueBB);
1650   MBB->addSuccessor(EndBB);
1651 
1652   // TrueBB falls through to the end.
1653   TrueBB->addSuccessor(EndBB);
1654 
1655   if (!NZCVKilled) {
1656     TrueBB->addLiveIn(AArch64::NZCV);
1657     EndBB->addLiveIn(AArch64::NZCV);
1658   }
1659 
1660   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1661       .addReg(IfTrueReg)
1662       .addMBB(TrueBB)
1663       .addReg(IfFalseReg)
1664       .addMBB(MBB);
1665 
1666   MI.eraseFromParent();
1667   return EndBB;
1668 }
1669 
1670 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1671        MachineInstr &MI, MachineBasicBlock *BB) const {
1672   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1673              BB->getParent()->getFunction().getPersonalityFn())) &&
1674          "SEH does not use catchret!");
1675   return BB;
1676 }
1677 
1678 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1679     MachineInstr &MI, MachineBasicBlock *BB) const {
1680   switch (MI.getOpcode()) {
1681   default:
1682 #ifndef NDEBUG
1683     MI.dump();
1684 #endif
1685     llvm_unreachable("Unexpected instruction for custom inserter!");
1686 
1687   case AArch64::F128CSEL:
1688     return EmitF128CSEL(MI, BB);
1689 
1690   case TargetOpcode::STACKMAP:
1691   case TargetOpcode::PATCHPOINT:
1692     return emitPatchPoint(MI, BB);
1693 
1694   case AArch64::CATCHRET:
1695     return EmitLoweredCatchRet(MI, BB);
1696   }
1697 }
1698 
1699 //===----------------------------------------------------------------------===//
1700 // AArch64 Lowering private implementation.
1701 //===----------------------------------------------------------------------===//
1702 
1703 //===----------------------------------------------------------------------===//
1704 // Lowering Code
1705 //===----------------------------------------------------------------------===//
1706 
1707 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1708 /// CC
1709 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1710   switch (CC) {
1711   default:
1712     llvm_unreachable("Unknown condition code!");
1713   case ISD::SETNE:
1714     return AArch64CC::NE;
1715   case ISD::SETEQ:
1716     return AArch64CC::EQ;
1717   case ISD::SETGT:
1718     return AArch64CC::GT;
1719   case ISD::SETGE:
1720     return AArch64CC::GE;
1721   case ISD::SETLT:
1722     return AArch64CC::LT;
1723   case ISD::SETLE:
1724     return AArch64CC::LE;
1725   case ISD::SETUGT:
1726     return AArch64CC::HI;
1727   case ISD::SETUGE:
1728     return AArch64CC::HS;
1729   case ISD::SETULT:
1730     return AArch64CC::LO;
1731   case ISD::SETULE:
1732     return AArch64CC::LS;
1733   }
1734 }
1735 
1736 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1737 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1738                                   AArch64CC::CondCode &CondCode,
1739                                   AArch64CC::CondCode &CondCode2) {
1740   CondCode2 = AArch64CC::AL;
1741   switch (CC) {
1742   default:
1743     llvm_unreachable("Unknown FP condition!");
1744   case ISD::SETEQ:
1745   case ISD::SETOEQ:
1746     CondCode = AArch64CC::EQ;
1747     break;
1748   case ISD::SETGT:
1749   case ISD::SETOGT:
1750     CondCode = AArch64CC::GT;
1751     break;
1752   case ISD::SETGE:
1753   case ISD::SETOGE:
1754     CondCode = AArch64CC::GE;
1755     break;
1756   case ISD::SETOLT:
1757     CondCode = AArch64CC::MI;
1758     break;
1759   case ISD::SETOLE:
1760     CondCode = AArch64CC::LS;
1761     break;
1762   case ISD::SETONE:
1763     CondCode = AArch64CC::MI;
1764     CondCode2 = AArch64CC::GT;
1765     break;
1766   case ISD::SETO:
1767     CondCode = AArch64CC::VC;
1768     break;
1769   case ISD::SETUO:
1770     CondCode = AArch64CC::VS;
1771     break;
1772   case ISD::SETUEQ:
1773     CondCode = AArch64CC::EQ;
1774     CondCode2 = AArch64CC::VS;
1775     break;
1776   case ISD::SETUGT:
1777     CondCode = AArch64CC::HI;
1778     break;
1779   case ISD::SETUGE:
1780     CondCode = AArch64CC::PL;
1781     break;
1782   case ISD::SETLT:
1783   case ISD::SETULT:
1784     CondCode = AArch64CC::LT;
1785     break;
1786   case ISD::SETLE:
1787   case ISD::SETULE:
1788     CondCode = AArch64CC::LE;
1789     break;
1790   case ISD::SETNE:
1791   case ISD::SETUNE:
1792     CondCode = AArch64CC::NE;
1793     break;
1794   }
1795 }
1796 
1797 /// Convert a DAG fp condition code to an AArch64 CC.
1798 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1799 /// should be AND'ed instead of OR'ed.
1800 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1801                                      AArch64CC::CondCode &CondCode,
1802                                      AArch64CC::CondCode &CondCode2) {
1803   CondCode2 = AArch64CC::AL;
1804   switch (CC) {
1805   default:
1806     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1807     assert(CondCode2 == AArch64CC::AL);
1808     break;
1809   case ISD::SETONE:
1810     // (a one b)
1811     // == ((a olt b) || (a ogt b))
1812     // == ((a ord b) && (a une b))
1813     CondCode = AArch64CC::VC;
1814     CondCode2 = AArch64CC::NE;
1815     break;
1816   case ISD::SETUEQ:
1817     // (a ueq b)
1818     // == ((a uno b) || (a oeq b))
1819     // == ((a ule b) && (a uge b))
1820     CondCode = AArch64CC::PL;
1821     CondCode2 = AArch64CC::LE;
1822     break;
1823   }
1824 }
1825 
1826 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1827 /// CC usable with the vector instructions. Fewer operations are available
1828 /// without a real NZCV register, so we have to use less efficient combinations
1829 /// to get the same effect.
1830 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1831                                         AArch64CC::CondCode &CondCode,
1832                                         AArch64CC::CondCode &CondCode2,
1833                                         bool &Invert) {
1834   Invert = false;
1835   switch (CC) {
1836   default:
1837     // Mostly the scalar mappings work fine.
1838     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1839     break;
1840   case ISD::SETUO:
1841     Invert = true;
1842     LLVM_FALLTHROUGH;
1843   case ISD::SETO:
1844     CondCode = AArch64CC::MI;
1845     CondCode2 = AArch64CC::GE;
1846     break;
1847   case ISD::SETUEQ:
1848   case ISD::SETULT:
1849   case ISD::SETULE:
1850   case ISD::SETUGT:
1851   case ISD::SETUGE:
1852     // All of the compare-mask comparisons are ordered, but we can switch
1853     // between the two by a double inversion. E.g. ULE == !OGT.
1854     Invert = true;
1855     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1856                           CondCode, CondCode2);
1857     break;
1858   }
1859 }
1860 
1861 static bool isLegalArithImmed(uint64_t C) {
1862   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1863   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1864   LLVM_DEBUG(dbgs() << "Is imm " << C
1865                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1866   return IsLegal;
1867 }
1868 
1869 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1870 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1871 // can be set differently by this operation. It comes down to whether
1872 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1873 // everything is fine. If not then the optimization is wrong. Thus general
1874 // comparisons are only valid if op2 != 0.
1875 //
1876 // So, finally, the only LLVM-native comparisons that don't mention C and V
1877 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1878 // the absence of information about op2.
1879 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1880   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1881          (CC == ISD::SETEQ || CC == ISD::SETNE);
1882 }
1883 
1884 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1885                                       SelectionDAG &DAG, SDValue Chain,
1886                                       bool IsSignaling) {
1887   EVT VT = LHS.getValueType();
1888   assert(VT != MVT::f128);
1889   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1890   unsigned Opcode =
1891       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1892   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1893 }
1894 
1895 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1896                               const SDLoc &dl, SelectionDAG &DAG) {
1897   EVT VT = LHS.getValueType();
1898   const bool FullFP16 =
1899     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1900 
1901   if (VT.isFloatingPoint()) {
1902     assert(VT != MVT::f128);
1903     if (VT == MVT::f16 && !FullFP16) {
1904       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1905       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1906       VT = MVT::f32;
1907     }
1908     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1909   }
1910 
1911   // The CMP instruction is just an alias for SUBS, and representing it as
1912   // SUBS means that it's possible to get CSE with subtract operations.
1913   // A later phase can perform the optimization of setting the destination
1914   // register to WZR/XZR if it ends up being unused.
1915   unsigned Opcode = AArch64ISD::SUBS;
1916 
1917   if (isCMN(RHS, CC)) {
1918     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1919     Opcode = AArch64ISD::ADDS;
1920     RHS = RHS.getOperand(1);
1921   } else if (isCMN(LHS, CC)) {
1922     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1923     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1924     Opcode = AArch64ISD::ADDS;
1925     LHS = LHS.getOperand(1);
1926   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
1927     if (LHS.getOpcode() == ISD::AND) {
1928       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1929       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1930       // of the signed comparisons.
1931       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
1932                                            DAG.getVTList(VT, MVT_CC),
1933                                            LHS.getOperand(0),
1934                                            LHS.getOperand(1));
1935       // Replace all users of (and X, Y) with newly generated (ands X, Y)
1936       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
1937       return ANDSNode.getValue(1);
1938     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
1939       // Use result of ANDS
1940       return LHS.getValue(1);
1941     }
1942   }
1943 
1944   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1945       .getValue(1);
1946 }
1947 
1948 /// \defgroup AArch64CCMP CMP;CCMP matching
1949 ///
1950 /// These functions deal with the formation of CMP;CCMP;... sequences.
1951 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1952 /// a comparison. They set the NZCV flags to a predefined value if their
1953 /// predicate is false. This allows to express arbitrary conjunctions, for
1954 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1955 /// expressed as:
1956 ///   cmp A
1957 ///   ccmp B, inv(CB), CA
1958 ///   check for CB flags
1959 ///
1960 /// This naturally lets us implement chains of AND operations with SETCC
1961 /// operands. And we can even implement some other situations by transforming
1962 /// them:
1963 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1964 ///     negating the flags used in a CCMP/FCCMP operations.
1965 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1966 ///     by negating the flags we test for afterwards. i.e.
1967 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1968 ///   - Note that we can only ever negate all previously processed results.
1969 ///     What we can not implement by flipping the flags to test is a negation
1970 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1971 ///     far, so the 2nd sub-tree we emit would also affect the first).
1972 /// With those tools we can implement some OR operations:
1973 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1974 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1975 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1976 ///     elimination rules from earlier to implement the whole thing as a
1977 ///     CCMP/FCCMP chain.
1978 ///
1979 /// As complete example:
1980 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1981 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1982 /// can be reassociated to:
1983 ///     or (and (setCC (cmp C)) setCD (cmp D))
1984 //         (or (setCA (cmp A)) (setCB (cmp B)))
1985 /// can be transformed to:
1986 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1987 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1988 /// which can be implemented as:
1989 ///   cmp C
1990 ///   ccmp D, inv(CD), CC
1991 ///   ccmp A, CA, inv(CD)
1992 ///   ccmp B, CB, inv(CA)
1993 ///   check for CB flags
1994 ///
1995 /// A counterexample is "or (and A B) (and C D)" which translates to
1996 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1997 /// can only implement 1 of the inner (not) operations, but not both!
1998 /// @{
1999 
2000 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2001 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2002                                          ISD::CondCode CC, SDValue CCOp,
2003                                          AArch64CC::CondCode Predicate,
2004                                          AArch64CC::CondCode OutCC,
2005                                          const SDLoc &DL, SelectionDAG &DAG) {
2006   unsigned Opcode = 0;
2007   const bool FullFP16 =
2008     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2009 
2010   if (LHS.getValueType().isFloatingPoint()) {
2011     assert(LHS.getValueType() != MVT::f128);
2012     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2013       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2014       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2015     }
2016     Opcode = AArch64ISD::FCCMP;
2017   } else if (RHS.getOpcode() == ISD::SUB) {
2018     SDValue SubOp0 = RHS.getOperand(0);
2019     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2020       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2021       Opcode = AArch64ISD::CCMN;
2022       RHS = RHS.getOperand(1);
2023     }
2024   }
2025   if (Opcode == 0)
2026     Opcode = AArch64ISD::CCMP;
2027 
2028   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2029   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2030   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2031   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2032   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2033 }
2034 
2035 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2036 /// expressed as a conjunction. See \ref AArch64CCMP.
2037 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2038 ///                     changing the conditions on the SETCC tests.
2039 ///                     (this means we can call emitConjunctionRec() with
2040 ///                      Negate==true on this sub-tree)
2041 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2042 ///                     cannot do the negation naturally. We are required to
2043 ///                     emit the subtree first in this case.
2044 /// \param WillNegate   Is true if are called when the result of this
2045 ///                     subexpression must be negated. This happens when the
2046 ///                     outer expression is an OR. We can use this fact to know
2047 ///                     that we have a double negation (or (or ...) ...) that
2048 ///                     can be implemented for free.
2049 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2050                                bool &MustBeFirst, bool WillNegate,
2051                                unsigned Depth = 0) {
2052   if (!Val.hasOneUse())
2053     return false;
2054   unsigned Opcode = Val->getOpcode();
2055   if (Opcode == ISD::SETCC) {
2056     if (Val->getOperand(0).getValueType() == MVT::f128)
2057       return false;
2058     CanNegate = true;
2059     MustBeFirst = false;
2060     return true;
2061   }
2062   // Protect against exponential runtime and stack overflow.
2063   if (Depth > 6)
2064     return false;
2065   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2066     bool IsOR = Opcode == ISD::OR;
2067     SDValue O0 = Val->getOperand(0);
2068     SDValue O1 = Val->getOperand(1);
2069     bool CanNegateL;
2070     bool MustBeFirstL;
2071     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2072       return false;
2073     bool CanNegateR;
2074     bool MustBeFirstR;
2075     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2076       return false;
2077 
2078     if (MustBeFirstL && MustBeFirstR)
2079       return false;
2080 
2081     if (IsOR) {
2082       // For an OR expression we need to be able to naturally negate at least
2083       // one side or we cannot do the transformation at all.
2084       if (!CanNegateL && !CanNegateR)
2085         return false;
2086       // If we the result of the OR will be negated and we can naturally negate
2087       // the leafs, then this sub-tree as a whole negates naturally.
2088       CanNegate = WillNegate && CanNegateL && CanNegateR;
2089       // If we cannot naturally negate the whole sub-tree, then this must be
2090       // emitted first.
2091       MustBeFirst = !CanNegate;
2092     } else {
2093       assert(Opcode == ISD::AND && "Must be OR or AND");
2094       // We cannot naturally negate an AND operation.
2095       CanNegate = false;
2096       MustBeFirst = MustBeFirstL || MustBeFirstR;
2097     }
2098     return true;
2099   }
2100   return false;
2101 }
2102 
2103 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2104 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2105 /// Tries to transform the given i1 producing node @p Val to a series compare
2106 /// and conditional compare operations. @returns an NZCV flags producing node
2107 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2108 /// transformation was not possible.
2109 /// \p Negate is true if we want this sub-tree being negated just by changing
2110 /// SETCC conditions.
2111 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2112     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2113     AArch64CC::CondCode Predicate) {
2114   // We're at a tree leaf, produce a conditional comparison operation.
2115   unsigned Opcode = Val->getOpcode();
2116   if (Opcode == ISD::SETCC) {
2117     SDValue LHS = Val->getOperand(0);
2118     SDValue RHS = Val->getOperand(1);
2119     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2120     bool isInteger = LHS.getValueType().isInteger();
2121     if (Negate)
2122       CC = getSetCCInverse(CC, LHS.getValueType());
2123     SDLoc DL(Val);
2124     // Determine OutCC and handle FP special case.
2125     if (isInteger) {
2126       OutCC = changeIntCCToAArch64CC(CC);
2127     } else {
2128       assert(LHS.getValueType().isFloatingPoint());
2129       AArch64CC::CondCode ExtraCC;
2130       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2131       // Some floating point conditions can't be tested with a single condition
2132       // code. Construct an additional comparison in this case.
2133       if (ExtraCC != AArch64CC::AL) {
2134         SDValue ExtraCmp;
2135         if (!CCOp.getNode())
2136           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2137         else
2138           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2139                                                ExtraCC, DL, DAG);
2140         CCOp = ExtraCmp;
2141         Predicate = ExtraCC;
2142       }
2143     }
2144 
2145     // Produce a normal comparison if we are first in the chain
2146     if (!CCOp)
2147       return emitComparison(LHS, RHS, CC, DL, DAG);
2148     // Otherwise produce a ccmp.
2149     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2150                                      DAG);
2151   }
2152   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2153 
2154   bool IsOR = Opcode == ISD::OR;
2155 
2156   SDValue LHS = Val->getOperand(0);
2157   bool CanNegateL;
2158   bool MustBeFirstL;
2159   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2160   assert(ValidL && "Valid conjunction/disjunction tree");
2161   (void)ValidL;
2162 
2163   SDValue RHS = Val->getOperand(1);
2164   bool CanNegateR;
2165   bool MustBeFirstR;
2166   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2167   assert(ValidR && "Valid conjunction/disjunction tree");
2168   (void)ValidR;
2169 
2170   // Swap sub-tree that must come first to the right side.
2171   if (MustBeFirstL) {
2172     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2173     std::swap(LHS, RHS);
2174     std::swap(CanNegateL, CanNegateR);
2175     std::swap(MustBeFirstL, MustBeFirstR);
2176   }
2177 
2178   bool NegateR;
2179   bool NegateAfterR;
2180   bool NegateL;
2181   bool NegateAfterAll;
2182   if (Opcode == ISD::OR) {
2183     // Swap the sub-tree that we can negate naturally to the left.
2184     if (!CanNegateL) {
2185       assert(CanNegateR && "at least one side must be negatable");
2186       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2187       assert(!Negate);
2188       std::swap(LHS, RHS);
2189       NegateR = false;
2190       NegateAfterR = true;
2191     } else {
2192       // Negate the left sub-tree if possible, otherwise negate the result.
2193       NegateR = CanNegateR;
2194       NegateAfterR = !CanNegateR;
2195     }
2196     NegateL = true;
2197     NegateAfterAll = !Negate;
2198   } else {
2199     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2200     assert(!Negate && "Valid conjunction/disjunction tree");
2201 
2202     NegateL = false;
2203     NegateR = false;
2204     NegateAfterR = false;
2205     NegateAfterAll = false;
2206   }
2207 
2208   // Emit sub-trees.
2209   AArch64CC::CondCode RHSCC;
2210   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2211   if (NegateAfterR)
2212     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2213   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2214   if (NegateAfterAll)
2215     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2216   return CmpL;
2217 }
2218 
2219 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2220 /// In some cases this is even possible with OR operations in the expression.
2221 /// See \ref AArch64CCMP.
2222 /// \see emitConjunctionRec().
2223 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2224                                AArch64CC::CondCode &OutCC) {
2225   bool DummyCanNegate;
2226   bool DummyMustBeFirst;
2227   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2228     return SDValue();
2229 
2230   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2231 }
2232 
2233 /// @}
2234 
2235 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2236 /// extension operations.
2237 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2238   auto isSupportedExtend = [&](SDValue V) {
2239     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2240       return true;
2241 
2242     if (V.getOpcode() == ISD::AND)
2243       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2244         uint64_t Mask = MaskCst->getZExtValue();
2245         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2246       }
2247 
2248     return false;
2249   };
2250 
2251   if (!Op.hasOneUse())
2252     return 0;
2253 
2254   if (isSupportedExtend(Op))
2255     return 1;
2256 
2257   unsigned Opc = Op.getOpcode();
2258   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2259     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2260       uint64_t Shift = ShiftCst->getZExtValue();
2261       if (isSupportedExtend(Op.getOperand(0)))
2262         return (Shift <= 4) ? 2 : 1;
2263       EVT VT = Op.getValueType();
2264       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2265         return 1;
2266     }
2267 
2268   return 0;
2269 }
2270 
2271 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2272                              SDValue &AArch64cc, SelectionDAG &DAG,
2273                              const SDLoc &dl) {
2274   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2275     EVT VT = RHS.getValueType();
2276     uint64_t C = RHSC->getZExtValue();
2277     if (!isLegalArithImmed(C)) {
2278       // Constant does not fit, try adjusting it by one?
2279       switch (CC) {
2280       default:
2281         break;
2282       case ISD::SETLT:
2283       case ISD::SETGE:
2284         if ((VT == MVT::i32 && C != 0x80000000 &&
2285              isLegalArithImmed((uint32_t)(C - 1))) ||
2286             (VT == MVT::i64 && C != 0x80000000ULL &&
2287              isLegalArithImmed(C - 1ULL))) {
2288           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2289           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2290           RHS = DAG.getConstant(C, dl, VT);
2291         }
2292         break;
2293       case ISD::SETULT:
2294       case ISD::SETUGE:
2295         if ((VT == MVT::i32 && C != 0 &&
2296              isLegalArithImmed((uint32_t)(C - 1))) ||
2297             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2298           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2299           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2300           RHS = DAG.getConstant(C, dl, VT);
2301         }
2302         break;
2303       case ISD::SETLE:
2304       case ISD::SETGT:
2305         if ((VT == MVT::i32 && C != INT32_MAX &&
2306              isLegalArithImmed((uint32_t)(C + 1))) ||
2307             (VT == MVT::i64 && C != INT64_MAX &&
2308              isLegalArithImmed(C + 1ULL))) {
2309           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2310           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2311           RHS = DAG.getConstant(C, dl, VT);
2312         }
2313         break;
2314       case ISD::SETULE:
2315       case ISD::SETUGT:
2316         if ((VT == MVT::i32 && C != UINT32_MAX &&
2317              isLegalArithImmed((uint32_t)(C + 1))) ||
2318             (VT == MVT::i64 && C != UINT64_MAX &&
2319              isLegalArithImmed(C + 1ULL))) {
2320           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2321           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2322           RHS = DAG.getConstant(C, dl, VT);
2323         }
2324         break;
2325       }
2326     }
2327   }
2328 
2329   // Comparisons are canonicalized so that the RHS operand is simpler than the
2330   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2331   // can fold some shift+extend operations on the RHS operand, so swap the
2332   // operands if that can be done.
2333   //
2334   // For example:
2335   //    lsl     w13, w11, #1
2336   //    cmp     w13, w12
2337   // can be turned into:
2338   //    cmp     w12, w11, lsl #1
2339   if (!isa<ConstantSDNode>(RHS) ||
2340       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2341     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2342 
2343     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2344       std::swap(LHS, RHS);
2345       CC = ISD::getSetCCSwappedOperands(CC);
2346     }
2347   }
2348 
2349   SDValue Cmp;
2350   AArch64CC::CondCode AArch64CC;
2351   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2352     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2353 
2354     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2355     // For the i8 operand, the largest immediate is 255, so this can be easily
2356     // encoded in the compare instruction. For the i16 operand, however, the
2357     // largest immediate cannot be encoded in the compare.
2358     // Therefore, use a sign extending load and cmn to avoid materializing the
2359     // -1 constant. For example,
2360     // movz w1, #65535
2361     // ldrh w0, [x0, #0]
2362     // cmp w0, w1
2363     // >
2364     // ldrsh w0, [x0, #0]
2365     // cmn w0, #1
2366     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2367     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2368     // ensure both the LHS and RHS are truly zero extended and to make sure the
2369     // transformation is profitable.
2370     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2371         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2372         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2373         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2374       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2375       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2376         SDValue SExt =
2377             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2378                         DAG.getValueType(MVT::i16));
2379         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2380                                                    RHS.getValueType()),
2381                              CC, dl, DAG);
2382         AArch64CC = changeIntCCToAArch64CC(CC);
2383       }
2384     }
2385 
2386     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2387       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2388         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2389           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2390       }
2391     }
2392   }
2393 
2394   if (!Cmp) {
2395     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2396     AArch64CC = changeIntCCToAArch64CC(CC);
2397   }
2398   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2399   return Cmp;
2400 }
2401 
2402 static std::pair<SDValue, SDValue>
2403 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2404   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2405          "Unsupported value type");
2406   SDValue Value, Overflow;
2407   SDLoc DL(Op);
2408   SDValue LHS = Op.getOperand(0);
2409   SDValue RHS = Op.getOperand(1);
2410   unsigned Opc = 0;
2411   switch (Op.getOpcode()) {
2412   default:
2413     llvm_unreachable("Unknown overflow instruction!");
2414   case ISD::SADDO:
2415     Opc = AArch64ISD::ADDS;
2416     CC = AArch64CC::VS;
2417     break;
2418   case ISD::UADDO:
2419     Opc = AArch64ISD::ADDS;
2420     CC = AArch64CC::HS;
2421     break;
2422   case ISD::SSUBO:
2423     Opc = AArch64ISD::SUBS;
2424     CC = AArch64CC::VS;
2425     break;
2426   case ISD::USUBO:
2427     Opc = AArch64ISD::SUBS;
2428     CC = AArch64CC::LO;
2429     break;
2430   // Multiply needs a little bit extra work.
2431   case ISD::SMULO:
2432   case ISD::UMULO: {
2433     CC = AArch64CC::NE;
2434     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2435     if (Op.getValueType() == MVT::i32) {
2436       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2437       // For a 32 bit multiply with overflow check we want the instruction
2438       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2439       // need to generate the following pattern:
2440       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2441       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2442       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2443       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2444       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2445                                 DAG.getConstant(0, DL, MVT::i64));
2446       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2447       // operation. We need to clear out the upper 32 bits, because we used a
2448       // widening multiply that wrote all 64 bits. In the end this should be a
2449       // noop.
2450       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2451       if (IsSigned) {
2452         // The signed overflow check requires more than just a simple check for
2453         // any bit set in the upper 32 bits of the result. These bits could be
2454         // just the sign bits of a negative number. To perform the overflow
2455         // check we have to arithmetic shift right the 32nd bit of the result by
2456         // 31 bits. Then we compare the result to the upper 32 bits.
2457         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2458                                         DAG.getConstant(32, DL, MVT::i64));
2459         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2460         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2461                                         DAG.getConstant(31, DL, MVT::i64));
2462         // It is important that LowerBits is last, otherwise the arithmetic
2463         // shift will not be folded into the compare (SUBS).
2464         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2465         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2466                        .getValue(1);
2467       } else {
2468         // The overflow check for unsigned multiply is easy. We only need to
2469         // check if any of the upper 32 bits are set. This can be done with a
2470         // CMP (shifted register). For that we need to generate the following
2471         // pattern:
2472         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2473         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2474                                         DAG.getConstant(32, DL, MVT::i64));
2475         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2476         Overflow =
2477             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2478                         DAG.getConstant(0, DL, MVT::i64),
2479                         UpperBits).getValue(1);
2480       }
2481       break;
2482     }
2483     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2484     // For the 64 bit multiply
2485     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2486     if (IsSigned) {
2487       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2488       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2489                                       DAG.getConstant(63, DL, MVT::i64));
2490       // It is important that LowerBits is last, otherwise the arithmetic
2491       // shift will not be folded into the compare (SUBS).
2492       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2493       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2494                      .getValue(1);
2495     } else {
2496       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2497       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2498       Overflow =
2499           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2500                       DAG.getConstant(0, DL, MVT::i64),
2501                       UpperBits).getValue(1);
2502     }
2503     break;
2504   }
2505   } // switch (...)
2506 
2507   if (Opc) {
2508     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2509 
2510     // Emit the AArch64 operation with overflow check.
2511     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2512     Overflow = Value.getValue(1);
2513   }
2514   return std::make_pair(Value, Overflow);
2515 }
2516 
2517 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2518                                              RTLIB::Libcall Call) const {
2519   bool IsStrict = Op->isStrictFPOpcode();
2520   unsigned Offset = IsStrict ? 1 : 0;
2521   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2522   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2523   MakeLibCallOptions CallOptions;
2524   SDValue Result;
2525   SDLoc dl(Op);
2526   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2527                                         CallOptions, dl, Chain);
2528   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2529 }
2530 
2531 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2532   SDValue Sel = Op.getOperand(0);
2533   SDValue Other = Op.getOperand(1);
2534   SDLoc dl(Sel);
2535 
2536   // If the operand is an overflow checking operation, invert the condition
2537   // code and kill the Not operation. I.e., transform:
2538   // (xor (overflow_op_bool, 1))
2539   //   -->
2540   // (csel 1, 0, invert(cc), overflow_op_bool)
2541   // ... which later gets transformed to just a cset instruction with an
2542   // inverted condition code, rather than a cset + eor sequence.
2543   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2544     // Only lower legal XALUO ops.
2545     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2546       return SDValue();
2547 
2548     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2549     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2550     AArch64CC::CondCode CC;
2551     SDValue Value, Overflow;
2552     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2553     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2554     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2555                        CCVal, Overflow);
2556   }
2557   // If neither operand is a SELECT_CC, give up.
2558   if (Sel.getOpcode() != ISD::SELECT_CC)
2559     std::swap(Sel, Other);
2560   if (Sel.getOpcode() != ISD::SELECT_CC)
2561     return Op;
2562 
2563   // The folding we want to perform is:
2564   // (xor x, (select_cc a, b, cc, 0, -1) )
2565   //   -->
2566   // (csel x, (xor x, -1), cc ...)
2567   //
2568   // The latter will get matched to a CSINV instruction.
2569 
2570   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2571   SDValue LHS = Sel.getOperand(0);
2572   SDValue RHS = Sel.getOperand(1);
2573   SDValue TVal = Sel.getOperand(2);
2574   SDValue FVal = Sel.getOperand(3);
2575 
2576   // FIXME: This could be generalized to non-integer comparisons.
2577   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2578     return Op;
2579 
2580   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2581   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2582 
2583   // The values aren't constants, this isn't the pattern we're looking for.
2584   if (!CFVal || !CTVal)
2585     return Op;
2586 
2587   // We can commute the SELECT_CC by inverting the condition.  This
2588   // might be needed to make this fit into a CSINV pattern.
2589   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2590     std::swap(TVal, FVal);
2591     std::swap(CTVal, CFVal);
2592     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2593   }
2594 
2595   // If the constants line up, perform the transform!
2596   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2597     SDValue CCVal;
2598     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2599 
2600     FVal = Other;
2601     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2602                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2603 
2604     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2605                        CCVal, Cmp);
2606   }
2607 
2608   return Op;
2609 }
2610 
2611 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2612   EVT VT = Op.getValueType();
2613 
2614   // Let legalize expand this if it isn't a legal type yet.
2615   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2616     return SDValue();
2617 
2618   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2619 
2620   unsigned Opc;
2621   bool ExtraOp = false;
2622   switch (Op.getOpcode()) {
2623   default:
2624     llvm_unreachable("Invalid code");
2625   case ISD::ADDC:
2626     Opc = AArch64ISD::ADDS;
2627     break;
2628   case ISD::SUBC:
2629     Opc = AArch64ISD::SUBS;
2630     break;
2631   case ISD::ADDE:
2632     Opc = AArch64ISD::ADCS;
2633     ExtraOp = true;
2634     break;
2635   case ISD::SUBE:
2636     Opc = AArch64ISD::SBCS;
2637     ExtraOp = true;
2638     break;
2639   }
2640 
2641   if (!ExtraOp)
2642     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2643   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2644                      Op.getOperand(2));
2645 }
2646 
2647 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2648   // Let legalize expand this if it isn't a legal type yet.
2649   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2650     return SDValue();
2651 
2652   SDLoc dl(Op);
2653   AArch64CC::CondCode CC;
2654   // The actual operation that sets the overflow or carry flag.
2655   SDValue Value, Overflow;
2656   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2657 
2658   // We use 0 and 1 as false and true values.
2659   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2660   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2661 
2662   // We use an inverted condition, because the conditional select is inverted
2663   // too. This will allow it to be selected to a single instruction:
2664   // CSINC Wd, WZR, WZR, invert(cond).
2665   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2666   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2667                          CCVal, Overflow);
2668 
2669   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2670   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2671 }
2672 
2673 // Prefetch operands are:
2674 // 1: Address to prefetch
2675 // 2: bool isWrite
2676 // 3: int locality (0 = no locality ... 3 = extreme locality)
2677 // 4: bool isDataCache
2678 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2679   SDLoc DL(Op);
2680   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2681   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2682   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2683 
2684   bool IsStream = !Locality;
2685   // When the locality number is set
2686   if (Locality) {
2687     // The front-end should have filtered out the out-of-range values
2688     assert(Locality <= 3 && "Prefetch locality out-of-range");
2689     // The locality degree is the opposite of the cache speed.
2690     // Put the number the other way around.
2691     // The encoding starts at 0 for level 1
2692     Locality = 3 - Locality;
2693   }
2694 
2695   // built the mask value encoding the expected behavior.
2696   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2697                    (!IsData << 3) |     // IsDataCache bit
2698                    (Locality << 1) |    // Cache level bits
2699                    (unsigned)IsStream;  // Stream bit
2700   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2701                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2702 }
2703 
2704 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2705                                               SelectionDAG &DAG) const {
2706   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2707 
2708   RTLIB::Libcall LC;
2709   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2710 
2711   return LowerF128Call(Op, DAG, LC);
2712 }
2713 
2714 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2715                                              SelectionDAG &DAG) const {
2716   bool IsStrict = Op->isStrictFPOpcode();
2717   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2718   EVT SrcVT = SrcVal.getValueType();
2719 
2720   if (SrcVT != MVT::f128) {
2721     // Expand cases where the input is a vector bigger than NEON.
2722     if (useSVEForFixedLengthVectorVT(SrcVT))
2723       return SDValue();
2724 
2725     // It's legal except when f128 is involved
2726     return Op;
2727   }
2728 
2729   RTLIB::Libcall LC;
2730   LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2731 
2732   // FP_ROUND node has a second operand indicating whether it is known to be
2733   // precise. That doesn't take part in the LibCall so we can't directly use
2734   // LowerF128Call.
2735   MakeLibCallOptions CallOptions;
2736   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2737   SDValue Result;
2738   SDLoc dl(Op);
2739   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2740                                         CallOptions, dl, Chain);
2741   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2742 }
2743 
2744 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2745                                                     SelectionDAG &DAG) const {
2746   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2747   // Any additional optimization in this function should be recorded
2748   // in the cost tables.
2749   EVT InVT = Op.getOperand(0).getValueType();
2750   EVT VT = Op.getValueType();
2751   unsigned NumElts = InVT.getVectorNumElements();
2752 
2753   // f16 conversions are promoted to f32 when full fp16 is not supported.
2754   if (InVT.getVectorElementType() == MVT::f16 &&
2755       !Subtarget->hasFullFP16()) {
2756     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2757     SDLoc dl(Op);
2758     return DAG.getNode(
2759         Op.getOpcode(), dl, Op.getValueType(),
2760         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2761   }
2762 
2763   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2764     SDLoc dl(Op);
2765     SDValue Cv =
2766         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2767                     Op.getOperand(0));
2768     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2769   }
2770 
2771   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2772     SDLoc dl(Op);
2773     MVT ExtVT =
2774         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2775                          VT.getVectorNumElements());
2776     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2777     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2778   }
2779 
2780   // Type changing conversions are illegal.
2781   return Op;
2782 }
2783 
2784 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2785                                               SelectionDAG &DAG) const {
2786   bool IsStrict = Op->isStrictFPOpcode();
2787   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2788 
2789   if (SrcVal.getValueType().isVector())
2790     return LowerVectorFP_TO_INT(Op, DAG);
2791 
2792   // f16 conversions are promoted to f32 when full fp16 is not supported.
2793   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2794     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2795     SDLoc dl(Op);
2796     return DAG.getNode(
2797         Op.getOpcode(), dl, Op.getValueType(),
2798         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2799   }
2800 
2801   if (SrcVal.getValueType() != MVT::f128) {
2802     // It's legal except when f128 is involved
2803     return Op;
2804   }
2805 
2806   RTLIB::Libcall LC;
2807   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2808       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2809     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2810   else
2811     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2812 
2813   return LowerF128Call(Op, DAG, LC);
2814 }
2815 
2816 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2817   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2818   // Any additional optimization in this function should be recorded
2819   // in the cost tables.
2820   EVT VT = Op.getValueType();
2821   SDLoc dl(Op);
2822   SDValue In = Op.getOperand(0);
2823   EVT InVT = In.getValueType();
2824 
2825   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2826     MVT CastVT =
2827         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2828                          InVT.getVectorNumElements());
2829     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2830     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2831   }
2832 
2833   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2834     unsigned CastOpc =
2835         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2836     EVT CastVT = VT.changeVectorElementTypeToInteger();
2837     In = DAG.getNode(CastOpc, dl, CastVT, In);
2838     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2839   }
2840 
2841   return Op;
2842 }
2843 
2844 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2845                                             SelectionDAG &DAG) const {
2846   if (Op.getValueType().isVector())
2847     return LowerVectorINT_TO_FP(Op, DAG);
2848 
2849   bool IsStrict = Op->isStrictFPOpcode();
2850   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2851 
2852   // f16 conversions are promoted to f32 when full fp16 is not supported.
2853   if (Op.getValueType() == MVT::f16 &&
2854       !Subtarget->hasFullFP16()) {
2855     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2856     SDLoc dl(Op);
2857     return DAG.getNode(
2858         ISD::FP_ROUND, dl, MVT::f16,
2859         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2860         DAG.getIntPtrConstant(0, dl));
2861   }
2862 
2863   // i128 conversions are libcalls.
2864   if (SrcVal.getValueType() == MVT::i128)
2865     return SDValue();
2866 
2867   // Other conversions are legal, unless it's to the completely software-based
2868   // fp128.
2869   if (Op.getValueType() != MVT::f128)
2870     return Op;
2871 
2872   RTLIB::Libcall LC;
2873   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2874       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2875     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2876   else
2877     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2878 
2879   return LowerF128Call(Op, DAG, LC);
2880 }
2881 
2882 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2883                                             SelectionDAG &DAG) const {
2884   // For iOS, we want to call an alternative entry point: __sincos_stret,
2885   // which returns the values in two S / D registers.
2886   SDLoc dl(Op);
2887   SDValue Arg = Op.getOperand(0);
2888   EVT ArgVT = Arg.getValueType();
2889   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2890 
2891   ArgListTy Args;
2892   ArgListEntry Entry;
2893 
2894   Entry.Node = Arg;
2895   Entry.Ty = ArgTy;
2896   Entry.IsSExt = false;
2897   Entry.IsZExt = false;
2898   Args.push_back(Entry);
2899 
2900   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2901                                         : RTLIB::SINCOS_STRET_F32;
2902   const char *LibcallName = getLibcallName(LC);
2903   SDValue Callee =
2904       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2905 
2906   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2907   TargetLowering::CallLoweringInfo CLI(DAG);
2908   CLI.setDebugLoc(dl)
2909       .setChain(DAG.getEntryNode())
2910       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2911 
2912   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2913   return CallResult.first;
2914 }
2915 
2916 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2917   EVT OpVT = Op.getValueType();
2918   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
2919     return SDValue();
2920 
2921   assert(Op.getOperand(0).getValueType() == MVT::i16);
2922   SDLoc DL(Op);
2923 
2924   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2925   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2926   return SDValue(
2927       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
2928                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2929       0);
2930 }
2931 
2932 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2933   if (OrigVT.getSizeInBits() >= 64)
2934     return OrigVT;
2935 
2936   assert(OrigVT.isSimple() && "Expecting a simple value type");
2937 
2938   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2939   switch (OrigSimpleTy) {
2940   default: llvm_unreachable("Unexpected Vector Type");
2941   case MVT::v2i8:
2942   case MVT::v2i16:
2943      return MVT::v2i32;
2944   case MVT::v4i8:
2945     return  MVT::v4i16;
2946   }
2947 }
2948 
2949 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2950                                                  const EVT &OrigTy,
2951                                                  const EVT &ExtTy,
2952                                                  unsigned ExtOpcode) {
2953   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2954   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2955   // 64-bits we need to insert a new extension so that it will be 64-bits.
2956   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2957   if (OrigTy.getSizeInBits() >= 64)
2958     return N;
2959 
2960   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2961   EVT NewVT = getExtensionTo64Bits(OrigTy);
2962 
2963   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2964 }
2965 
2966 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2967                                    bool isSigned) {
2968   EVT VT = N->getValueType(0);
2969 
2970   if (N->getOpcode() != ISD::BUILD_VECTOR)
2971     return false;
2972 
2973   for (const SDValue &Elt : N->op_values()) {
2974     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2975       unsigned EltSize = VT.getScalarSizeInBits();
2976       unsigned HalfSize = EltSize / 2;
2977       if (isSigned) {
2978         if (!isIntN(HalfSize, C->getSExtValue()))
2979           return false;
2980       } else {
2981         if (!isUIntN(HalfSize, C->getZExtValue()))
2982           return false;
2983       }
2984       continue;
2985     }
2986     return false;
2987   }
2988 
2989   return true;
2990 }
2991 
2992 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2993   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2994     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2995                                              N->getOperand(0)->getValueType(0),
2996                                              N->getValueType(0),
2997                                              N->getOpcode());
2998 
2999   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3000   EVT VT = N->getValueType(0);
3001   SDLoc dl(N);
3002   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3003   unsigned NumElts = VT.getVectorNumElements();
3004   MVT TruncVT = MVT::getIntegerVT(EltSize);
3005   SmallVector<SDValue, 8> Ops;
3006   for (unsigned i = 0; i != NumElts; ++i) {
3007     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3008     const APInt &CInt = C->getAPIntValue();
3009     // Element types smaller than 32 bits are not legal, so use i32 elements.
3010     // The values are implicitly truncated so sext vs. zext doesn't matter.
3011     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3012   }
3013   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3014 }
3015 
3016 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3017   return N->getOpcode() == ISD::SIGN_EXTEND ||
3018          isExtendedBUILD_VECTOR(N, DAG, true);
3019 }
3020 
3021 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3022   return N->getOpcode() == ISD::ZERO_EXTEND ||
3023          isExtendedBUILD_VECTOR(N, DAG, false);
3024 }
3025 
3026 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3027   unsigned Opcode = N->getOpcode();
3028   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3029     SDNode *N0 = N->getOperand(0).getNode();
3030     SDNode *N1 = N->getOperand(1).getNode();
3031     return N0->hasOneUse() && N1->hasOneUse() &&
3032       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3033   }
3034   return false;
3035 }
3036 
3037 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3038   unsigned Opcode = N->getOpcode();
3039   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3040     SDNode *N0 = N->getOperand(0).getNode();
3041     SDNode *N1 = N->getOperand(1).getNode();
3042     return N0->hasOneUse() && N1->hasOneUse() &&
3043       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3044   }
3045   return false;
3046 }
3047 
3048 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3049                                                 SelectionDAG &DAG) const {
3050   // The rounding mode is in bits 23:22 of the FPSCR.
3051   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3052   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3053   // so that the shift + and get folded into a bitfield extract.
3054   SDLoc dl(Op);
3055 
3056   SDValue Chain = Op.getOperand(0);
3057   SDValue FPCR_64 = DAG.getNode(
3058       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3059       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3060   Chain = FPCR_64.getValue(1);
3061   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3062   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3063                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3064   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3065                               DAG.getConstant(22, dl, MVT::i32));
3066   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3067                             DAG.getConstant(3, dl, MVT::i32));
3068   return DAG.getMergeValues({AND, Chain}, dl);
3069 }
3070 
3071 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
3072   // Multiplications are only custom-lowered for 128-bit vectors so that
3073   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3074   EVT VT = Op.getValueType();
3075   assert(VT.is128BitVector() && VT.isInteger() &&
3076          "unexpected type for custom-lowering ISD::MUL");
3077   SDNode *N0 = Op.getOperand(0).getNode();
3078   SDNode *N1 = Op.getOperand(1).getNode();
3079   unsigned NewOpc = 0;
3080   bool isMLA = false;
3081   bool isN0SExt = isSignExtended(N0, DAG);
3082   bool isN1SExt = isSignExtended(N1, DAG);
3083   if (isN0SExt && isN1SExt)
3084     NewOpc = AArch64ISD::SMULL;
3085   else {
3086     bool isN0ZExt = isZeroExtended(N0, DAG);
3087     bool isN1ZExt = isZeroExtended(N1, DAG);
3088     if (isN0ZExt && isN1ZExt)
3089       NewOpc = AArch64ISD::UMULL;
3090     else if (isN1SExt || isN1ZExt) {
3091       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3092       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3093       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3094         NewOpc = AArch64ISD::SMULL;
3095         isMLA = true;
3096       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3097         NewOpc =  AArch64ISD::UMULL;
3098         isMLA = true;
3099       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3100         std::swap(N0, N1);
3101         NewOpc =  AArch64ISD::UMULL;
3102         isMLA = true;
3103       }
3104     }
3105 
3106     if (!NewOpc) {
3107       if (VT == MVT::v2i64)
3108         // Fall through to expand this.  It is not legal.
3109         return SDValue();
3110       else
3111         // Other vector multiplications are legal.
3112         return Op;
3113     }
3114   }
3115 
3116   // Legalize to a S/UMULL instruction
3117   SDLoc DL(Op);
3118   SDValue Op0;
3119   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3120   if (!isMLA) {
3121     Op0 = skipExtensionForVectorMULL(N0, DAG);
3122     assert(Op0.getValueType().is64BitVector() &&
3123            Op1.getValueType().is64BitVector() &&
3124            "unexpected types for extended operands to VMULL");
3125     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3126   }
3127   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3128   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3129   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3130   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3131   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3132   EVT Op1VT = Op1.getValueType();
3133   return DAG.getNode(N0->getOpcode(), DL, VT,
3134                      DAG.getNode(NewOpc, DL, VT,
3135                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3136                      DAG.getNode(NewOpc, DL, VT,
3137                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3138 }
3139 
3140 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3141                                int Pattern) {
3142   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3143                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3144 }
3145 
3146 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3147                                                      SelectionDAG &DAG) const {
3148   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3149   SDLoc dl(Op);
3150   switch (IntNo) {
3151   default: return SDValue();    // Don't custom lower most intrinsics.
3152   case Intrinsic::thread_pointer: {
3153     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3154     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3155   }
3156   case Intrinsic::aarch64_neon_abs: {
3157     EVT Ty = Op.getValueType();
3158     if (Ty == MVT::i64) {
3159       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3160                                    Op.getOperand(1));
3161       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3162       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3163     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3164       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3165     } else {
3166       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3167     }
3168   }
3169   case Intrinsic::aarch64_neon_smax:
3170     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3171                        Op.getOperand(1), Op.getOperand(2));
3172   case Intrinsic::aarch64_neon_umax:
3173     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3174                        Op.getOperand(1), Op.getOperand(2));
3175   case Intrinsic::aarch64_neon_smin:
3176     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3177                        Op.getOperand(1), Op.getOperand(2));
3178   case Intrinsic::aarch64_neon_umin:
3179     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3180                        Op.getOperand(1), Op.getOperand(2));
3181 
3182   case Intrinsic::aarch64_sve_sunpkhi:
3183     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3184                        Op.getOperand(1));
3185   case Intrinsic::aarch64_sve_sunpklo:
3186     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3187                        Op.getOperand(1));
3188   case Intrinsic::aarch64_sve_uunpkhi:
3189     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3190                        Op.getOperand(1));
3191   case Intrinsic::aarch64_sve_uunpklo:
3192     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3193                        Op.getOperand(1));
3194   case Intrinsic::aarch64_sve_clasta_n:
3195     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3196                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3197   case Intrinsic::aarch64_sve_clastb_n:
3198     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3199                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3200   case Intrinsic::aarch64_sve_lasta:
3201     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3202                        Op.getOperand(1), Op.getOperand(2));
3203   case Intrinsic::aarch64_sve_lastb:
3204     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3205                        Op.getOperand(1), Op.getOperand(2));
3206   case Intrinsic::aarch64_sve_rev:
3207     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3208                        Op.getOperand(1));
3209   case Intrinsic::aarch64_sve_tbl:
3210     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3211                        Op.getOperand(1), Op.getOperand(2));
3212   case Intrinsic::aarch64_sve_trn1:
3213     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3214                        Op.getOperand(1), Op.getOperand(2));
3215   case Intrinsic::aarch64_sve_trn2:
3216     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3217                        Op.getOperand(1), Op.getOperand(2));
3218   case Intrinsic::aarch64_sve_uzp1:
3219     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3220                        Op.getOperand(1), Op.getOperand(2));
3221   case Intrinsic::aarch64_sve_uzp2:
3222     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3223                        Op.getOperand(1), Op.getOperand(2));
3224   case Intrinsic::aarch64_sve_zip1:
3225     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3226                        Op.getOperand(1), Op.getOperand(2));
3227   case Intrinsic::aarch64_sve_zip2:
3228     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3229                        Op.getOperand(1), Op.getOperand(2));
3230   case Intrinsic::aarch64_sve_ptrue:
3231     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3232                        Op.getOperand(1));
3233   case Intrinsic::aarch64_sve_dupq_lane:
3234     return LowerDUPQLane(Op, DAG);
3235   case Intrinsic::aarch64_sve_convert_from_svbool:
3236     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3237                        Op.getOperand(1));
3238   case Intrinsic::aarch64_sve_convert_to_svbool: {
3239     EVT OutVT = Op.getValueType();
3240     EVT InVT = Op.getOperand(1).getValueType();
3241     // Return the operand if the cast isn't changing type,
3242     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3243     if (InVT == OutVT)
3244       return Op.getOperand(1);
3245     // Otherwise, zero the newly introduced lanes.
3246     SDValue Reinterpret =
3247         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3248     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3249     SDValue MaskReinterpret =
3250         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3251     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3252   }
3253 
3254   case Intrinsic::aarch64_sve_insr: {
3255     SDValue Scalar = Op.getOperand(2);
3256     EVT ScalarTy = Scalar.getValueType();
3257     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3258       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3259 
3260     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3261                        Op.getOperand(1), Scalar);
3262   }
3263 
3264   case Intrinsic::localaddress: {
3265     const auto &MF = DAG.getMachineFunction();
3266     const auto *RegInfo = Subtarget->getRegisterInfo();
3267     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3268     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3269                               Op.getSimpleValueType());
3270   }
3271 
3272   case Intrinsic::eh_recoverfp: {
3273     // FIXME: This needs to be implemented to correctly handle highly aligned
3274     // stack objects. For now we simply return the incoming FP. Refer D53541
3275     // for more details.
3276     SDValue FnOp = Op.getOperand(1);
3277     SDValue IncomingFPOp = Op.getOperand(2);
3278     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3279     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3280     if (!Fn)
3281       report_fatal_error(
3282           "llvm.eh.recoverfp must take a function as the first argument");
3283     return IncomingFPOp;
3284   }
3285 
3286   case Intrinsic::aarch64_neon_vsri:
3287   case Intrinsic::aarch64_neon_vsli: {
3288     EVT Ty = Op.getValueType();
3289 
3290     if (!Ty.isVector())
3291       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3292 
3293     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3294 
3295     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3296     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3297     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3298                        Op.getOperand(3));
3299   }
3300 
3301   case Intrinsic::aarch64_neon_srhadd:
3302   case Intrinsic::aarch64_neon_urhadd: {
3303     bool IsSignedAdd = IntNo == Intrinsic::aarch64_neon_srhadd;
3304     unsigned Opcode = IsSignedAdd ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
3305     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3306                        Op.getOperand(2));
3307   }
3308   }
3309 }
3310 
3311 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3312   return ExtVal.getValueType().isScalableVector();
3313 }
3314 
3315 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3316 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3317                                         EVT VT, EVT MemVT,
3318                                         SelectionDAG &DAG) {
3319   assert(VT.isVector() && "VT should be a vector type");
3320   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3321 
3322   SDValue Value = ST->getValue();
3323 
3324   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3325   // the word lane which represent the v4i8 subvector.  It optimizes the store
3326   // to:
3327   //
3328   //   xtn  v0.8b, v0.8h
3329   //   str  s0, [x0]
3330 
3331   SDValue Undef = DAG.getUNDEF(MVT::i16);
3332   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3333                                         {Undef, Undef, Undef, Undef});
3334 
3335   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3336                                  Value, UndefVec);
3337   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3338 
3339   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3340   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3341                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3342 
3343   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3344                       ST->getBasePtr(), ST->getMemOperand());
3345 }
3346 
3347 // Custom lowering for any store, vector or scalar and/or default or with
3348 // a truncate operations.  Currently only custom lower truncate operation
3349 // from vector v4i16 to v4i8 or volatile stores of i128.
3350 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3351                                           SelectionDAG &DAG) const {
3352   SDLoc Dl(Op);
3353   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3354   assert (StoreNode && "Can only custom lower store nodes");
3355 
3356   SDValue Value = StoreNode->getValue();
3357 
3358   EVT VT = Value.getValueType();
3359   EVT MemVT = StoreNode->getMemoryVT();
3360 
3361   if (VT.isVector()) {
3362     if (useSVEForFixedLengthVectorVT(VT))
3363       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3364 
3365     unsigned AS = StoreNode->getAddressSpace();
3366     Align Alignment = StoreNode->getAlign();
3367     if (Alignment < MemVT.getStoreSize() &&
3368         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3369                                         StoreNode->getMemOperand()->getFlags(),
3370                                         nullptr)) {
3371       return scalarizeVectorStore(StoreNode, DAG);
3372     }
3373 
3374     if (StoreNode->isTruncatingStore()) {
3375       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3376     }
3377     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3378     // the custom lowering, as there are no un-paired non-temporal stores and
3379     // legalization will break up 256 bit inputs.
3380     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3381         MemVT.getVectorElementCount().Min % 2u == 0 &&
3382         ((MemVT.getScalarSizeInBits() == 8u ||
3383           MemVT.getScalarSizeInBits() == 16u ||
3384           MemVT.getScalarSizeInBits() == 32u ||
3385           MemVT.getScalarSizeInBits() == 64u))) {
3386       SDValue Lo =
3387           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3388                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3389                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3390       SDValue Hi = DAG.getNode(
3391           ISD::EXTRACT_SUBVECTOR, Dl,
3392           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3393           StoreNode->getValue(),
3394           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3395       SDValue Result = DAG.getMemIntrinsicNode(
3396           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3397           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3398           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3399       return Result;
3400     }
3401   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3402     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3403     SDValue Lo =
3404         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3405                     DAG.getConstant(0, Dl, MVT::i64));
3406     SDValue Hi =
3407         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3408                     DAG.getConstant(1, Dl, MVT::i64));
3409     SDValue Result = DAG.getMemIntrinsicNode(
3410         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3411         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3412         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3413     return Result;
3414   }
3415 
3416   return SDValue();
3417 }
3418 
3419 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3420                                               SelectionDAG &DAG) const {
3421   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3422   LLVM_DEBUG(Op.dump());
3423 
3424   switch (Op.getOpcode()) {
3425   default:
3426     llvm_unreachable("unimplemented operand");
3427     return SDValue();
3428   case ISD::BITCAST:
3429     return LowerBITCAST(Op, DAG);
3430   case ISD::GlobalAddress:
3431     return LowerGlobalAddress(Op, DAG);
3432   case ISD::GlobalTLSAddress:
3433     return LowerGlobalTLSAddress(Op, DAG);
3434   case ISD::SETCC:
3435   case ISD::STRICT_FSETCC:
3436   case ISD::STRICT_FSETCCS:
3437     return LowerSETCC(Op, DAG);
3438   case ISD::BR_CC:
3439     return LowerBR_CC(Op, DAG);
3440   case ISD::SELECT:
3441     return LowerSELECT(Op, DAG);
3442   case ISD::SELECT_CC:
3443     return LowerSELECT_CC(Op, DAG);
3444   case ISD::JumpTable:
3445     return LowerJumpTable(Op, DAG);
3446   case ISD::BR_JT:
3447     return LowerBR_JT(Op, DAG);
3448   case ISD::ConstantPool:
3449     return LowerConstantPool(Op, DAG);
3450   case ISD::BlockAddress:
3451     return LowerBlockAddress(Op, DAG);
3452   case ISD::VASTART:
3453     return LowerVASTART(Op, DAG);
3454   case ISD::VACOPY:
3455     return LowerVACOPY(Op, DAG);
3456   case ISD::VAARG:
3457     return LowerVAARG(Op, DAG);
3458   case ISD::ADDC:
3459   case ISD::ADDE:
3460   case ISD::SUBC:
3461   case ISD::SUBE:
3462     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3463   case ISD::SADDO:
3464   case ISD::UADDO:
3465   case ISD::SSUBO:
3466   case ISD::USUBO:
3467   case ISD::SMULO:
3468   case ISD::UMULO:
3469     return LowerXALUO(Op, DAG);
3470   case ISD::FADD:
3471     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3472       return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3473     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3474   case ISD::FSUB:
3475     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3476   case ISD::FMUL:
3477     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3478   case ISD::FMA:
3479     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3480   case ISD::FDIV:
3481     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3482   case ISD::FP_ROUND:
3483   case ISD::STRICT_FP_ROUND:
3484     return LowerFP_ROUND(Op, DAG);
3485   case ISD::FP_EXTEND:
3486     return LowerFP_EXTEND(Op, DAG);
3487   case ISD::FRAMEADDR:
3488     return LowerFRAMEADDR(Op, DAG);
3489   case ISD::SPONENTRY:
3490     return LowerSPONENTRY(Op, DAG);
3491   case ISD::RETURNADDR:
3492     return LowerRETURNADDR(Op, DAG);
3493   case ISD::ADDROFRETURNADDR:
3494     return LowerADDROFRETURNADDR(Op, DAG);
3495   case ISD::INSERT_VECTOR_ELT:
3496     return LowerINSERT_VECTOR_ELT(Op, DAG);
3497   case ISD::EXTRACT_VECTOR_ELT:
3498     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3499   case ISD::BUILD_VECTOR:
3500     return LowerBUILD_VECTOR(Op, DAG);
3501   case ISD::VECTOR_SHUFFLE:
3502     return LowerVECTOR_SHUFFLE(Op, DAG);
3503   case ISD::SPLAT_VECTOR:
3504     return LowerSPLAT_VECTOR(Op, DAG);
3505   case ISD::EXTRACT_SUBVECTOR:
3506     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3507   case ISD::INSERT_SUBVECTOR:
3508     return LowerINSERT_SUBVECTOR(Op, DAG);
3509   case ISD::SDIV:
3510     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SDIV_PRED);
3511   case ISD::UDIV:
3512     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UDIV_PRED);
3513   case ISD::SMIN:
3514     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_MERGE_OP1);
3515   case ISD::UMIN:
3516     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_MERGE_OP1);
3517   case ISD::SMAX:
3518     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_MERGE_OP1);
3519   case ISD::UMAX:
3520     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_MERGE_OP1);
3521   case ISD::SRA:
3522   case ISD::SRL:
3523   case ISD::SHL:
3524     return LowerVectorSRA_SRL_SHL(Op, DAG);
3525   case ISD::SHL_PARTS:
3526     return LowerShiftLeftParts(Op, DAG);
3527   case ISD::SRL_PARTS:
3528   case ISD::SRA_PARTS:
3529     return LowerShiftRightParts(Op, DAG);
3530   case ISD::CTPOP:
3531     return LowerCTPOP(Op, DAG);
3532   case ISD::FCOPYSIGN:
3533     return LowerFCOPYSIGN(Op, DAG);
3534   case ISD::OR:
3535     return LowerVectorOR(Op, DAG);
3536   case ISD::XOR:
3537     return LowerXOR(Op, DAG);
3538   case ISD::PREFETCH:
3539     return LowerPREFETCH(Op, DAG);
3540   case ISD::SINT_TO_FP:
3541   case ISD::UINT_TO_FP:
3542   case ISD::STRICT_SINT_TO_FP:
3543   case ISD::STRICT_UINT_TO_FP:
3544     return LowerINT_TO_FP(Op, DAG);
3545   case ISD::FP_TO_SINT:
3546   case ISD::FP_TO_UINT:
3547   case ISD::STRICT_FP_TO_SINT:
3548   case ISD::STRICT_FP_TO_UINT:
3549     return LowerFP_TO_INT(Op, DAG);
3550   case ISD::FSINCOS:
3551     return LowerFSINCOS(Op, DAG);
3552   case ISD::FLT_ROUNDS_:
3553     return LowerFLT_ROUNDS_(Op, DAG);
3554   case ISD::MUL:
3555     return LowerMUL(Op, DAG);
3556   case ISD::INTRINSIC_WO_CHAIN:
3557     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3558   case ISD::STORE:
3559     return LowerSTORE(Op, DAG);
3560   case ISD::VECREDUCE_ADD:
3561   case ISD::VECREDUCE_SMAX:
3562   case ISD::VECREDUCE_SMIN:
3563   case ISD::VECREDUCE_UMAX:
3564   case ISD::VECREDUCE_UMIN:
3565   case ISD::VECREDUCE_FMAX:
3566   case ISD::VECREDUCE_FMIN:
3567     return LowerVECREDUCE(Op, DAG);
3568   case ISD::ATOMIC_LOAD_SUB:
3569     return LowerATOMIC_LOAD_SUB(Op, DAG);
3570   case ISD::ATOMIC_LOAD_AND:
3571     return LowerATOMIC_LOAD_AND(Op, DAG);
3572   case ISD::DYNAMIC_STACKALLOC:
3573     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3574   case ISD::VSCALE:
3575     return LowerVSCALE(Op, DAG);
3576   case ISD::TRUNCATE:
3577     return LowerTRUNCATE(Op, DAG);
3578   case ISD::LOAD:
3579     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3580       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
3581     llvm_unreachable("Unexpected request to lower ISD::LOAD");
3582   case ISD::ADD:
3583     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3584       return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
3585     llvm_unreachable("Unexpected request to lower ISD::ADD");
3586   }
3587 }
3588 
3589 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
3590   // Prefer NEON unless larger SVE registers are available.
3591   return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
3592 }
3593 
3594 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(EVT VT) const {
3595   if (!useSVEForFixedLengthVectors())
3596     return false;
3597 
3598   if (!VT.isFixedLengthVector())
3599     return false;
3600 
3601   // Fixed length predicates should be promoted to i8.
3602   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
3603   if (VT.getVectorElementType() == MVT::i1)
3604     return false;
3605 
3606   // Don't use SVE for vectors we cannot scalarize if required.
3607   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
3608   default:
3609     return false;
3610   case MVT::i8:
3611   case MVT::i16:
3612   case MVT::i32:
3613   case MVT::i64:
3614   case MVT::f16:
3615   case MVT::f32:
3616   case MVT::f64:
3617     break;
3618   }
3619 
3620   // Ensure NEON MVTs only belong to a single register class.
3621   if (VT.getSizeInBits() <= 128)
3622     return false;
3623 
3624   // Don't use SVE for types that don't fit.
3625   if (VT.getSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
3626     return false;
3627 
3628   // TODO: Perhaps an artificial restriction, but worth having whilst getting
3629   // the base fixed length SVE support in place.
3630   if (!VT.isPow2VectorType())
3631     return false;
3632 
3633   return true;
3634 }
3635 
3636 //===----------------------------------------------------------------------===//
3637 //                      Calling Convention Implementation
3638 //===----------------------------------------------------------------------===//
3639 
3640 /// Selects the correct CCAssignFn for a given CallingConvention value.
3641 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3642                                                      bool IsVarArg) const {
3643   switch (CC) {
3644   default:
3645     report_fatal_error("Unsupported calling convention.");
3646   case CallingConv::WebKit_JS:
3647     return CC_AArch64_WebKit_JS;
3648   case CallingConv::GHC:
3649     return CC_AArch64_GHC;
3650   case CallingConv::C:
3651   case CallingConv::Fast:
3652   case CallingConv::PreserveMost:
3653   case CallingConv::CXX_FAST_TLS:
3654   case CallingConv::Swift:
3655     if (Subtarget->isTargetWindows() && IsVarArg)
3656       return CC_AArch64_Win64_VarArg;
3657     if (!Subtarget->isTargetDarwin())
3658       return CC_AArch64_AAPCS;
3659     if (!IsVarArg)
3660       return CC_AArch64_DarwinPCS;
3661     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3662                                       : CC_AArch64_DarwinPCS_VarArg;
3663    case CallingConv::Win64:
3664     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3665    case CallingConv::CFGuard_Check:
3666      return CC_AArch64_Win64_CFGuard_Check;
3667    case CallingConv::AArch64_VectorCall:
3668    case CallingConv::AArch64_SVE_VectorCall:
3669      return CC_AArch64_AAPCS;
3670   }
3671 }
3672 
3673 CCAssignFn *
3674 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3675   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3676                                       : RetCC_AArch64_AAPCS;
3677 }
3678 
3679 SDValue AArch64TargetLowering::LowerFormalArguments(
3680     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3681     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3682     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3683   MachineFunction &MF = DAG.getMachineFunction();
3684   MachineFrameInfo &MFI = MF.getFrameInfo();
3685   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3686 
3687   // Assign locations to all of the incoming arguments.
3688   SmallVector<CCValAssign, 16> ArgLocs;
3689   DenseMap<unsigned, SDValue> CopiedRegs;
3690   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3691                  *DAG.getContext());
3692 
3693   // At this point, Ins[].VT may already be promoted to i32. To correctly
3694   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3695   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3696   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3697   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3698   // LocVT.
3699   unsigned NumArgs = Ins.size();
3700   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3701   unsigned CurArgIdx = 0;
3702   for (unsigned i = 0; i != NumArgs; ++i) {
3703     MVT ValVT = Ins[i].VT;
3704     if (Ins[i].isOrigArg()) {
3705       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3706       CurArgIdx = Ins[i].getOrigArgIndex();
3707 
3708       // Get type of the original argument.
3709       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3710                                   /*AllowUnknown*/ true);
3711       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3712       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3713       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3714         ValVT = MVT::i8;
3715       else if (ActualMVT == MVT::i16)
3716         ValVT = MVT::i16;
3717     }
3718     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3719     bool Res =
3720         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3721     assert(!Res && "Call operand has unhandled type");
3722     (void)Res;
3723   }
3724   assert(ArgLocs.size() == Ins.size());
3725   SmallVector<SDValue, 16> ArgValues;
3726   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3727     CCValAssign &VA = ArgLocs[i];
3728 
3729     if (Ins[i].Flags.isByVal()) {
3730       // Byval is used for HFAs in the PCS, but the system should work in a
3731       // non-compliant manner for larger structs.
3732       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3733       int Size = Ins[i].Flags.getByValSize();
3734       unsigned NumRegs = (Size + 7) / 8;
3735 
3736       // FIXME: This works on big-endian for composite byvals, which are the common
3737       // case. It should also work for fundamental types too.
3738       unsigned FrameIdx =
3739         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3740       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3741       InVals.push_back(FrameIdxN);
3742 
3743       continue;
3744     }
3745 
3746     SDValue ArgValue;
3747     if (VA.isRegLoc()) {
3748       // Arguments stored in registers.
3749       EVT RegVT = VA.getLocVT();
3750       const TargetRegisterClass *RC;
3751 
3752       if (RegVT == MVT::i32)
3753         RC = &AArch64::GPR32RegClass;
3754       else if (RegVT == MVT::i64)
3755         RC = &AArch64::GPR64RegClass;
3756       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
3757         RC = &AArch64::FPR16RegClass;
3758       else if (RegVT == MVT::f32)
3759         RC = &AArch64::FPR32RegClass;
3760       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3761         RC = &AArch64::FPR64RegClass;
3762       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3763         RC = &AArch64::FPR128RegClass;
3764       else if (RegVT.isScalableVector() &&
3765                RegVT.getVectorElementType() == MVT::i1)
3766         RC = &AArch64::PPRRegClass;
3767       else if (RegVT.isScalableVector())
3768         RC = &AArch64::ZPRRegClass;
3769       else
3770         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3771 
3772       // Transform the arguments in physical registers into virtual ones.
3773       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3774       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3775 
3776       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3777       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3778       // truncate to the right size.
3779       switch (VA.getLocInfo()) {
3780       default:
3781         llvm_unreachable("Unknown loc info!");
3782       case CCValAssign::Full:
3783         break;
3784       case CCValAssign::Indirect:
3785         assert(VA.getValVT().isScalableVector() &&
3786                "Only scalable vectors can be passed indirectly");
3787         break;
3788       case CCValAssign::BCvt:
3789         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3790         break;
3791       case CCValAssign::AExt:
3792       case CCValAssign::SExt:
3793       case CCValAssign::ZExt:
3794         break;
3795       case CCValAssign::AExtUpper:
3796         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3797                                DAG.getConstant(32, DL, RegVT));
3798         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3799         break;
3800       }
3801     } else { // VA.isRegLoc()
3802       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3803       unsigned ArgOffset = VA.getLocMemOffset();
3804       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3805                               ? VA.getLocVT().getSizeInBits()
3806                               : VA.getValVT().getSizeInBits()) / 8;
3807 
3808       uint32_t BEAlign = 0;
3809       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3810           !Ins[i].Flags.isInConsecutiveRegs())
3811         BEAlign = 8 - ArgSize;
3812 
3813       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3814 
3815       // Create load nodes to retrieve arguments from the stack.
3816       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3817 
3818       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3819       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3820       MVT MemVT = VA.getValVT();
3821 
3822       switch (VA.getLocInfo()) {
3823       default:
3824         break;
3825       case CCValAssign::Trunc:
3826       case CCValAssign::BCvt:
3827         MemVT = VA.getLocVT();
3828         break;
3829       case CCValAssign::Indirect:
3830         assert(VA.getValVT().isScalableVector() &&
3831                "Only scalable vectors can be passed indirectly");
3832         MemVT = VA.getLocVT();
3833         break;
3834       case CCValAssign::SExt:
3835         ExtType = ISD::SEXTLOAD;
3836         break;
3837       case CCValAssign::ZExt:
3838         ExtType = ISD::ZEXTLOAD;
3839         break;
3840       case CCValAssign::AExt:
3841         ExtType = ISD::EXTLOAD;
3842         break;
3843       }
3844 
3845       ArgValue = DAG.getExtLoad(
3846           ExtType, DL, VA.getLocVT(), Chain, FIN,
3847           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3848           MemVT);
3849 
3850     }
3851 
3852     if (VA.getLocInfo() == CCValAssign::Indirect) {
3853       assert(VA.getValVT().isScalableVector() &&
3854            "Only scalable vectors can be passed indirectly");
3855       // If value is passed via pointer - do a load.
3856       ArgValue =
3857           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
3858     }
3859 
3860     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3861       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3862                              ArgValue, DAG.getValueType(MVT::i32));
3863     InVals.push_back(ArgValue);
3864   }
3865 
3866   // varargs
3867   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3868   if (isVarArg) {
3869     if (!Subtarget->isTargetDarwin() || IsWin64) {
3870       // The AAPCS variadic function ABI is identical to the non-variadic
3871       // one. As a result there may be more arguments in registers and we should
3872       // save them for future reference.
3873       // Win64 variadic functions also pass arguments in registers, but all float
3874       // arguments are passed in integer registers.
3875       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3876     }
3877 
3878     // This will point to the next argument passed via stack.
3879     unsigned StackOffset = CCInfo.getNextStackOffset();
3880     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3881     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3882     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3883 
3884     if (MFI.hasMustTailInVarArgFunc()) {
3885       SmallVector<MVT, 2> RegParmTypes;
3886       RegParmTypes.push_back(MVT::i64);
3887       RegParmTypes.push_back(MVT::f128);
3888       // Compute the set of forwarded registers. The rest are scratch.
3889       SmallVectorImpl<ForwardedRegister> &Forwards =
3890                                        FuncInfo->getForwardedMustTailRegParms();
3891       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3892                                                CC_AArch64_AAPCS);
3893 
3894       // Conservatively forward X8, since it might be used for aggregate return.
3895       if (!CCInfo.isAllocated(AArch64::X8)) {
3896         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3897         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3898       }
3899     }
3900   }
3901 
3902   // On Windows, InReg pointers must be returned, so record the pointer in a
3903   // virtual register at the start of the function so it can be returned in the
3904   // epilogue.
3905   if (IsWin64) {
3906     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3907       if (Ins[I].Flags.isInReg()) {
3908         assert(!FuncInfo->getSRetReturnReg());
3909 
3910         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3911         Register Reg =
3912             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3913         FuncInfo->setSRetReturnReg(Reg);
3914 
3915         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3916         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3917         break;
3918       }
3919     }
3920   }
3921 
3922   unsigned StackArgSize = CCInfo.getNextStackOffset();
3923   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3924   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3925     // This is a non-standard ABI so by fiat I say we're allowed to make full
3926     // use of the stack area to be popped, which must be aligned to 16 bytes in
3927     // any case:
3928     StackArgSize = alignTo(StackArgSize, 16);
3929 
3930     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3931     // a multiple of 16.
3932     FuncInfo->setArgumentStackToRestore(StackArgSize);
3933 
3934     // This realignment carries over to the available bytes below. Our own
3935     // callers will guarantee the space is free by giving an aligned value to
3936     // CALLSEQ_START.
3937   }
3938   // Even if we're not expected to free up the space, it's useful to know how
3939   // much is there while considering tail calls (because we can reuse it).
3940   FuncInfo->setBytesInStackArgArea(StackArgSize);
3941 
3942   if (Subtarget->hasCustomCallingConv())
3943     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3944 
3945   return Chain;
3946 }
3947 
3948 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3949                                                 SelectionDAG &DAG,
3950                                                 const SDLoc &DL,
3951                                                 SDValue &Chain) const {
3952   MachineFunction &MF = DAG.getMachineFunction();
3953   MachineFrameInfo &MFI = MF.getFrameInfo();
3954   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3955   auto PtrVT = getPointerTy(DAG.getDataLayout());
3956   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3957 
3958   SmallVector<SDValue, 8> MemOps;
3959 
3960   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3961                                           AArch64::X3, AArch64::X4, AArch64::X5,
3962                                           AArch64::X6, AArch64::X7 };
3963   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3964   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3965 
3966   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3967   int GPRIdx = 0;
3968   if (GPRSaveSize != 0) {
3969     if (IsWin64) {
3970       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3971       if (GPRSaveSize & 15)
3972         // The extra size here, if triggered, will always be 8.
3973         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3974     } else
3975       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
3976 
3977     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3978 
3979     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3980       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3981       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3982       SDValue Store = DAG.getStore(
3983           Val.getValue(1), DL, Val, FIN,
3984           IsWin64
3985               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3986                                                   GPRIdx,
3987                                                   (i - FirstVariadicGPR) * 8)
3988               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3989       MemOps.push_back(Store);
3990       FIN =
3991           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3992     }
3993   }
3994   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3995   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3996 
3997   if (Subtarget->hasFPARMv8() && !IsWin64) {
3998     static const MCPhysReg FPRArgRegs[] = {
3999         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4000         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4001     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4002     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4003 
4004     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4005     int FPRIdx = 0;
4006     if (FPRSaveSize != 0) {
4007       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4008 
4009       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4010 
4011       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4012         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4013         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4014 
4015         SDValue Store = DAG.getStore(
4016             Val.getValue(1), DL, Val, FIN,
4017             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4018         MemOps.push_back(Store);
4019         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4020                           DAG.getConstant(16, DL, PtrVT));
4021       }
4022     }
4023     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4024     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4025   }
4026 
4027   if (!MemOps.empty()) {
4028     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4029   }
4030 }
4031 
4032 /// LowerCallResult - Lower the result values of a call into the
4033 /// appropriate copies out of appropriate physical registers.
4034 SDValue AArch64TargetLowering::LowerCallResult(
4035     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4036     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4037     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4038     SDValue ThisVal) const {
4039   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4040                           ? RetCC_AArch64_WebKit_JS
4041                           : RetCC_AArch64_AAPCS;
4042   // Assign locations to each value returned by this call.
4043   SmallVector<CCValAssign, 16> RVLocs;
4044   DenseMap<unsigned, SDValue> CopiedRegs;
4045   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4046                  *DAG.getContext());
4047   CCInfo.AnalyzeCallResult(Ins, RetCC);
4048 
4049   // Copy all of the result registers out of their specified physreg.
4050   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4051     CCValAssign VA = RVLocs[i];
4052 
4053     // Pass 'this' value directly from the argument to return value, to avoid
4054     // reg unit interference
4055     if (i == 0 && isThisReturn) {
4056       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4057              "unexpected return calling convention register assignment");
4058       InVals.push_back(ThisVal);
4059       continue;
4060     }
4061 
4062     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4063     // allows one use of a physreg per block.
4064     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4065     if (!Val) {
4066       Val =
4067           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4068       Chain = Val.getValue(1);
4069       InFlag = Val.getValue(2);
4070       CopiedRegs[VA.getLocReg()] = Val;
4071     }
4072 
4073     switch (VA.getLocInfo()) {
4074     default:
4075       llvm_unreachable("Unknown loc info!");
4076     case CCValAssign::Full:
4077       break;
4078     case CCValAssign::BCvt:
4079       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4080       break;
4081     case CCValAssign::AExtUpper:
4082       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4083                         DAG.getConstant(32, DL, VA.getLocVT()));
4084       LLVM_FALLTHROUGH;
4085     case CCValAssign::AExt:
4086       LLVM_FALLTHROUGH;
4087     case CCValAssign::ZExt:
4088       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4089       break;
4090     }
4091 
4092     InVals.push_back(Val);
4093   }
4094 
4095   return Chain;
4096 }
4097 
4098 /// Return true if the calling convention is one that we can guarantee TCO for.
4099 static bool canGuaranteeTCO(CallingConv::ID CC) {
4100   return CC == CallingConv::Fast;
4101 }
4102 
4103 /// Return true if we might ever do TCO for calls with this calling convention.
4104 static bool mayTailCallThisCC(CallingConv::ID CC) {
4105   switch (CC) {
4106   case CallingConv::C:
4107   case CallingConv::PreserveMost:
4108   case CallingConv::Swift:
4109     return true;
4110   default:
4111     return canGuaranteeTCO(CC);
4112   }
4113 }
4114 
4115 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4116     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4117     const SmallVectorImpl<ISD::OutputArg> &Outs,
4118     const SmallVectorImpl<SDValue> &OutVals,
4119     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4120   if (!mayTailCallThisCC(CalleeCC))
4121     return false;
4122 
4123   MachineFunction &MF = DAG.getMachineFunction();
4124   const Function &CallerF = MF.getFunction();
4125   CallingConv::ID CallerCC = CallerF.getCallingConv();
4126   bool CCMatch = CallerCC == CalleeCC;
4127 
4128   // When using the Windows calling convention on a non-windows OS, we want
4129   // to back up and restore X18 in such functions; we can't do a tail call
4130   // from those functions.
4131   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4132       CalleeCC != CallingConv::Win64)
4133     return false;
4134 
4135   // Byval parameters hand the function a pointer directly into the stack area
4136   // we want to reuse during a tail call. Working around this *is* possible (see
4137   // X86) but less efficient and uglier in LowerCall.
4138   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4139                                     e = CallerF.arg_end();
4140        i != e; ++i) {
4141     if (i->hasByValAttr())
4142       return false;
4143 
4144     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4145     // In this case, it is necessary to save/restore X0 in the callee. Tail
4146     // call opt interferes with this. So we disable tail call opt when the
4147     // caller has an argument with "inreg" attribute.
4148 
4149     // FIXME: Check whether the callee also has an "inreg" argument.
4150     if (i->hasInRegAttr())
4151       return false;
4152   }
4153 
4154   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4155     return canGuaranteeTCO(CalleeCC) && CCMatch;
4156 
4157   // Externally-defined functions with weak linkage should not be
4158   // tail-called on AArch64 when the OS does not support dynamic
4159   // pre-emption of symbols, as the AAELF spec requires normal calls
4160   // to undefined weak functions to be replaced with a NOP or jump to the
4161   // next instruction. The behaviour of branch instructions in this
4162   // situation (as used for tail calls) is implementation-defined, so we
4163   // cannot rely on the linker replacing the tail call with a return.
4164   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4165     const GlobalValue *GV = G->getGlobal();
4166     const Triple &TT = getTargetMachine().getTargetTriple();
4167     if (GV->hasExternalWeakLinkage() &&
4168         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4169       return false;
4170   }
4171 
4172   // Now we search for cases where we can use a tail call without changing the
4173   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4174   // concept.
4175 
4176   // I want anyone implementing a new calling convention to think long and hard
4177   // about this assert.
4178   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4179          "Unexpected variadic calling convention");
4180 
4181   LLVMContext &C = *DAG.getContext();
4182   if (isVarArg && !Outs.empty()) {
4183     // At least two cases here: if caller is fastcc then we can't have any
4184     // memory arguments (we'd be expected to clean up the stack afterwards). If
4185     // caller is C then we could potentially use its argument area.
4186 
4187     // FIXME: for now we take the most conservative of these in both cases:
4188     // disallow all variadic memory operands.
4189     SmallVector<CCValAssign, 16> ArgLocs;
4190     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4191 
4192     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4193     for (const CCValAssign &ArgLoc : ArgLocs)
4194       if (!ArgLoc.isRegLoc())
4195         return false;
4196   }
4197 
4198   // Check that the call results are passed in the same way.
4199   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4200                                   CCAssignFnForCall(CalleeCC, isVarArg),
4201                                   CCAssignFnForCall(CallerCC, isVarArg)))
4202     return false;
4203   // The callee has to preserve all registers the caller needs to preserve.
4204   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4205   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4206   if (!CCMatch) {
4207     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4208     if (Subtarget->hasCustomCallingConv()) {
4209       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4210       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4211     }
4212     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4213       return false;
4214   }
4215 
4216   // Nothing more to check if the callee is taking no arguments
4217   if (Outs.empty())
4218     return true;
4219 
4220   SmallVector<CCValAssign, 16> ArgLocs;
4221   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4222 
4223   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4224 
4225   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4226 
4227   // If any of the arguments is passed indirectly, it must be SVE, so the
4228   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4229   // allocate space on the stack. That is why we determine this explicitly here
4230   // the call cannot be a tailcall.
4231   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4232         assert((A.getLocInfo() != CCValAssign::Indirect ||
4233                 A.getValVT().isScalableVector()) &&
4234                "Expected value to be scalable");
4235         return A.getLocInfo() == CCValAssign::Indirect;
4236       }))
4237     return false;
4238 
4239   // If the stack arguments for this call do not fit into our own save area then
4240   // the call cannot be made tail.
4241   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4242     return false;
4243 
4244   const MachineRegisterInfo &MRI = MF.getRegInfo();
4245   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4246     return false;
4247 
4248   return true;
4249 }
4250 
4251 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4252                                                    SelectionDAG &DAG,
4253                                                    MachineFrameInfo &MFI,
4254                                                    int ClobberedFI) const {
4255   SmallVector<SDValue, 8> ArgChains;
4256   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4257   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4258 
4259   // Include the original chain at the beginning of the list. When this is
4260   // used by target LowerCall hooks, this helps legalize find the
4261   // CALLSEQ_BEGIN node.
4262   ArgChains.push_back(Chain);
4263 
4264   // Add a chain value for each stack argument corresponding
4265   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4266                             UE = DAG.getEntryNode().getNode()->use_end();
4267        U != UE; ++U)
4268     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4269       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4270         if (FI->getIndex() < 0) {
4271           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4272           int64_t InLastByte = InFirstByte;
4273           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4274 
4275           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4276               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4277             ArgChains.push_back(SDValue(L, 1));
4278         }
4279 
4280   // Build a tokenfactor for all the chains.
4281   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4282 }
4283 
4284 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4285                                                    bool TailCallOpt) const {
4286   return CallCC == CallingConv::Fast && TailCallOpt;
4287 }
4288 
4289 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4290 /// and add input and output parameter nodes.
4291 SDValue
4292 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4293                                  SmallVectorImpl<SDValue> &InVals) const {
4294   SelectionDAG &DAG = CLI.DAG;
4295   SDLoc &DL = CLI.DL;
4296   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4297   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4298   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4299   SDValue Chain = CLI.Chain;
4300   SDValue Callee = CLI.Callee;
4301   bool &IsTailCall = CLI.IsTailCall;
4302   CallingConv::ID CallConv = CLI.CallConv;
4303   bool IsVarArg = CLI.IsVarArg;
4304 
4305   MachineFunction &MF = DAG.getMachineFunction();
4306   MachineFunction::CallSiteInfo CSInfo;
4307   bool IsThisReturn = false;
4308 
4309   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4310   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4311   bool IsSibCall = false;
4312 
4313   if (IsTailCall) {
4314     // Check if it's really possible to do a tail call.
4315     IsTailCall = isEligibleForTailCallOptimization(
4316         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4317     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4318       report_fatal_error("failed to perform tail call elimination on a call "
4319                          "site marked musttail");
4320 
4321     // A sibling call is one where we're under the usual C ABI and not planning
4322     // to change that but can still do a tail call:
4323     if (!TailCallOpt && IsTailCall)
4324       IsSibCall = true;
4325 
4326     if (IsTailCall)
4327       ++NumTailCalls;
4328   }
4329 
4330   // Analyze operands of the call, assigning locations to each operand.
4331   SmallVector<CCValAssign, 16> ArgLocs;
4332   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4333                  *DAG.getContext());
4334 
4335   if (IsVarArg) {
4336     // Handle fixed and variable vector arguments differently.
4337     // Variable vector arguments always go into memory.
4338     unsigned NumArgs = Outs.size();
4339 
4340     for (unsigned i = 0; i != NumArgs; ++i) {
4341       MVT ArgVT = Outs[i].VT;
4342       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4343       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4344                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4345       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4346       assert(!Res && "Call operand has unhandled type");
4347       (void)Res;
4348     }
4349   } else {
4350     // At this point, Outs[].VT may already be promoted to i32. To correctly
4351     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4352     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4353     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4354     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4355     // LocVT.
4356     unsigned NumArgs = Outs.size();
4357     for (unsigned i = 0; i != NumArgs; ++i) {
4358       MVT ValVT = Outs[i].VT;
4359       // Get type of the original argument.
4360       EVT ActualVT = getValueType(DAG.getDataLayout(),
4361                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4362                                   /*AllowUnknown*/ true);
4363       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4364       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4365       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4366       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4367         ValVT = MVT::i8;
4368       else if (ActualMVT == MVT::i16)
4369         ValVT = MVT::i16;
4370 
4371       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4372       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4373       assert(!Res && "Call operand has unhandled type");
4374       (void)Res;
4375     }
4376   }
4377 
4378   // Get a count of how many bytes are to be pushed on the stack.
4379   unsigned NumBytes = CCInfo.getNextStackOffset();
4380 
4381   if (IsSibCall) {
4382     // Since we're not changing the ABI to make this a tail call, the memory
4383     // operands are already available in the caller's incoming argument space.
4384     NumBytes = 0;
4385   }
4386 
4387   // FPDiff is the byte offset of the call's argument area from the callee's.
4388   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4389   // by this amount for a tail call. In a sibling call it must be 0 because the
4390   // caller will deallocate the entire stack and the callee still expects its
4391   // arguments to begin at SP+0. Completely unused for non-tail calls.
4392   int FPDiff = 0;
4393 
4394   if (IsTailCall && !IsSibCall) {
4395     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4396 
4397     // Since callee will pop argument stack as a tail call, we must keep the
4398     // popped size 16-byte aligned.
4399     NumBytes = alignTo(NumBytes, 16);
4400 
4401     // FPDiff will be negative if this tail call requires more space than we
4402     // would automatically have in our incoming argument space. Positive if we
4403     // can actually shrink the stack.
4404     FPDiff = NumReusableBytes - NumBytes;
4405 
4406     // The stack pointer must be 16-byte aligned at all times it's used for a
4407     // memory operation, which in practice means at *all* times and in
4408     // particular across call boundaries. Therefore our own arguments started at
4409     // a 16-byte aligned SP and the delta applied for the tail call should
4410     // satisfy the same constraint.
4411     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4412   }
4413 
4414   // Adjust the stack pointer for the new arguments...
4415   // These operations are automatically eliminated by the prolog/epilog pass
4416   if (!IsSibCall)
4417     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4418 
4419   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4420                                         getPointerTy(DAG.getDataLayout()));
4421 
4422   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4423   SmallSet<unsigned, 8> RegsUsed;
4424   SmallVector<SDValue, 8> MemOpChains;
4425   auto PtrVT = getPointerTy(DAG.getDataLayout());
4426 
4427   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4428     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4429     for (const auto &F : Forwards) {
4430       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4431        RegsToPass.emplace_back(F.PReg, Val);
4432     }
4433   }
4434 
4435   // Walk the register/memloc assignments, inserting copies/loads.
4436   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4437     CCValAssign &VA = ArgLocs[i];
4438     SDValue Arg = OutVals[i];
4439     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4440 
4441     // Promote the value if needed.
4442     switch (VA.getLocInfo()) {
4443     default:
4444       llvm_unreachable("Unknown loc info!");
4445     case CCValAssign::Full:
4446       break;
4447     case CCValAssign::SExt:
4448       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4449       break;
4450     case CCValAssign::ZExt:
4451       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4452       break;
4453     case CCValAssign::AExt:
4454       if (Outs[i].ArgVT == MVT::i1) {
4455         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4456         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4457         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4458       }
4459       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4460       break;
4461     case CCValAssign::AExtUpper:
4462       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4463       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4464       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4465                         DAG.getConstant(32, DL, VA.getLocVT()));
4466       break;
4467     case CCValAssign::BCvt:
4468       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4469       break;
4470     case CCValAssign::Trunc:
4471       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4472       break;
4473     case CCValAssign::FPExt:
4474       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4475       break;
4476     case CCValAssign::Indirect:
4477       assert(VA.getValVT().isScalableVector() &&
4478              "Only scalable vectors can be passed indirectly");
4479       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4480       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4481       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4482       int FI = MFI.CreateStackObject(
4483           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4484       MFI.setStackID(FI, TargetStackID::SVEVector);
4485 
4486       SDValue SpillSlot = DAG.getFrameIndex(
4487           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4488       Chain = DAG.getStore(
4489           Chain, DL, Arg, SpillSlot,
4490           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4491       Arg = SpillSlot;
4492       break;
4493     }
4494 
4495     if (VA.isRegLoc()) {
4496       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4497           Outs[0].VT == MVT::i64) {
4498         assert(VA.getLocVT() == MVT::i64 &&
4499                "unexpected calling convention register assignment");
4500         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4501                "unexpected use of 'returned'");
4502         IsThisReturn = true;
4503       }
4504       if (RegsUsed.count(VA.getLocReg())) {
4505         // If this register has already been used then we're trying to pack
4506         // parts of an [N x i32] into an X-register. The extension type will
4507         // take care of putting the two halves in the right place but we have to
4508         // combine them.
4509         SDValue &Bits =
4510             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4511                          [=](const std::pair<unsigned, SDValue> &Elt) {
4512                            return Elt.first == VA.getLocReg();
4513                          })
4514                 ->second;
4515         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4516         // Call site info is used for function's parameter entry value
4517         // tracking. For now we track only simple cases when parameter
4518         // is transferred through whole register.
4519         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4520                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4521                                       return ArgReg.Reg == VA.getLocReg();
4522                                     }),
4523                      CSInfo.end());
4524       } else {
4525         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4526         RegsUsed.insert(VA.getLocReg());
4527         const TargetOptions &Options = DAG.getTarget().Options;
4528         if (Options.EmitCallSiteInfo)
4529           CSInfo.emplace_back(VA.getLocReg(), i);
4530       }
4531     } else {
4532       assert(VA.isMemLoc());
4533 
4534       SDValue DstAddr;
4535       MachinePointerInfo DstInfo;
4536 
4537       // FIXME: This works on big-endian for composite byvals, which are the
4538       // common case. It should also work for fundamental types too.
4539       uint32_t BEAlign = 0;
4540       unsigned OpSize;
4541       if (VA.getLocInfo() == CCValAssign::Indirect)
4542         OpSize = VA.getLocVT().getSizeInBits();
4543       else
4544         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4545                                  : VA.getValVT().getSizeInBits();
4546       OpSize = (OpSize + 7) / 8;
4547       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4548           !Flags.isInConsecutiveRegs()) {
4549         if (OpSize < 8)
4550           BEAlign = 8 - OpSize;
4551       }
4552       unsigned LocMemOffset = VA.getLocMemOffset();
4553       int32_t Offset = LocMemOffset + BEAlign;
4554       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4555       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4556 
4557       if (IsTailCall) {
4558         Offset = Offset + FPDiff;
4559         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4560 
4561         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4562         DstInfo =
4563             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4564 
4565         // Make sure any stack arguments overlapping with where we're storing
4566         // are loaded before this eventual operation. Otherwise they'll be
4567         // clobbered.
4568         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4569       } else {
4570         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4571 
4572         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4573         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4574                                                LocMemOffset);
4575       }
4576 
4577       if (Outs[i].Flags.isByVal()) {
4578         SDValue SizeNode =
4579             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4580         SDValue Cpy = DAG.getMemcpy(
4581             Chain, DL, DstAddr, Arg, SizeNode,
4582             Outs[i].Flags.getNonZeroByValAlign(),
4583             /*isVol = */ false, /*AlwaysInline = */ false,
4584             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4585 
4586         MemOpChains.push_back(Cpy);
4587       } else {
4588         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4589         // promoted to a legal register type i32, we should truncate Arg back to
4590         // i1/i8/i16.
4591         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4592             VA.getValVT() == MVT::i16)
4593           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4594 
4595         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4596         MemOpChains.push_back(Store);
4597       }
4598     }
4599   }
4600 
4601   if (!MemOpChains.empty())
4602     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4603 
4604   // Build a sequence of copy-to-reg nodes chained together with token chain
4605   // and flag operands which copy the outgoing args into the appropriate regs.
4606   SDValue InFlag;
4607   for (auto &RegToPass : RegsToPass) {
4608     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4609                              RegToPass.second, InFlag);
4610     InFlag = Chain.getValue(1);
4611   }
4612 
4613   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4614   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4615   // node so that legalize doesn't hack it.
4616   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4617     auto GV = G->getGlobal();
4618     unsigned OpFlags =
4619         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4620     if (OpFlags & AArch64II::MO_GOT) {
4621       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4622       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4623     } else {
4624       const GlobalValue *GV = G->getGlobal();
4625       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4626     }
4627   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4628     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4629         Subtarget->isTargetMachO()) {
4630       const char *Sym = S->getSymbol();
4631       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4632       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4633     } else {
4634       const char *Sym = S->getSymbol();
4635       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4636     }
4637   }
4638 
4639   // We don't usually want to end the call-sequence here because we would tidy
4640   // the frame up *after* the call, however in the ABI-changing tail-call case
4641   // we've carefully laid out the parameters so that when sp is reset they'll be
4642   // in the correct location.
4643   if (IsTailCall && !IsSibCall) {
4644     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4645                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4646     InFlag = Chain.getValue(1);
4647   }
4648 
4649   std::vector<SDValue> Ops;
4650   Ops.push_back(Chain);
4651   Ops.push_back(Callee);
4652 
4653   if (IsTailCall) {
4654     // Each tail call may have to adjust the stack by a different amount, so
4655     // this information must travel along with the operation for eventual
4656     // consumption by emitEpilogue.
4657     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4658   }
4659 
4660   // Add argument registers to the end of the list so that they are known live
4661   // into the call.
4662   for (auto &RegToPass : RegsToPass)
4663     Ops.push_back(DAG.getRegister(RegToPass.first,
4664                                   RegToPass.second.getValueType()));
4665 
4666   // Check callee args/returns for SVE registers and set calling convention
4667   // accordingly.
4668   if (CallConv == CallingConv::C) {
4669     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4670       return Out.VT.isScalableVector();
4671     });
4672     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4673       return In.VT.isScalableVector();
4674     });
4675 
4676     if (CalleeInSVE || CalleeOutSVE)
4677       CallConv = CallingConv::AArch64_SVE_VectorCall;
4678   }
4679 
4680   // Add a register mask operand representing the call-preserved registers.
4681   const uint32_t *Mask;
4682   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4683   if (IsThisReturn) {
4684     // For 'this' returns, use the X0-preserving mask if applicable
4685     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4686     if (!Mask) {
4687       IsThisReturn = false;
4688       Mask = TRI->getCallPreservedMask(MF, CallConv);
4689     }
4690   } else
4691     Mask = TRI->getCallPreservedMask(MF, CallConv);
4692 
4693   if (Subtarget->hasCustomCallingConv())
4694     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4695 
4696   if (TRI->isAnyArgRegReserved(MF))
4697     TRI->emitReservedArgRegCallError(MF);
4698 
4699   assert(Mask && "Missing call preserved mask for calling convention");
4700   Ops.push_back(DAG.getRegisterMask(Mask));
4701 
4702   if (InFlag.getNode())
4703     Ops.push_back(InFlag);
4704 
4705   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4706 
4707   // If we're doing a tall call, use a TC_RETURN here rather than an
4708   // actual call instruction.
4709   if (IsTailCall) {
4710     MF.getFrameInfo().setHasTailCall();
4711     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4712     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4713     return Ret;
4714   }
4715 
4716   // Returns a chain and a flag for retval copy to use.
4717   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4718   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4719   InFlag = Chain.getValue(1);
4720   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4721 
4722   uint64_t CalleePopBytes =
4723       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4724 
4725   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4726                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4727                              InFlag, DL);
4728   if (!Ins.empty())
4729     InFlag = Chain.getValue(1);
4730 
4731   // Handle result values, copying them out of physregs into vregs that we
4732   // return.
4733   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4734                          InVals, IsThisReturn,
4735                          IsThisReturn ? OutVals[0] : SDValue());
4736 }
4737 
4738 bool AArch64TargetLowering::CanLowerReturn(
4739     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4740     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4741   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4742                           ? RetCC_AArch64_WebKit_JS
4743                           : RetCC_AArch64_AAPCS;
4744   SmallVector<CCValAssign, 16> RVLocs;
4745   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4746   return CCInfo.CheckReturn(Outs, RetCC);
4747 }
4748 
4749 SDValue
4750 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4751                                    bool isVarArg,
4752                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4753                                    const SmallVectorImpl<SDValue> &OutVals,
4754                                    const SDLoc &DL, SelectionDAG &DAG) const {
4755   auto &MF = DAG.getMachineFunction();
4756   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4757 
4758   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4759                           ? RetCC_AArch64_WebKit_JS
4760                           : RetCC_AArch64_AAPCS;
4761   SmallVector<CCValAssign, 16> RVLocs;
4762   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4763                  *DAG.getContext());
4764   CCInfo.AnalyzeReturn(Outs, RetCC);
4765 
4766   // Copy the result values into the output registers.
4767   SDValue Flag;
4768   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4769   SmallSet<unsigned, 4> RegsUsed;
4770   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4771        ++i, ++realRVLocIdx) {
4772     CCValAssign &VA = RVLocs[i];
4773     assert(VA.isRegLoc() && "Can only return in registers!");
4774     SDValue Arg = OutVals[realRVLocIdx];
4775 
4776     switch (VA.getLocInfo()) {
4777     default:
4778       llvm_unreachable("Unknown loc info!");
4779     case CCValAssign::Full:
4780       if (Outs[i].ArgVT == MVT::i1) {
4781         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4782         // value. This is strictly redundant on Darwin (which uses "zeroext
4783         // i1"), but will be optimised out before ISel.
4784         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4785         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4786       }
4787       break;
4788     case CCValAssign::BCvt:
4789       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4790       break;
4791     case CCValAssign::AExt:
4792     case CCValAssign::ZExt:
4793       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4794       break;
4795     case CCValAssign::AExtUpper:
4796       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4797       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4798       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4799                         DAG.getConstant(32, DL, VA.getLocVT()));
4800       break;
4801     }
4802 
4803     if (RegsUsed.count(VA.getLocReg())) {
4804       SDValue &Bits =
4805           std::find_if(RetVals.begin(), RetVals.end(),
4806                        [=](const std::pair<unsigned, SDValue> &Elt) {
4807                          return Elt.first == VA.getLocReg();
4808                        })
4809               ->second;
4810       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4811     } else {
4812       RetVals.emplace_back(VA.getLocReg(), Arg);
4813       RegsUsed.insert(VA.getLocReg());
4814     }
4815   }
4816 
4817   SmallVector<SDValue, 4> RetOps(1, Chain);
4818   for (auto &RetVal : RetVals) {
4819     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4820     Flag = Chain.getValue(1);
4821     RetOps.push_back(
4822         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4823   }
4824 
4825   // Windows AArch64 ABIs require that for returning structs by value we copy
4826   // the sret argument into X0 for the return.
4827   // We saved the argument into a virtual register in the entry block,
4828   // so now we copy the value out and into X0.
4829   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4830     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4831                                      getPointerTy(MF.getDataLayout()));
4832 
4833     unsigned RetValReg = AArch64::X0;
4834     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4835     Flag = Chain.getValue(1);
4836 
4837     RetOps.push_back(
4838       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4839   }
4840 
4841   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4842   const MCPhysReg *I =
4843       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4844   if (I) {
4845     for (; *I; ++I) {
4846       if (AArch64::GPR64RegClass.contains(*I))
4847         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4848       else if (AArch64::FPR64RegClass.contains(*I))
4849         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4850       else
4851         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4852     }
4853   }
4854 
4855   RetOps[0] = Chain; // Update chain.
4856 
4857   // Add the flag if we have it.
4858   if (Flag.getNode())
4859     RetOps.push_back(Flag);
4860 
4861   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4862 }
4863 
4864 //===----------------------------------------------------------------------===//
4865 //  Other Lowering Code
4866 //===----------------------------------------------------------------------===//
4867 
4868 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4869                                              SelectionDAG &DAG,
4870                                              unsigned Flag) const {
4871   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4872                                     N->getOffset(), Flag);
4873 }
4874 
4875 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4876                                              SelectionDAG &DAG,
4877                                              unsigned Flag) const {
4878   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4879 }
4880 
4881 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4882                                              SelectionDAG &DAG,
4883                                              unsigned Flag) const {
4884   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
4885                                    N->getOffset(), Flag);
4886 }
4887 
4888 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4889                                              SelectionDAG &DAG,
4890                                              unsigned Flag) const {
4891   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4892 }
4893 
4894 // (loadGOT sym)
4895 template <class NodeTy>
4896 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4897                                       unsigned Flags) const {
4898   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4899   SDLoc DL(N);
4900   EVT Ty = getPointerTy(DAG.getDataLayout());
4901   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4902   // FIXME: Once remat is capable of dealing with instructions with register
4903   // operands, expand this into two nodes instead of using a wrapper node.
4904   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4905 }
4906 
4907 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4908 template <class NodeTy>
4909 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4910                                             unsigned Flags) const {
4911   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4912   SDLoc DL(N);
4913   EVT Ty = getPointerTy(DAG.getDataLayout());
4914   const unsigned char MO_NC = AArch64II::MO_NC;
4915   return DAG.getNode(
4916       AArch64ISD::WrapperLarge, DL, Ty,
4917       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4918       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4919       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4920       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4921 }
4922 
4923 // (addlow (adrp %hi(sym)) %lo(sym))
4924 template <class NodeTy>
4925 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4926                                        unsigned Flags) const {
4927   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4928   SDLoc DL(N);
4929   EVT Ty = getPointerTy(DAG.getDataLayout());
4930   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4931   SDValue Lo = getTargetNode(N, Ty, DAG,
4932                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4933   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4934   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4935 }
4936 
4937 // (adr sym)
4938 template <class NodeTy>
4939 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4940                                            unsigned Flags) const {
4941   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4942   SDLoc DL(N);
4943   EVT Ty = getPointerTy(DAG.getDataLayout());
4944   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4945   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4946 }
4947 
4948 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4949                                                   SelectionDAG &DAG) const {
4950   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4951   const GlobalValue *GV = GN->getGlobal();
4952   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4953 
4954   if (OpFlags != AArch64II::MO_NO_FLAG)
4955     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4956            "unexpected offset in global node");
4957 
4958   // This also catches the large code model case for Darwin, and tiny code
4959   // model with got relocations.
4960   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4961     return getGOT(GN, DAG, OpFlags);
4962   }
4963 
4964   SDValue Result;
4965   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4966     Result = getAddrLarge(GN, DAG, OpFlags);
4967   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4968     Result = getAddrTiny(GN, DAG, OpFlags);
4969   } else {
4970     Result = getAddr(GN, DAG, OpFlags);
4971   }
4972   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4973   SDLoc DL(GN);
4974   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4975     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4976                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4977   return Result;
4978 }
4979 
4980 /// Convert a TLS address reference into the correct sequence of loads
4981 /// and calls to compute the variable's address (for Darwin, currently) and
4982 /// return an SDValue containing the final node.
4983 
4984 /// Darwin only has one TLS scheme which must be capable of dealing with the
4985 /// fully general situation, in the worst case. This means:
4986 ///     + "extern __thread" declaration.
4987 ///     + Defined in a possibly unknown dynamic library.
4988 ///
4989 /// The general system is that each __thread variable has a [3 x i64] descriptor
4990 /// which contains information used by the runtime to calculate the address. The
4991 /// only part of this the compiler needs to know about is the first xword, which
4992 /// contains a function pointer that must be called with the address of the
4993 /// entire descriptor in "x0".
4994 ///
4995 /// Since this descriptor may be in a different unit, in general even the
4996 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4997 /// is:
4998 ///     adrp x0, _var@TLVPPAGE
4999 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5000 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5001 ///                                      ; the function pointer
5002 ///     blr x1                           ; Uses descriptor address in x0
5003 ///     ; Address of _var is now in x0.
5004 ///
5005 /// If the address of _var's descriptor *is* known to the linker, then it can
5006 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5007 /// a slight efficiency gain.
5008 SDValue
5009 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5010                                                    SelectionDAG &DAG) const {
5011   assert(Subtarget->isTargetDarwin() &&
5012          "This function expects a Darwin target");
5013 
5014   SDLoc DL(Op);
5015   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5016   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5017   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5018 
5019   SDValue TLVPAddr =
5020       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5021   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5022 
5023   // The first entry in the descriptor is a function pointer that we must call
5024   // to obtain the address of the variable.
5025   SDValue Chain = DAG.getEntryNode();
5026   SDValue FuncTLVGet = DAG.getLoad(
5027       PtrMemVT, DL, Chain, DescAddr,
5028       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5029       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
5030       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5031   Chain = FuncTLVGet.getValue(1);
5032 
5033   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5034   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5035 
5036   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5037   MFI.setAdjustsStack(true);
5038 
5039   // TLS calls preserve all registers except those that absolutely must be
5040   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5041   // silly).
5042   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5043   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5044   if (Subtarget->hasCustomCallingConv())
5045     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5046 
5047   // Finally, we can make the call. This is just a degenerate version of a
5048   // normal AArch64 call node: x0 takes the address of the descriptor, and
5049   // returns the address of the variable in this thread.
5050   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5051   Chain =
5052       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5053                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5054                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5055   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5056 }
5057 
5058 /// Convert a thread-local variable reference into a sequence of instructions to
5059 /// compute the variable's address for the local exec TLS model of ELF targets.
5060 /// The sequence depends on the maximum TLS area size.
5061 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5062                                                     SDValue ThreadBase,
5063                                                     const SDLoc &DL,
5064                                                     SelectionDAG &DAG) const {
5065   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5066   SDValue TPOff, Addr;
5067 
5068   switch (DAG.getTarget().Options.TLSSize) {
5069   default:
5070     llvm_unreachable("Unexpected TLS size");
5071 
5072   case 12: {
5073     // mrs   x0, TPIDR_EL0
5074     // add   x0, x0, :tprel_lo12:a
5075     SDValue Var = DAG.getTargetGlobalAddress(
5076         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5077     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5078                                       Var,
5079                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5080                    0);
5081   }
5082 
5083   case 24: {
5084     // mrs   x0, TPIDR_EL0
5085     // add   x0, x0, :tprel_hi12:a
5086     // add   x0, x0, :tprel_lo12_nc:a
5087     SDValue HiVar = DAG.getTargetGlobalAddress(
5088         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5089     SDValue LoVar = DAG.getTargetGlobalAddress(
5090         GV, DL, PtrVT, 0,
5091         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5092     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5093                                       HiVar,
5094                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5095                    0);
5096     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5097                                       LoVar,
5098                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5099                    0);
5100   }
5101 
5102   case 32: {
5103     // mrs   x1, TPIDR_EL0
5104     // movz  x0, #:tprel_g1:a
5105     // movk  x0, #:tprel_g0_nc:a
5106     // add   x0, x1, x0
5107     SDValue HiVar = DAG.getTargetGlobalAddress(
5108         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5109     SDValue LoVar = DAG.getTargetGlobalAddress(
5110         GV, DL, PtrVT, 0,
5111         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5112     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5113                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5114                     0);
5115     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5116                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5117                     0);
5118     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5119   }
5120 
5121   case 48: {
5122     // mrs   x1, TPIDR_EL0
5123     // movz  x0, #:tprel_g2:a
5124     // movk  x0, #:tprel_g1_nc:a
5125     // movk  x0, #:tprel_g0_nc:a
5126     // add   x0, x1, x0
5127     SDValue HiVar = DAG.getTargetGlobalAddress(
5128         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5129     SDValue MiVar = DAG.getTargetGlobalAddress(
5130         GV, DL, PtrVT, 0,
5131         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5132     SDValue LoVar = DAG.getTargetGlobalAddress(
5133         GV, DL, PtrVT, 0,
5134         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5135     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5136                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5137                     0);
5138     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5139                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5140                     0);
5141     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5142                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5143                     0);
5144     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5145   }
5146   }
5147 }
5148 
5149 /// When accessing thread-local variables under either the general-dynamic or
5150 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5151 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5152 /// is a function pointer to carry out the resolution.
5153 ///
5154 /// The sequence is:
5155 ///    adrp  x0, :tlsdesc:var
5156 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5157 ///    add   x0, x0, #:tlsdesc_lo12:var
5158 ///    .tlsdesccall var
5159 ///    blr   x1
5160 ///    (TPIDR_EL0 offset now in x0)
5161 ///
5162 ///  The above sequence must be produced unscheduled, to enable the linker to
5163 ///  optimize/relax this sequence.
5164 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5165 ///  above sequence, and expanded really late in the compilation flow, to ensure
5166 ///  the sequence is produced as per above.
5167 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5168                                                       const SDLoc &DL,
5169                                                       SelectionDAG &DAG) const {
5170   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5171 
5172   SDValue Chain = DAG.getEntryNode();
5173   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5174 
5175   Chain =
5176       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5177   SDValue Glue = Chain.getValue(1);
5178 
5179   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5180 }
5181 
5182 SDValue
5183 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5184                                                 SelectionDAG &DAG) const {
5185   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5186 
5187   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5188 
5189   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5190 
5191   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5192     if (Model == TLSModel::LocalDynamic)
5193       Model = TLSModel::GeneralDynamic;
5194   }
5195 
5196   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5197       Model != TLSModel::LocalExec)
5198     report_fatal_error("ELF TLS only supported in small memory model or "
5199                        "in local exec TLS model");
5200   // Different choices can be made for the maximum size of the TLS area for a
5201   // module. For the small address model, the default TLS size is 16MiB and the
5202   // maximum TLS size is 4GiB.
5203   // FIXME: add tiny and large code model support for TLS access models other
5204   // than local exec. We currently generate the same code as small for tiny,
5205   // which may be larger than needed.
5206 
5207   SDValue TPOff;
5208   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5209   SDLoc DL(Op);
5210   const GlobalValue *GV = GA->getGlobal();
5211 
5212   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5213 
5214   if (Model == TLSModel::LocalExec) {
5215     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5216   } else if (Model == TLSModel::InitialExec) {
5217     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5218     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5219   } else if (Model == TLSModel::LocalDynamic) {
5220     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5221     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5222     // the beginning of the module's TLS region, followed by a DTPREL offset
5223     // calculation.
5224 
5225     // These accesses will need deduplicating if there's more than one.
5226     AArch64FunctionInfo *MFI =
5227         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5228     MFI->incNumLocalDynamicTLSAccesses();
5229 
5230     // The call needs a relocation too for linker relaxation. It doesn't make
5231     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5232     // the address.
5233     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5234                                                   AArch64II::MO_TLS);
5235 
5236     // Now we can calculate the offset from TPIDR_EL0 to this module's
5237     // thread-local area.
5238     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5239 
5240     // Now use :dtprel_whatever: operations to calculate this variable's offset
5241     // in its thread-storage area.
5242     SDValue HiVar = DAG.getTargetGlobalAddress(
5243         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5244     SDValue LoVar = DAG.getTargetGlobalAddress(
5245         GV, DL, MVT::i64, 0,
5246         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5247 
5248     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5249                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5250                     0);
5251     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5252                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5253                     0);
5254   } else if (Model == TLSModel::GeneralDynamic) {
5255     // The call needs a relocation too for linker relaxation. It doesn't make
5256     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5257     // the address.
5258     SDValue SymAddr =
5259         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5260 
5261     // Finally we can make a call to calculate the offset from tpidr_el0.
5262     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5263   } else
5264     llvm_unreachable("Unsupported ELF TLS access model");
5265 
5266   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5267 }
5268 
5269 SDValue
5270 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5271                                                     SelectionDAG &DAG) const {
5272   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5273 
5274   SDValue Chain = DAG.getEntryNode();
5275   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5276   SDLoc DL(Op);
5277 
5278   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5279 
5280   // Load the ThreadLocalStoragePointer from the TEB
5281   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5282   SDValue TLSArray =
5283       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5284   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5285   Chain = TLSArray.getValue(1);
5286 
5287   // Load the TLS index from the C runtime;
5288   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5289   // This also does the same as LOADgot, but using a generic i32 load,
5290   // while LOADgot only loads i64.
5291   SDValue TLSIndexHi =
5292       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5293   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5294       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5295   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5296   SDValue TLSIndex =
5297       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5298   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5299   Chain = TLSIndex.getValue(1);
5300 
5301   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5302   // offset into the TLSArray.
5303   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5304   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5305                              DAG.getConstant(3, DL, PtrVT));
5306   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5307                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5308                             MachinePointerInfo());
5309   Chain = TLS.getValue(1);
5310 
5311   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5312   const GlobalValue *GV = GA->getGlobal();
5313   SDValue TGAHi = DAG.getTargetGlobalAddress(
5314       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5315   SDValue TGALo = DAG.getTargetGlobalAddress(
5316       GV, DL, PtrVT, 0,
5317       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5318 
5319   // Add the offset from the start of the .tls section (section base).
5320   SDValue Addr =
5321       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5322                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5323               0);
5324   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5325   return Addr;
5326 }
5327 
5328 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5329                                                      SelectionDAG &DAG) const {
5330   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5331   if (DAG.getTarget().useEmulatedTLS())
5332     return LowerToTLSEmulatedModel(GA, DAG);
5333 
5334   if (Subtarget->isTargetDarwin())
5335     return LowerDarwinGlobalTLSAddress(Op, DAG);
5336   if (Subtarget->isTargetELF())
5337     return LowerELFGlobalTLSAddress(Op, DAG);
5338   if (Subtarget->isTargetWindows())
5339     return LowerWindowsGlobalTLSAddress(Op, DAG);
5340 
5341   llvm_unreachable("Unexpected platform trying to use TLS");
5342 }
5343 
5344 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5345   SDValue Chain = Op.getOperand(0);
5346   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5347   SDValue LHS = Op.getOperand(2);
5348   SDValue RHS = Op.getOperand(3);
5349   SDValue Dest = Op.getOperand(4);
5350   SDLoc dl(Op);
5351 
5352   MachineFunction &MF = DAG.getMachineFunction();
5353   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5354   // will not be produced, as they are conditional branch instructions that do
5355   // not set flags.
5356   bool ProduceNonFlagSettingCondBr =
5357       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5358 
5359   // Handle f128 first, since lowering it will result in comparing the return
5360   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5361   // is expecting to deal with.
5362   if (LHS.getValueType() == MVT::f128) {
5363     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5364 
5365     // If softenSetCCOperands returned a scalar, we need to compare the result
5366     // against zero to select between true and false values.
5367     if (!RHS.getNode()) {
5368       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5369       CC = ISD::SETNE;
5370     }
5371   }
5372 
5373   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5374   // instruction.
5375   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5376       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5377     // Only lower legal XALUO ops.
5378     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5379       return SDValue();
5380 
5381     // The actual operation with overflow check.
5382     AArch64CC::CondCode OFCC;
5383     SDValue Value, Overflow;
5384     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5385 
5386     if (CC == ISD::SETNE)
5387       OFCC = getInvertedCondCode(OFCC);
5388     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5389 
5390     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5391                        Overflow);
5392   }
5393 
5394   if (LHS.getValueType().isInteger()) {
5395     assert((LHS.getValueType() == RHS.getValueType()) &&
5396            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5397 
5398     // If the RHS of the comparison is zero, we can potentially fold this
5399     // to a specialized branch.
5400     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5401     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5402       if (CC == ISD::SETEQ) {
5403         // See if we can use a TBZ to fold in an AND as well.
5404         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5405         // out of bounds, a late MI-layer pass rewrites branches.
5406         // 403.gcc is an example that hits this case.
5407         if (LHS.getOpcode() == ISD::AND &&
5408             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5409             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5410           SDValue Test = LHS.getOperand(0);
5411           uint64_t Mask = LHS.getConstantOperandVal(1);
5412           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5413                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5414                              Dest);
5415         }
5416 
5417         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5418       } else if (CC == ISD::SETNE) {
5419         // See if we can use a TBZ to fold in an AND as well.
5420         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5421         // out of bounds, a late MI-layer pass rewrites branches.
5422         // 403.gcc is an example that hits this case.
5423         if (LHS.getOpcode() == ISD::AND &&
5424             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5425             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5426           SDValue Test = LHS.getOperand(0);
5427           uint64_t Mask = LHS.getConstantOperandVal(1);
5428           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5429                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5430                              Dest);
5431         }
5432 
5433         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5434       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5435         // Don't combine AND since emitComparison converts the AND to an ANDS
5436         // (a.k.a. TST) and the test in the test bit and branch instruction
5437         // becomes redundant.  This would also increase register pressure.
5438         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5439         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5440                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5441       }
5442     }
5443     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5444         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5445       // Don't combine AND since emitComparison converts the AND to an ANDS
5446       // (a.k.a. TST) and the test in the test bit and branch instruction
5447       // becomes redundant.  This would also increase register pressure.
5448       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5449       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5450                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5451     }
5452 
5453     SDValue CCVal;
5454     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5455     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5456                        Cmp);
5457   }
5458 
5459   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5460          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5461 
5462   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5463   // clean.  Some of them require two branches to implement.
5464   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5465   AArch64CC::CondCode CC1, CC2;
5466   changeFPCCToAArch64CC(CC, CC1, CC2);
5467   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5468   SDValue BR1 =
5469       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5470   if (CC2 != AArch64CC::AL) {
5471     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5472     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5473                        Cmp);
5474   }
5475 
5476   return BR1;
5477 }
5478 
5479 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5480                                               SelectionDAG &DAG) const {
5481   EVT VT = Op.getValueType();
5482   SDLoc DL(Op);
5483 
5484   SDValue In1 = Op.getOperand(0);
5485   SDValue In2 = Op.getOperand(1);
5486   EVT SrcVT = In2.getValueType();
5487 
5488   if (SrcVT.bitsLT(VT))
5489     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5490   else if (SrcVT.bitsGT(VT))
5491     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5492 
5493   EVT VecVT;
5494   uint64_t EltMask;
5495   SDValue VecVal1, VecVal2;
5496 
5497   auto setVecVal = [&] (int Idx) {
5498     if (!VT.isVector()) {
5499       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5500                                           DAG.getUNDEF(VecVT), In1);
5501       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5502                                           DAG.getUNDEF(VecVT), In2);
5503     } else {
5504       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5505       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5506     }
5507   };
5508 
5509   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5510     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5511     EltMask = 0x80000000ULL;
5512     setVecVal(AArch64::ssub);
5513   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5514     VecVT = MVT::v2i64;
5515 
5516     // We want to materialize a mask with the high bit set, but the AdvSIMD
5517     // immediate moves cannot materialize that in a single instruction for
5518     // 64-bit elements. Instead, materialize zero and then negate it.
5519     EltMask = 0;
5520 
5521     setVecVal(AArch64::dsub);
5522   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5523     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5524     EltMask = 0x8000ULL;
5525     setVecVal(AArch64::hsub);
5526   } else {
5527     llvm_unreachable("Invalid type for copysign!");
5528   }
5529 
5530   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5531 
5532   // If we couldn't materialize the mask above, then the mask vector will be
5533   // the zero vector, and we need to negate it here.
5534   if (VT == MVT::f64 || VT == MVT::v2f64) {
5535     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5536     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5537     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5538   }
5539 
5540   SDValue Sel =
5541       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5542 
5543   if (VT == MVT::f16)
5544     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5545   if (VT == MVT::f32)
5546     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5547   else if (VT == MVT::f64)
5548     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5549   else
5550     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5551 }
5552 
5553 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5554   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5555           Attribute::NoImplicitFloat))
5556     return SDValue();
5557 
5558   if (!Subtarget->hasNEON())
5559     return SDValue();
5560 
5561   // While there is no integer popcount instruction, it can
5562   // be more efficiently lowered to the following sequence that uses
5563   // AdvSIMD registers/instructions as long as the copies to/from
5564   // the AdvSIMD registers are cheap.
5565   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5566   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5567   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5568   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5569   SDValue Val = Op.getOperand(0);
5570   SDLoc DL(Op);
5571   EVT VT = Op.getValueType();
5572 
5573   if (VT == MVT::i32 || VT == MVT::i64) {
5574     if (VT == MVT::i32)
5575       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5576     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5577 
5578     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5579     SDValue UaddLV = DAG.getNode(
5580         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5581         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5582 
5583     if (VT == MVT::i64)
5584       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5585     return UaddLV;
5586   } else if (VT == MVT::i128) {
5587     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
5588 
5589     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
5590     SDValue UaddLV = DAG.getNode(
5591         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5592         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5593 
5594     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
5595   }
5596 
5597   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5598           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5599          "Unexpected type for custom ctpop lowering");
5600 
5601   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5602   Val = DAG.getBitcast(VT8Bit, Val);
5603   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5604 
5605   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5606   unsigned EltSize = 8;
5607   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5608   while (EltSize != VT.getScalarSizeInBits()) {
5609     EltSize *= 2;
5610     NumElts /= 2;
5611     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5612     Val = DAG.getNode(
5613         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5614         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5615   }
5616 
5617   return Val;
5618 }
5619 
5620 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5621 
5622   if (Op.getValueType().isVector())
5623     return LowerVSETCC(Op, DAG);
5624 
5625   bool IsStrict = Op->isStrictFPOpcode();
5626   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5627   unsigned OpNo = IsStrict ? 1 : 0;
5628   SDValue Chain;
5629   if (IsStrict)
5630     Chain = Op.getOperand(0);
5631   SDValue LHS = Op.getOperand(OpNo + 0);
5632   SDValue RHS = Op.getOperand(OpNo + 1);
5633   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5634   SDLoc dl(Op);
5635 
5636   // We chose ZeroOrOneBooleanContents, so use zero and one.
5637   EVT VT = Op.getValueType();
5638   SDValue TVal = DAG.getConstant(1, dl, VT);
5639   SDValue FVal = DAG.getConstant(0, dl, VT);
5640 
5641   // Handle f128 first, since one possible outcome is a normal integer
5642   // comparison which gets picked up by the next if statement.
5643   if (LHS.getValueType() == MVT::f128) {
5644     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5645                         IsSignaling);
5646 
5647     // If softenSetCCOperands returned a scalar, use it.
5648     if (!RHS.getNode()) {
5649       assert(LHS.getValueType() == Op.getValueType() &&
5650              "Unexpected setcc expansion!");
5651       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5652     }
5653   }
5654 
5655   if (LHS.getValueType().isInteger()) {
5656     SDValue CCVal;
5657     SDValue Cmp = getAArch64Cmp(
5658         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5659 
5660     // Note that we inverted the condition above, so we reverse the order of
5661     // the true and false operands here.  This will allow the setcc to be
5662     // matched to a single CSINC instruction.
5663     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5664     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5665   }
5666 
5667   // Now we know we're dealing with FP values.
5668   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5669          LHS.getValueType() == MVT::f64);
5670 
5671   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5672   // and do the comparison.
5673   SDValue Cmp;
5674   if (IsStrict)
5675     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5676   else
5677     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5678 
5679   AArch64CC::CondCode CC1, CC2;
5680   changeFPCCToAArch64CC(CC, CC1, CC2);
5681   SDValue Res;
5682   if (CC2 == AArch64CC::AL) {
5683     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5684                           CC2);
5685     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5686 
5687     // Note that we inverted the condition above, so we reverse the order of
5688     // the true and false operands here.  This will allow the setcc to be
5689     // matched to a single CSINC instruction.
5690     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5691   } else {
5692     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5693     // totally clean.  Some of them require two CSELs to implement.  As is in
5694     // this case, we emit the first CSEL and then emit a second using the output
5695     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5696 
5697     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5698     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5699     SDValue CS1 =
5700         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5701 
5702     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5703     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5704   }
5705   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5706 }
5707 
5708 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5709                                               SDValue RHS, SDValue TVal,
5710                                               SDValue FVal, const SDLoc &dl,
5711                                               SelectionDAG &DAG) const {
5712   // Handle f128 first, because it will result in a comparison of some RTLIB
5713   // call result against zero.
5714   if (LHS.getValueType() == MVT::f128) {
5715     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5716 
5717     // If softenSetCCOperands returned a scalar, we need to compare the result
5718     // against zero to select between true and false values.
5719     if (!RHS.getNode()) {
5720       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5721       CC = ISD::SETNE;
5722     }
5723   }
5724 
5725   // Also handle f16, for which we need to do a f32 comparison.
5726   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5727     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5728     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5729   }
5730 
5731   // Next, handle integers.
5732   if (LHS.getValueType().isInteger()) {
5733     assert((LHS.getValueType() == RHS.getValueType()) &&
5734            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5735 
5736     unsigned Opcode = AArch64ISD::CSEL;
5737 
5738     // If both the TVal and the FVal are constants, see if we can swap them in
5739     // order to for a CSINV or CSINC out of them.
5740     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5741     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5742 
5743     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5744       std::swap(TVal, FVal);
5745       std::swap(CTVal, CFVal);
5746       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5747     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5748       std::swap(TVal, FVal);
5749       std::swap(CTVal, CFVal);
5750       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5751     } else if (TVal.getOpcode() == ISD::XOR) {
5752       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5753       // with a CSINV rather than a CSEL.
5754       if (isAllOnesConstant(TVal.getOperand(1))) {
5755         std::swap(TVal, FVal);
5756         std::swap(CTVal, CFVal);
5757         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5758       }
5759     } else if (TVal.getOpcode() == ISD::SUB) {
5760       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5761       // that we can match with a CSNEG rather than a CSEL.
5762       if (isNullConstant(TVal.getOperand(0))) {
5763         std::swap(TVal, FVal);
5764         std::swap(CTVal, CFVal);
5765         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5766       }
5767     } else if (CTVal && CFVal) {
5768       const int64_t TrueVal = CTVal->getSExtValue();
5769       const int64_t FalseVal = CFVal->getSExtValue();
5770       bool Swap = false;
5771 
5772       // If both TVal and FVal are constants, see if FVal is the
5773       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5774       // instead of a CSEL in that case.
5775       if (TrueVal == ~FalseVal) {
5776         Opcode = AArch64ISD::CSINV;
5777       } else if (TrueVal == -FalseVal) {
5778         Opcode = AArch64ISD::CSNEG;
5779       } else if (TVal.getValueType() == MVT::i32) {
5780         // If our operands are only 32-bit wide, make sure we use 32-bit
5781         // arithmetic for the check whether we can use CSINC. This ensures that
5782         // the addition in the check will wrap around properly in case there is
5783         // an overflow (which would not be the case if we do the check with
5784         // 64-bit arithmetic).
5785         const uint32_t TrueVal32 = CTVal->getZExtValue();
5786         const uint32_t FalseVal32 = CFVal->getZExtValue();
5787 
5788         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5789           Opcode = AArch64ISD::CSINC;
5790 
5791           if (TrueVal32 > FalseVal32) {
5792             Swap = true;
5793           }
5794         }
5795         // 64-bit check whether we can use CSINC.
5796       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5797         Opcode = AArch64ISD::CSINC;
5798 
5799         if (TrueVal > FalseVal) {
5800           Swap = true;
5801         }
5802       }
5803 
5804       // Swap TVal and FVal if necessary.
5805       if (Swap) {
5806         std::swap(TVal, FVal);
5807         std::swap(CTVal, CFVal);
5808         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5809       }
5810 
5811       if (Opcode != AArch64ISD::CSEL) {
5812         // Drop FVal since we can get its value by simply inverting/negating
5813         // TVal.
5814         FVal = TVal;
5815       }
5816     }
5817 
5818     // Avoid materializing a constant when possible by reusing a known value in
5819     // a register.  However, don't perform this optimization if the known value
5820     // is one, zero or negative one in the case of a CSEL.  We can always
5821     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5822     // FVal, respectively.
5823     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5824     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5825         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5826       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5827       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5828       // "a != C ? x : a" to avoid materializing C.
5829       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5830         TVal = LHS;
5831       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5832         FVal = LHS;
5833     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5834       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5835       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5836       // avoid materializing C.
5837       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5838       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5839         Opcode = AArch64ISD::CSINV;
5840         TVal = LHS;
5841         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5842       }
5843     }
5844 
5845     SDValue CCVal;
5846     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5847     EVT VT = TVal.getValueType();
5848     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5849   }
5850 
5851   // Now we know we're dealing with FP values.
5852   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5853          LHS.getValueType() == MVT::f64);
5854   assert(LHS.getValueType() == RHS.getValueType());
5855   EVT VT = TVal.getValueType();
5856   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5857 
5858   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5859   // clean.  Some of them require two CSELs to implement.
5860   AArch64CC::CondCode CC1, CC2;
5861   changeFPCCToAArch64CC(CC, CC1, CC2);
5862 
5863   if (DAG.getTarget().Options.UnsafeFPMath) {
5864     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5865     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5866     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5867     if (RHSVal && RHSVal->isZero()) {
5868       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5869       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5870 
5871       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5872           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5873         TVal = LHS;
5874       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5875                CFVal && CFVal->isZero() &&
5876                FVal.getValueType() == LHS.getValueType())
5877         FVal = LHS;
5878     }
5879   }
5880 
5881   // Emit first, and possibly only, CSEL.
5882   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5883   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5884 
5885   // If we need a second CSEL, emit it, using the output of the first as the
5886   // RHS.  We're effectively OR'ing the two CC's together.
5887   if (CC2 != AArch64CC::AL) {
5888     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5889     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5890   }
5891 
5892   // Otherwise, return the output of the first CSEL.
5893   return CS1;
5894 }
5895 
5896 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5897                                               SelectionDAG &DAG) const {
5898   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5899   SDValue LHS = Op.getOperand(0);
5900   SDValue RHS = Op.getOperand(1);
5901   SDValue TVal = Op.getOperand(2);
5902   SDValue FVal = Op.getOperand(3);
5903   SDLoc DL(Op);
5904   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5905 }
5906 
5907 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5908                                            SelectionDAG &DAG) const {
5909   SDValue CCVal = Op->getOperand(0);
5910   SDValue TVal = Op->getOperand(1);
5911   SDValue FVal = Op->getOperand(2);
5912   SDLoc DL(Op);
5913 
5914   EVT Ty = Op.getValueType();
5915   if (Ty.isScalableVector()) {
5916     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
5917     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
5918     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
5919     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
5920   }
5921 
5922   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5923   // instruction.
5924   if (ISD::isOverflowIntrOpRes(CCVal)) {
5925     // Only lower legal XALUO ops.
5926     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5927       return SDValue();
5928 
5929     AArch64CC::CondCode OFCC;
5930     SDValue Value, Overflow;
5931     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5932     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5933 
5934     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5935                        CCVal, Overflow);
5936   }
5937 
5938   // Lower it the same way as we would lower a SELECT_CC node.
5939   ISD::CondCode CC;
5940   SDValue LHS, RHS;
5941   if (CCVal.getOpcode() == ISD::SETCC) {
5942     LHS = CCVal.getOperand(0);
5943     RHS = CCVal.getOperand(1);
5944     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5945   } else {
5946     LHS = CCVal;
5947     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5948     CC = ISD::SETNE;
5949   }
5950   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5951 }
5952 
5953 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5954                                               SelectionDAG &DAG) const {
5955   // Jump table entries as PC relative offsets. No additional tweaking
5956   // is necessary here. Just get the address of the jump table.
5957   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5958 
5959   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5960       !Subtarget->isTargetMachO()) {
5961     return getAddrLarge(JT, DAG);
5962   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5963     return getAddrTiny(JT, DAG);
5964   }
5965   return getAddr(JT, DAG);
5966 }
5967 
5968 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5969                                           SelectionDAG &DAG) const {
5970   // Jump table entries as PC relative offsets. No additional tweaking
5971   // is necessary here. Just get the address of the jump table.
5972   SDLoc DL(Op);
5973   SDValue JT = Op.getOperand(1);
5974   SDValue Entry = Op.getOperand(2);
5975   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5976 
5977   SDNode *Dest =
5978       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5979                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5980   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5981                      SDValue(Dest, 0));
5982 }
5983 
5984 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5985                                                  SelectionDAG &DAG) const {
5986   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5987 
5988   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5989     // Use the GOT for the large code model on iOS.
5990     if (Subtarget->isTargetMachO()) {
5991       return getGOT(CP, DAG);
5992     }
5993     return getAddrLarge(CP, DAG);
5994   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5995     return getAddrTiny(CP, DAG);
5996   } else {
5997     return getAddr(CP, DAG);
5998   }
5999 }
6000 
6001 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6002                                                SelectionDAG &DAG) const {
6003   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6004   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6005       !Subtarget->isTargetMachO()) {
6006     return getAddrLarge(BA, DAG);
6007   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6008     return getAddrTiny(BA, DAG);
6009   }
6010   return getAddr(BA, DAG);
6011 }
6012 
6013 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6014                                                  SelectionDAG &DAG) const {
6015   AArch64FunctionInfo *FuncInfo =
6016       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6017 
6018   SDLoc DL(Op);
6019   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6020                                  getPointerTy(DAG.getDataLayout()));
6021   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6022   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6023   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6024                       MachinePointerInfo(SV));
6025 }
6026 
6027 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6028                                                   SelectionDAG &DAG) const {
6029   AArch64FunctionInfo *FuncInfo =
6030       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6031 
6032   SDLoc DL(Op);
6033   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6034                                      ? FuncInfo->getVarArgsGPRIndex()
6035                                      : FuncInfo->getVarArgsStackIndex(),
6036                                  getPointerTy(DAG.getDataLayout()));
6037   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6038   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6039                       MachinePointerInfo(SV));
6040 }
6041 
6042 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6043                                                 SelectionDAG &DAG) const {
6044   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6045   // Standard, section B.3.
6046   MachineFunction &MF = DAG.getMachineFunction();
6047   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6048   auto PtrVT = getPointerTy(DAG.getDataLayout());
6049   SDLoc DL(Op);
6050 
6051   SDValue Chain = Op.getOperand(0);
6052   SDValue VAList = Op.getOperand(1);
6053   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6054   SmallVector<SDValue, 4> MemOps;
6055 
6056   // void *__stack at offset 0
6057   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6058   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
6059                                 MachinePointerInfo(SV), /* Alignment = */ 8));
6060 
6061   // void *__gr_top at offset 8
6062   int GPRSize = FuncInfo->getVarArgsGPRSize();
6063   if (GPRSize > 0) {
6064     SDValue GRTop, GRTopAddr;
6065 
6066     GRTopAddr =
6067         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6068 
6069     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6070     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6071                         DAG.getConstant(GPRSize, DL, PtrVT));
6072 
6073     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6074                                   MachinePointerInfo(SV, 8),
6075                                   /* Alignment = */ 8));
6076   }
6077 
6078   // void *__vr_top at offset 16
6079   int FPRSize = FuncInfo->getVarArgsFPRSize();
6080   if (FPRSize > 0) {
6081     SDValue VRTop, VRTopAddr;
6082     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6083                             DAG.getConstant(16, DL, PtrVT));
6084 
6085     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6086     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6087                         DAG.getConstant(FPRSize, DL, PtrVT));
6088 
6089     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6090                                   MachinePointerInfo(SV, 16),
6091                                   /* Alignment = */ 8));
6092   }
6093 
6094   // int __gr_offs at offset 24
6095   SDValue GROffsAddr =
6096       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6097   MemOps.push_back(DAG.getStore(
6098       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
6099       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
6100 
6101   // int __vr_offs at offset 28
6102   SDValue VROffsAddr =
6103       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6104   MemOps.push_back(DAG.getStore(
6105       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
6106       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
6107 
6108   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6109 }
6110 
6111 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6112                                             SelectionDAG &DAG) const {
6113   MachineFunction &MF = DAG.getMachineFunction();
6114 
6115   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6116     return LowerWin64_VASTART(Op, DAG);
6117   else if (Subtarget->isTargetDarwin())
6118     return LowerDarwin_VASTART(Op, DAG);
6119   else
6120     return LowerAAPCS_VASTART(Op, DAG);
6121 }
6122 
6123 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6124                                            SelectionDAG &DAG) const {
6125   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6126   // pointer.
6127   SDLoc DL(Op);
6128   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6129   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6130                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6131   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6132   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6133 
6134   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6135                        DAG.getConstant(VaListSize, DL, MVT::i32),
6136                        Align(PtrSize), false, false, false,
6137                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6138 }
6139 
6140 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6141   assert(Subtarget->isTargetDarwin() &&
6142          "automatic va_arg instruction only works on Darwin");
6143 
6144   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6145   EVT VT = Op.getValueType();
6146   SDLoc DL(Op);
6147   SDValue Chain = Op.getOperand(0);
6148   SDValue Addr = Op.getOperand(1);
6149   MaybeAlign Align(Op.getConstantOperandVal(3));
6150   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6151   auto PtrVT = getPointerTy(DAG.getDataLayout());
6152   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6153   SDValue VAList =
6154       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6155   Chain = VAList.getValue(1);
6156   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6157 
6158   if (Align && *Align > MinSlotSize) {
6159     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6160                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6161     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6162                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6163   }
6164 
6165   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6166   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6167 
6168   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6169   // up to 64 bits.  At the very least, we have to increase the striding of the
6170   // vaargs list to match this, and for FP values we need to introduce
6171   // FP_ROUND nodes as well.
6172   if (VT.isInteger() && !VT.isVector())
6173     ArgSize = std::max(ArgSize, MinSlotSize);
6174   bool NeedFPTrunc = false;
6175   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6176     ArgSize = 8;
6177     NeedFPTrunc = true;
6178   }
6179 
6180   // Increment the pointer, VAList, to the next vaarg
6181   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6182                                DAG.getConstant(ArgSize, DL, PtrVT));
6183   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6184 
6185   // Store the incremented VAList to the legalized pointer
6186   SDValue APStore =
6187       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6188 
6189   // Load the actual argument out of the pointer VAList
6190   if (NeedFPTrunc) {
6191     // Load the value as an f64.
6192     SDValue WideFP =
6193         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6194     // Round the value down to an f32.
6195     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6196                                    DAG.getIntPtrConstant(1, DL));
6197     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6198     // Merge the rounded value with the chain output of the load.
6199     return DAG.getMergeValues(Ops, DL);
6200   }
6201 
6202   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6203 }
6204 
6205 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6206                                               SelectionDAG &DAG) const {
6207   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6208   MFI.setFrameAddressIsTaken(true);
6209 
6210   EVT VT = Op.getValueType();
6211   SDLoc DL(Op);
6212   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6213   SDValue FrameAddr =
6214       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6215   while (Depth--)
6216     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6217                             MachinePointerInfo());
6218 
6219   if (Subtarget->isTargetILP32())
6220     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6221                             DAG.getValueType(VT));
6222 
6223   return FrameAddr;
6224 }
6225 
6226 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6227                                               SelectionDAG &DAG) const {
6228   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6229 
6230   EVT VT = getPointerTy(DAG.getDataLayout());
6231   SDLoc DL(Op);
6232   int FI = MFI.CreateFixedObject(4, 0, false);
6233   return DAG.getFrameIndex(FI, VT);
6234 }
6235 
6236 #define GET_REGISTER_MATCHER
6237 #include "AArch64GenAsmMatcher.inc"
6238 
6239 // FIXME? Maybe this could be a TableGen attribute on some registers and
6240 // this table could be generated automatically from RegInfo.
6241 Register AArch64TargetLowering::
6242 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6243   Register Reg = MatchRegisterName(RegName);
6244   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6245     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6246     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6247     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6248       Reg = 0;
6249   }
6250   if (Reg)
6251     return Reg;
6252   report_fatal_error(Twine("Invalid register name \""
6253                               + StringRef(RegName)  + "\"."));
6254 }
6255 
6256 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6257                                                      SelectionDAG &DAG) const {
6258   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6259 
6260   EVT VT = Op.getValueType();
6261   SDLoc DL(Op);
6262 
6263   SDValue FrameAddr =
6264       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6265   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6266 
6267   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6268 }
6269 
6270 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6271                                                SelectionDAG &DAG) const {
6272   MachineFunction &MF = DAG.getMachineFunction();
6273   MachineFrameInfo &MFI = MF.getFrameInfo();
6274   MFI.setReturnAddressIsTaken(true);
6275 
6276   EVT VT = Op.getValueType();
6277   SDLoc DL(Op);
6278   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6279   if (Depth) {
6280     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6281     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6282     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6283                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6284                        MachinePointerInfo());
6285   }
6286 
6287   // Return LR, which contains the return address. Mark it an implicit live-in.
6288   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6289   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6290 }
6291 
6292 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6293 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6294 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6295                                                     SelectionDAG &DAG) const {
6296   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6297   EVT VT = Op.getValueType();
6298   unsigned VTBits = VT.getSizeInBits();
6299   SDLoc dl(Op);
6300   SDValue ShOpLo = Op.getOperand(0);
6301   SDValue ShOpHi = Op.getOperand(1);
6302   SDValue ShAmt = Op.getOperand(2);
6303   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6304 
6305   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6306 
6307   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6308                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6309   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6310 
6311   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6312   // is "undef". We wanted 0, so CSEL it directly.
6313   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6314                                ISD::SETEQ, dl, DAG);
6315   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6316   HiBitsForLo =
6317       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6318                   HiBitsForLo, CCVal, Cmp);
6319 
6320   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6321                                    DAG.getConstant(VTBits, dl, MVT::i64));
6322 
6323   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6324   SDValue LoForNormalShift =
6325       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6326 
6327   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6328                        dl, DAG);
6329   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6330   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6331   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6332                            LoForNormalShift, CCVal, Cmp);
6333 
6334   // AArch64 shifts larger than the register width are wrapped rather than
6335   // clamped, so we can't just emit "hi >> x".
6336   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6337   SDValue HiForBigShift =
6338       Opc == ISD::SRA
6339           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6340                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6341           : DAG.getConstant(0, dl, VT);
6342   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6343                            HiForNormalShift, CCVal, Cmp);
6344 
6345   SDValue Ops[2] = { Lo, Hi };
6346   return DAG.getMergeValues(Ops, dl);
6347 }
6348 
6349 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6350 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6351 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6352                                                    SelectionDAG &DAG) const {
6353   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6354   EVT VT = Op.getValueType();
6355   unsigned VTBits = VT.getSizeInBits();
6356   SDLoc dl(Op);
6357   SDValue ShOpLo = Op.getOperand(0);
6358   SDValue ShOpHi = Op.getOperand(1);
6359   SDValue ShAmt = Op.getOperand(2);
6360 
6361   assert(Op.getOpcode() == ISD::SHL_PARTS);
6362   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6363                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6364   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6365 
6366   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6367   // is "undef". We wanted 0, so CSEL it directly.
6368   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6369                                ISD::SETEQ, dl, DAG);
6370   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6371   LoBitsForHi =
6372       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6373                   LoBitsForHi, CCVal, Cmp);
6374 
6375   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6376                                    DAG.getConstant(VTBits, dl, MVT::i64));
6377   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6378   SDValue HiForNormalShift =
6379       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6380 
6381   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6382 
6383   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6384                        dl, DAG);
6385   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6386   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6387                            HiForNormalShift, CCVal, Cmp);
6388 
6389   // AArch64 shifts of larger than register sizes are wrapped rather than
6390   // clamped, so we can't just emit "lo << a" if a is too big.
6391   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6392   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6393   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6394                            LoForNormalShift, CCVal, Cmp);
6395 
6396   SDValue Ops[2] = { Lo, Hi };
6397   return DAG.getMergeValues(Ops, dl);
6398 }
6399 
6400 bool AArch64TargetLowering::isOffsetFoldingLegal(
6401     const GlobalAddressSDNode *GA) const {
6402   // Offsets are folded in the DAG combine rather than here so that we can
6403   // intelligently choose an offset based on the uses.
6404   return false;
6405 }
6406 
6407 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6408                                          bool OptForSize) const {
6409   bool IsLegal = false;
6410   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6411   // 16-bit case when target has full fp16 support.
6412   // FIXME: We should be able to handle f128 as well with a clever lowering.
6413   const APInt ImmInt = Imm.bitcastToAPInt();
6414   if (VT == MVT::f64)
6415     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6416   else if (VT == MVT::f32)
6417     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6418   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6419     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6420   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6421   //       generate that fmov.
6422 
6423   // If we can not materialize in immediate field for fmov, check if the
6424   // value can be encoded as the immediate operand of a logical instruction.
6425   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6426   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6427     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6428     // however the mov+fmov sequence is always better because of the reduced
6429     // cache pressure. The timings are still the same if you consider
6430     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6431     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6432     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6433     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6434 			      Insn);
6435     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6436     IsLegal = Insn.size() <= Limit;
6437   }
6438 
6439   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6440                     << " imm value: "; Imm.dump(););
6441   return IsLegal;
6442 }
6443 
6444 //===----------------------------------------------------------------------===//
6445 //                          AArch64 Optimization Hooks
6446 //===----------------------------------------------------------------------===//
6447 
6448 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6449                            SDValue Operand, SelectionDAG &DAG,
6450                            int &ExtraSteps) {
6451   EVT VT = Operand.getValueType();
6452   if (ST->hasNEON() &&
6453       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6454        VT == MVT::f32 || VT == MVT::v1f32 ||
6455        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6456     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6457       // For the reciprocal estimates, convergence is quadratic, so the number
6458       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6459       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6460       // the result for float (23 mantissa bits) is 2 and for double (52
6461       // mantissa bits) is 3.
6462       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6463 
6464     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6465   }
6466 
6467   return SDValue();
6468 }
6469 
6470 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6471                                                SelectionDAG &DAG, int Enabled,
6472                                                int &ExtraSteps,
6473                                                bool &UseOneConst,
6474                                                bool Reciprocal) const {
6475   if (Enabled == ReciprocalEstimate::Enabled ||
6476       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6477     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6478                                        DAG, ExtraSteps)) {
6479       SDLoc DL(Operand);
6480       EVT VT = Operand.getValueType();
6481 
6482       SDNodeFlags Flags;
6483       Flags.setAllowReassociation(true);
6484 
6485       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6486       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6487       for (int i = ExtraSteps; i > 0; --i) {
6488         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6489                                    Flags);
6490         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6491         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6492       }
6493       if (!Reciprocal) {
6494         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6495                                       VT);
6496         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6497         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6498 
6499         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6500         // Correct the result if the operand is 0.0.
6501         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6502                                VT, Eq, Operand, Estimate);
6503       }
6504 
6505       ExtraSteps = 0;
6506       return Estimate;
6507     }
6508 
6509   return SDValue();
6510 }
6511 
6512 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6513                                                 SelectionDAG &DAG, int Enabled,
6514                                                 int &ExtraSteps) const {
6515   if (Enabled == ReciprocalEstimate::Enabled)
6516     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6517                                        DAG, ExtraSteps)) {
6518       SDLoc DL(Operand);
6519       EVT VT = Operand.getValueType();
6520 
6521       SDNodeFlags Flags;
6522       Flags.setAllowReassociation(true);
6523 
6524       // Newton reciprocal iteration: E * (2 - X * E)
6525       // AArch64 reciprocal iteration instruction: (2 - M * N)
6526       for (int i = ExtraSteps; i > 0; --i) {
6527         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6528                                    Estimate, Flags);
6529         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6530       }
6531 
6532       ExtraSteps = 0;
6533       return Estimate;
6534     }
6535 
6536   return SDValue();
6537 }
6538 
6539 //===----------------------------------------------------------------------===//
6540 //                          AArch64 Inline Assembly Support
6541 //===----------------------------------------------------------------------===//
6542 
6543 // Table of Constraints
6544 // TODO: This is the current set of constraints supported by ARM for the
6545 // compiler, not all of them may make sense.
6546 //
6547 // r - A general register
6548 // w - An FP/SIMD register of some size in the range v0-v31
6549 // x - An FP/SIMD register of some size in the range v0-v15
6550 // I - Constant that can be used with an ADD instruction
6551 // J - Constant that can be used with a SUB instruction
6552 // K - Constant that can be used with a 32-bit logical instruction
6553 // L - Constant that can be used with a 64-bit logical instruction
6554 // M - Constant that can be used as a 32-bit MOV immediate
6555 // N - Constant that can be used as a 64-bit MOV immediate
6556 // Q - A memory reference with base register and no offset
6557 // S - A symbolic address
6558 // Y - Floating point constant zero
6559 // Z - Integer constant zero
6560 //
6561 //   Note that general register operands will be output using their 64-bit x
6562 // register name, whatever the size of the variable, unless the asm operand
6563 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6564 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6565 // %q modifier.
6566 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6567   // At this point, we have to lower this constraint to something else, so we
6568   // lower it to an "r" or "w". However, by doing this we will force the result
6569   // to be in register, while the X constraint is much more permissive.
6570   //
6571   // Although we are correct (we are free to emit anything, without
6572   // constraints), we might break use cases that would expect us to be more
6573   // efficient and emit something else.
6574   if (!Subtarget->hasFPARMv8())
6575     return "r";
6576 
6577   if (ConstraintVT.isFloatingPoint())
6578     return "w";
6579 
6580   if (ConstraintVT.isVector() &&
6581      (ConstraintVT.getSizeInBits() == 64 ||
6582       ConstraintVT.getSizeInBits() == 128))
6583     return "w";
6584 
6585   return "r";
6586 }
6587 
6588 enum PredicateConstraint {
6589   Upl,
6590   Upa,
6591   Invalid
6592 };
6593 
6594 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6595   PredicateConstraint P = PredicateConstraint::Invalid;
6596   if (Constraint == "Upa")
6597     P = PredicateConstraint::Upa;
6598   if (Constraint == "Upl")
6599     P = PredicateConstraint::Upl;
6600   return P;
6601 }
6602 
6603 /// getConstraintType - Given a constraint letter, return the type of
6604 /// constraint it is for this target.
6605 AArch64TargetLowering::ConstraintType
6606 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6607   if (Constraint.size() == 1) {
6608     switch (Constraint[0]) {
6609     default:
6610       break;
6611     case 'x':
6612     case 'w':
6613     case 'y':
6614       return C_RegisterClass;
6615     // An address with a single base register. Due to the way we
6616     // currently handle addresses it is the same as 'r'.
6617     case 'Q':
6618       return C_Memory;
6619     case 'I':
6620     case 'J':
6621     case 'K':
6622     case 'L':
6623     case 'M':
6624     case 'N':
6625     case 'Y':
6626     case 'Z':
6627       return C_Immediate;
6628     case 'z':
6629     case 'S': // A symbolic address
6630       return C_Other;
6631     }
6632   } else if (parsePredicateConstraint(Constraint) !=
6633              PredicateConstraint::Invalid)
6634       return C_RegisterClass;
6635   return TargetLowering::getConstraintType(Constraint);
6636 }
6637 
6638 /// Examine constraint type and operand type and determine a weight value.
6639 /// This object must already have been set up with the operand type
6640 /// and the current alternative constraint selected.
6641 TargetLowering::ConstraintWeight
6642 AArch64TargetLowering::getSingleConstraintMatchWeight(
6643     AsmOperandInfo &info, const char *constraint) const {
6644   ConstraintWeight weight = CW_Invalid;
6645   Value *CallOperandVal = info.CallOperandVal;
6646   // If we don't have a value, we can't do a match,
6647   // but allow it at the lowest weight.
6648   if (!CallOperandVal)
6649     return CW_Default;
6650   Type *type = CallOperandVal->getType();
6651   // Look at the constraint type.
6652   switch (*constraint) {
6653   default:
6654     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6655     break;
6656   case 'x':
6657   case 'w':
6658   case 'y':
6659     if (type->isFloatingPointTy() || type->isVectorTy())
6660       weight = CW_Register;
6661     break;
6662   case 'z':
6663     weight = CW_Constant;
6664     break;
6665   case 'U':
6666     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6667       weight = CW_Register;
6668     break;
6669   }
6670   return weight;
6671 }
6672 
6673 std::pair<unsigned, const TargetRegisterClass *>
6674 AArch64TargetLowering::getRegForInlineAsmConstraint(
6675     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6676   if (Constraint.size() == 1) {
6677     switch (Constraint[0]) {
6678     case 'r':
6679       if (VT.getSizeInBits() == 64)
6680         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6681       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6682     case 'w':
6683       if (!Subtarget->hasFPARMv8())
6684         break;
6685       if (VT.isScalableVector())
6686         return std::make_pair(0U, &AArch64::ZPRRegClass);
6687       if (VT.getSizeInBits() == 16)
6688         return std::make_pair(0U, &AArch64::FPR16RegClass);
6689       if (VT.getSizeInBits() == 32)
6690         return std::make_pair(0U, &AArch64::FPR32RegClass);
6691       if (VT.getSizeInBits() == 64)
6692         return std::make_pair(0U, &AArch64::FPR64RegClass);
6693       if (VT.getSizeInBits() == 128)
6694         return std::make_pair(0U, &AArch64::FPR128RegClass);
6695       break;
6696     // The instructions that this constraint is designed for can
6697     // only take 128-bit registers so just use that regclass.
6698     case 'x':
6699       if (!Subtarget->hasFPARMv8())
6700         break;
6701       if (VT.isScalableVector())
6702         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6703       if (VT.getSizeInBits() == 128)
6704         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6705       break;
6706     case 'y':
6707       if (!Subtarget->hasFPARMv8())
6708         break;
6709       if (VT.isScalableVector())
6710         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6711       break;
6712     }
6713   } else {
6714     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6715     if (PC != PredicateConstraint::Invalid) {
6716       assert(VT.isScalableVector());
6717       bool restricted = (PC == PredicateConstraint::Upl);
6718       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6719                           : std::make_pair(0U, &AArch64::PPRRegClass);
6720     }
6721   }
6722   if (StringRef("{cc}").equals_lower(Constraint))
6723     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6724 
6725   // Use the default implementation in TargetLowering to convert the register
6726   // constraint into a member of a register class.
6727   std::pair<unsigned, const TargetRegisterClass *> Res;
6728   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6729 
6730   // Not found as a standard register?
6731   if (!Res.second) {
6732     unsigned Size = Constraint.size();
6733     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6734         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6735       int RegNo;
6736       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6737       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6738         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6739         // By default we'll emit v0-v31 for this unless there's a modifier where
6740         // we'll emit the correct register as well.
6741         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6742           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6743           Res.second = &AArch64::FPR64RegClass;
6744         } else {
6745           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6746           Res.second = &AArch64::FPR128RegClass;
6747         }
6748       }
6749     }
6750   }
6751 
6752   if (Res.second && !Subtarget->hasFPARMv8() &&
6753       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6754       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6755     return std::make_pair(0U, nullptr);
6756 
6757   return Res;
6758 }
6759 
6760 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6761 /// vector.  If it is invalid, don't add anything to Ops.
6762 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6763     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6764     SelectionDAG &DAG) const {
6765   SDValue Result;
6766 
6767   // Currently only support length 1 constraints.
6768   if (Constraint.length() != 1)
6769     return;
6770 
6771   char ConstraintLetter = Constraint[0];
6772   switch (ConstraintLetter) {
6773   default:
6774     break;
6775 
6776   // This set of constraints deal with valid constants for various instructions.
6777   // Validate and return a target constant for them if we can.
6778   case 'z': {
6779     // 'z' maps to xzr or wzr so it needs an input of 0.
6780     if (!isNullConstant(Op))
6781       return;
6782 
6783     if (Op.getValueType() == MVT::i64)
6784       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6785     else
6786       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6787     break;
6788   }
6789   case 'S': {
6790     // An absolute symbolic address or label reference.
6791     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6792       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6793                                           GA->getValueType(0));
6794     } else if (const BlockAddressSDNode *BA =
6795                    dyn_cast<BlockAddressSDNode>(Op)) {
6796       Result =
6797           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6798     } else if (const ExternalSymbolSDNode *ES =
6799                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6800       Result =
6801           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6802     } else
6803       return;
6804     break;
6805   }
6806 
6807   case 'I':
6808   case 'J':
6809   case 'K':
6810   case 'L':
6811   case 'M':
6812   case 'N':
6813     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6814     if (!C)
6815       return;
6816 
6817     // Grab the value and do some validation.
6818     uint64_t CVal = C->getZExtValue();
6819     switch (ConstraintLetter) {
6820     // The I constraint applies only to simple ADD or SUB immediate operands:
6821     // i.e. 0 to 4095 with optional shift by 12
6822     // The J constraint applies only to ADD or SUB immediates that would be
6823     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6824     // instruction [or vice versa], in other words -1 to -4095 with optional
6825     // left shift by 12.
6826     case 'I':
6827       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6828         break;
6829       return;
6830     case 'J': {
6831       uint64_t NVal = -C->getSExtValue();
6832       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6833         CVal = C->getSExtValue();
6834         break;
6835       }
6836       return;
6837     }
6838     // The K and L constraints apply *only* to logical immediates, including
6839     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6840     // been removed and MOV should be used). So these constraints have to
6841     // distinguish between bit patterns that are valid 32-bit or 64-bit
6842     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6843     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6844     // versa.
6845     case 'K':
6846       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6847         break;
6848       return;
6849     case 'L':
6850       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6851         break;
6852       return;
6853     // The M and N constraints are a superset of K and L respectively, for use
6854     // with the MOV (immediate) alias. As well as the logical immediates they
6855     // also match 32 or 64-bit immediates that can be loaded either using a
6856     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6857     // (M) or 64-bit 0x1234000000000000 (N) etc.
6858     // As a note some of this code is liberally stolen from the asm parser.
6859     case 'M': {
6860       if (!isUInt<32>(CVal))
6861         return;
6862       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6863         break;
6864       if ((CVal & 0xFFFF) == CVal)
6865         break;
6866       if ((CVal & 0xFFFF0000ULL) == CVal)
6867         break;
6868       uint64_t NCVal = ~(uint32_t)CVal;
6869       if ((NCVal & 0xFFFFULL) == NCVal)
6870         break;
6871       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6872         break;
6873       return;
6874     }
6875     case 'N': {
6876       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6877         break;
6878       if ((CVal & 0xFFFFULL) == CVal)
6879         break;
6880       if ((CVal & 0xFFFF0000ULL) == CVal)
6881         break;
6882       if ((CVal & 0xFFFF00000000ULL) == CVal)
6883         break;
6884       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6885         break;
6886       uint64_t NCVal = ~CVal;
6887       if ((NCVal & 0xFFFFULL) == NCVal)
6888         break;
6889       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6890         break;
6891       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6892         break;
6893       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6894         break;
6895       return;
6896     }
6897     default:
6898       return;
6899     }
6900 
6901     // All assembler immediates are 64-bit integers.
6902     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6903     break;
6904   }
6905 
6906   if (Result.getNode()) {
6907     Ops.push_back(Result);
6908     return;
6909   }
6910 
6911   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6912 }
6913 
6914 //===----------------------------------------------------------------------===//
6915 //                     AArch64 Advanced SIMD Support
6916 //===----------------------------------------------------------------------===//
6917 
6918 /// WidenVector - Given a value in the V64 register class, produce the
6919 /// equivalent value in the V128 register class.
6920 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6921   EVT VT = V64Reg.getValueType();
6922   unsigned NarrowSize = VT.getVectorNumElements();
6923   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6924   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6925   SDLoc DL(V64Reg);
6926 
6927   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6928                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6929 }
6930 
6931 /// getExtFactor - Determine the adjustment factor for the position when
6932 /// generating an "extract from vector registers" instruction.
6933 static unsigned getExtFactor(SDValue &V) {
6934   EVT EltType = V.getValueType().getVectorElementType();
6935   return EltType.getSizeInBits() / 8;
6936 }
6937 
6938 /// NarrowVector - Given a value in the V128 register class, produce the
6939 /// equivalent value in the V64 register class.
6940 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6941   EVT VT = V128Reg.getValueType();
6942   unsigned WideSize = VT.getVectorNumElements();
6943   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6944   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6945   SDLoc DL(V128Reg);
6946 
6947   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6948 }
6949 
6950 // Gather data to see if the operation can be modelled as a
6951 // shuffle in combination with VEXTs.
6952 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6953                                                   SelectionDAG &DAG) const {
6954   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6955   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6956   SDLoc dl(Op);
6957   EVT VT = Op.getValueType();
6958   unsigned NumElts = VT.getVectorNumElements();
6959 
6960   struct ShuffleSourceInfo {
6961     SDValue Vec;
6962     unsigned MinElt;
6963     unsigned MaxElt;
6964 
6965     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6966     // be compatible with the shuffle we intend to construct. As a result
6967     // ShuffleVec will be some sliding window into the original Vec.
6968     SDValue ShuffleVec;
6969 
6970     // Code should guarantee that element i in Vec starts at element "WindowBase
6971     // + i * WindowScale in ShuffleVec".
6972     int WindowBase;
6973     int WindowScale;
6974 
6975     ShuffleSourceInfo(SDValue Vec)
6976       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6977           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6978 
6979     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6980   };
6981 
6982   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6983   // node.
6984   SmallVector<ShuffleSourceInfo, 2> Sources;
6985   for (unsigned i = 0; i < NumElts; ++i) {
6986     SDValue V = Op.getOperand(i);
6987     if (V.isUndef())
6988       continue;
6989     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6990              !isa<ConstantSDNode>(V.getOperand(1))) {
6991       LLVM_DEBUG(
6992           dbgs() << "Reshuffle failed: "
6993                     "a shuffle can only come from building a vector from "
6994                     "various elements of other vectors, provided their "
6995                     "indices are constant\n");
6996       return SDValue();
6997     }
6998 
6999     // Add this element source to the list if it's not already there.
7000     SDValue SourceVec = V.getOperand(0);
7001     auto Source = find(Sources, SourceVec);
7002     if (Source == Sources.end())
7003       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7004 
7005     // Update the minimum and maximum lane number seen.
7006     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7007     Source->MinElt = std::min(Source->MinElt, EltNo);
7008     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7009   }
7010 
7011   if (Sources.size() > 2) {
7012     LLVM_DEBUG(
7013         dbgs() << "Reshuffle failed: currently only do something sane when at "
7014                   "most two source vectors are involved\n");
7015     return SDValue();
7016   }
7017 
7018   // Find out the smallest element size among result and two sources, and use
7019   // it as element size to build the shuffle_vector.
7020   EVT SmallestEltTy = VT.getVectorElementType();
7021   for (auto &Source : Sources) {
7022     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7023     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7024       SmallestEltTy = SrcEltTy;
7025     }
7026   }
7027   unsigned ResMultiplier =
7028       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7029   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7030   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7031 
7032   // If the source vector is too wide or too narrow, we may nevertheless be able
7033   // to construct a compatible shuffle either by concatenating it with UNDEF or
7034   // extracting a suitable range of elements.
7035   for (auto &Src : Sources) {
7036     EVT SrcVT = Src.ShuffleVec.getValueType();
7037 
7038     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7039       continue;
7040 
7041     // This stage of the search produces a source with the same element type as
7042     // the original, but with a total width matching the BUILD_VECTOR output.
7043     EVT EltVT = SrcVT.getVectorElementType();
7044     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7045     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7046 
7047     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7048       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
7049       // We can pad out the smaller vector for free, so if it's part of a
7050       // shuffle...
7051       Src.ShuffleVec =
7052           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7053                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7054       continue;
7055     }
7056 
7057     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
7058 
7059     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7060       LLVM_DEBUG(
7061           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7062       return SDValue();
7063     }
7064 
7065     if (Src.MinElt >= NumSrcElts) {
7066       // The extraction can just take the second half
7067       Src.ShuffleVec =
7068           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7069                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7070       Src.WindowBase = -NumSrcElts;
7071     } else if (Src.MaxElt < NumSrcElts) {
7072       // The extraction can just take the first half
7073       Src.ShuffleVec =
7074           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7075                       DAG.getConstant(0, dl, MVT::i64));
7076     } else {
7077       // An actual VEXT is needed
7078       SDValue VEXTSrc1 =
7079           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7080                       DAG.getConstant(0, dl, MVT::i64));
7081       SDValue VEXTSrc2 =
7082           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7083                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7084       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7085 
7086       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7087                                    VEXTSrc2,
7088                                    DAG.getConstant(Imm, dl, MVT::i32));
7089       Src.WindowBase = -Src.MinElt;
7090     }
7091   }
7092 
7093   // Another possible incompatibility occurs from the vector element types. We
7094   // can fix this by bitcasting the source vectors to the same type we intend
7095   // for the shuffle.
7096   for (auto &Src : Sources) {
7097     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7098     if (SrcEltTy == SmallestEltTy)
7099       continue;
7100     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7101     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7102     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7103     Src.WindowBase *= Src.WindowScale;
7104   }
7105 
7106   // Final sanity check before we try to actually produce a shuffle.
7107   LLVM_DEBUG(for (auto Src
7108                   : Sources)
7109                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7110 
7111   // The stars all align, our next step is to produce the mask for the shuffle.
7112   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7113   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7114   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7115     SDValue Entry = Op.getOperand(i);
7116     if (Entry.isUndef())
7117       continue;
7118 
7119     auto Src = find(Sources, Entry.getOperand(0));
7120     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7121 
7122     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7123     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7124     // segment.
7125     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7126     int BitsDefined =
7127         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
7128     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7129 
7130     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7131     // starting at the appropriate offset.
7132     int *LaneMask = &Mask[i * ResMultiplier];
7133 
7134     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7135     ExtractBase += NumElts * (Src - Sources.begin());
7136     for (int j = 0; j < LanesDefined; ++j)
7137       LaneMask[j] = ExtractBase + j;
7138   }
7139 
7140   // Final check before we try to produce nonsense...
7141   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7142     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7143     return SDValue();
7144   }
7145 
7146   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7147   for (unsigned i = 0; i < Sources.size(); ++i)
7148     ShuffleOps[i] = Sources[i].ShuffleVec;
7149 
7150   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7151                                          ShuffleOps[1], Mask);
7152   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7153 
7154   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7155              dbgs() << "Reshuffle, creating node: "; V.dump(););
7156 
7157   return V;
7158 }
7159 
7160 // check if an EXT instruction can handle the shuffle mask when the
7161 // vector sources of the shuffle are the same.
7162 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7163   unsigned NumElts = VT.getVectorNumElements();
7164 
7165   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7166   if (M[0] < 0)
7167     return false;
7168 
7169   Imm = M[0];
7170 
7171   // If this is a VEXT shuffle, the immediate value is the index of the first
7172   // element.  The other shuffle indices must be the successive elements after
7173   // the first one.
7174   unsigned ExpectedElt = Imm;
7175   for (unsigned i = 1; i < NumElts; ++i) {
7176     // Increment the expected index.  If it wraps around, just follow it
7177     // back to index zero and keep going.
7178     ++ExpectedElt;
7179     if (ExpectedElt == NumElts)
7180       ExpectedElt = 0;
7181 
7182     if (M[i] < 0)
7183       continue; // ignore UNDEF indices
7184     if (ExpectedElt != static_cast<unsigned>(M[i]))
7185       return false;
7186   }
7187 
7188   return true;
7189 }
7190 
7191 // check if an EXT instruction can handle the shuffle mask when the
7192 // vector sources of the shuffle are different.
7193 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7194                       unsigned &Imm) {
7195   // Look for the first non-undef element.
7196   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7197 
7198   // Benefit form APInt to handle overflow when calculating expected element.
7199   unsigned NumElts = VT.getVectorNumElements();
7200   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7201   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7202   // The following shuffle indices must be the successive elements after the
7203   // first real element.
7204   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7205       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7206   if (FirstWrongElt != M.end())
7207     return false;
7208 
7209   // The index of an EXT is the first element if it is not UNDEF.
7210   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7211   // value of the first element.  E.g.
7212   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7213   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7214   // ExpectedElt is the last mask index plus 1.
7215   Imm = ExpectedElt.getZExtValue();
7216 
7217   // There are two difference cases requiring to reverse input vectors.
7218   // For example, for vector <4 x i32> we have the following cases,
7219   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7220   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7221   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7222   // to reverse two input vectors.
7223   if (Imm < NumElts)
7224     ReverseEXT = true;
7225   else
7226     Imm -= NumElts;
7227 
7228   return true;
7229 }
7230 
7231 /// isREVMask - Check if a vector shuffle corresponds to a REV
7232 /// instruction with the specified blocksize.  (The order of the elements
7233 /// within each block of the vector is reversed.)
7234 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7235   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7236          "Only possible block sizes for REV are: 16, 32, 64");
7237 
7238   unsigned EltSz = VT.getScalarSizeInBits();
7239   if (EltSz == 64)
7240     return false;
7241 
7242   unsigned NumElts = VT.getVectorNumElements();
7243   unsigned BlockElts = M[0] + 1;
7244   // If the first shuffle index is UNDEF, be optimistic.
7245   if (M[0] < 0)
7246     BlockElts = BlockSize / EltSz;
7247 
7248   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7249     return false;
7250 
7251   for (unsigned i = 0; i < NumElts; ++i) {
7252     if (M[i] < 0)
7253       continue; // ignore UNDEF indices
7254     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7255       return false;
7256   }
7257 
7258   return true;
7259 }
7260 
7261 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7262   unsigned NumElts = VT.getVectorNumElements();
7263   if (NumElts % 2 != 0)
7264     return false;
7265   WhichResult = (M[0] == 0 ? 0 : 1);
7266   unsigned Idx = WhichResult * NumElts / 2;
7267   for (unsigned i = 0; i != NumElts; i += 2) {
7268     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7269         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7270       return false;
7271     Idx += 1;
7272   }
7273 
7274   return true;
7275 }
7276 
7277 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7278   unsigned NumElts = VT.getVectorNumElements();
7279   WhichResult = (M[0] == 0 ? 0 : 1);
7280   for (unsigned i = 0; i != NumElts; ++i) {
7281     if (M[i] < 0)
7282       continue; // ignore UNDEF indices
7283     if ((unsigned)M[i] != 2 * i + WhichResult)
7284       return false;
7285   }
7286 
7287   return true;
7288 }
7289 
7290 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7291   unsigned NumElts = VT.getVectorNumElements();
7292   if (NumElts % 2 != 0)
7293     return false;
7294   WhichResult = (M[0] == 0 ? 0 : 1);
7295   for (unsigned i = 0; i < NumElts; i += 2) {
7296     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7297         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7298       return false;
7299   }
7300   return true;
7301 }
7302 
7303 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7304 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7305 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7306 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7307   unsigned NumElts = VT.getVectorNumElements();
7308   if (NumElts % 2 != 0)
7309     return false;
7310   WhichResult = (M[0] == 0 ? 0 : 1);
7311   unsigned Idx = WhichResult * NumElts / 2;
7312   for (unsigned i = 0; i != NumElts; i += 2) {
7313     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7314         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7315       return false;
7316     Idx += 1;
7317   }
7318 
7319   return true;
7320 }
7321 
7322 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7323 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7324 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7325 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7326   unsigned Half = VT.getVectorNumElements() / 2;
7327   WhichResult = (M[0] == 0 ? 0 : 1);
7328   for (unsigned j = 0; j != 2; ++j) {
7329     unsigned Idx = WhichResult;
7330     for (unsigned i = 0; i != Half; ++i) {
7331       int MIdx = M[i + j * Half];
7332       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7333         return false;
7334       Idx += 2;
7335     }
7336   }
7337 
7338   return true;
7339 }
7340 
7341 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7342 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7343 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7344 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7345   unsigned NumElts = VT.getVectorNumElements();
7346   if (NumElts % 2 != 0)
7347     return false;
7348   WhichResult = (M[0] == 0 ? 0 : 1);
7349   for (unsigned i = 0; i < NumElts; i += 2) {
7350     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7351         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7352       return false;
7353   }
7354   return true;
7355 }
7356 
7357 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7358                       bool &DstIsLeft, int &Anomaly) {
7359   if (M.size() != static_cast<size_t>(NumInputElements))
7360     return false;
7361 
7362   int NumLHSMatch = 0, NumRHSMatch = 0;
7363   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7364 
7365   for (int i = 0; i < NumInputElements; ++i) {
7366     if (M[i] == -1) {
7367       ++NumLHSMatch;
7368       ++NumRHSMatch;
7369       continue;
7370     }
7371 
7372     if (M[i] == i)
7373       ++NumLHSMatch;
7374     else
7375       LastLHSMismatch = i;
7376 
7377     if (M[i] == i + NumInputElements)
7378       ++NumRHSMatch;
7379     else
7380       LastRHSMismatch = i;
7381   }
7382 
7383   if (NumLHSMatch == NumInputElements - 1) {
7384     DstIsLeft = true;
7385     Anomaly = LastLHSMismatch;
7386     return true;
7387   } else if (NumRHSMatch == NumInputElements - 1) {
7388     DstIsLeft = false;
7389     Anomaly = LastRHSMismatch;
7390     return true;
7391   }
7392 
7393   return false;
7394 }
7395 
7396 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7397   if (VT.getSizeInBits() != 128)
7398     return false;
7399 
7400   unsigned NumElts = VT.getVectorNumElements();
7401 
7402   for (int I = 0, E = NumElts / 2; I != E; I++) {
7403     if (Mask[I] != I)
7404       return false;
7405   }
7406 
7407   int Offset = NumElts / 2;
7408   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7409     if (Mask[I] != I + SplitLHS * Offset)
7410       return false;
7411   }
7412 
7413   return true;
7414 }
7415 
7416 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7417   SDLoc DL(Op);
7418   EVT VT = Op.getValueType();
7419   SDValue V0 = Op.getOperand(0);
7420   SDValue V1 = Op.getOperand(1);
7421   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7422 
7423   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7424       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7425     return SDValue();
7426 
7427   bool SplitV0 = V0.getValueSizeInBits() == 128;
7428 
7429   if (!isConcatMask(Mask, VT, SplitV0))
7430     return SDValue();
7431 
7432   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7433   if (SplitV0) {
7434     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7435                      DAG.getConstant(0, DL, MVT::i64));
7436   }
7437   if (V1.getValueSizeInBits() == 128) {
7438     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7439                      DAG.getConstant(0, DL, MVT::i64));
7440   }
7441   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7442 }
7443 
7444 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7445 /// the specified operations to build the shuffle.
7446 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7447                                       SDValue RHS, SelectionDAG &DAG,
7448                                       const SDLoc &dl) {
7449   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7450   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7451   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7452 
7453   enum {
7454     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7455     OP_VREV,
7456     OP_VDUP0,
7457     OP_VDUP1,
7458     OP_VDUP2,
7459     OP_VDUP3,
7460     OP_VEXT1,
7461     OP_VEXT2,
7462     OP_VEXT3,
7463     OP_VUZPL, // VUZP, left result
7464     OP_VUZPR, // VUZP, right result
7465     OP_VZIPL, // VZIP, left result
7466     OP_VZIPR, // VZIP, right result
7467     OP_VTRNL, // VTRN, left result
7468     OP_VTRNR  // VTRN, right result
7469   };
7470 
7471   if (OpNum == OP_COPY) {
7472     if (LHSID == (1 * 9 + 2) * 9 + 3)
7473       return LHS;
7474     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7475     return RHS;
7476   }
7477 
7478   SDValue OpLHS, OpRHS;
7479   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7480   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7481   EVT VT = OpLHS.getValueType();
7482 
7483   switch (OpNum) {
7484   default:
7485     llvm_unreachable("Unknown shuffle opcode!");
7486   case OP_VREV:
7487     // VREV divides the vector in half and swaps within the half.
7488     if (VT.getVectorElementType() == MVT::i32 ||
7489         VT.getVectorElementType() == MVT::f32)
7490       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7491     // vrev <4 x i16> -> REV32
7492     if (VT.getVectorElementType() == MVT::i16 ||
7493         VT.getVectorElementType() == MVT::f16 ||
7494         VT.getVectorElementType() == MVT::bf16)
7495       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7496     // vrev <4 x i8> -> REV16
7497     assert(VT.getVectorElementType() == MVT::i8);
7498     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7499   case OP_VDUP0:
7500   case OP_VDUP1:
7501   case OP_VDUP2:
7502   case OP_VDUP3: {
7503     EVT EltTy = VT.getVectorElementType();
7504     unsigned Opcode;
7505     if (EltTy == MVT::i8)
7506       Opcode = AArch64ISD::DUPLANE8;
7507     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
7508       Opcode = AArch64ISD::DUPLANE16;
7509     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7510       Opcode = AArch64ISD::DUPLANE32;
7511     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7512       Opcode = AArch64ISD::DUPLANE64;
7513     else
7514       llvm_unreachable("Invalid vector element type?");
7515 
7516     if (VT.getSizeInBits() == 64)
7517       OpLHS = WidenVector(OpLHS, DAG);
7518     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7519     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7520   }
7521   case OP_VEXT1:
7522   case OP_VEXT2:
7523   case OP_VEXT3: {
7524     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7525     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7526                        DAG.getConstant(Imm, dl, MVT::i32));
7527   }
7528   case OP_VUZPL:
7529     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7530                        OpRHS);
7531   case OP_VUZPR:
7532     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7533                        OpRHS);
7534   case OP_VZIPL:
7535     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7536                        OpRHS);
7537   case OP_VZIPR:
7538     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7539                        OpRHS);
7540   case OP_VTRNL:
7541     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7542                        OpRHS);
7543   case OP_VTRNR:
7544     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7545                        OpRHS);
7546   }
7547 }
7548 
7549 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7550                            SelectionDAG &DAG) {
7551   // Check to see if we can use the TBL instruction.
7552   SDValue V1 = Op.getOperand(0);
7553   SDValue V2 = Op.getOperand(1);
7554   SDLoc DL(Op);
7555 
7556   EVT EltVT = Op.getValueType().getVectorElementType();
7557   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7558 
7559   SmallVector<SDValue, 8> TBLMask;
7560   for (int Val : ShuffleMask) {
7561     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7562       unsigned Offset = Byte + Val * BytesPerElt;
7563       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7564     }
7565   }
7566 
7567   MVT IndexVT = MVT::v8i8;
7568   unsigned IndexLen = 8;
7569   if (Op.getValueSizeInBits() == 128) {
7570     IndexVT = MVT::v16i8;
7571     IndexLen = 16;
7572   }
7573 
7574   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7575   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7576 
7577   SDValue Shuffle;
7578   if (V2.getNode()->isUndef()) {
7579     if (IndexLen == 8)
7580       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7581     Shuffle = DAG.getNode(
7582         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7583         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7584         DAG.getBuildVector(IndexVT, DL,
7585                            makeArrayRef(TBLMask.data(), IndexLen)));
7586   } else {
7587     if (IndexLen == 8) {
7588       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7589       Shuffle = DAG.getNode(
7590           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7591           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7592           DAG.getBuildVector(IndexVT, DL,
7593                              makeArrayRef(TBLMask.data(), IndexLen)));
7594     } else {
7595       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7596       // cannot currently represent the register constraints on the input
7597       // table registers.
7598       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7599       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7600       //                   IndexLen));
7601       Shuffle = DAG.getNode(
7602           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7603           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7604           V2Cst, DAG.getBuildVector(IndexVT, DL,
7605                                     makeArrayRef(TBLMask.data(), IndexLen)));
7606     }
7607   }
7608   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7609 }
7610 
7611 static unsigned getDUPLANEOp(EVT EltType) {
7612   if (EltType == MVT::i8)
7613     return AArch64ISD::DUPLANE8;
7614   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
7615     return AArch64ISD::DUPLANE16;
7616   if (EltType == MVT::i32 || EltType == MVT::f32)
7617     return AArch64ISD::DUPLANE32;
7618   if (EltType == MVT::i64 || EltType == MVT::f64)
7619     return AArch64ISD::DUPLANE64;
7620 
7621   llvm_unreachable("Invalid vector element type?");
7622 }
7623 
7624 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7625                                                    SelectionDAG &DAG) const {
7626   SDLoc dl(Op);
7627   EVT VT = Op.getValueType();
7628 
7629   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7630 
7631   // Convert shuffles that are directly supported on NEON to target-specific
7632   // DAG nodes, instead of keeping them as shuffles and matching them again
7633   // during code selection.  This is more efficient and avoids the possibility
7634   // of inconsistencies between legalization and selection.
7635   ArrayRef<int> ShuffleMask = SVN->getMask();
7636 
7637   SDValue V1 = Op.getOperand(0);
7638   SDValue V2 = Op.getOperand(1);
7639 
7640   if (SVN->isSplat()) {
7641     int Lane = SVN->getSplatIndex();
7642     // If this is undef splat, generate it via "just" vdup, if possible.
7643     if (Lane == -1)
7644       Lane = 0;
7645 
7646     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7647       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7648                          V1.getOperand(0));
7649     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7650     // constant. If so, we can just reference the lane's definition directly.
7651     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7652         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7653       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7654 
7655     // Otherwise, duplicate from the lane of the input vector.
7656     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7657 
7658     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7659     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7660       // Match: dup (bitcast (extract_subv X, C)), LaneC
7661       if (BitCast.getOpcode() != ISD::BITCAST ||
7662           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7663         return false;
7664 
7665       // The extract index must align in the destination type. That may not
7666       // happen if the bitcast is from narrow to wide type.
7667       SDValue Extract = BitCast.getOperand(0);
7668       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7669       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7670       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7671       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7672       if (ExtIdxInBits % CastedEltBitWidth != 0)
7673         return false;
7674 
7675       // Update the lane value by offsetting with the scaled extract index.
7676       LaneC += ExtIdxInBits / CastedEltBitWidth;
7677 
7678       // Determine the casted vector type of the wide vector input.
7679       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7680       // Examples:
7681       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7682       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7683       unsigned SrcVecNumElts =
7684           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7685       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7686                                 SrcVecNumElts);
7687       return true;
7688     };
7689     MVT CastVT;
7690     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7691       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7692     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7693       // The lane is incremented by the index of the extract.
7694       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7695       Lane += V1.getConstantOperandVal(1);
7696       V1 = V1.getOperand(0);
7697     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7698       // The lane is decremented if we are splatting from the 2nd operand.
7699       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7700       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7701       Lane -= Idx * VT.getVectorNumElements() / 2;
7702       V1 = WidenVector(V1.getOperand(Idx), DAG);
7703     } else if (VT.getSizeInBits() == 64) {
7704       // Widen the operand to 128-bit register with undef.
7705       V1 = WidenVector(V1, DAG);
7706     }
7707     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7708   }
7709 
7710   if (isREVMask(ShuffleMask, VT, 64))
7711     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7712   if (isREVMask(ShuffleMask, VT, 32))
7713     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7714   if (isREVMask(ShuffleMask, VT, 16))
7715     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7716 
7717   bool ReverseEXT = false;
7718   unsigned Imm;
7719   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7720     if (ReverseEXT)
7721       std::swap(V1, V2);
7722     Imm *= getExtFactor(V1);
7723     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7724                        DAG.getConstant(Imm, dl, MVT::i32));
7725   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7726     Imm *= getExtFactor(V1);
7727     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7728                        DAG.getConstant(Imm, dl, MVT::i32));
7729   }
7730 
7731   unsigned WhichResult;
7732   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7733     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7734     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7735   }
7736   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7737     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7738     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7739   }
7740   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7741     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7742     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7743   }
7744 
7745   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7746     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7747     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7748   }
7749   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7750     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7751     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7752   }
7753   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7754     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7755     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7756   }
7757 
7758   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7759     return Concat;
7760 
7761   bool DstIsLeft;
7762   int Anomaly;
7763   int NumInputElements = V1.getValueType().getVectorNumElements();
7764   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7765     SDValue DstVec = DstIsLeft ? V1 : V2;
7766     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7767 
7768     SDValue SrcVec = V1;
7769     int SrcLane = ShuffleMask[Anomaly];
7770     if (SrcLane >= NumInputElements) {
7771       SrcVec = V2;
7772       SrcLane -= VT.getVectorNumElements();
7773     }
7774     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7775 
7776     EVT ScalarVT = VT.getVectorElementType();
7777 
7778     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7779       ScalarVT = MVT::i32;
7780 
7781     return DAG.getNode(
7782         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7783         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7784         DstLaneV);
7785   }
7786 
7787   // If the shuffle is not directly supported and it has 4 elements, use
7788   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7789   unsigned NumElts = VT.getVectorNumElements();
7790   if (NumElts == 4) {
7791     unsigned PFIndexes[4];
7792     for (unsigned i = 0; i != 4; ++i) {
7793       if (ShuffleMask[i] < 0)
7794         PFIndexes[i] = 8;
7795       else
7796         PFIndexes[i] = ShuffleMask[i];
7797     }
7798 
7799     // Compute the index in the perfect shuffle table.
7800     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7801                             PFIndexes[2] * 9 + PFIndexes[3];
7802     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7803     unsigned Cost = (PFEntry >> 30);
7804 
7805     if (Cost <= 4)
7806       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7807   }
7808 
7809   return GenerateTBL(Op, ShuffleMask, DAG);
7810 }
7811 
7812 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7813                                                  SelectionDAG &DAG) const {
7814   SDLoc dl(Op);
7815   EVT VT = Op.getValueType();
7816   EVT ElemVT = VT.getScalarType();
7817 
7818   SDValue SplatVal = Op.getOperand(0);
7819 
7820   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7821   // FPRs don't have this restriction.
7822   switch (ElemVT.getSimpleVT().SimpleTy) {
7823   case MVT::i1: {
7824     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
7825     // lowering code.
7826     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
7827       if (ConstVal->isOne())
7828         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
7829       // TODO: Add special case for constant false
7830     }
7831     // The general case of i1.  There isn't any natural way to do this,
7832     // so we use some trickery with whilelo.
7833     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7834     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7835                            DAG.getValueType(MVT::i1));
7836     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7837                                        MVT::i64);
7838     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7839                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7840   }
7841   case MVT::i8:
7842   case MVT::i16:
7843   case MVT::i32:
7844     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7845     break;
7846   case MVT::i64:
7847     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7848     break;
7849   case MVT::f16:
7850   case MVT::bf16:
7851   case MVT::f32:
7852   case MVT::f64:
7853     // Fine as is
7854     break;
7855   default:
7856     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7857   }
7858 
7859   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7860 }
7861 
7862 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
7863                                              SelectionDAG &DAG) const {
7864   SDLoc DL(Op);
7865 
7866   EVT VT = Op.getValueType();
7867   if (!isTypeLegal(VT) || !VT.isScalableVector())
7868     return SDValue();
7869 
7870   // Current lowering only supports the SVE-ACLE types.
7871   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
7872     return SDValue();
7873 
7874   // The DUPQ operation is indepedent of element type so normalise to i64s.
7875   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
7876   SDValue Idx128 = Op.getOperand(2);
7877 
7878   // DUPQ can be used when idx is in range.
7879   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
7880   if (CIdx && (CIdx->getZExtValue() <= 3)) {
7881     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
7882     SDNode *DUPQ =
7883         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
7884     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
7885   }
7886 
7887   // The ACLE says this must produce the same result as:
7888   //   svtbl(data, svadd_x(svptrue_b64(),
7889   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
7890   //                       index * 2))
7891   SDValue One = DAG.getConstant(1, DL, MVT::i64);
7892   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
7893 
7894   // create the vector 0,1,0,1,...
7895   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
7896   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
7897                            DL, MVT::nxv2i64, Zero, One);
7898   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
7899 
7900   // create the vector idx64,idx64+1,idx64,idx64+1,...
7901   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
7902   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
7903   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
7904 
7905   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
7906   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
7907   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
7908 }
7909 
7910 
7911 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7912                                APInt &UndefBits) {
7913   EVT VT = BVN->getValueType(0);
7914   APInt SplatBits, SplatUndef;
7915   unsigned SplatBitSize;
7916   bool HasAnyUndefs;
7917   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7918     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7919 
7920     for (unsigned i = 0; i < NumSplats; ++i) {
7921       CnstBits <<= SplatBitSize;
7922       UndefBits <<= SplatBitSize;
7923       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7924       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7925     }
7926 
7927     return true;
7928   }
7929 
7930   return false;
7931 }
7932 
7933 // Try 64-bit splatted SIMD immediate.
7934 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7935                                  const APInt &Bits) {
7936   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7937     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7938     EVT VT = Op.getValueType();
7939     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7940 
7941     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7942       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7943 
7944       SDLoc dl(Op);
7945       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7946                                 DAG.getConstant(Value, dl, MVT::i32));
7947       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7948     }
7949   }
7950 
7951   return SDValue();
7952 }
7953 
7954 // Try 32-bit splatted SIMD immediate.
7955 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7956                                   const APInt &Bits,
7957                                   const SDValue *LHS = nullptr) {
7958   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7959     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7960     EVT VT = Op.getValueType();
7961     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7962     bool isAdvSIMDModImm = false;
7963     uint64_t Shift;
7964 
7965     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7966       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7967       Shift = 0;
7968     }
7969     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7970       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7971       Shift = 8;
7972     }
7973     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7974       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7975       Shift = 16;
7976     }
7977     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7978       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7979       Shift = 24;
7980     }
7981 
7982     if (isAdvSIMDModImm) {
7983       SDLoc dl(Op);
7984       SDValue Mov;
7985 
7986       if (LHS)
7987         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7988                           DAG.getConstant(Value, dl, MVT::i32),
7989                           DAG.getConstant(Shift, dl, MVT::i32));
7990       else
7991         Mov = DAG.getNode(NewOp, dl, MovTy,
7992                           DAG.getConstant(Value, dl, MVT::i32),
7993                           DAG.getConstant(Shift, dl, MVT::i32));
7994 
7995       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7996     }
7997   }
7998 
7999   return SDValue();
8000 }
8001 
8002 // Try 16-bit splatted SIMD immediate.
8003 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8004                                   const APInt &Bits,
8005                                   const SDValue *LHS = nullptr) {
8006   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8007     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8008     EVT VT = Op.getValueType();
8009     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8010     bool isAdvSIMDModImm = false;
8011     uint64_t Shift;
8012 
8013     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8014       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8015       Shift = 0;
8016     }
8017     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8018       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8019       Shift = 8;
8020     }
8021 
8022     if (isAdvSIMDModImm) {
8023       SDLoc dl(Op);
8024       SDValue Mov;
8025 
8026       if (LHS)
8027         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8028                           DAG.getConstant(Value, dl, MVT::i32),
8029                           DAG.getConstant(Shift, dl, MVT::i32));
8030       else
8031         Mov = DAG.getNode(NewOp, dl, MovTy,
8032                           DAG.getConstant(Value, dl, MVT::i32),
8033                           DAG.getConstant(Shift, dl, MVT::i32));
8034 
8035       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8036     }
8037   }
8038 
8039   return SDValue();
8040 }
8041 
8042 // Try 32-bit splatted SIMD immediate with shifted ones.
8043 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8044                                     SelectionDAG &DAG, const APInt &Bits) {
8045   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8046     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8047     EVT VT = Op.getValueType();
8048     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8049     bool isAdvSIMDModImm = false;
8050     uint64_t Shift;
8051 
8052     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8053       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8054       Shift = 264;
8055     }
8056     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8057       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8058       Shift = 272;
8059     }
8060 
8061     if (isAdvSIMDModImm) {
8062       SDLoc dl(Op);
8063       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8064                                 DAG.getConstant(Value, dl, MVT::i32),
8065                                 DAG.getConstant(Shift, dl, MVT::i32));
8066       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8067     }
8068   }
8069 
8070   return SDValue();
8071 }
8072 
8073 // Try 8-bit splatted SIMD immediate.
8074 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8075                                  const APInt &Bits) {
8076   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8077     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8078     EVT VT = Op.getValueType();
8079     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8080 
8081     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8082       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8083 
8084       SDLoc dl(Op);
8085       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8086                                 DAG.getConstant(Value, dl, MVT::i32));
8087       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8088     }
8089   }
8090 
8091   return SDValue();
8092 }
8093 
8094 // Try FP splatted SIMD immediate.
8095 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8096                                   const APInt &Bits) {
8097   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8098     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8099     EVT VT = Op.getValueType();
8100     bool isWide = (VT.getSizeInBits() == 128);
8101     MVT MovTy;
8102     bool isAdvSIMDModImm = false;
8103 
8104     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8105       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8106       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8107     }
8108     else if (isWide &&
8109              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8110       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8111       MovTy = MVT::v2f64;
8112     }
8113 
8114     if (isAdvSIMDModImm) {
8115       SDLoc dl(Op);
8116       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8117                                 DAG.getConstant(Value, dl, MVT::i32));
8118       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8119     }
8120   }
8121 
8122   return SDValue();
8123 }
8124 
8125 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8126 // consists of only the same constant int value, returned in reference arg
8127 // ConstVal
8128 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8129                                      uint64_t &ConstVal) {
8130   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8131   if (!Bvec)
8132     return false;
8133   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8134   if (!FirstElt)
8135     return false;
8136   EVT VT = Bvec->getValueType(0);
8137   unsigned NumElts = VT.getVectorNumElements();
8138   for (unsigned i = 1; i < NumElts; ++i)
8139     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8140       return false;
8141   ConstVal = FirstElt->getZExtValue();
8142   return true;
8143 }
8144 
8145 static unsigned getIntrinsicID(const SDNode *N) {
8146   unsigned Opcode = N->getOpcode();
8147   switch (Opcode) {
8148   default:
8149     return Intrinsic::not_intrinsic;
8150   case ISD::INTRINSIC_WO_CHAIN: {
8151     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8152     if (IID < Intrinsic::num_intrinsics)
8153       return IID;
8154     return Intrinsic::not_intrinsic;
8155   }
8156   }
8157 }
8158 
8159 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8160 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8161 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8162 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8163 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8164 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8165 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8166   EVT VT = N->getValueType(0);
8167 
8168   if (!VT.isVector())
8169     return SDValue();
8170 
8171   SDLoc DL(N);
8172 
8173   SDValue And;
8174   SDValue Shift;
8175 
8176   SDValue FirstOp = N->getOperand(0);
8177   unsigned FirstOpc = FirstOp.getOpcode();
8178   SDValue SecondOp = N->getOperand(1);
8179   unsigned SecondOpc = SecondOp.getOpcode();
8180 
8181   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8182   // a BICi in order to use an immediate instead of a register.
8183   // Is the other operand an shl or lshr? This will have been turned into:
8184   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8185   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8186       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8187     And = FirstOp;
8188     Shift = SecondOp;
8189 
8190   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8191              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8192     And = SecondOp;
8193     Shift = FirstOp;
8194   } else
8195     return SDValue();
8196 
8197   bool IsAnd = And.getOpcode() == ISD::AND;
8198   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8199 
8200   // Is the shift amount constant?
8201   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8202   if (!C2node)
8203     return SDValue();
8204 
8205   uint64_t C1;
8206   if (IsAnd) {
8207     // Is the and mask vector all constant?
8208     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8209       return SDValue();
8210   } else {
8211     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8212     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8213     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8214     assert(C1nodeImm && C1nodeShift);
8215     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8216   }
8217 
8218   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8219   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8220   // how much one can shift elements of a particular size?
8221   uint64_t C2 = C2node->getZExtValue();
8222   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8223   if (C2 > ElemSizeInBits)
8224     return SDValue();
8225 
8226   APInt C1AsAPInt(ElemSizeInBits, C1);
8227   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8228                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8229   if (C1AsAPInt != RequiredC1)
8230     return SDValue();
8231 
8232   SDValue X = And.getOperand(0);
8233   SDValue Y = Shift.getOperand(0);
8234 
8235   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8236   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8237 
8238   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8239   LLVM_DEBUG(N->dump(&DAG));
8240   LLVM_DEBUG(dbgs() << "into: \n");
8241   LLVM_DEBUG(ResultSLI->dump(&DAG));
8242 
8243   ++NumShiftInserts;
8244   return ResultSLI;
8245 }
8246 
8247 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8248                                              SelectionDAG &DAG) const {
8249   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8250   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8251     return Res;
8252 
8253   EVT VT = Op.getValueType();
8254 
8255   SDValue LHS = Op.getOperand(0);
8256   BuildVectorSDNode *BVN =
8257       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8258   if (!BVN) {
8259     // OR commutes, so try swapping the operands.
8260     LHS = Op.getOperand(1);
8261     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8262   }
8263   if (!BVN)
8264     return Op;
8265 
8266   APInt DefBits(VT.getSizeInBits(), 0);
8267   APInt UndefBits(VT.getSizeInBits(), 0);
8268   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8269     SDValue NewOp;
8270 
8271     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8272                                     DefBits, &LHS)) ||
8273         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8274                                     DefBits, &LHS)))
8275       return NewOp;
8276 
8277     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8278                                     UndefBits, &LHS)) ||
8279         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8280                                     UndefBits, &LHS)))
8281       return NewOp;
8282   }
8283 
8284   // We can always fall back to a non-immediate OR.
8285   return Op;
8286 }
8287 
8288 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8289 // be truncated to fit element width.
8290 static SDValue NormalizeBuildVector(SDValue Op,
8291                                     SelectionDAG &DAG) {
8292   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8293   SDLoc dl(Op);
8294   EVT VT = Op.getValueType();
8295   EVT EltTy= VT.getVectorElementType();
8296 
8297   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8298     return Op;
8299 
8300   SmallVector<SDValue, 16> Ops;
8301   for (SDValue Lane : Op->ops()) {
8302     // For integer vectors, type legalization would have promoted the
8303     // operands already. Otherwise, if Op is a floating-point splat
8304     // (with operands cast to integers), then the only possibilities
8305     // are constants and UNDEFs.
8306     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8307       APInt LowBits(EltTy.getSizeInBits(),
8308                     CstLane->getZExtValue());
8309       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8310     } else if (Lane.getNode()->isUndef()) {
8311       Lane = DAG.getUNDEF(MVT::i32);
8312     } else {
8313       assert(Lane.getValueType() == MVT::i32 &&
8314              "Unexpected BUILD_VECTOR operand type");
8315     }
8316     Ops.push_back(Lane);
8317   }
8318   return DAG.getBuildVector(VT, dl, Ops);
8319 }
8320 
8321 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8322   EVT VT = Op.getValueType();
8323 
8324   APInt DefBits(VT.getSizeInBits(), 0);
8325   APInt UndefBits(VT.getSizeInBits(), 0);
8326   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8327   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8328     SDValue NewOp;
8329     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8330         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8331         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8332         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8333         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8334         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8335       return NewOp;
8336 
8337     DefBits = ~DefBits;
8338     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8339         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8340         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8341       return NewOp;
8342 
8343     DefBits = UndefBits;
8344     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8345         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8346         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8347         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8348         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8349         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8350       return NewOp;
8351 
8352     DefBits = ~UndefBits;
8353     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8354         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8355         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8356       return NewOp;
8357   }
8358 
8359   return SDValue();
8360 }
8361 
8362 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8363                                                  SelectionDAG &DAG) const {
8364   EVT VT = Op.getValueType();
8365 
8366   // Try to build a simple constant vector.
8367   Op = NormalizeBuildVector(Op, DAG);
8368   if (VT.isInteger()) {
8369     // Certain vector constants, used to express things like logical NOT and
8370     // arithmetic NEG, are passed through unmodified.  This allows special
8371     // patterns for these operations to match, which will lower these constants
8372     // to whatever is proven necessary.
8373     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8374     if (BVN->isConstant())
8375       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8376         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8377         APInt Val(BitSize,
8378                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8379         if (Val.isNullValue() || Val.isAllOnesValue())
8380           return Op;
8381       }
8382   }
8383 
8384   if (SDValue V = ConstantBuildVector(Op, DAG))
8385     return V;
8386 
8387   // Scan through the operands to find some interesting properties we can
8388   // exploit:
8389   //   1) If only one value is used, we can use a DUP, or
8390   //   2) if only the low element is not undef, we can just insert that, or
8391   //   3) if only one constant value is used (w/ some non-constant lanes),
8392   //      we can splat the constant value into the whole vector then fill
8393   //      in the non-constant lanes.
8394   //   4) FIXME: If different constant values are used, but we can intelligently
8395   //             select the values we'll be overwriting for the non-constant
8396   //             lanes such that we can directly materialize the vector
8397   //             some other way (MOVI, e.g.), we can be sneaky.
8398   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8399   SDLoc dl(Op);
8400   unsigned NumElts = VT.getVectorNumElements();
8401   bool isOnlyLowElement = true;
8402   bool usesOnlyOneValue = true;
8403   bool usesOnlyOneConstantValue = true;
8404   bool isConstant = true;
8405   bool AllLanesExtractElt = true;
8406   unsigned NumConstantLanes = 0;
8407   SDValue Value;
8408   SDValue ConstantValue;
8409   for (unsigned i = 0; i < NumElts; ++i) {
8410     SDValue V = Op.getOperand(i);
8411     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8412       AllLanesExtractElt = false;
8413     if (V.isUndef())
8414       continue;
8415     if (i > 0)
8416       isOnlyLowElement = false;
8417     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8418       isConstant = false;
8419 
8420     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8421       ++NumConstantLanes;
8422       if (!ConstantValue.getNode())
8423         ConstantValue = V;
8424       else if (ConstantValue != V)
8425         usesOnlyOneConstantValue = false;
8426     }
8427 
8428     if (!Value.getNode())
8429       Value = V;
8430     else if (V != Value)
8431       usesOnlyOneValue = false;
8432   }
8433 
8434   if (!Value.getNode()) {
8435     LLVM_DEBUG(
8436         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8437     return DAG.getUNDEF(VT);
8438   }
8439 
8440   // Convert BUILD_VECTOR where all elements but the lowest are undef into
8441   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8442   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8443   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8444     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8445                          "SCALAR_TO_VECTOR node\n");
8446     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8447   }
8448 
8449   if (AllLanesExtractElt) {
8450     SDNode *Vector = nullptr;
8451     bool Even = false;
8452     bool Odd = false;
8453     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8454     // the Odd pattern <1,3,5,...>.
8455     for (unsigned i = 0; i < NumElts; ++i) {
8456       SDValue V = Op.getOperand(i);
8457       const SDNode *N = V.getNode();
8458       if (!isa<ConstantSDNode>(N->getOperand(1)))
8459         break;
8460       SDValue N0 = N->getOperand(0);
8461 
8462       // All elements are extracted from the same vector.
8463       if (!Vector) {
8464         Vector = N0.getNode();
8465         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8466         // BUILD_VECTOR.
8467         if (VT.getVectorElementType() !=
8468             N0.getValueType().getVectorElementType())
8469           break;
8470       } else if (Vector != N0.getNode()) {
8471         Odd = false;
8472         Even = false;
8473         break;
8474       }
8475 
8476       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8477       // indices <1,3,5,...>.
8478       uint64_t Val = N->getConstantOperandVal(1);
8479       if (Val == 2 * i) {
8480         Even = true;
8481         continue;
8482       }
8483       if (Val - 1 == 2 * i) {
8484         Odd = true;
8485         continue;
8486       }
8487 
8488       // Something does not match: abort.
8489       Odd = false;
8490       Even = false;
8491       break;
8492     }
8493     if (Even || Odd) {
8494       SDValue LHS =
8495           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8496                       DAG.getConstant(0, dl, MVT::i64));
8497       SDValue RHS =
8498           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8499                       DAG.getConstant(NumElts, dl, MVT::i64));
8500 
8501       if (Even && !Odd)
8502         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8503                            RHS);
8504       if (Odd && !Even)
8505         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8506                            RHS);
8507     }
8508   }
8509 
8510   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8511   // i32 and try again.
8512   if (usesOnlyOneValue) {
8513     if (!isConstant) {
8514       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8515           Value.getValueType() != VT) {
8516         LLVM_DEBUG(
8517             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8518         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8519       }
8520 
8521       // This is actually a DUPLANExx operation, which keeps everything vectory.
8522 
8523       SDValue Lane = Value.getOperand(1);
8524       Value = Value.getOperand(0);
8525       if (Value.getValueSizeInBits() == 64) {
8526         LLVM_DEBUG(
8527             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8528                       "widening it\n");
8529         Value = WidenVector(Value, DAG);
8530       }
8531 
8532       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8533       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8534     }
8535 
8536     if (VT.getVectorElementType().isFloatingPoint()) {
8537       SmallVector<SDValue, 8> Ops;
8538       EVT EltTy = VT.getVectorElementType();
8539       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
8540                EltTy == MVT::f64) && "Unsupported floating-point vector type");
8541       LLVM_DEBUG(
8542           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8543                     "BITCASTS, and try again\n");
8544       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8545       for (unsigned i = 0; i < NumElts; ++i)
8546         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8547       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8548       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8549       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8550                  Val.dump(););
8551       Val = LowerBUILD_VECTOR(Val, DAG);
8552       if (Val.getNode())
8553         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8554     }
8555   }
8556 
8557   // If there was only one constant value used and for more than one lane,
8558   // start by splatting that value, then replace the non-constant lanes. This
8559   // is better than the default, which will perform a separate initialization
8560   // for each lane.
8561   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8562     // Firstly, try to materialize the splat constant.
8563     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8564             Val = ConstantBuildVector(Vec, DAG);
8565     if (!Val) {
8566       // Otherwise, materialize the constant and splat it.
8567       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8568       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8569     }
8570 
8571     // Now insert the non-constant lanes.
8572     for (unsigned i = 0; i < NumElts; ++i) {
8573       SDValue V = Op.getOperand(i);
8574       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8575       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8576         // Note that type legalization likely mucked about with the VT of the
8577         // source operand, so we may have to convert it here before inserting.
8578         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8579     }
8580     return Val;
8581   }
8582 
8583   // This will generate a load from the constant pool.
8584   if (isConstant) {
8585     LLVM_DEBUG(
8586         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8587                   "expansion\n");
8588     return SDValue();
8589   }
8590 
8591   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8592   if (NumElts >= 4) {
8593     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8594       return shuffle;
8595   }
8596 
8597   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8598   // know the default expansion would otherwise fall back on something even
8599   // worse. For a vector with one or two non-undef values, that's
8600   // scalar_to_vector for the elements followed by a shuffle (provided the
8601   // shuffle is valid for the target) and materialization element by element
8602   // on the stack followed by a load for everything else.
8603   if (!isConstant && !usesOnlyOneValue) {
8604     LLVM_DEBUG(
8605         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8606                   "of INSERT_VECTOR_ELT\n");
8607 
8608     SDValue Vec = DAG.getUNDEF(VT);
8609     SDValue Op0 = Op.getOperand(0);
8610     unsigned i = 0;
8611 
8612     // Use SCALAR_TO_VECTOR for lane zero to
8613     // a) Avoid a RMW dependency on the full vector register, and
8614     // b) Allow the register coalescer to fold away the copy if the
8615     //    value is already in an S or D register, and we're forced to emit an
8616     //    INSERT_SUBREG that we can't fold anywhere.
8617     //
8618     // We also allow types like i8 and i16 which are illegal scalar but legal
8619     // vector element types. After type-legalization the inserted value is
8620     // extended (i32) and it is safe to cast them to the vector type by ignoring
8621     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8622     if (!Op0.isUndef()) {
8623       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8624       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8625       ++i;
8626     }
8627     LLVM_DEBUG(if (i < NumElts) dbgs()
8628                    << "Creating nodes for the other vector elements:\n";);
8629     for (; i < NumElts; ++i) {
8630       SDValue V = Op.getOperand(i);
8631       if (V.isUndef())
8632         continue;
8633       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8634       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8635     }
8636     return Vec;
8637   }
8638 
8639   LLVM_DEBUG(
8640       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8641                 "better alternative\n");
8642   return SDValue();
8643 }
8644 
8645 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8646                                                       SelectionDAG &DAG) const {
8647   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8648 
8649   // Check for non-constant or out of range lane.
8650   EVT VT = Op.getOperand(0).getValueType();
8651   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8652   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8653     return SDValue();
8654 
8655 
8656   // Insertion/extraction are legal for V128 types.
8657   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8658       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8659       VT == MVT::v8f16 || VT == MVT::v8bf16)
8660     return Op;
8661 
8662   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8663       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8664       VT != MVT::v4bf16)
8665     return SDValue();
8666 
8667   // For V64 types, we perform insertion by expanding the value
8668   // to a V128 type and perform the insertion on that.
8669   SDLoc DL(Op);
8670   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8671   EVT WideTy = WideVec.getValueType();
8672 
8673   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8674                              Op.getOperand(1), Op.getOperand(2));
8675   // Re-narrow the resultant vector.
8676   return NarrowVector(Node, DAG);
8677 }
8678 
8679 SDValue
8680 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8681                                                SelectionDAG &DAG) const {
8682   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8683 
8684   // Check for non-constant or out of range lane.
8685   EVT VT = Op.getOperand(0).getValueType();
8686   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8687   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8688     return SDValue();
8689 
8690 
8691   // Insertion/extraction are legal for V128 types.
8692   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8693       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8694       VT == MVT::v8f16 || VT == MVT::v8bf16)
8695     return Op;
8696 
8697   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8698       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8699       VT != MVT::v4bf16)
8700     return SDValue();
8701 
8702   // For V64 types, we perform extraction by expanding the value
8703   // to a V128 type and perform the extraction on that.
8704   SDLoc DL(Op);
8705   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8706   EVT WideTy = WideVec.getValueType();
8707 
8708   EVT ExtrTy = WideTy.getVectorElementType();
8709   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8710     ExtrTy = MVT::i32;
8711 
8712   // For extractions, we just return the result directly.
8713   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8714                      Op.getOperand(1));
8715 }
8716 
8717 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8718                                                       SelectionDAG &DAG) const {
8719   assert(Op.getValueType().isFixedLengthVector() &&
8720          "Only cases that extract a fixed length vector are supported!");
8721 
8722   EVT InVT = Op.getOperand(0).getValueType();
8723   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8724   unsigned Size = Op.getValueSizeInBits();
8725 
8726   if (InVT.isScalableVector()) {
8727     // This will be matched by custom code during ISelDAGToDAG.
8728     if (Idx == 0 && isPackedVectorType(InVT, DAG))
8729       return Op;
8730 
8731     return SDValue();
8732   }
8733 
8734   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8735   if (Idx == 0 && InVT.getSizeInBits() <= 128)
8736     return Op;
8737 
8738   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8739   // that directly.
8740   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64)
8741     return Op;
8742 
8743   return SDValue();
8744 }
8745 
8746 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
8747                                                      SelectionDAG &DAG) const {
8748   assert(Op.getValueType().isScalableVector() &&
8749          "Only expect to lower inserts into scalable vectors!");
8750 
8751   EVT InVT = Op.getOperand(1).getValueType();
8752   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8753 
8754   // We don't have any patterns for scalable vector yet.
8755   if (InVT.isScalableVector() || !useSVEForFixedLengthVectorVT(InVT))
8756     return SDValue();
8757 
8758   // This will be matched by custom code during ISelDAGToDAG.
8759   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
8760     return Op;
8761 
8762   return SDValue();
8763 }
8764 
8765 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8766   // Currently no fixed length shuffles that require SVE are legal.
8767   if (useSVEForFixedLengthVectorVT(VT))
8768     return false;
8769 
8770   if (VT.getVectorNumElements() == 4 &&
8771       (VT.is128BitVector() || VT.is64BitVector())) {
8772     unsigned PFIndexes[4];
8773     for (unsigned i = 0; i != 4; ++i) {
8774       if (M[i] < 0)
8775         PFIndexes[i] = 8;
8776       else
8777         PFIndexes[i] = M[i];
8778     }
8779 
8780     // Compute the index in the perfect shuffle table.
8781     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8782                             PFIndexes[2] * 9 + PFIndexes[3];
8783     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8784     unsigned Cost = (PFEntry >> 30);
8785 
8786     if (Cost <= 4)
8787       return true;
8788   }
8789 
8790   bool DummyBool;
8791   int DummyInt;
8792   unsigned DummyUnsigned;
8793 
8794   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8795           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8796           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8797           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8798           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8799           isZIPMask(M, VT, DummyUnsigned) ||
8800           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8801           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8802           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8803           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8804           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8805 }
8806 
8807 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8808 /// operand of a vector shift operation, where all the elements of the
8809 /// build_vector must have the same constant integer value.
8810 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8811   // Ignore bit_converts.
8812   while (Op.getOpcode() == ISD::BITCAST)
8813     Op = Op.getOperand(0);
8814   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8815   APInt SplatBits, SplatUndef;
8816   unsigned SplatBitSize;
8817   bool HasAnyUndefs;
8818   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8819                                     HasAnyUndefs, ElementBits) ||
8820       SplatBitSize > ElementBits)
8821     return false;
8822   Cnt = SplatBits.getSExtValue();
8823   return true;
8824 }
8825 
8826 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8827 /// operand of a vector shift left operation.  That value must be in the range:
8828 ///   0 <= Value < ElementBits for a left shift; or
8829 ///   0 <= Value <= ElementBits for a long left shift.
8830 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8831   assert(VT.isVector() && "vector shift count is not a vector type");
8832   int64_t ElementBits = VT.getScalarSizeInBits();
8833   if (!getVShiftImm(Op, ElementBits, Cnt))
8834     return false;
8835   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8836 }
8837 
8838 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8839 /// operand of a vector shift right operation. The value must be in the range:
8840 ///   1 <= Value <= ElementBits for a right shift; or
8841 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8842   assert(VT.isVector() && "vector shift count is not a vector type");
8843   int64_t ElementBits = VT.getScalarSizeInBits();
8844   if (!getVShiftImm(Op, ElementBits, Cnt))
8845     return false;
8846   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8847 }
8848 
8849 // Attempt to form urhadd(OpA, OpB) from
8850 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)).
8851 // The original form of this expression is
8852 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and before this function
8853 // is called the srl will have been lowered to AArch64ISD::VLSHR and the
8854 // ((OpA + OpB + 1) >> 1) expression will have been changed to (OpB - (~OpA)).
8855 // This pass can also recognize a variant of this pattern that uses sign
8856 // extension instead of zero extension and form a srhadd(OpA, OpB) from it.
8857 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
8858                                              SelectionDAG &DAG) const {
8859   EVT VT = Op.getValueType();
8860 
8861   if (!VT.isVector() || VT.isScalableVector())
8862     return Op;
8863 
8864   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
8865     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
8866 
8867   // Since we are looking for a right shift by a constant value of 1 and we are
8868   // operating on types at least 16 bits in length (sign/zero extended OpA and
8869   // OpB, which are at least 8 bits), it follows that the truncate will always
8870   // discard the shifted-in bit and therefore the right shift will be logical
8871   // regardless of the signedness of OpA and OpB.
8872   SDValue Shift = Op.getOperand(0);
8873   if (Shift.getOpcode() != AArch64ISD::VLSHR)
8874     return Op;
8875 
8876   // Is the right shift using an immediate value of 1?
8877   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
8878   if (ShiftAmount != 1)
8879     return Op;
8880 
8881   SDValue Sub = Shift->getOperand(0);
8882   if (Sub.getOpcode() != ISD::SUB)
8883     return Op;
8884 
8885   SDValue Xor = Sub.getOperand(1);
8886   if (Xor.getOpcode() != ISD::XOR)
8887     return Op;
8888 
8889   SDValue ExtendOpA = Xor.getOperand(0);
8890   SDValue ExtendOpB = Sub.getOperand(0);
8891   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
8892   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
8893   if (!(ExtendOpAOpc == ExtendOpBOpc &&
8894         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
8895     return Op;
8896 
8897   // Is the result of the right shift being truncated to the same value type as
8898   // the original operands, OpA and OpB?
8899   SDValue OpA = ExtendOpA.getOperand(0);
8900   SDValue OpB = ExtendOpB.getOperand(0);
8901   EVT OpAVT = OpA.getValueType();
8902   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
8903   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
8904     return Op;
8905 
8906   // Is the XOR using a constant amount of all ones in the right hand side?
8907   uint64_t C;
8908   if (!isAllConstantBuildVector(Xor.getOperand(1), C))
8909     return Op;
8910 
8911   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8912   APInt CAsAPInt(ElemSizeInBits, C);
8913   if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
8914     return Op;
8915 
8916   SDLoc DL(Op);
8917   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
8918   unsigned RHADDOpc = IsSignExtend ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
8919   SDValue ResultURHADD = DAG.getNode(RHADDOpc, DL, VT, OpA, OpB);
8920 
8921   return ResultURHADD;
8922 }
8923 
8924 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8925                                                       SelectionDAG &DAG) const {
8926   EVT VT = Op.getValueType();
8927   SDLoc DL(Op);
8928   int64_t Cnt;
8929 
8930   if (!Op.getOperand(1).getValueType().isVector())
8931     return Op;
8932   unsigned EltSize = VT.getScalarSizeInBits();
8933 
8934   switch (Op.getOpcode()) {
8935   default:
8936     llvm_unreachable("unexpected shift opcode");
8937 
8938   case ISD::SHL:
8939     if (VT.isScalableVector())
8940       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_MERGE_OP1);
8941 
8942     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8943       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8944                          DAG.getConstant(Cnt, DL, MVT::i32));
8945     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8946                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8947                                        MVT::i32),
8948                        Op.getOperand(0), Op.getOperand(1));
8949   case ISD::SRA:
8950   case ISD::SRL:
8951     if (VT.isScalableVector()) {
8952       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_MERGE_OP1
8953                                                 : AArch64ISD::SRL_MERGE_OP1;
8954       return LowerToPredicatedOp(Op, DAG, Opc);
8955     }
8956 
8957     // Right shift immediate
8958     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8959       unsigned Opc =
8960           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8961       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8962                          DAG.getConstant(Cnt, DL, MVT::i32));
8963     }
8964 
8965     // Right shift register.  Note, there is not a shift right register
8966     // instruction, but the shift left register instruction takes a signed
8967     // value, where negative numbers specify a right shift.
8968     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8969                                                 : Intrinsic::aarch64_neon_ushl;
8970     // negate the shift amount
8971     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8972     SDValue NegShiftLeft =
8973         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8974                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8975                     NegShift);
8976     return NegShiftLeft;
8977   }
8978 
8979   return SDValue();
8980 }
8981 
8982 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8983                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8984                                     const SDLoc &dl, SelectionDAG &DAG) {
8985   EVT SrcVT = LHS.getValueType();
8986   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8987          "function only supposed to emit natural comparisons");
8988 
8989   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8990   APInt CnstBits(VT.getSizeInBits(), 0);
8991   APInt UndefBits(VT.getSizeInBits(), 0);
8992   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8993   bool IsZero = IsCnst && (CnstBits == 0);
8994 
8995   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8996     switch (CC) {
8997     default:
8998       return SDValue();
8999     case AArch64CC::NE: {
9000       SDValue Fcmeq;
9001       if (IsZero)
9002         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9003       else
9004         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9005       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9006     }
9007     case AArch64CC::EQ:
9008       if (IsZero)
9009         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9010       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9011     case AArch64CC::GE:
9012       if (IsZero)
9013         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9014       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9015     case AArch64CC::GT:
9016       if (IsZero)
9017         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9018       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9019     case AArch64CC::LS:
9020       if (IsZero)
9021         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9022       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9023     case AArch64CC::LT:
9024       if (!NoNans)
9025         return SDValue();
9026       // If we ignore NaNs then we can use to the MI implementation.
9027       LLVM_FALLTHROUGH;
9028     case AArch64CC::MI:
9029       if (IsZero)
9030         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9031       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9032     }
9033   }
9034 
9035   switch (CC) {
9036   default:
9037     return SDValue();
9038   case AArch64CC::NE: {
9039     SDValue Cmeq;
9040     if (IsZero)
9041       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9042     else
9043       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9044     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9045   }
9046   case AArch64CC::EQ:
9047     if (IsZero)
9048       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9049     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9050   case AArch64CC::GE:
9051     if (IsZero)
9052       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9053     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9054   case AArch64CC::GT:
9055     if (IsZero)
9056       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9057     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9058   case AArch64CC::LE:
9059     if (IsZero)
9060       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9061     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9062   case AArch64CC::LS:
9063     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9064   case AArch64CC::LO:
9065     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9066   case AArch64CC::LT:
9067     if (IsZero)
9068       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9069     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9070   case AArch64CC::HI:
9071     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9072   case AArch64CC::HS:
9073     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9074   }
9075 }
9076 
9077 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9078                                            SelectionDAG &DAG) const {
9079   if (Op.getValueType().isScalableVector()) {
9080     if (Op.getOperand(0).getValueType().isFloatingPoint())
9081       return Op;
9082     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9083   }
9084 
9085   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9086   SDValue LHS = Op.getOperand(0);
9087   SDValue RHS = Op.getOperand(1);
9088   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9089   SDLoc dl(Op);
9090 
9091   if (LHS.getValueType().getVectorElementType().isInteger()) {
9092     assert(LHS.getValueType() == RHS.getValueType());
9093     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9094     SDValue Cmp =
9095         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9096     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9097   }
9098 
9099   const bool FullFP16 =
9100     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9101 
9102   // Make v4f16 (only) fcmp operations utilise vector instructions
9103   // v8f16 support will be a litle more complicated
9104   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9105     if (LHS.getValueType().getVectorNumElements() == 4) {
9106       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9107       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9108       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9109       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9110       CmpVT = MVT::v4i32;
9111     } else
9112       return SDValue();
9113   }
9114 
9115   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9116           LHS.getValueType().getVectorElementType() != MVT::f128);
9117 
9118   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9119   // clean.  Some of them require two branches to implement.
9120   AArch64CC::CondCode CC1, CC2;
9121   bool ShouldInvert;
9122   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9123 
9124   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9125   SDValue Cmp =
9126       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9127   if (!Cmp.getNode())
9128     return SDValue();
9129 
9130   if (CC2 != AArch64CC::AL) {
9131     SDValue Cmp2 =
9132         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9133     if (!Cmp2.getNode())
9134       return SDValue();
9135 
9136     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9137   }
9138 
9139   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9140 
9141   if (ShouldInvert)
9142     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9143 
9144   return Cmp;
9145 }
9146 
9147 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9148                                   SelectionDAG &DAG) {
9149   SDValue VecOp = ScalarOp.getOperand(0);
9150   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9151   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9152                      DAG.getConstant(0, DL, MVT::i64));
9153 }
9154 
9155 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9156                                               SelectionDAG &DAG) const {
9157   SDLoc dl(Op);
9158   switch (Op.getOpcode()) {
9159   case ISD::VECREDUCE_ADD:
9160     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9161   case ISD::VECREDUCE_SMAX:
9162     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9163   case ISD::VECREDUCE_SMIN:
9164     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9165   case ISD::VECREDUCE_UMAX:
9166     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9167   case ISD::VECREDUCE_UMIN:
9168     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9169   case ISD::VECREDUCE_FMAX: {
9170     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
9171     return DAG.getNode(
9172         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9173         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9174         Op.getOperand(0));
9175   }
9176   case ISD::VECREDUCE_FMIN: {
9177     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
9178     return DAG.getNode(
9179         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9180         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9181         Op.getOperand(0));
9182   }
9183   default:
9184     llvm_unreachable("Unhandled reduction");
9185   }
9186 }
9187 
9188 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9189                                                     SelectionDAG &DAG) const {
9190   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9191   if (!Subtarget.hasLSE())
9192     return SDValue();
9193 
9194   // LSE has an atomic load-add instruction, but not a load-sub.
9195   SDLoc dl(Op);
9196   MVT VT = Op.getSimpleValueType();
9197   SDValue RHS = Op.getOperand(2);
9198   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9199   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9200   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9201                        Op.getOperand(0), Op.getOperand(1), RHS,
9202                        AN->getMemOperand());
9203 }
9204 
9205 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9206                                                     SelectionDAG &DAG) const {
9207   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9208   if (!Subtarget.hasLSE())
9209     return SDValue();
9210 
9211   // LSE has an atomic load-clear instruction, but not a load-and.
9212   SDLoc dl(Op);
9213   MVT VT = Op.getSimpleValueType();
9214   SDValue RHS = Op.getOperand(2);
9215   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9216   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9217   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9218                        Op.getOperand(0), Op.getOperand(1), RHS,
9219                        AN->getMemOperand());
9220 }
9221 
9222 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9223     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9224   SDLoc dl(Op);
9225   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9226   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9227 
9228   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9229   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9230   if (Subtarget->hasCustomCallingConv())
9231     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9232 
9233   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9234                      DAG.getConstant(4, dl, MVT::i64));
9235   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9236   Chain =
9237       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9238                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9239                   DAG.getRegisterMask(Mask), Chain.getValue(1));
9240   // To match the actual intent better, we should read the output from X15 here
9241   // again (instead of potentially spilling it to the stack), but rereading Size
9242   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9243   // here.
9244 
9245   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9246                      DAG.getConstant(4, dl, MVT::i64));
9247   return Chain;
9248 }
9249 
9250 SDValue
9251 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9252                                                SelectionDAG &DAG) const {
9253   assert(Subtarget->isTargetWindows() &&
9254          "Only Windows alloca probing supported");
9255   SDLoc dl(Op);
9256   // Get the inputs.
9257   SDNode *Node = Op.getNode();
9258   SDValue Chain = Op.getOperand(0);
9259   SDValue Size = Op.getOperand(1);
9260   MaybeAlign Align =
9261       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9262   EVT VT = Node->getValueType(0);
9263 
9264   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9265           "no-stack-arg-probe")) {
9266     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9267     Chain = SP.getValue(1);
9268     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9269     if (Align)
9270       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9271                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9272     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9273     SDValue Ops[2] = {SP, Chain};
9274     return DAG.getMergeValues(Ops, dl);
9275   }
9276 
9277   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9278 
9279   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9280 
9281   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9282   Chain = SP.getValue(1);
9283   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9284   if (Align)
9285     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9286                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9287   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9288 
9289   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9290                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9291 
9292   SDValue Ops[2] = {SP, Chain};
9293   return DAG.getMergeValues(Ops, dl);
9294 }
9295 
9296 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9297                                            SelectionDAG &DAG) const {
9298   EVT VT = Op.getValueType();
9299   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9300 
9301   SDLoc DL(Op);
9302   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9303   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9304                             DL, VT);
9305 }
9306 
9307 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9308 template <unsigned NumVecs>
9309 static bool setInfoSVEStN(AArch64TargetLowering::IntrinsicInfo &Info,
9310                           const CallInst &CI) {
9311   Info.opc = ISD::INTRINSIC_VOID;
9312   // Retrieve EC from first vector argument.
9313   const EVT VT = EVT::getEVT(CI.getArgOperand(0)->getType());
9314   ElementCount EC = VT.getVectorElementCount();
9315 #ifndef NDEBUG
9316   // Check the assumption that all input vectors are the same type.
9317   for (unsigned I = 0; I < NumVecs; ++I)
9318     assert(VT == EVT::getEVT(CI.getArgOperand(I)->getType()) &&
9319            "Invalid type.");
9320 #endif
9321   // memVT is `NumVecs * VT`.
9322   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9323                                 EC * NumVecs);
9324   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9325   Info.offset = 0;
9326   Info.align.reset();
9327   Info.flags = MachineMemOperand::MOStore;
9328   return true;
9329 }
9330 
9331 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9332 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9333 /// specified in the intrinsic calls.
9334 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9335                                                const CallInst &I,
9336                                                MachineFunction &MF,
9337                                                unsigned Intrinsic) const {
9338   auto &DL = I.getModule()->getDataLayout();
9339   switch (Intrinsic) {
9340   case Intrinsic::aarch64_sve_st2:
9341     return setInfoSVEStN<2>(Info, I);
9342   case Intrinsic::aarch64_sve_st3:
9343     return setInfoSVEStN<3>(Info, I);
9344   case Intrinsic::aarch64_sve_st4:
9345     return setInfoSVEStN<4>(Info, I);
9346   case Intrinsic::aarch64_neon_ld2:
9347   case Intrinsic::aarch64_neon_ld3:
9348   case Intrinsic::aarch64_neon_ld4:
9349   case Intrinsic::aarch64_neon_ld1x2:
9350   case Intrinsic::aarch64_neon_ld1x3:
9351   case Intrinsic::aarch64_neon_ld1x4:
9352   case Intrinsic::aarch64_neon_ld2lane:
9353   case Intrinsic::aarch64_neon_ld3lane:
9354   case Intrinsic::aarch64_neon_ld4lane:
9355   case Intrinsic::aarch64_neon_ld2r:
9356   case Intrinsic::aarch64_neon_ld3r:
9357   case Intrinsic::aarch64_neon_ld4r: {
9358     Info.opc = ISD::INTRINSIC_W_CHAIN;
9359     // Conservatively set memVT to the entire set of vectors loaded.
9360     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
9361     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9362     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9363     Info.offset = 0;
9364     Info.align.reset();
9365     // volatile loads with NEON intrinsics not supported
9366     Info.flags = MachineMemOperand::MOLoad;
9367     return true;
9368   }
9369   case Intrinsic::aarch64_neon_st2:
9370   case Intrinsic::aarch64_neon_st3:
9371   case Intrinsic::aarch64_neon_st4:
9372   case Intrinsic::aarch64_neon_st1x2:
9373   case Intrinsic::aarch64_neon_st1x3:
9374   case Intrinsic::aarch64_neon_st1x4:
9375   case Intrinsic::aarch64_neon_st2lane:
9376   case Intrinsic::aarch64_neon_st3lane:
9377   case Intrinsic::aarch64_neon_st4lane: {
9378     Info.opc = ISD::INTRINSIC_VOID;
9379     // Conservatively set memVT to the entire set of vectors stored.
9380     unsigned NumElts = 0;
9381     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9382       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9383       if (!ArgTy->isVectorTy())
9384         break;
9385       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
9386     }
9387     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9388     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9389     Info.offset = 0;
9390     Info.align.reset();
9391     // volatile stores with NEON intrinsics not supported
9392     Info.flags = MachineMemOperand::MOStore;
9393     return true;
9394   }
9395   case Intrinsic::aarch64_ldaxr:
9396   case Intrinsic::aarch64_ldxr: {
9397     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
9398     Info.opc = ISD::INTRINSIC_W_CHAIN;
9399     Info.memVT = MVT::getVT(PtrTy->getElementType());
9400     Info.ptrVal = I.getArgOperand(0);
9401     Info.offset = 0;
9402     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9403     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9404     return true;
9405   }
9406   case Intrinsic::aarch64_stlxr:
9407   case Intrinsic::aarch64_stxr: {
9408     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9409     Info.opc = ISD::INTRINSIC_W_CHAIN;
9410     Info.memVT = MVT::getVT(PtrTy->getElementType());
9411     Info.ptrVal = I.getArgOperand(1);
9412     Info.offset = 0;
9413     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9414     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9415     return true;
9416   }
9417   case Intrinsic::aarch64_ldaxp:
9418   case Intrinsic::aarch64_ldxp:
9419     Info.opc = ISD::INTRINSIC_W_CHAIN;
9420     Info.memVT = MVT::i128;
9421     Info.ptrVal = I.getArgOperand(0);
9422     Info.offset = 0;
9423     Info.align = Align(16);
9424     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9425     return true;
9426   case Intrinsic::aarch64_stlxp:
9427   case Intrinsic::aarch64_stxp:
9428     Info.opc = ISD::INTRINSIC_W_CHAIN;
9429     Info.memVT = MVT::i128;
9430     Info.ptrVal = I.getArgOperand(2);
9431     Info.offset = 0;
9432     Info.align = Align(16);
9433     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9434     return true;
9435   case Intrinsic::aarch64_sve_ldnt1: {
9436     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9437     Info.opc = ISD::INTRINSIC_W_CHAIN;
9438     Info.memVT = MVT::getVT(I.getType());
9439     Info.ptrVal = I.getArgOperand(1);
9440     Info.offset = 0;
9441     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9442     Info.flags = MachineMemOperand::MOLoad;
9443     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9444       Info.flags |= MachineMemOperand::MONonTemporal;
9445     return true;
9446   }
9447   case Intrinsic::aarch64_sve_stnt1: {
9448     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9449     Info.opc = ISD::INTRINSIC_W_CHAIN;
9450     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9451     Info.ptrVal = I.getArgOperand(2);
9452     Info.offset = 0;
9453     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9454     Info.flags = MachineMemOperand::MOStore;
9455     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9456       Info.flags |= MachineMemOperand::MONonTemporal;
9457     return true;
9458   }
9459   default:
9460     break;
9461   }
9462 
9463   return false;
9464 }
9465 
9466 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9467                                                   ISD::LoadExtType ExtTy,
9468                                                   EVT NewVT) const {
9469   // TODO: This may be worth removing. Check regression tests for diffs.
9470   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9471     return false;
9472 
9473   // If we're reducing the load width in order to avoid having to use an extra
9474   // instruction to do extension then it's probably a good idea.
9475   if (ExtTy != ISD::NON_EXTLOAD)
9476     return true;
9477   // Don't reduce load width if it would prevent us from combining a shift into
9478   // the offset.
9479   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9480   assert(Mem);
9481   const SDValue &Base = Mem->getBasePtr();
9482   if (Base.getOpcode() == ISD::ADD &&
9483       Base.getOperand(1).getOpcode() == ISD::SHL &&
9484       Base.getOperand(1).hasOneUse() &&
9485       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9486     // The shift can be combined if it matches the size of the value being
9487     // loaded (and so reducing the width would make it not match).
9488     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9489     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9490     if (ShiftAmount == Log2_32(LoadBytes))
9491       return false;
9492   }
9493   // We have no reason to disallow reducing the load width, so allow it.
9494   return true;
9495 }
9496 
9497 // Truncations from 64-bit GPR to 32-bit GPR is free.
9498 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9499   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9500     return false;
9501   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9502   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9503   return NumBits1 > NumBits2;
9504 }
9505 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9506   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9507     return false;
9508   unsigned NumBits1 = VT1.getSizeInBits();
9509   unsigned NumBits2 = VT2.getSizeInBits();
9510   return NumBits1 > NumBits2;
9511 }
9512 
9513 /// Check if it is profitable to hoist instruction in then/else to if.
9514 /// Not profitable if I and it's user can form a FMA instruction
9515 /// because we prefer FMSUB/FMADD.
9516 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9517   if (I->getOpcode() != Instruction::FMul)
9518     return true;
9519 
9520   if (!I->hasOneUse())
9521     return true;
9522 
9523   Instruction *User = I->user_back();
9524 
9525   if (User &&
9526       !(User->getOpcode() == Instruction::FSub ||
9527         User->getOpcode() == Instruction::FAdd))
9528     return true;
9529 
9530   const TargetOptions &Options = getTargetMachine().Options;
9531   const Function *F = I->getFunction();
9532   const DataLayout &DL = F->getParent()->getDataLayout();
9533   Type *Ty = User->getOperand(0)->getType();
9534 
9535   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9536            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9537            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9538             Options.UnsafeFPMath));
9539 }
9540 
9541 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9542 // 64-bit GPR.
9543 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9544   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9545     return false;
9546   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9547   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9548   return NumBits1 == 32 && NumBits2 == 64;
9549 }
9550 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9551   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9552     return false;
9553   unsigned NumBits1 = VT1.getSizeInBits();
9554   unsigned NumBits2 = VT2.getSizeInBits();
9555   return NumBits1 == 32 && NumBits2 == 64;
9556 }
9557 
9558 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9559   EVT VT1 = Val.getValueType();
9560   if (isZExtFree(VT1, VT2)) {
9561     return true;
9562   }
9563 
9564   if (Val.getOpcode() != ISD::LOAD)
9565     return false;
9566 
9567   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9568   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9569           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9570           VT1.getSizeInBits() <= 32);
9571 }
9572 
9573 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9574   if (isa<FPExtInst>(Ext))
9575     return false;
9576 
9577   // Vector types are not free.
9578   if (Ext->getType()->isVectorTy())
9579     return false;
9580 
9581   for (const Use &U : Ext->uses()) {
9582     // The extension is free if we can fold it with a left shift in an
9583     // addressing mode or an arithmetic operation: add, sub, and cmp.
9584 
9585     // Is there a shift?
9586     const Instruction *Instr = cast<Instruction>(U.getUser());
9587 
9588     // Is this a constant shift?
9589     switch (Instr->getOpcode()) {
9590     case Instruction::Shl:
9591       if (!isa<ConstantInt>(Instr->getOperand(1)))
9592         return false;
9593       break;
9594     case Instruction::GetElementPtr: {
9595       gep_type_iterator GTI = gep_type_begin(Instr);
9596       auto &DL = Ext->getModule()->getDataLayout();
9597       std::advance(GTI, U.getOperandNo()-1);
9598       Type *IdxTy = GTI.getIndexedType();
9599       // This extension will end up with a shift because of the scaling factor.
9600       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9601       // Get the shift amount based on the scaling factor:
9602       // log2(sizeof(IdxTy)) - log2(8).
9603       uint64_t ShiftAmt =
9604         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9605       // Is the constant foldable in the shift of the addressing mode?
9606       // I.e., shift amount is between 1 and 4 inclusive.
9607       if (ShiftAmt == 0 || ShiftAmt > 4)
9608         return false;
9609       break;
9610     }
9611     case Instruction::Trunc:
9612       // Check if this is a noop.
9613       // trunc(sext ty1 to ty2) to ty1.
9614       if (Instr->getType() == Ext->getOperand(0)->getType())
9615         continue;
9616       LLVM_FALLTHROUGH;
9617     default:
9618       return false;
9619     }
9620 
9621     // At this point we can use the bfm family, so this extension is free
9622     // for that use.
9623   }
9624   return true;
9625 }
9626 
9627 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9628 /// or upper half of the vector elements.
9629 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9630   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9631     auto *FullTy = FullV->getType();
9632     auto *HalfTy = HalfV->getType();
9633     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
9634            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
9635   };
9636 
9637   auto extractHalf = [](Value *FullV, Value *HalfV) {
9638     auto *FullVT = cast<FixedVectorType>(FullV->getType());
9639     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
9640     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9641   };
9642 
9643   ArrayRef<int> M1, M2;
9644   Value *S1Op1, *S2Op1;
9645   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9646       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9647     return false;
9648 
9649   // Check that the operands are half as wide as the result and we extract
9650   // half of the elements of the input vectors.
9651   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9652       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9653     return false;
9654 
9655   // Check the mask extracts either the lower or upper half of vector
9656   // elements.
9657   int M1Start = -1;
9658   int M2Start = -1;
9659   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
9660   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9661       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9662       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9663     return false;
9664 
9665   return true;
9666 }
9667 
9668 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9669 /// of the vector elements.
9670 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9671   auto areExtDoubled = [](Instruction *Ext) {
9672     return Ext->getType()->getScalarSizeInBits() ==
9673            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9674   };
9675 
9676   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9677       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9678       !areExtDoubled(cast<Instruction>(Ext1)) ||
9679       !areExtDoubled(cast<Instruction>(Ext2)))
9680     return false;
9681 
9682   return true;
9683 }
9684 
9685 /// Check if Op could be used with vmull_high_p64 intrinsic.
9686 static bool isOperandOfVmullHighP64(Value *Op) {
9687   Value *VectorOperand = nullptr;
9688   ConstantInt *ElementIndex = nullptr;
9689   return match(Op, m_ExtractElt(m_Value(VectorOperand),
9690                                 m_ConstantInt(ElementIndex))) &&
9691          ElementIndex->getValue() == 1 &&
9692          isa<FixedVectorType>(VectorOperand->getType()) &&
9693          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
9694 }
9695 
9696 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
9697 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
9698   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
9699 }
9700 
9701 /// Check if sinking \p I's operands to I's basic block is profitable, because
9702 /// the operands can be folded into a target instruction, e.g.
9703 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9704 bool AArch64TargetLowering::shouldSinkOperands(
9705     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9706   if (!I->getType()->isVectorTy())
9707     return false;
9708 
9709   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9710     switch (II->getIntrinsicID()) {
9711     case Intrinsic::aarch64_neon_umull:
9712       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9713         return false;
9714       Ops.push_back(&II->getOperandUse(0));
9715       Ops.push_back(&II->getOperandUse(1));
9716       return true;
9717 
9718     case Intrinsic::aarch64_neon_pmull64:
9719       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
9720                                      II->getArgOperand(1)))
9721         return false;
9722       Ops.push_back(&II->getArgOperandUse(0));
9723       Ops.push_back(&II->getArgOperandUse(1));
9724       return true;
9725 
9726     default:
9727       return false;
9728     }
9729   }
9730 
9731   switch (I->getOpcode()) {
9732   case Instruction::Sub:
9733   case Instruction::Add: {
9734     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9735       return false;
9736 
9737     // If the exts' operands extract either the lower or upper elements, we
9738     // can sink them too.
9739     auto Ext1 = cast<Instruction>(I->getOperand(0));
9740     auto Ext2 = cast<Instruction>(I->getOperand(1));
9741     if (areExtractShuffleVectors(Ext1, Ext2)) {
9742       Ops.push_back(&Ext1->getOperandUse(0));
9743       Ops.push_back(&Ext2->getOperandUse(0));
9744     }
9745 
9746     Ops.push_back(&I->getOperandUse(0));
9747     Ops.push_back(&I->getOperandUse(1));
9748 
9749     return true;
9750   }
9751   default:
9752     return false;
9753   }
9754   return false;
9755 }
9756 
9757 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9758                                           Align &RequiredAligment) const {
9759   if (!LoadedType.isSimple() ||
9760       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9761     return false;
9762   // Cyclone supports unaligned accesses.
9763   RequiredAligment = Align(1);
9764   unsigned NumBits = LoadedType.getSizeInBits();
9765   return NumBits == 32 || NumBits == 64;
9766 }
9767 
9768 /// A helper function for determining the number of interleaved accesses we
9769 /// will generate when lowering accesses of the given type.
9770 unsigned
9771 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9772                                                  const DataLayout &DL) const {
9773   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9774 }
9775 
9776 MachineMemOperand::Flags
9777 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9778   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9779       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9780     return MOStridedAccess;
9781   return MachineMemOperand::MONone;
9782 }
9783 
9784 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9785     VectorType *VecTy, const DataLayout &DL) const {
9786 
9787   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9788   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9789 
9790   // Ensure the number of vector elements is greater than 1.
9791   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
9792     return false;
9793 
9794   // Ensure the element type is legal.
9795   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9796     return false;
9797 
9798   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9799   // 128 will be split into multiple interleaved accesses.
9800   return VecSize == 64 || VecSize % 128 == 0;
9801 }
9802 
9803 /// Lower an interleaved load into a ldN intrinsic.
9804 ///
9805 /// E.g. Lower an interleaved load (Factor = 2):
9806 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9807 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9808 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9809 ///
9810 ///      Into:
9811 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9812 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9813 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9814 bool AArch64TargetLowering::lowerInterleavedLoad(
9815     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9816     ArrayRef<unsigned> Indices, unsigned Factor) const {
9817   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9818          "Invalid interleave factor");
9819   assert(!Shuffles.empty() && "Empty shufflevector input");
9820   assert(Shuffles.size() == Indices.size() &&
9821          "Unmatched number of shufflevectors and indices");
9822 
9823   const DataLayout &DL = LI->getModule()->getDataLayout();
9824 
9825   VectorType *VTy = Shuffles[0]->getType();
9826 
9827   // Skip if we do not have NEON and skip illegal vector types. We can
9828   // "legalize" wide vector types into multiple interleaved accesses as long as
9829   // the vector types are divisible by 128.
9830   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
9831     return false;
9832 
9833   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
9834 
9835   auto *FVTy = cast<FixedVectorType>(VTy);
9836 
9837   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9838   // load integer vectors first and then convert to pointer vectors.
9839   Type *EltTy = FVTy->getElementType();
9840   if (EltTy->isPointerTy())
9841     FVTy =
9842         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
9843 
9844   IRBuilder<> Builder(LI);
9845 
9846   // The base address of the load.
9847   Value *BaseAddr = LI->getPointerOperand();
9848 
9849   if (NumLoads > 1) {
9850     // If we're going to generate more than one load, reset the sub-vector type
9851     // to something legal.
9852     FVTy = FixedVectorType::get(FVTy->getElementType(),
9853                                 FVTy->getNumElements() / NumLoads);
9854 
9855     // We will compute the pointer operand of each load from the original base
9856     // address using GEPs. Cast the base address to a pointer to the scalar
9857     // element type.
9858     BaseAddr = Builder.CreateBitCast(
9859         BaseAddr,
9860         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
9861   }
9862 
9863   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
9864   Type *Tys[2] = {FVTy, PtrTy};
9865   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9866                                             Intrinsic::aarch64_neon_ld3,
9867                                             Intrinsic::aarch64_neon_ld4};
9868   Function *LdNFunc =
9869       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9870 
9871   // Holds sub-vectors extracted from the load intrinsic return values. The
9872   // sub-vectors are associated with the shufflevector instructions they will
9873   // replace.
9874   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9875 
9876   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9877 
9878     // If we're generating more than one load, compute the base address of
9879     // subsequent loads as an offset from the previous.
9880     if (LoadCount > 0)
9881       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
9882                                             FVTy->getNumElements() * Factor);
9883 
9884     CallInst *LdN = Builder.CreateCall(
9885         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9886 
9887     // Extract and store the sub-vectors returned by the load intrinsic.
9888     for (unsigned i = 0; i < Shuffles.size(); i++) {
9889       ShuffleVectorInst *SVI = Shuffles[i];
9890       unsigned Index = Indices[i];
9891 
9892       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9893 
9894       // Convert the integer vector to pointer vector if the element is pointer.
9895       if (EltTy->isPointerTy())
9896         SubVec = Builder.CreateIntToPtr(
9897             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
9898                                          FVTy->getNumElements()));
9899       SubVecs[SVI].push_back(SubVec);
9900     }
9901   }
9902 
9903   // Replace uses of the shufflevector instructions with the sub-vectors
9904   // returned by the load intrinsic. If a shufflevector instruction is
9905   // associated with more than one sub-vector, those sub-vectors will be
9906   // concatenated into a single wide vector.
9907   for (ShuffleVectorInst *SVI : Shuffles) {
9908     auto &SubVec = SubVecs[SVI];
9909     auto *WideVec =
9910         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9911     SVI->replaceAllUsesWith(WideVec);
9912   }
9913 
9914   return true;
9915 }
9916 
9917 /// Lower an interleaved store into a stN intrinsic.
9918 ///
9919 /// E.g. Lower an interleaved store (Factor = 3):
9920 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9921 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9922 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9923 ///
9924 ///      Into:
9925 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9926 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9927 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9928 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9929 ///
9930 /// Note that the new shufflevectors will be removed and we'll only generate one
9931 /// st3 instruction in CodeGen.
9932 ///
9933 /// Example for a more general valid mask (Factor 3). Lower:
9934 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9935 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9936 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9937 ///
9938 ///      Into:
9939 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9940 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9941 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9942 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9943 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9944                                                   ShuffleVectorInst *SVI,
9945                                                   unsigned Factor) const {
9946   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9947          "Invalid interleave factor");
9948 
9949   auto *VecTy = cast<FixedVectorType>(SVI->getType());
9950   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
9951 
9952   unsigned LaneLen = VecTy->getNumElements() / Factor;
9953   Type *EltTy = VecTy->getElementType();
9954   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
9955 
9956   const DataLayout &DL = SI->getModule()->getDataLayout();
9957 
9958   // Skip if we do not have NEON and skip illegal vector types. We can
9959   // "legalize" wide vector types into multiple interleaved accesses as long as
9960   // the vector types are divisible by 128.
9961   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9962     return false;
9963 
9964   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9965 
9966   Value *Op0 = SVI->getOperand(0);
9967   Value *Op1 = SVI->getOperand(1);
9968   IRBuilder<> Builder(SI);
9969 
9970   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9971   // vectors to integer vectors.
9972   if (EltTy->isPointerTy()) {
9973     Type *IntTy = DL.getIntPtrType(EltTy);
9974     unsigned NumOpElts =
9975         cast<FixedVectorType>(Op0->getType())->getNumElements();
9976 
9977     // Convert to the corresponding integer vector.
9978     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
9979     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9980     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9981 
9982     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
9983   }
9984 
9985   // The base address of the store.
9986   Value *BaseAddr = SI->getPointerOperand();
9987 
9988   if (NumStores > 1) {
9989     // If we're going to generate more than one store, reset the lane length
9990     // and sub-vector type to something legal.
9991     LaneLen /= NumStores;
9992     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
9993 
9994     // We will compute the pointer operand of each store from the original base
9995     // address using GEPs. Cast the base address to a pointer to the scalar
9996     // element type.
9997     BaseAddr = Builder.CreateBitCast(
9998         BaseAddr,
9999         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10000   }
10001 
10002   auto Mask = SVI->getShuffleMask();
10003 
10004   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10005   Type *Tys[2] = {SubVecTy, PtrTy};
10006   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10007                                              Intrinsic::aarch64_neon_st3,
10008                                              Intrinsic::aarch64_neon_st4};
10009   Function *StNFunc =
10010       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10011 
10012   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10013 
10014     SmallVector<Value *, 5> Ops;
10015 
10016     // Split the shufflevector operands into sub vectors for the new stN call.
10017     for (unsigned i = 0; i < Factor; i++) {
10018       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10019       if (Mask[IdxI] >= 0) {
10020         Ops.push_back(Builder.CreateShuffleVector(
10021             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10022       } else {
10023         unsigned StartMask = 0;
10024         for (unsigned j = 1; j < LaneLen; j++) {
10025           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10026           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10027             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10028             break;
10029           }
10030         }
10031         // Note: Filling undef gaps with random elements is ok, since
10032         // those elements were being written anyway (with undefs).
10033         // In the case of all undefs we're defaulting to using elems from 0
10034         // Note: StartMask cannot be negative, it's checked in
10035         // isReInterleaveMask
10036         Ops.push_back(Builder.CreateShuffleVector(
10037             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10038       }
10039     }
10040 
10041     // If we generating more than one store, we compute the base address of
10042     // subsequent stores as an offset from the previous.
10043     if (StoreCount > 0)
10044       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10045                                             BaseAddr, LaneLen * Factor);
10046 
10047     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10048     Builder.CreateCall(StNFunc, Ops);
10049   }
10050   return true;
10051 }
10052 
10053 // Lower an SVE structured load intrinsic returning a tuple type to target
10054 // specific intrinsic taking the same input but returning a multi-result value
10055 // of the split tuple type.
10056 //
10057 // E.g. Lowering an LD3:
10058 //
10059 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10060 //                                                    <vscale x 4 x i1> %pred,
10061 //                                                    <vscale x 4 x i32>* %addr)
10062 //
10063 //  Output DAG:
10064 //
10065 //    t0: ch = EntryToken
10066 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10067 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10068 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10069 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10070 //
10071 // This is called pre-legalization to avoid widening/splitting issues with
10072 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10073 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10074                                                   ArrayRef<SDValue> LoadOps,
10075                                                   EVT VT, SelectionDAG &DAG,
10076                                                   const SDLoc &DL) const {
10077   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10078 
10079   unsigned N, Opcode;
10080   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10081       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10082       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10083       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10084 
10085   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10086   assert(VT.getVectorElementCount().Min % N == 0 &&
10087          "invalid tuple vector type!");
10088 
10089   EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10090                                  VT.getVectorElementCount() / N);
10091   assert(isTypeLegal(SplitVT));
10092 
10093   SmallVector<EVT, 5> VTs(N, SplitVT);
10094   VTs.push_back(MVT::Other); // Chain
10095   SDVTList NodeTys = DAG.getVTList(VTs);
10096 
10097   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10098   SmallVector<SDValue, 4> PseudoLoadOps;
10099   for (unsigned I = 0; I < N; ++I)
10100     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10101   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10102 }
10103 
10104 EVT AArch64TargetLowering::getOptimalMemOpType(
10105     const MemOp &Op, const AttributeList &FuncAttributes) const {
10106   bool CanImplicitFloat =
10107       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10108   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10109   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10110   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10111   // taken one instruction to materialize the v2i64 zero and one store (with
10112   // restrictive addressing mode). Just do i64 stores.
10113   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10114   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10115     if (Op.isAligned(AlignCheck))
10116       return true;
10117     bool Fast;
10118     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10119                                           &Fast) &&
10120            Fast;
10121   };
10122 
10123   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10124       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10125     return MVT::v2i64;
10126   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10127     return MVT::f128;
10128   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10129     return MVT::i64;
10130   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10131     return MVT::i32;
10132   return MVT::Other;
10133 }
10134 
10135 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10136     const MemOp &Op, const AttributeList &FuncAttributes) const {
10137   bool CanImplicitFloat =
10138       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10139   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10140   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10141   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10142   // taken one instruction to materialize the v2i64 zero and one store (with
10143   // restrictive addressing mode). Just do i64 stores.
10144   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10145   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10146     if (Op.isAligned(AlignCheck))
10147       return true;
10148     bool Fast;
10149     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10150                                           &Fast) &&
10151            Fast;
10152   };
10153 
10154   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10155       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10156     return LLT::vector(2, 64);
10157   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10158     return LLT::scalar(128);
10159   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10160     return LLT::scalar(64);
10161   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10162     return LLT::scalar(32);
10163   return LLT();
10164 }
10165 
10166 // 12-bit optionally shifted immediates are legal for adds.
10167 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10168   if (Immed == std::numeric_limits<int64_t>::min()) {
10169     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10170                       << ": avoid UB for INT64_MIN\n");
10171     return false;
10172   }
10173   // Same encoding for add/sub, just flip the sign.
10174   Immed = std::abs(Immed);
10175   bool IsLegal = ((Immed >> 12) == 0 ||
10176                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10177   LLVM_DEBUG(dbgs() << "Is " << Immed
10178                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10179   return IsLegal;
10180 }
10181 
10182 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10183 // immediates is the same as for an add or a sub.
10184 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10185   return isLegalAddImmediate(Immed);
10186 }
10187 
10188 /// isLegalAddressingMode - Return true if the addressing mode represented
10189 /// by AM is legal for this target, for a load/store of the specified type.
10190 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10191                                                   const AddrMode &AM, Type *Ty,
10192                                                   unsigned AS, Instruction *I) const {
10193   // AArch64 has five basic addressing modes:
10194   //  reg
10195   //  reg + 9-bit signed offset
10196   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
10197   //  reg1 + reg2
10198   //  reg + SIZE_IN_BYTES * reg
10199 
10200   // No global is ever allowed as a base.
10201   if (AM.BaseGV)
10202     return false;
10203 
10204   // No reg+reg+imm addressing.
10205   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10206     return false;
10207 
10208   // FIXME: Update this method to support scalable addressing modes.
10209   if (isa<ScalableVectorType>(Ty))
10210     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10211 
10212   // check reg + imm case:
10213   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10214   uint64_t NumBytes = 0;
10215   if (Ty->isSized()) {
10216     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10217     NumBytes = NumBits / 8;
10218     if (!isPowerOf2_64(NumBits))
10219       NumBytes = 0;
10220   }
10221 
10222   if (!AM.Scale) {
10223     int64_t Offset = AM.BaseOffs;
10224 
10225     // 9-bit signed offset
10226     if (isInt<9>(Offset))
10227       return true;
10228 
10229     // 12-bit unsigned offset
10230     unsigned shift = Log2_64(NumBytes);
10231     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10232         // Must be a multiple of NumBytes (NumBytes is a power of 2)
10233         (Offset >> shift) << shift == Offset)
10234       return true;
10235     return false;
10236   }
10237 
10238   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10239 
10240   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10241 }
10242 
10243 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10244   // Consider splitting large offset of struct or array.
10245   return true;
10246 }
10247 
10248 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10249                                                 const AddrMode &AM, Type *Ty,
10250                                                 unsigned AS) const {
10251   // Scaling factors are not free at all.
10252   // Operands                     | Rt Latency
10253   // -------------------------------------------
10254   // Rt, [Xn, Xm]                 | 4
10255   // -------------------------------------------
10256   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
10257   // Rt, [Xn, Wm, <extend> #imm]  |
10258   if (isLegalAddressingMode(DL, AM, Ty, AS))
10259     // Scale represents reg2 * scale, thus account for 1 if
10260     // it is not equal to 0 or 1.
10261     return AM.Scale != 0 && AM.Scale != 1;
10262   return -1;
10263 }
10264 
10265 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10266     const MachineFunction &MF, EVT VT) const {
10267   VT = VT.getScalarType();
10268 
10269   if (!VT.isSimple())
10270     return false;
10271 
10272   switch (VT.getSimpleVT().SimpleTy) {
10273   case MVT::f32:
10274   case MVT::f64:
10275     return true;
10276   default:
10277     break;
10278   }
10279 
10280   return false;
10281 }
10282 
10283 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10284                                                        Type *Ty) const {
10285   switch (Ty->getScalarType()->getTypeID()) {
10286   case Type::FloatTyID:
10287   case Type::DoubleTyID:
10288     return true;
10289   default:
10290     return false;
10291   }
10292 }
10293 
10294 const MCPhysReg *
10295 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10296   // LR is a callee-save register, but we must treat it as clobbered by any call
10297   // site. Hence we include LR in the scratch registers, which are in turn added
10298   // as implicit-defs for stackmaps and patchpoints.
10299   static const MCPhysReg ScratchRegs[] = {
10300     AArch64::X16, AArch64::X17, AArch64::LR, 0
10301   };
10302   return ScratchRegs;
10303 }
10304 
10305 bool
10306 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10307                                                      CombineLevel Level) const {
10308   N = N->getOperand(0).getNode();
10309   EVT VT = N->getValueType(0);
10310     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10311     // it with shift to let it be lowered to UBFX.
10312   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10313       isa<ConstantSDNode>(N->getOperand(1))) {
10314     uint64_t TruncMask = N->getConstantOperandVal(1);
10315     if (isMask_64(TruncMask) &&
10316       N->getOperand(0).getOpcode() == ISD::SRL &&
10317       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10318       return false;
10319   }
10320   return true;
10321 }
10322 
10323 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10324                                                               Type *Ty) const {
10325   assert(Ty->isIntegerTy());
10326 
10327   unsigned BitSize = Ty->getPrimitiveSizeInBits();
10328   if (BitSize == 0)
10329     return false;
10330 
10331   int64_t Val = Imm.getSExtValue();
10332   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10333     return true;
10334 
10335   if ((int64_t)Val < 0)
10336     Val = ~Val;
10337   if (BitSize == 32)
10338     Val &= (1LL << 32) - 1;
10339 
10340   unsigned LZ = countLeadingZeros((uint64_t)Val);
10341   unsigned Shift = (63 - LZ) / 16;
10342   // MOVZ is free so return true for one or fewer MOVK.
10343   return Shift < 3;
10344 }
10345 
10346 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10347                                                     unsigned Index) const {
10348   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10349     return false;
10350 
10351   return (Index == 0 || Index == ResVT.getVectorNumElements());
10352 }
10353 
10354 /// Turn vector tests of the signbit in the form of:
10355 ///   xor (sra X, elt_size(X)-1), -1
10356 /// into:
10357 ///   cmge X, X, #0
10358 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
10359                                          const AArch64Subtarget *Subtarget) {
10360   EVT VT = N->getValueType(0);
10361   if (!Subtarget->hasNEON() || !VT.isVector())
10362     return SDValue();
10363 
10364   // There must be a shift right algebraic before the xor, and the xor must be a
10365   // 'not' operation.
10366   SDValue Shift = N->getOperand(0);
10367   SDValue Ones = N->getOperand(1);
10368   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
10369       !ISD::isBuildVectorAllOnes(Ones.getNode()))
10370     return SDValue();
10371 
10372   // The shift should be smearing the sign bit across each vector element.
10373   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10374   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
10375   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
10376     return SDValue();
10377 
10378   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
10379 }
10380 
10381 // Generate SUBS and CSEL for integer abs.
10382 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
10383   EVT VT = N->getValueType(0);
10384 
10385   SDValue N0 = N->getOperand(0);
10386   SDValue N1 = N->getOperand(1);
10387   SDLoc DL(N);
10388 
10389   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
10390   // and change it to SUB and CSEL.
10391   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
10392       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
10393       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
10394     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
10395       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
10396         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
10397                                   N0.getOperand(0));
10398         // Generate SUBS & CSEL.
10399         SDValue Cmp =
10400             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
10401                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
10402         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
10403                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
10404                            SDValue(Cmp.getNode(), 1));
10405       }
10406   return SDValue();
10407 }
10408 
10409 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
10410                                  TargetLowering::DAGCombinerInfo &DCI,
10411                                  const AArch64Subtarget *Subtarget) {
10412   if (DCI.isBeforeLegalizeOps())
10413     return SDValue();
10414 
10415   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
10416     return Cmp;
10417 
10418   return performIntegerAbsCombine(N, DAG);
10419 }
10420 
10421 SDValue
10422 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10423                                      SelectionDAG &DAG,
10424                                      SmallVectorImpl<SDNode *> &Created) const {
10425   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10426   if (isIntDivCheap(N->getValueType(0), Attr))
10427     return SDValue(N,0); // Lower SDIV as SDIV
10428 
10429   // fold (sdiv X, pow2)
10430   EVT VT = N->getValueType(0);
10431   if ((VT != MVT::i32 && VT != MVT::i64) ||
10432       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10433     return SDValue();
10434 
10435   SDLoc DL(N);
10436   SDValue N0 = N->getOperand(0);
10437   unsigned Lg2 = Divisor.countTrailingZeros();
10438   SDValue Zero = DAG.getConstant(0, DL, VT);
10439   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10440 
10441   // Add (N0 < 0) ? Pow2 - 1 : 0;
10442   SDValue CCVal;
10443   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
10444   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10445   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
10446 
10447   Created.push_back(Cmp.getNode());
10448   Created.push_back(Add.getNode());
10449   Created.push_back(CSel.getNode());
10450 
10451   // Divide by pow2.
10452   SDValue SRA =
10453       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
10454 
10455   // If we're dividing by a positive value, we're done.  Otherwise, we must
10456   // negate the result.
10457   if (Divisor.isNonNegative())
10458     return SRA;
10459 
10460   Created.push_back(SRA.getNode());
10461   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10462 }
10463 
10464 static bool IsSVECntIntrinsic(SDValue S) {
10465   switch(getIntrinsicID(S.getNode())) {
10466   default:
10467     break;
10468   case Intrinsic::aarch64_sve_cntb:
10469   case Intrinsic::aarch64_sve_cnth:
10470   case Intrinsic::aarch64_sve_cntw:
10471   case Intrinsic::aarch64_sve_cntd:
10472     return true;
10473   }
10474   return false;
10475 }
10476 
10477 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
10478                                  TargetLowering::DAGCombinerInfo &DCI,
10479                                  const AArch64Subtarget *Subtarget) {
10480   if (DCI.isBeforeLegalizeOps())
10481     return SDValue();
10482 
10483   // The below optimizations require a constant RHS.
10484   if (!isa<ConstantSDNode>(N->getOperand(1)))
10485     return SDValue();
10486 
10487   SDValue N0 = N->getOperand(0);
10488   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
10489   const APInt &ConstValue = C->getAPIntValue();
10490 
10491   // Allow the scaling to be folded into the `cnt` instruction by preventing
10492   // the scaling to be obscured here. This makes it easier to pattern match.
10493   if (IsSVECntIntrinsic(N0) ||
10494      (N0->getOpcode() == ISD::TRUNCATE &&
10495       (IsSVECntIntrinsic(N0->getOperand(0)))))
10496        if (ConstValue.sge(1) && ConstValue.sle(16))
10497          return SDValue();
10498 
10499   // Multiplication of a power of two plus/minus one can be done more
10500   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
10501   // future CPUs have a cheaper MADD instruction, this may need to be
10502   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
10503   // 64-bit is 5 cycles, so this is always a win.
10504   // More aggressively, some multiplications N0 * C can be lowered to
10505   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
10506   // e.g. 6=3*2=(2+1)*2.
10507   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
10508   // which equals to (1+2)*16-(1+2).
10509   // TrailingZeroes is used to test if the mul can be lowered to
10510   // shift+add+shift.
10511   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10512   if (TrailingZeroes) {
10513     // Conservatively do not lower to shift+add+shift if the mul might be
10514     // folded into smul or umul.
10515     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10516                             isZeroExtended(N0.getNode(), DAG)))
10517       return SDValue();
10518     // Conservatively do not lower to shift+add+shift if the mul might be
10519     // folded into madd or msub.
10520     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10521                            N->use_begin()->getOpcode() == ISD::SUB))
10522       return SDValue();
10523   }
10524   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10525   // and shift+add+shift.
10526   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10527 
10528   unsigned ShiftAmt, AddSubOpc;
10529   // Is the shifted value the LHS operand of the add/sub?
10530   bool ShiftValUseIsN0 = true;
10531   // Do we need to negate the result?
10532   bool NegateResult = false;
10533 
10534   if (ConstValue.isNonNegative()) {
10535     // (mul x, 2^N + 1) => (add (shl x, N), x)
10536     // (mul x, 2^N - 1) => (sub (shl x, N), x)
10537     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10538     APInt SCVMinus1 = ShiftedConstValue - 1;
10539     APInt CVPlus1 = ConstValue + 1;
10540     if (SCVMinus1.isPowerOf2()) {
10541       ShiftAmt = SCVMinus1.logBase2();
10542       AddSubOpc = ISD::ADD;
10543     } else if (CVPlus1.isPowerOf2()) {
10544       ShiftAmt = CVPlus1.logBase2();
10545       AddSubOpc = ISD::SUB;
10546     } else
10547       return SDValue();
10548   } else {
10549     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10550     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10551     APInt CVNegPlus1 = -ConstValue + 1;
10552     APInt CVNegMinus1 = -ConstValue - 1;
10553     if (CVNegPlus1.isPowerOf2()) {
10554       ShiftAmt = CVNegPlus1.logBase2();
10555       AddSubOpc = ISD::SUB;
10556       ShiftValUseIsN0 = false;
10557     } else if (CVNegMinus1.isPowerOf2()) {
10558       ShiftAmt = CVNegMinus1.logBase2();
10559       AddSubOpc = ISD::ADD;
10560       NegateResult = true;
10561     } else
10562       return SDValue();
10563   }
10564 
10565   SDLoc DL(N);
10566   EVT VT = N->getValueType(0);
10567   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10568                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
10569 
10570   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10571   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10572   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10573   assert(!(NegateResult && TrailingZeroes) &&
10574          "NegateResult and TrailingZeroes cannot both be true for now.");
10575   // Negate the result.
10576   if (NegateResult)
10577     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10578   // Shift the result.
10579   if (TrailingZeroes)
10580     return DAG.getNode(ISD::SHL, DL, VT, Res,
10581                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10582   return Res;
10583 }
10584 
10585 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10586                                                          SelectionDAG &DAG) {
10587   // Take advantage of vector comparisons producing 0 or -1 in each lane to
10588   // optimize away operation when it's from a constant.
10589   //
10590   // The general transformation is:
10591   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10592   //       AND(VECTOR_CMP(x,y), constant2)
10593   //    constant2 = UNARYOP(constant)
10594 
10595   // Early exit if this isn't a vector operation, the operand of the
10596   // unary operation isn't a bitwise AND, or if the sizes of the operations
10597   // aren't the same.
10598   EVT VT = N->getValueType(0);
10599   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10600       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10601       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10602     return SDValue();
10603 
10604   // Now check that the other operand of the AND is a constant. We could
10605   // make the transformation for non-constant splats as well, but it's unclear
10606   // that would be a benefit as it would not eliminate any operations, just
10607   // perform one more step in scalar code before moving to the vector unit.
10608   if (BuildVectorSDNode *BV =
10609           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10610     // Bail out if the vector isn't a constant.
10611     if (!BV->isConstant())
10612       return SDValue();
10613 
10614     // Everything checks out. Build up the new and improved node.
10615     SDLoc DL(N);
10616     EVT IntVT = BV->getValueType(0);
10617     // Create a new constant of the appropriate type for the transformed
10618     // DAG.
10619     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10620     // The AND node needs bitcasts to/from an integer vector type around it.
10621     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10622     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10623                                  N->getOperand(0)->getOperand(0), MaskConst);
10624     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10625     return Res;
10626   }
10627 
10628   return SDValue();
10629 }
10630 
10631 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10632                                      const AArch64Subtarget *Subtarget) {
10633   // First try to optimize away the conversion when it's conditionally from
10634   // a constant. Vectors only.
10635   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10636     return Res;
10637 
10638   EVT VT = N->getValueType(0);
10639   if (VT != MVT::f32 && VT != MVT::f64)
10640     return SDValue();
10641 
10642   // Only optimize when the source and destination types have the same width.
10643   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10644     return SDValue();
10645 
10646   // If the result of an integer load is only used by an integer-to-float
10647   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10648   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10649   SDValue N0 = N->getOperand(0);
10650   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10651       // Do not change the width of a volatile load.
10652       !cast<LoadSDNode>(N0)->isVolatile()) {
10653     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10654     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10655                                LN0->getPointerInfo(), LN0->getAlignment(),
10656                                LN0->getMemOperand()->getFlags());
10657 
10658     // Make sure successors of the original load stay after it by updating them
10659     // to use the new Chain.
10660     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10661 
10662     unsigned Opcode =
10663         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10664     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10665   }
10666 
10667   return SDValue();
10668 }
10669 
10670 /// Fold a floating-point multiply by power of two into floating-point to
10671 /// fixed-point conversion.
10672 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10673                                      TargetLowering::DAGCombinerInfo &DCI,
10674                                      const AArch64Subtarget *Subtarget) {
10675   if (!Subtarget->hasNEON())
10676     return SDValue();
10677 
10678   if (!N->getValueType(0).isSimple())
10679     return SDValue();
10680 
10681   SDValue Op = N->getOperand(0);
10682   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10683       Op.getOpcode() != ISD::FMUL)
10684     return SDValue();
10685 
10686   SDValue ConstVec = Op->getOperand(1);
10687   if (!isa<BuildVectorSDNode>(ConstVec))
10688     return SDValue();
10689 
10690   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10691   uint32_t FloatBits = FloatTy.getSizeInBits();
10692   if (FloatBits != 32 && FloatBits != 64)
10693     return SDValue();
10694 
10695   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10696   uint32_t IntBits = IntTy.getSizeInBits();
10697   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10698     return SDValue();
10699 
10700   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10701   if (IntBits > FloatBits)
10702     return SDValue();
10703 
10704   BitVector UndefElements;
10705   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10706   int32_t Bits = IntBits == 64 ? 64 : 32;
10707   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10708   if (C == -1 || C == 0 || C > Bits)
10709     return SDValue();
10710 
10711   MVT ResTy;
10712   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10713   switch (NumLanes) {
10714   default:
10715     return SDValue();
10716   case 2:
10717     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10718     break;
10719   case 4:
10720     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10721     break;
10722   }
10723 
10724   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10725     return SDValue();
10726 
10727   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10728          "Illegal vector type after legalization");
10729 
10730   SDLoc DL(N);
10731   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10732   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10733                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10734   SDValue FixConv =
10735       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10736                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10737                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10738   // We can handle smaller integers by generating an extra trunc.
10739   if (IntBits < FloatBits)
10740     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10741 
10742   return FixConv;
10743 }
10744 
10745 /// Fold a floating-point divide by power of two into fixed-point to
10746 /// floating-point conversion.
10747 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10748                                   TargetLowering::DAGCombinerInfo &DCI,
10749                                   const AArch64Subtarget *Subtarget) {
10750   if (!Subtarget->hasNEON())
10751     return SDValue();
10752 
10753   SDValue Op = N->getOperand(0);
10754   unsigned Opc = Op->getOpcode();
10755   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10756       !Op.getOperand(0).getValueType().isSimple() ||
10757       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10758     return SDValue();
10759 
10760   SDValue ConstVec = N->getOperand(1);
10761   if (!isa<BuildVectorSDNode>(ConstVec))
10762     return SDValue();
10763 
10764   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10765   int32_t IntBits = IntTy.getSizeInBits();
10766   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10767     return SDValue();
10768 
10769   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10770   int32_t FloatBits = FloatTy.getSizeInBits();
10771   if (FloatBits != 32 && FloatBits != 64)
10772     return SDValue();
10773 
10774   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10775   if (IntBits > FloatBits)
10776     return SDValue();
10777 
10778   BitVector UndefElements;
10779   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10780   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10781   if (C == -1 || C == 0 || C > FloatBits)
10782     return SDValue();
10783 
10784   MVT ResTy;
10785   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10786   switch (NumLanes) {
10787   default:
10788     return SDValue();
10789   case 2:
10790     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10791     break;
10792   case 4:
10793     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10794     break;
10795   }
10796 
10797   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10798     return SDValue();
10799 
10800   SDLoc DL(N);
10801   SDValue ConvInput = Op.getOperand(0);
10802   bool IsSigned = Opc == ISD::SINT_TO_FP;
10803   if (IntBits < FloatBits)
10804     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10805                             ResTy, ConvInput);
10806 
10807   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10808                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10809   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10810                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10811                      DAG.getConstant(C, DL, MVT::i32));
10812 }
10813 
10814 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10815 /// searches for and classifies those shifts.
10816 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10817                          bool &FromHi) {
10818   if (N.getOpcode() == ISD::SHL)
10819     FromHi = false;
10820   else if (N.getOpcode() == ISD::SRL)
10821     FromHi = true;
10822   else
10823     return false;
10824 
10825   if (!isa<ConstantSDNode>(N.getOperand(1)))
10826     return false;
10827 
10828   ShiftAmount = N->getConstantOperandVal(1);
10829   Src = N->getOperand(0);
10830   return true;
10831 }
10832 
10833 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10834 /// registers viewed as a high/low pair. This function looks for the pattern:
10835 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10836 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10837 /// aren't independent.
10838 static SDValue tryCombineToEXTR(SDNode *N,
10839                                 TargetLowering::DAGCombinerInfo &DCI) {
10840   SelectionDAG &DAG = DCI.DAG;
10841   SDLoc DL(N);
10842   EVT VT = N->getValueType(0);
10843 
10844   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10845 
10846   if (VT != MVT::i32 && VT != MVT::i64)
10847     return SDValue();
10848 
10849   SDValue LHS;
10850   uint32_t ShiftLHS = 0;
10851   bool LHSFromHi = false;
10852   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10853     return SDValue();
10854 
10855   SDValue RHS;
10856   uint32_t ShiftRHS = 0;
10857   bool RHSFromHi = false;
10858   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10859     return SDValue();
10860 
10861   // If they're both trying to come from the high part of the register, they're
10862   // not really an EXTR.
10863   if (LHSFromHi == RHSFromHi)
10864     return SDValue();
10865 
10866   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10867     return SDValue();
10868 
10869   if (LHSFromHi) {
10870     std::swap(LHS, RHS);
10871     std::swap(ShiftLHS, ShiftRHS);
10872   }
10873 
10874   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10875                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10876 }
10877 
10878 static SDValue tryCombineToBSL(SDNode *N,
10879                                 TargetLowering::DAGCombinerInfo &DCI) {
10880   EVT VT = N->getValueType(0);
10881   SelectionDAG &DAG = DCI.DAG;
10882   SDLoc DL(N);
10883 
10884   if (!VT.isVector())
10885     return SDValue();
10886 
10887   SDValue N0 = N->getOperand(0);
10888   if (N0.getOpcode() != ISD::AND)
10889     return SDValue();
10890 
10891   SDValue N1 = N->getOperand(1);
10892   if (N1.getOpcode() != ISD::AND)
10893     return SDValue();
10894 
10895   // We only have to look for constant vectors here since the general, variable
10896   // case can be handled in TableGen.
10897   unsigned Bits = VT.getScalarSizeInBits();
10898   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10899   for (int i = 1; i >= 0; --i)
10900     for (int j = 1; j >= 0; --j) {
10901       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10902       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10903       if (!BVN0 || !BVN1)
10904         continue;
10905 
10906       bool FoundMatch = true;
10907       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10908         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10909         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10910         if (!CN0 || !CN1 ||
10911             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10912           FoundMatch = false;
10913           break;
10914         }
10915       }
10916 
10917       if (FoundMatch)
10918         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
10919                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10920     }
10921 
10922   return SDValue();
10923 }
10924 
10925 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10926                                 const AArch64Subtarget *Subtarget) {
10927   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10928   SelectionDAG &DAG = DCI.DAG;
10929   EVT VT = N->getValueType(0);
10930 
10931   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10932     return SDValue();
10933 
10934   if (SDValue Res = tryCombineToEXTR(N, DCI))
10935     return Res;
10936 
10937   if (SDValue Res = tryCombineToBSL(N, DCI))
10938     return Res;
10939 
10940   return SDValue();
10941 }
10942 
10943 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10944   if (!MemVT.getVectorElementType().isSimple())
10945     return false;
10946 
10947   uint64_t MaskForTy = 0ull;
10948   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10949   case MVT::i8:
10950     MaskForTy = 0xffull;
10951     break;
10952   case MVT::i16:
10953     MaskForTy = 0xffffull;
10954     break;
10955   case MVT::i32:
10956     MaskForTy = 0xffffffffull;
10957     break;
10958   default:
10959     return false;
10960     break;
10961   }
10962 
10963   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10964     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10965       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10966 
10967   return false;
10968 }
10969 
10970 static SDValue performSVEAndCombine(SDNode *N,
10971                                     TargetLowering::DAGCombinerInfo &DCI) {
10972   if (DCI.isBeforeLegalizeOps())
10973     return SDValue();
10974 
10975   SelectionDAG &DAG = DCI.DAG;
10976   SDValue Src = N->getOperand(0);
10977   unsigned Opc = Src->getOpcode();
10978 
10979   // Zero/any extend of an unsigned unpack
10980   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
10981     SDValue UnpkOp = Src->getOperand(0);
10982     SDValue Dup = N->getOperand(1);
10983 
10984     if (Dup.getOpcode() != AArch64ISD::DUP)
10985       return SDValue();
10986 
10987     SDLoc DL(N);
10988     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
10989     uint64_t ExtVal = C->getZExtValue();
10990 
10991     // If the mask is fully covered by the unpack, we don't need to push
10992     // a new AND onto the operand
10993     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
10994     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
10995         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
10996         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
10997       return Src;
10998 
10999     // Truncate to prevent a DUP with an over wide constant
11000     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11001 
11002     // Otherwise, make sure we propagate the AND to the operand
11003     // of the unpack
11004     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11005                       UnpkOp->getValueType(0),
11006                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11007 
11008     SDValue And = DAG.getNode(ISD::AND, DL,
11009                               UnpkOp->getValueType(0), UnpkOp, Dup);
11010 
11011     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11012   }
11013 
11014   SDValue Mask = N->getOperand(1);
11015 
11016   if (!Src.hasOneUse())
11017     return SDValue();
11018 
11019   EVT MemVT;
11020 
11021   // SVE load instructions perform an implicit zero-extend, which makes them
11022   // perfect candidates for combining.
11023   switch (Opc) {
11024   case AArch64ISD::LD1_MERGE_ZERO:
11025   case AArch64ISD::LDNF1_MERGE_ZERO:
11026   case AArch64ISD::LDFF1_MERGE_ZERO:
11027     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11028     break;
11029   case AArch64ISD::GLD1_MERGE_ZERO:
11030   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11031   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11032   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11033   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11034   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11035   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11036   case AArch64ISD::GLDFF1_MERGE_ZERO:
11037   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11038   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11039   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11040   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11041   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11042   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11043   case AArch64ISD::GLDNT1_MERGE_ZERO:
11044     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11045     break;
11046   default:
11047     return SDValue();
11048   }
11049 
11050   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11051     return Src;
11052 
11053   return SDValue();
11054 }
11055 
11056 static SDValue performANDCombine(SDNode *N,
11057                                  TargetLowering::DAGCombinerInfo &DCI) {
11058   SelectionDAG &DAG = DCI.DAG;
11059   SDValue LHS = N->getOperand(0);
11060   EVT VT = N->getValueType(0);
11061   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11062     return SDValue();
11063 
11064   if (VT.isScalableVector())
11065     return performSVEAndCombine(N, DCI);
11066 
11067   BuildVectorSDNode *BVN =
11068       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11069   if (!BVN)
11070     return SDValue();
11071 
11072   // AND does not accept an immediate, so check if we can use a BIC immediate
11073   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11074   // pattern in isel, because some immediates may be lowered to the preferred
11075   // (and x, (movi imm)) form, even though an mvni representation also exists.
11076   APInt DefBits(VT.getSizeInBits(), 0);
11077   APInt UndefBits(VT.getSizeInBits(), 0);
11078   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11079     SDValue NewOp;
11080 
11081     DefBits = ~DefBits;
11082     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11083                                     DefBits, &LHS)) ||
11084         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11085                                     DefBits, &LHS)))
11086       return NewOp;
11087 
11088     UndefBits = ~UndefBits;
11089     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11090                                     UndefBits, &LHS)) ||
11091         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11092                                     UndefBits, &LHS)))
11093       return NewOp;
11094   }
11095 
11096   return SDValue();
11097 }
11098 
11099 static SDValue performSRLCombine(SDNode *N,
11100                                  TargetLowering::DAGCombinerInfo &DCI) {
11101   SelectionDAG &DAG = DCI.DAG;
11102   EVT VT = N->getValueType(0);
11103   if (VT != MVT::i32 && VT != MVT::i64)
11104     return SDValue();
11105 
11106   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11107   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11108   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11109   SDValue N0 = N->getOperand(0);
11110   if (N0.getOpcode() == ISD::BSWAP) {
11111     SDLoc DL(N);
11112     SDValue N1 = N->getOperand(1);
11113     SDValue N00 = N0.getOperand(0);
11114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11115       uint64_t ShiftAmt = C->getZExtValue();
11116       if (VT == MVT::i32 && ShiftAmt == 16 &&
11117           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11118         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11119       if (VT == MVT::i64 && ShiftAmt == 32 &&
11120           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11121         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11122     }
11123   }
11124   return SDValue();
11125 }
11126 
11127 static SDValue performConcatVectorsCombine(SDNode *N,
11128                                            TargetLowering::DAGCombinerInfo &DCI,
11129                                            SelectionDAG &DAG) {
11130   SDLoc dl(N);
11131   EVT VT = N->getValueType(0);
11132   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11133   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11134 
11135   // Optimize concat_vectors of truncated vectors, where the intermediate
11136   // type is illegal, to avoid said illegality,  e.g.,
11137   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11138   //                          (v2i16 (truncate (v2i64)))))
11139   // ->
11140   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11141   //                                    (v4i32 (bitcast (v2i64))),
11142   //                                    <0, 2, 4, 6>)))
11143   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
11144   // on both input and result type, so we might generate worse code.
11145   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
11146   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
11147       N1Opc == ISD::TRUNCATE) {
11148     SDValue N00 = N0->getOperand(0);
11149     SDValue N10 = N1->getOperand(0);
11150     EVT N00VT = N00.getValueType();
11151 
11152     if (N00VT == N10.getValueType() &&
11153         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
11154         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
11155       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
11156       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
11157       for (size_t i = 0; i < Mask.size(); ++i)
11158         Mask[i] = i * 2;
11159       return DAG.getNode(ISD::TRUNCATE, dl, VT,
11160                          DAG.getVectorShuffle(
11161                              MidVT, dl,
11162                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
11163                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
11164     }
11165   }
11166 
11167   // Wait 'til after everything is legalized to try this. That way we have
11168   // legal vector types and such.
11169   if (DCI.isBeforeLegalizeOps())
11170     return SDValue();
11171 
11172   // Optimise concat_vectors of two [us]rhadds that use extracted subvectors
11173   // from the same original vectors. Combine these into a single [us]rhadd that
11174   // operates on the two original vectors. Example:
11175   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
11176   //                                        extract_subvector (v16i8 OpB,
11177   //                                        <0>))),
11178   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
11179   //                                        extract_subvector (v16i8 OpB,
11180   //                                        <8>)))))
11181   // ->
11182   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
11183   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
11184       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD)) {
11185     SDValue N00 = N0->getOperand(0);
11186     SDValue N01 = N0->getOperand(1);
11187     SDValue N10 = N1->getOperand(0);
11188     SDValue N11 = N1->getOperand(1);
11189 
11190     EVT N00VT = N00.getValueType();
11191     EVT N10VT = N10.getValueType();
11192 
11193     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11194         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11195         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11196         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
11197       SDValue N00Source = N00->getOperand(0);
11198       SDValue N01Source = N01->getOperand(0);
11199       SDValue N10Source = N10->getOperand(0);
11200       SDValue N11Source = N11->getOperand(0);
11201 
11202       if (N00Source == N10Source && N01Source == N11Source &&
11203           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
11204         assert(N0.getValueType() == N1.getValueType());
11205 
11206         uint64_t N00Index = N00.getConstantOperandVal(1);
11207         uint64_t N01Index = N01.getConstantOperandVal(1);
11208         uint64_t N10Index = N10.getConstantOperandVal(1);
11209         uint64_t N11Index = N11.getConstantOperandVal(1);
11210 
11211         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
11212             N10Index == N00VT.getVectorNumElements())
11213           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
11214       }
11215     }
11216   }
11217 
11218   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
11219   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
11220   // canonicalise to that.
11221   if (N0 == N1 && VT.getVectorNumElements() == 2) {
11222     assert(VT.getScalarSizeInBits() == 64);
11223     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
11224                        DAG.getConstant(0, dl, MVT::i64));
11225   }
11226 
11227   // Canonicalise concat_vectors so that the right-hand vector has as few
11228   // bit-casts as possible before its real operation. The primary matching
11229   // destination for these operations will be the narrowing "2" instructions,
11230   // which depend on the operation being performed on this right-hand vector.
11231   // For example,
11232   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
11233   // becomes
11234   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
11235 
11236   if (N1Opc != ISD::BITCAST)
11237     return SDValue();
11238   SDValue RHS = N1->getOperand(0);
11239   MVT RHSTy = RHS.getValueType().getSimpleVT();
11240   // If the RHS is not a vector, this is not the pattern we're looking for.
11241   if (!RHSTy.isVector())
11242     return SDValue();
11243 
11244   LLVM_DEBUG(
11245       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
11246 
11247   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
11248                                   RHSTy.getVectorNumElements() * 2);
11249   return DAG.getNode(ISD::BITCAST, dl, VT,
11250                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
11251                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
11252                                  RHS));
11253 }
11254 
11255 static SDValue tryCombineFixedPointConvert(SDNode *N,
11256                                            TargetLowering::DAGCombinerInfo &DCI,
11257                                            SelectionDAG &DAG) {
11258   // Wait until after everything is legalized to try this. That way we have
11259   // legal vector types and such.
11260   if (DCI.isBeforeLegalizeOps())
11261     return SDValue();
11262   // Transform a scalar conversion of a value from a lane extract into a
11263   // lane extract of a vector conversion. E.g., from foo1 to foo2:
11264   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
11265   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
11266   //
11267   // The second form interacts better with instruction selection and the
11268   // register allocator to avoid cross-class register copies that aren't
11269   // coalescable due to a lane reference.
11270 
11271   // Check the operand and see if it originates from a lane extract.
11272   SDValue Op1 = N->getOperand(1);
11273   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11274     // Yep, no additional predication needed. Perform the transform.
11275     SDValue IID = N->getOperand(0);
11276     SDValue Shift = N->getOperand(2);
11277     SDValue Vec = Op1.getOperand(0);
11278     SDValue Lane = Op1.getOperand(1);
11279     EVT ResTy = N->getValueType(0);
11280     EVT VecResTy;
11281     SDLoc DL(N);
11282 
11283     // The vector width should be 128 bits by the time we get here, even
11284     // if it started as 64 bits (the extract_vector handling will have
11285     // done so).
11286     assert(Vec.getValueSizeInBits() == 128 &&
11287            "unexpected vector size on extract_vector_elt!");
11288     if (Vec.getValueType() == MVT::v4i32)
11289       VecResTy = MVT::v4f32;
11290     else if (Vec.getValueType() == MVT::v2i64)
11291       VecResTy = MVT::v2f64;
11292     else
11293       llvm_unreachable("unexpected vector type!");
11294 
11295     SDValue Convert =
11296         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
11297     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
11298   }
11299   return SDValue();
11300 }
11301 
11302 // AArch64 high-vector "long" operations are formed by performing the non-high
11303 // version on an extract_subvector of each operand which gets the high half:
11304 //
11305 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
11306 //
11307 // However, there are cases which don't have an extract_high explicitly, but
11308 // have another operation that can be made compatible with one for free. For
11309 // example:
11310 //
11311 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
11312 //
11313 // This routine does the actual conversion of such DUPs, once outer routines
11314 // have determined that everything else is in order.
11315 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
11316 // similarly here.
11317 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
11318   switch (N.getOpcode()) {
11319   case AArch64ISD::DUP:
11320   case AArch64ISD::DUPLANE8:
11321   case AArch64ISD::DUPLANE16:
11322   case AArch64ISD::DUPLANE32:
11323   case AArch64ISD::DUPLANE64:
11324   case AArch64ISD::MOVI:
11325   case AArch64ISD::MOVIshift:
11326   case AArch64ISD::MOVIedit:
11327   case AArch64ISD::MOVImsl:
11328   case AArch64ISD::MVNIshift:
11329   case AArch64ISD::MVNImsl:
11330     break;
11331   default:
11332     // FMOV could be supported, but isn't very useful, as it would only occur
11333     // if you passed a bitcast' floating point immediate to an eligible long
11334     // integer op (addl, smull, ...).
11335     return SDValue();
11336   }
11337 
11338   MVT NarrowTy = N.getSimpleValueType();
11339   if (!NarrowTy.is64BitVector())
11340     return SDValue();
11341 
11342   MVT ElementTy = NarrowTy.getVectorElementType();
11343   unsigned NumElems = NarrowTy.getVectorNumElements();
11344   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
11345 
11346   SDLoc dl(N);
11347   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
11348                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
11349                      DAG.getConstant(NumElems, dl, MVT::i64));
11350 }
11351 
11352 static bool isEssentiallyExtractHighSubvector(SDValue N) {
11353   if (N.getOpcode() == ISD::BITCAST)
11354     N = N.getOperand(0);
11355   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11356     return false;
11357   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
11358          N.getOperand(0).getValueType().getVectorNumElements() / 2;
11359 }
11360 
11361 /// Helper structure to keep track of ISD::SET_CC operands.
11362 struct GenericSetCCInfo {
11363   const SDValue *Opnd0;
11364   const SDValue *Opnd1;
11365   ISD::CondCode CC;
11366 };
11367 
11368 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
11369 struct AArch64SetCCInfo {
11370   const SDValue *Cmp;
11371   AArch64CC::CondCode CC;
11372 };
11373 
11374 /// Helper structure to keep track of SetCC information.
11375 union SetCCInfo {
11376   GenericSetCCInfo Generic;
11377   AArch64SetCCInfo AArch64;
11378 };
11379 
11380 /// Helper structure to be able to read SetCC information.  If set to
11381 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
11382 /// GenericSetCCInfo.
11383 struct SetCCInfoAndKind {
11384   SetCCInfo Info;
11385   bool IsAArch64;
11386 };
11387 
11388 /// Check whether or not \p Op is a SET_CC operation, either a generic or
11389 /// an
11390 /// AArch64 lowered one.
11391 /// \p SetCCInfo is filled accordingly.
11392 /// \post SetCCInfo is meanginfull only when this function returns true.
11393 /// \return True when Op is a kind of SET_CC operation.
11394 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
11395   // If this is a setcc, this is straight forward.
11396   if (Op.getOpcode() == ISD::SETCC) {
11397     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
11398     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
11399     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11400     SetCCInfo.IsAArch64 = false;
11401     return true;
11402   }
11403   // Otherwise, check if this is a matching csel instruction.
11404   // In other words:
11405   // - csel 1, 0, cc
11406   // - csel 0, 1, !cc
11407   if (Op.getOpcode() != AArch64ISD::CSEL)
11408     return false;
11409   // Set the information about the operands.
11410   // TODO: we want the operands of the Cmp not the csel
11411   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
11412   SetCCInfo.IsAArch64 = true;
11413   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
11414       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11415 
11416   // Check that the operands matches the constraints:
11417   // (1) Both operands must be constants.
11418   // (2) One must be 1 and the other must be 0.
11419   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
11420   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11421 
11422   // Check (1).
11423   if (!TValue || !FValue)
11424     return false;
11425 
11426   // Check (2).
11427   if (!TValue->isOne()) {
11428     // Update the comparison when we are interested in !cc.
11429     std::swap(TValue, FValue);
11430     SetCCInfo.Info.AArch64.CC =
11431         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
11432   }
11433   return TValue->isOne() && FValue->isNullValue();
11434 }
11435 
11436 // Returns true if Op is setcc or zext of setcc.
11437 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
11438   if (isSetCC(Op, Info))
11439     return true;
11440   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
11441     isSetCC(Op->getOperand(0), Info));
11442 }
11443 
11444 // The folding we want to perform is:
11445 // (add x, [zext] (setcc cc ...) )
11446 //   -->
11447 // (csel x, (add x, 1), !cc ...)
11448 //
11449 // The latter will get matched to a CSINC instruction.
11450 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
11451   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
11452   SDValue LHS = Op->getOperand(0);
11453   SDValue RHS = Op->getOperand(1);
11454   SetCCInfoAndKind InfoAndKind;
11455 
11456   // If neither operand is a SET_CC, give up.
11457   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
11458     std::swap(LHS, RHS);
11459     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
11460       return SDValue();
11461   }
11462 
11463   // FIXME: This could be generatized to work for FP comparisons.
11464   EVT CmpVT = InfoAndKind.IsAArch64
11465                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
11466                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
11467   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
11468     return SDValue();
11469 
11470   SDValue CCVal;
11471   SDValue Cmp;
11472   SDLoc dl(Op);
11473   if (InfoAndKind.IsAArch64) {
11474     CCVal = DAG.getConstant(
11475         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
11476         MVT::i32);
11477     Cmp = *InfoAndKind.Info.AArch64.Cmp;
11478   } else
11479     Cmp = getAArch64Cmp(
11480         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
11481         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
11482         dl);
11483 
11484   EVT VT = Op->getValueType(0);
11485   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
11486   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
11487 }
11488 
11489 // The basic add/sub long vector instructions have variants with "2" on the end
11490 // which act on the high-half of their inputs. They are normally matched by
11491 // patterns like:
11492 //
11493 // (add (zeroext (extract_high LHS)),
11494 //      (zeroext (extract_high RHS)))
11495 // -> uaddl2 vD, vN, vM
11496 //
11497 // However, if one of the extracts is something like a duplicate, this
11498 // instruction can still be used profitably. This function puts the DAG into a
11499 // more appropriate form for those patterns to trigger.
11500 static SDValue performAddSubLongCombine(SDNode *N,
11501                                         TargetLowering::DAGCombinerInfo &DCI,
11502                                         SelectionDAG &DAG) {
11503   if (DCI.isBeforeLegalizeOps())
11504     return SDValue();
11505 
11506   MVT VT = N->getSimpleValueType(0);
11507   if (!VT.is128BitVector()) {
11508     if (N->getOpcode() == ISD::ADD)
11509       return performSetccAddFolding(N, DAG);
11510     return SDValue();
11511   }
11512 
11513   // Make sure both branches are extended in the same way.
11514   SDValue LHS = N->getOperand(0);
11515   SDValue RHS = N->getOperand(1);
11516   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
11517        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
11518       LHS.getOpcode() != RHS.getOpcode())
11519     return SDValue();
11520 
11521   unsigned ExtType = LHS.getOpcode();
11522 
11523   // It's not worth doing if at least one of the inputs isn't already an
11524   // extract, but we don't know which it'll be so we have to try both.
11525   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
11526     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
11527     if (!RHS.getNode())
11528       return SDValue();
11529 
11530     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
11531   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
11532     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
11533     if (!LHS.getNode())
11534       return SDValue();
11535 
11536     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
11537   }
11538 
11539   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
11540 }
11541 
11542 // Massage DAGs which we can use the high-half "long" operations on into
11543 // something isel will recognize better. E.g.
11544 //
11545 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
11546 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
11547 //                     (extract_high (v2i64 (dup128 scalar)))))
11548 //
11549 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
11550                                        TargetLowering::DAGCombinerInfo &DCI,
11551                                        SelectionDAG &DAG) {
11552   if (DCI.isBeforeLegalizeOps())
11553     return SDValue();
11554 
11555   SDValue LHS = N->getOperand(1);
11556   SDValue RHS = N->getOperand(2);
11557   assert(LHS.getValueType().is64BitVector() &&
11558          RHS.getValueType().is64BitVector() &&
11559          "unexpected shape for long operation");
11560 
11561   // Either node could be a DUP, but it's not worth doing both of them (you'd
11562   // just as well use the non-high version) so look for a corresponding extract
11563   // operation on the other "wing".
11564   if (isEssentiallyExtractHighSubvector(LHS)) {
11565     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
11566     if (!RHS.getNode())
11567       return SDValue();
11568   } else if (isEssentiallyExtractHighSubvector(RHS)) {
11569     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
11570     if (!LHS.getNode())
11571       return SDValue();
11572   }
11573 
11574   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
11575                      N->getOperand(0), LHS, RHS);
11576 }
11577 
11578 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
11579   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
11580   unsigned ElemBits = ElemTy.getSizeInBits();
11581 
11582   int64_t ShiftAmount;
11583   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
11584     APInt SplatValue, SplatUndef;
11585     unsigned SplatBitSize;
11586     bool HasAnyUndefs;
11587     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11588                               HasAnyUndefs, ElemBits) ||
11589         SplatBitSize != ElemBits)
11590       return SDValue();
11591 
11592     ShiftAmount = SplatValue.getSExtValue();
11593   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
11594     ShiftAmount = CVN->getSExtValue();
11595   } else
11596     return SDValue();
11597 
11598   unsigned Opcode;
11599   bool IsRightShift;
11600   switch (IID) {
11601   default:
11602     llvm_unreachable("Unknown shift intrinsic");
11603   case Intrinsic::aarch64_neon_sqshl:
11604     Opcode = AArch64ISD::SQSHL_I;
11605     IsRightShift = false;
11606     break;
11607   case Intrinsic::aarch64_neon_uqshl:
11608     Opcode = AArch64ISD::UQSHL_I;
11609     IsRightShift = false;
11610     break;
11611   case Intrinsic::aarch64_neon_srshl:
11612     Opcode = AArch64ISD::SRSHR_I;
11613     IsRightShift = true;
11614     break;
11615   case Intrinsic::aarch64_neon_urshl:
11616     Opcode = AArch64ISD::URSHR_I;
11617     IsRightShift = true;
11618     break;
11619   case Intrinsic::aarch64_neon_sqshlu:
11620     Opcode = AArch64ISD::SQSHLU_I;
11621     IsRightShift = false;
11622     break;
11623   case Intrinsic::aarch64_neon_sshl:
11624   case Intrinsic::aarch64_neon_ushl:
11625     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11626     // left shift for positive shift amounts. Below, we only replace the current
11627     // node with VSHL, if this condition is met.
11628     Opcode = AArch64ISD::VSHL;
11629     IsRightShift = false;
11630     break;
11631   }
11632 
11633   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11634     SDLoc dl(N);
11635     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11636                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11637   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11638     SDLoc dl(N);
11639     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11640                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
11641   }
11642 
11643   return SDValue();
11644 }
11645 
11646 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11647 // the intrinsics must be legal and take an i32, this means there's almost
11648 // certainly going to be a zext in the DAG which we can eliminate.
11649 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11650   SDValue AndN = N->getOperand(2);
11651   if (AndN.getOpcode() != ISD::AND)
11652     return SDValue();
11653 
11654   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11655   if (!CMask || CMask->getZExtValue() != Mask)
11656     return SDValue();
11657 
11658   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11659                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11660 }
11661 
11662 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11663                                            SelectionDAG &DAG) {
11664   SDLoc dl(N);
11665   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11666                      DAG.getNode(Opc, dl,
11667                                  N->getOperand(1).getSimpleValueType(),
11668                                  N->getOperand(1)),
11669                      DAG.getConstant(0, dl, MVT::i64));
11670 }
11671 
11672 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11673                                     SelectionDAG &DAG) {
11674   SDLoc dl(N);
11675   LLVMContext &Ctx = *DAG.getContext();
11676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11677 
11678   EVT VT = N->getValueType(0);
11679   SDValue Pred = N->getOperand(1);
11680   SDValue Data = N->getOperand(2);
11681   EVT DataVT = Data.getValueType();
11682 
11683   if (DataVT.getVectorElementType().isScalarInteger() &&
11684       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11685     if (!TLI.isTypeLegal(DataVT))
11686       return SDValue();
11687 
11688     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11689       AArch64::NeonBitsPerVector / VT.getSizeInBits());
11690     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11691     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11692     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11693 
11694     return Result;
11695   }
11696 
11697   return SDValue();
11698 }
11699 
11700 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11701   SDLoc DL(N);
11702   SDValue Op1 = N->getOperand(1);
11703   SDValue Op2 = N->getOperand(2);
11704   EVT ScalarTy = Op1.getValueType();
11705 
11706   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11707     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11708     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11709   }
11710 
11711   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11712                      Op1, Op2);
11713 }
11714 
11715 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11716   SDLoc dl(N);
11717   SDValue Scalar = N->getOperand(3);
11718   EVT ScalarTy = Scalar.getValueType();
11719 
11720   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11721     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11722 
11723   SDValue Passthru = N->getOperand(1);
11724   SDValue Pred = N->getOperand(2);
11725   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
11726                      Pred, Scalar, Passthru);
11727 }
11728 
11729 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11730   SDLoc dl(N);
11731   LLVMContext &Ctx = *DAG.getContext();
11732   EVT VT = N->getValueType(0);
11733 
11734   assert(VT.isScalableVector() && "Expected a scalable vector.");
11735 
11736   // Current lowering only supports the SVE-ACLE types.
11737   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11738     return SDValue();
11739 
11740   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11741   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11742   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
11743 
11744   // Convert everything to the domain of EXT (i.e bytes).
11745   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
11746   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
11747   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
11748                             DAG.getConstant(ElemSize, dl, MVT::i32));
11749 
11750   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
11751   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
11752 }
11753 
11754 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
11755                                         TargetLowering::DAGCombinerInfo &DCI,
11756                                         SelectionDAG &DAG) {
11757   if (DCI.isBeforeLegalize())
11758     return SDValue();
11759 
11760   SDValue Comparator = N->getOperand(3);
11761   if (Comparator.getOpcode() == AArch64ISD::DUP ||
11762       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
11763     unsigned IID = getIntrinsicID(N);
11764     EVT VT = N->getValueType(0);
11765     EVT CmpVT = N->getOperand(2).getValueType();
11766     SDValue Pred = N->getOperand(1);
11767     SDValue Imm;
11768     SDLoc DL(N);
11769 
11770     switch (IID) {
11771     default:
11772       llvm_unreachable("Called with wrong intrinsic!");
11773       break;
11774 
11775     // Signed comparisons
11776     case Intrinsic::aarch64_sve_cmpeq_wide:
11777     case Intrinsic::aarch64_sve_cmpne_wide:
11778     case Intrinsic::aarch64_sve_cmpge_wide:
11779     case Intrinsic::aarch64_sve_cmpgt_wide:
11780     case Intrinsic::aarch64_sve_cmplt_wide:
11781     case Intrinsic::aarch64_sve_cmple_wide: {
11782       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11783         int64_t ImmVal = CN->getSExtValue();
11784         if (ImmVal >= -16 && ImmVal <= 15)
11785           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11786         else
11787           return SDValue();
11788       }
11789       break;
11790     }
11791     // Unsigned comparisons
11792     case Intrinsic::aarch64_sve_cmphs_wide:
11793     case Intrinsic::aarch64_sve_cmphi_wide:
11794     case Intrinsic::aarch64_sve_cmplo_wide:
11795     case Intrinsic::aarch64_sve_cmpls_wide:  {
11796       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11797         uint64_t ImmVal = CN->getZExtValue();
11798         if (ImmVal <= 127)
11799           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11800         else
11801           return SDValue();
11802       }
11803       break;
11804     }
11805     }
11806 
11807     if (!Imm)
11808       return SDValue();
11809 
11810     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11811     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
11812                        N->getOperand(2), Splat, DAG.getCondCode(CC));
11813   }
11814 
11815   return SDValue();
11816 }
11817 
11818 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11819                         AArch64CC::CondCode Cond) {
11820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11821 
11822   SDLoc DL(Op);
11823   assert(Op.getValueType().isScalableVector() &&
11824          TLI.isTypeLegal(Op.getValueType()) &&
11825          "Expected legal scalable vector type!");
11826 
11827   // Ensure target specific opcodes are using legal type.
11828   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11829   SDValue TVal = DAG.getConstant(1, DL, OutVT);
11830   SDValue FVal = DAG.getConstant(0, DL, OutVT);
11831 
11832   // Set condition code (CC) flags.
11833   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11834 
11835   // Convert CC to integer based on requested condition.
11836   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11837   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11838   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11839   return DAG.getZExtOrTrunc(Res, DL, VT);
11840 }
11841 
11842 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
11843                                      SelectionDAG &DAG) {
11844   SDLoc DL(N);
11845 
11846   SDValue Pred = N->getOperand(1);
11847   SDValue VecToReduce = N->getOperand(2);
11848 
11849   EVT ReduceVT = VecToReduce.getValueType();
11850   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
11851 
11852   // SVE reductions set the whole vector register with the first element
11853   // containing the reduction result, which we'll now extract.
11854   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11855   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11856                      Zero);
11857 }
11858 
11859 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
11860                                             SelectionDAG &DAG) {
11861   SDLoc DL(N);
11862 
11863   SDValue Pred = N->getOperand(1);
11864   SDValue InitVal = N->getOperand(2);
11865   SDValue VecToReduce = N->getOperand(3);
11866   EVT ReduceVT = VecToReduce.getValueType();
11867 
11868   // Ordered reductions use the first lane of the result vector as the
11869   // reduction's initial value.
11870   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11871   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
11872                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
11873 
11874   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
11875 
11876   // SVE reductions set the whole vector register with the first element
11877   // containing the reduction result, which we'll now extract.
11878   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11879                      Zero);
11880 }
11881 
11882 static SDValue performIntrinsicCombine(SDNode *N,
11883                                        TargetLowering::DAGCombinerInfo &DCI,
11884                                        const AArch64Subtarget *Subtarget) {
11885   SelectionDAG &DAG = DCI.DAG;
11886   unsigned IID = getIntrinsicID(N);
11887   switch (IID) {
11888   default:
11889     break;
11890   case Intrinsic::aarch64_neon_vcvtfxs2fp:
11891   case Intrinsic::aarch64_neon_vcvtfxu2fp:
11892     return tryCombineFixedPointConvert(N, DCI, DAG);
11893   case Intrinsic::aarch64_neon_saddv:
11894     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11895   case Intrinsic::aarch64_neon_uaddv:
11896     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11897   case Intrinsic::aarch64_neon_sminv:
11898     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11899   case Intrinsic::aarch64_neon_uminv:
11900     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11901   case Intrinsic::aarch64_neon_smaxv:
11902     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11903   case Intrinsic::aarch64_neon_umaxv:
11904     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11905   case Intrinsic::aarch64_neon_fmax:
11906     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11907                        N->getOperand(1), N->getOperand(2));
11908   case Intrinsic::aarch64_neon_fmin:
11909     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11910                        N->getOperand(1), N->getOperand(2));
11911   case Intrinsic::aarch64_neon_fmaxnm:
11912     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11913                        N->getOperand(1), N->getOperand(2));
11914   case Intrinsic::aarch64_neon_fminnm:
11915     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11916                        N->getOperand(1), N->getOperand(2));
11917   case Intrinsic::aarch64_neon_smull:
11918   case Intrinsic::aarch64_neon_umull:
11919   case Intrinsic::aarch64_neon_pmull:
11920   case Intrinsic::aarch64_neon_sqdmull:
11921     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11922   case Intrinsic::aarch64_neon_sqshl:
11923   case Intrinsic::aarch64_neon_uqshl:
11924   case Intrinsic::aarch64_neon_sqshlu:
11925   case Intrinsic::aarch64_neon_srshl:
11926   case Intrinsic::aarch64_neon_urshl:
11927   case Intrinsic::aarch64_neon_sshl:
11928   case Intrinsic::aarch64_neon_ushl:
11929     return tryCombineShiftImm(IID, N, DAG);
11930   case Intrinsic::aarch64_crc32b:
11931   case Intrinsic::aarch64_crc32cb:
11932     return tryCombineCRC32(0xff, N, DAG);
11933   case Intrinsic::aarch64_crc32h:
11934   case Intrinsic::aarch64_crc32ch:
11935     return tryCombineCRC32(0xffff, N, DAG);
11936   case Intrinsic::aarch64_sve_smaxv:
11937     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11938   case Intrinsic::aarch64_sve_umaxv:
11939     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11940   case Intrinsic::aarch64_sve_sminv:
11941     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11942   case Intrinsic::aarch64_sve_uminv:
11943     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11944   case Intrinsic::aarch64_sve_orv:
11945     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11946   case Intrinsic::aarch64_sve_eorv:
11947     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11948   case Intrinsic::aarch64_sve_andv:
11949     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11950   case Intrinsic::aarch64_sve_index:
11951     return LowerSVEIntrinsicIndex(N, DAG);
11952   case Intrinsic::aarch64_sve_dup:
11953     return LowerSVEIntrinsicDUP(N, DAG);
11954   case Intrinsic::aarch64_sve_dup_x:
11955     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
11956                        N->getOperand(1));
11957   case Intrinsic::aarch64_sve_ext:
11958     return LowerSVEIntrinsicEXT(N, DAG);
11959   case Intrinsic::aarch64_sve_smin:
11960     return DAG.getNode(AArch64ISD::SMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11961                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11962   case Intrinsic::aarch64_sve_umin:
11963     return DAG.getNode(AArch64ISD::UMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11964                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11965   case Intrinsic::aarch64_sve_smax:
11966     return DAG.getNode(AArch64ISD::SMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
11967                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11968   case Intrinsic::aarch64_sve_umax:
11969     return DAG.getNode(AArch64ISD::UMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
11970                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11971   case Intrinsic::aarch64_sve_lsl:
11972     return DAG.getNode(AArch64ISD::SHL_MERGE_OP1, SDLoc(N), N->getValueType(0),
11973                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11974   case Intrinsic::aarch64_sve_lsr:
11975     return DAG.getNode(AArch64ISD::SRL_MERGE_OP1, SDLoc(N), N->getValueType(0),
11976                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11977   case Intrinsic::aarch64_sve_asr:
11978     return DAG.getNode(AArch64ISD::SRA_MERGE_OP1, SDLoc(N), N->getValueType(0),
11979                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11980   case Intrinsic::aarch64_sve_cmphs:
11981     if (!N->getOperand(2).getValueType().isFloatingPoint())
11982       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
11983                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
11984                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
11985     break;
11986   case Intrinsic::aarch64_sve_cmphi:
11987     if (!N->getOperand(2).getValueType().isFloatingPoint())
11988       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
11989                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
11990                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
11991     break;
11992   case Intrinsic::aarch64_sve_cmpge:
11993     if (!N->getOperand(2).getValueType().isFloatingPoint())
11994       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
11995                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
11996                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
11997     break;
11998   case Intrinsic::aarch64_sve_cmpgt:
11999     if (!N->getOperand(2).getValueType().isFloatingPoint())
12000       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12001                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12002                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12003     break;
12004   case Intrinsic::aarch64_sve_cmpeq:
12005     if (!N->getOperand(2).getValueType().isFloatingPoint())
12006       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12007                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12008                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12009     break;
12010   case Intrinsic::aarch64_sve_cmpne:
12011     if (!N->getOperand(2).getValueType().isFloatingPoint())
12012       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12013                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
12014                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12015     break;
12016   case Intrinsic::aarch64_sve_fadda:
12017     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12018   case Intrinsic::aarch64_sve_faddv:
12019     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12020   case Intrinsic::aarch64_sve_fmaxnmv:
12021     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12022   case Intrinsic::aarch64_sve_fmaxv:
12023     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12024   case Intrinsic::aarch64_sve_fminnmv:
12025     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12026   case Intrinsic::aarch64_sve_fminv:
12027     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12028   case Intrinsic::aarch64_sve_sel:
12029     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12030                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
12031   case Intrinsic::aarch64_sve_cmpeq_wide:
12032     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12033   case Intrinsic::aarch64_sve_cmpne_wide:
12034     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12035   case Intrinsic::aarch64_sve_cmpge_wide:
12036     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12037   case Intrinsic::aarch64_sve_cmpgt_wide:
12038     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12039   case Intrinsic::aarch64_sve_cmplt_wide:
12040     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12041   case Intrinsic::aarch64_sve_cmple_wide:
12042     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12043   case Intrinsic::aarch64_sve_cmphs_wide:
12044     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12045   case Intrinsic::aarch64_sve_cmphi_wide:
12046     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12047   case Intrinsic::aarch64_sve_cmplo_wide:
12048     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12049   case Intrinsic::aarch64_sve_cmpls_wide:
12050     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12051   case Intrinsic::aarch64_sve_ptest_any:
12052     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12053                     AArch64CC::ANY_ACTIVE);
12054   case Intrinsic::aarch64_sve_ptest_first:
12055     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12056                     AArch64CC::FIRST_ACTIVE);
12057   case Intrinsic::aarch64_sve_ptest_last:
12058     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12059                     AArch64CC::LAST_ACTIVE);
12060   }
12061   return SDValue();
12062 }
12063 
12064 static SDValue performExtendCombine(SDNode *N,
12065                                     TargetLowering::DAGCombinerInfo &DCI,
12066                                     SelectionDAG &DAG) {
12067   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12068   // we can convert that DUP into another extract_high (of a bigger DUP), which
12069   // helps the backend to decide that an sabdl2 would be useful, saving a real
12070   // extract_high operation.
12071   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12072       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
12073     SDNode *ABDNode = N->getOperand(0).getNode();
12074     unsigned IID = getIntrinsicID(ABDNode);
12075     if (IID == Intrinsic::aarch64_neon_sabd ||
12076         IID == Intrinsic::aarch64_neon_uabd) {
12077       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
12078       if (!NewABD.getNode())
12079         return SDValue();
12080 
12081       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
12082                          NewABD);
12083     }
12084   }
12085 
12086   // This is effectively a custom type legalization for AArch64.
12087   //
12088   // Type legalization will split an extend of a small, legal, type to a larger
12089   // illegal type by first splitting the destination type, often creating
12090   // illegal source types, which then get legalized in isel-confusing ways,
12091   // leading to really terrible codegen. E.g.,
12092   //   %result = v8i32 sext v8i8 %value
12093   // becomes
12094   //   %losrc = extract_subreg %value, ...
12095   //   %hisrc = extract_subreg %value, ...
12096   //   %lo = v4i32 sext v4i8 %losrc
12097   //   %hi = v4i32 sext v4i8 %hisrc
12098   // Things go rapidly downhill from there.
12099   //
12100   // For AArch64, the [sz]ext vector instructions can only go up one element
12101   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
12102   // take two instructions.
12103   //
12104   // This implies that the most efficient way to do the extend from v8i8
12105   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
12106   // the normal splitting to happen for the v8i16->v8i32.
12107 
12108   // This is pre-legalization to catch some cases where the default
12109   // type legalization will create ill-tempered code.
12110   if (!DCI.isBeforeLegalizeOps())
12111     return SDValue();
12112 
12113   // We're only interested in cleaning things up for non-legal vector types
12114   // here. If both the source and destination are legal, things will just
12115   // work naturally without any fiddling.
12116   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12117   EVT ResVT = N->getValueType(0);
12118   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
12119     return SDValue();
12120   // If the vector type isn't a simple VT, it's beyond the scope of what
12121   // we're  worried about here. Let legalization do its thing and hope for
12122   // the best.
12123   SDValue Src = N->getOperand(0);
12124   EVT SrcVT = Src->getValueType(0);
12125   if (!ResVT.isSimple() || !SrcVT.isSimple())
12126     return SDValue();
12127 
12128   // If the source VT is a 64-bit fixed or scalable vector, we can play games
12129   // and get the better results we want.
12130   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
12131     return SDValue();
12132 
12133   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
12134   ElementCount SrcEC = SrcVT.getVectorElementCount();
12135   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
12136   SDLoc DL(N);
12137   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
12138 
12139   // Now split the rest of the operation into two halves, each with a 64
12140   // bit source.
12141   EVT LoVT, HiVT;
12142   SDValue Lo, Hi;
12143   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
12144 
12145   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
12146                                LoVT.getVectorElementCount());
12147   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12148                    DAG.getConstant(0, DL, MVT::i64));
12149   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12150                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
12151   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
12152   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
12153 
12154   // Now combine the parts back together so we still have a single result
12155   // like the combiner expects.
12156   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
12157 }
12158 
12159 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
12160                                SDValue SplatVal, unsigned NumVecElts) {
12161   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
12162   unsigned OrigAlignment = St.getAlignment();
12163   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
12164 
12165   // Create scalar stores. This is at least as good as the code sequence for a
12166   // split unaligned store which is a dup.s, ext.b, and two stores.
12167   // Most of the time the three stores should be replaced by store pair
12168   // instructions (stp).
12169   SDLoc DL(&St);
12170   SDValue BasePtr = St.getBasePtr();
12171   uint64_t BaseOffset = 0;
12172 
12173   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
12174   SDValue NewST1 =
12175       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
12176                    OrigAlignment, St.getMemOperand()->getFlags());
12177 
12178   // As this in ISel, we will not merge this add which may degrade results.
12179   if (BasePtr->getOpcode() == ISD::ADD &&
12180       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
12181     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
12182     BasePtr = BasePtr->getOperand(0);
12183   }
12184 
12185   unsigned Offset = EltOffset;
12186   while (--NumVecElts) {
12187     unsigned Alignment = MinAlign(OrigAlignment, Offset);
12188     SDValue OffsetPtr =
12189         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12190                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
12191     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
12192                           PtrInfo.getWithOffset(Offset), Alignment,
12193                           St.getMemOperand()->getFlags());
12194     Offset += EltOffset;
12195   }
12196   return NewST1;
12197 }
12198 
12199 // Returns an SVE type that ContentTy can be trivially sign or zero extended
12200 // into.
12201 static MVT getSVEContainerType(EVT ContentTy) {
12202   assert(ContentTy.isSimple() && "No SVE containers for extended types");
12203 
12204   switch (ContentTy.getSimpleVT().SimpleTy) {
12205   default:
12206     llvm_unreachable("No known SVE container for this MVT type");
12207   case MVT::nxv2i8:
12208   case MVT::nxv2i16:
12209   case MVT::nxv2i32:
12210   case MVT::nxv2i64:
12211   case MVT::nxv2f32:
12212   case MVT::nxv2f64:
12213     return MVT::nxv2i64;
12214   case MVT::nxv4i8:
12215   case MVT::nxv4i16:
12216   case MVT::nxv4i32:
12217   case MVT::nxv4f32:
12218     return MVT::nxv4i32;
12219   case MVT::nxv8i8:
12220   case MVT::nxv8i16:
12221   case MVT::nxv8f16:
12222   case MVT::nxv8bf16:
12223     return MVT::nxv8i16;
12224   case MVT::nxv16i8:
12225     return MVT::nxv16i8;
12226   }
12227 }
12228 
12229 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
12230   SDLoc DL(N);
12231   EVT VT = N->getValueType(0);
12232 
12233   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12234     return SDValue();
12235 
12236   EVT ContainerVT = VT;
12237   if (ContainerVT.isInteger())
12238     ContainerVT = getSVEContainerType(ContainerVT);
12239 
12240   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
12241   SDValue Ops[] = { N->getOperand(0), // Chain
12242                     N->getOperand(2), // Pg
12243                     N->getOperand(3), // Base
12244                     DAG.getValueType(VT) };
12245 
12246   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
12247   SDValue LoadChain = SDValue(Load.getNode(), 1);
12248 
12249   if (ContainerVT.isInteger() && (VT != ContainerVT))
12250     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
12251 
12252   return DAG.getMergeValues({ Load, LoadChain }, DL);
12253 }
12254 
12255 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
12256   SDLoc DL(N);
12257   EVT VT = N->getValueType(0);
12258   EVT PtrTy = N->getOperand(3).getValueType();
12259 
12260   if (VT == MVT::nxv8bf16 &&
12261       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12262     return SDValue();
12263 
12264   EVT LoadVT = VT;
12265   if (VT.isFloatingPoint())
12266     LoadVT = VT.changeTypeToInteger();
12267 
12268   auto *MINode = cast<MemIntrinsicSDNode>(N);
12269   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
12270   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
12271                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
12272                                 MINode->getOperand(2), PassThru,
12273                                 MINode->getMemoryVT(), MINode->getMemOperand(),
12274                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
12275 
12276    if (VT.isFloatingPoint()) {
12277      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
12278      return DAG.getMergeValues(Ops, DL);
12279    }
12280 
12281   return L;
12282 }
12283 
12284 template <unsigned Opcode>
12285 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
12286   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
12287                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
12288                 "Unsupported opcode.");
12289   SDLoc DL(N);
12290   EVT VT = N->getValueType(0);
12291 
12292   EVT LoadVT = VT;
12293   if (VT.isFloatingPoint())
12294     LoadVT = VT.changeTypeToInteger();
12295 
12296   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
12297   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
12298   SDValue LoadChain = SDValue(Load.getNode(), 1);
12299 
12300   if (VT.isFloatingPoint())
12301     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
12302 
12303   return DAG.getMergeValues({Load, LoadChain}, DL);
12304 }
12305 
12306 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
12307   SDLoc DL(N);
12308   SDValue Data = N->getOperand(2);
12309   EVT DataVT = Data.getValueType();
12310   EVT HwSrcVt = getSVEContainerType(DataVT);
12311   SDValue InputVT = DAG.getValueType(DataVT);
12312 
12313   if (DataVT == MVT::nxv8bf16 &&
12314       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12315     return SDValue();
12316 
12317   if (DataVT.isFloatingPoint())
12318     InputVT = DAG.getValueType(HwSrcVt);
12319 
12320   SDValue SrcNew;
12321   if (Data.getValueType().isFloatingPoint())
12322     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
12323   else
12324     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
12325 
12326   SDValue Ops[] = { N->getOperand(0), // Chain
12327                     SrcNew,
12328                     N->getOperand(4), // Base
12329                     N->getOperand(3), // Pg
12330                     InputVT
12331                   };
12332 
12333   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
12334 }
12335 
12336 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
12337   SDLoc DL(N);
12338 
12339   SDValue Data = N->getOperand(2);
12340   EVT DataVT = Data.getValueType();
12341   EVT PtrTy = N->getOperand(4).getValueType();
12342 
12343   if (DataVT == MVT::nxv8bf16 &&
12344       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12345     return SDValue();
12346 
12347   if (DataVT.isFloatingPoint())
12348     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
12349 
12350   auto *MINode = cast<MemIntrinsicSDNode>(N);
12351   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
12352                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
12353                             MINode->getMemoryVT(), MINode->getMemOperand(),
12354                             ISD::UNINDEXED, false, false);
12355 }
12356 
12357 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
12358 /// load store optimizer pass will merge them to store pair stores.  This should
12359 /// be better than a movi to create the vector zero followed by a vector store
12360 /// if the zero constant is not re-used, since one instructions and one register
12361 /// live range will be removed.
12362 ///
12363 /// For example, the final generated code should be:
12364 ///
12365 ///   stp xzr, xzr, [x0]
12366 ///
12367 /// instead of:
12368 ///
12369 ///   movi v0.2d, #0
12370 ///   str q0, [x0]
12371 ///
12372 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12373   SDValue StVal = St.getValue();
12374   EVT VT = StVal.getValueType();
12375 
12376   // Avoid scalarizing zero splat stores for scalable vectors.
12377   if (VT.isScalableVector())
12378     return SDValue();
12379 
12380   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
12381   // 2, 3 or 4 i32 elements.
12382   int NumVecElts = VT.getVectorNumElements();
12383   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
12384          VT.getVectorElementType().getSizeInBits() == 64) ||
12385         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
12386          VT.getVectorElementType().getSizeInBits() == 32)))
12387     return SDValue();
12388 
12389   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
12390     return SDValue();
12391 
12392   // If the zero constant has more than one use then the vector store could be
12393   // better since the constant mov will be amortized and stp q instructions
12394   // should be able to be formed.
12395   if (!StVal.hasOneUse())
12396     return SDValue();
12397 
12398   // If the store is truncating then it's going down to i16 or smaller, which
12399   // means it can be implemented in a single store anyway.
12400   if (St.isTruncatingStore())
12401     return SDValue();
12402 
12403   // If the immediate offset of the address operand is too large for the stp
12404   // instruction, then bail out.
12405   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
12406     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
12407     if (Offset < -512 || Offset > 504)
12408       return SDValue();
12409   }
12410 
12411   for (int I = 0; I < NumVecElts; ++I) {
12412     SDValue EltVal = StVal.getOperand(I);
12413     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
12414       return SDValue();
12415   }
12416 
12417   // Use a CopyFromReg WZR/XZR here to prevent
12418   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
12419   SDLoc DL(&St);
12420   unsigned ZeroReg;
12421   EVT ZeroVT;
12422   if (VT.getVectorElementType().getSizeInBits() == 32) {
12423     ZeroReg = AArch64::WZR;
12424     ZeroVT = MVT::i32;
12425   } else {
12426     ZeroReg = AArch64::XZR;
12427     ZeroVT = MVT::i64;
12428   }
12429   SDValue SplatVal =
12430       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
12431   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12432 }
12433 
12434 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
12435 /// value. The load store optimizer pass will merge them to store pair stores.
12436 /// This has better performance than a splat of the scalar followed by a split
12437 /// vector store. Even if the stores are not merged it is four stores vs a dup,
12438 /// followed by an ext.b and two stores.
12439 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12440   SDValue StVal = St.getValue();
12441   EVT VT = StVal.getValueType();
12442 
12443   // Don't replace floating point stores, they possibly won't be transformed to
12444   // stp because of the store pair suppress pass.
12445   if (VT.isFloatingPoint())
12446     return SDValue();
12447 
12448   // We can express a splat as store pair(s) for 2 or 4 elements.
12449   unsigned NumVecElts = VT.getVectorNumElements();
12450   if (NumVecElts != 4 && NumVecElts != 2)
12451     return SDValue();
12452 
12453   // If the store is truncating then it's going down to i16 or smaller, which
12454   // means it can be implemented in a single store anyway.
12455   if (St.isTruncatingStore())
12456     return SDValue();
12457 
12458   // Check that this is a splat.
12459   // Make sure that each of the relevant vector element locations are inserted
12460   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
12461   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
12462   SDValue SplatVal;
12463   for (unsigned I = 0; I < NumVecElts; ++I) {
12464     // Check for insert vector elements.
12465     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
12466       return SDValue();
12467 
12468     // Check that same value is inserted at each vector element.
12469     if (I == 0)
12470       SplatVal = StVal.getOperand(1);
12471     else if (StVal.getOperand(1) != SplatVal)
12472       return SDValue();
12473 
12474     // Check insert element index.
12475     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
12476     if (!CIndex)
12477       return SDValue();
12478     uint64_t IndexVal = CIndex->getZExtValue();
12479     if (IndexVal >= NumVecElts)
12480       return SDValue();
12481     IndexNotInserted.reset(IndexVal);
12482 
12483     StVal = StVal.getOperand(0);
12484   }
12485   // Check that all vector element locations were inserted to.
12486   if (IndexNotInserted.any())
12487       return SDValue();
12488 
12489   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12490 }
12491 
12492 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12493                            SelectionDAG &DAG,
12494                            const AArch64Subtarget *Subtarget) {
12495 
12496   StoreSDNode *S = cast<StoreSDNode>(N);
12497   if (S->isVolatile() || S->isIndexed())
12498     return SDValue();
12499 
12500   SDValue StVal = S->getValue();
12501   EVT VT = StVal.getValueType();
12502 
12503   if (!VT.isFixedLengthVector())
12504     return SDValue();
12505 
12506   // If we get a splat of zeros, convert this vector store to a store of
12507   // scalars. They will be merged into store pairs of xzr thereby removing one
12508   // instruction and one register.
12509   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
12510     return ReplacedZeroSplat;
12511 
12512   // FIXME: The logic for deciding if an unaligned store should be split should
12513   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
12514   // a call to that function here.
12515 
12516   if (!Subtarget->isMisaligned128StoreSlow())
12517     return SDValue();
12518 
12519   // Don't split at -Oz.
12520   if (DAG.getMachineFunction().getFunction().hasMinSize())
12521     return SDValue();
12522 
12523   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
12524   // those up regresses performance on micro-benchmarks and olden/bh.
12525   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
12526     return SDValue();
12527 
12528   // Split unaligned 16B stores. They are terrible for performance.
12529   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
12530   // extensions can use this to mark that it does not want splitting to happen
12531   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
12532   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
12533   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
12534       S->getAlignment() <= 2)
12535     return SDValue();
12536 
12537   // If we get a splat of a scalar convert this vector store to a store of
12538   // scalars. They will be merged into store pairs thereby removing two
12539   // instructions.
12540   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
12541     return ReplacedSplat;
12542 
12543   SDLoc DL(S);
12544 
12545   // Split VT into two.
12546   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12547   unsigned NumElts = HalfVT.getVectorNumElements();
12548   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12549                                    DAG.getConstant(0, DL, MVT::i64));
12550   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12551                                    DAG.getConstant(NumElts, DL, MVT::i64));
12552   SDValue BasePtr = S->getBasePtr();
12553   SDValue NewST1 =
12554       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
12555                    S->getAlignment(), S->getMemOperand()->getFlags());
12556   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12557                                   DAG.getConstant(8, DL, MVT::i64));
12558   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
12559                       S->getPointerInfo(), S->getAlignment(),
12560                       S->getMemOperand()->getFlags());
12561 }
12562 
12563 /// Target-specific DAG combine function for post-increment LD1 (lane) and
12564 /// post-increment LD1R.
12565 static SDValue performPostLD1Combine(SDNode *N,
12566                                      TargetLowering::DAGCombinerInfo &DCI,
12567                                      bool IsLaneOp) {
12568   if (DCI.isBeforeLegalizeOps())
12569     return SDValue();
12570 
12571   SelectionDAG &DAG = DCI.DAG;
12572   EVT VT = N->getValueType(0);
12573 
12574   if (VT.isScalableVector())
12575     return SDValue();
12576 
12577   unsigned LoadIdx = IsLaneOp ? 1 : 0;
12578   SDNode *LD = N->getOperand(LoadIdx).getNode();
12579   // If it is not LOAD, can not do such combine.
12580   if (LD->getOpcode() != ISD::LOAD)
12581     return SDValue();
12582 
12583   // The vector lane must be a constant in the LD1LANE opcode.
12584   SDValue Lane;
12585   if (IsLaneOp) {
12586     Lane = N->getOperand(2);
12587     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
12588     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
12589       return SDValue();
12590   }
12591 
12592   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
12593   EVT MemVT = LoadSDN->getMemoryVT();
12594   // Check if memory operand is the same type as the vector element.
12595   if (MemVT != VT.getVectorElementType())
12596     return SDValue();
12597 
12598   // Check if there are other uses. If so, do not combine as it will introduce
12599   // an extra load.
12600   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
12601        ++UI) {
12602     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
12603       continue;
12604     if (*UI != N)
12605       return SDValue();
12606   }
12607 
12608   SDValue Addr = LD->getOperand(1);
12609   SDValue Vector = N->getOperand(0);
12610   // Search for a use of the address operand that is an increment.
12611   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
12612        Addr.getNode()->use_end(); UI != UE; ++UI) {
12613     SDNode *User = *UI;
12614     if (User->getOpcode() != ISD::ADD
12615         || UI.getUse().getResNo() != Addr.getResNo())
12616       continue;
12617 
12618     // If the increment is a constant, it must match the memory ref size.
12619     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12620     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12621       uint32_t IncVal = CInc->getZExtValue();
12622       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
12623       if (IncVal != NumBytes)
12624         continue;
12625       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12626     }
12627 
12628     // To avoid cycle construction make sure that neither the load nor the add
12629     // are predecessors to each other or the Vector.
12630     SmallPtrSet<const SDNode *, 32> Visited;
12631     SmallVector<const SDNode *, 16> Worklist;
12632     Visited.insert(Addr.getNode());
12633     Worklist.push_back(User);
12634     Worklist.push_back(LD);
12635     Worklist.push_back(Vector.getNode());
12636     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
12637         SDNode::hasPredecessorHelper(User, Visited, Worklist))
12638       continue;
12639 
12640     SmallVector<SDValue, 8> Ops;
12641     Ops.push_back(LD->getOperand(0));  // Chain
12642     if (IsLaneOp) {
12643       Ops.push_back(Vector);           // The vector to be inserted
12644       Ops.push_back(Lane);             // The lane to be inserted in the vector
12645     }
12646     Ops.push_back(Addr);
12647     Ops.push_back(Inc);
12648 
12649     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
12650     SDVTList SDTys = DAG.getVTList(Tys);
12651     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
12652     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
12653                                            MemVT,
12654                                            LoadSDN->getMemOperand());
12655 
12656     // Update the uses.
12657     SDValue NewResults[] = {
12658         SDValue(LD, 0),            // The result of load
12659         SDValue(UpdN.getNode(), 2) // Chain
12660     };
12661     DCI.CombineTo(LD, NewResults);
12662     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
12663     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
12664 
12665     break;
12666   }
12667   return SDValue();
12668 }
12669 
12670 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
12671 /// address translation.
12672 static bool performTBISimplification(SDValue Addr,
12673                                      TargetLowering::DAGCombinerInfo &DCI,
12674                                      SelectionDAG &DAG) {
12675   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
12676   KnownBits Known;
12677   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12678                                         !DCI.isBeforeLegalizeOps());
12679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12680   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
12681     DCI.CommitTargetLoweringOpt(TLO);
12682     return true;
12683   }
12684   return false;
12685 }
12686 
12687 static SDValue performSTORECombine(SDNode *N,
12688                                    TargetLowering::DAGCombinerInfo &DCI,
12689                                    SelectionDAG &DAG,
12690                                    const AArch64Subtarget *Subtarget) {
12691   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
12692     return Split;
12693 
12694   if (Subtarget->supportsAddressTopByteIgnored() &&
12695       performTBISimplification(N->getOperand(2), DCI, DAG))
12696     return SDValue(N, 0);
12697 
12698   return SDValue();
12699 }
12700 
12701 
12702 /// Target-specific DAG combine function for NEON load/store intrinsics
12703 /// to merge base address updates.
12704 static SDValue performNEONPostLDSTCombine(SDNode *N,
12705                                           TargetLowering::DAGCombinerInfo &DCI,
12706                                           SelectionDAG &DAG) {
12707   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12708     return SDValue();
12709 
12710   unsigned AddrOpIdx = N->getNumOperands() - 1;
12711   SDValue Addr = N->getOperand(AddrOpIdx);
12712 
12713   // Search for a use of the address operand that is an increment.
12714   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12715        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12716     SDNode *User = *UI;
12717     if (User->getOpcode() != ISD::ADD ||
12718         UI.getUse().getResNo() != Addr.getResNo())
12719       continue;
12720 
12721     // Check that the add is independent of the load/store.  Otherwise, folding
12722     // it would create a cycle.
12723     SmallPtrSet<const SDNode *, 32> Visited;
12724     SmallVector<const SDNode *, 16> Worklist;
12725     Visited.insert(Addr.getNode());
12726     Worklist.push_back(N);
12727     Worklist.push_back(User);
12728     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12729         SDNode::hasPredecessorHelper(User, Visited, Worklist))
12730       continue;
12731 
12732     // Find the new opcode for the updating load/store.
12733     bool IsStore = false;
12734     bool IsLaneOp = false;
12735     bool IsDupOp = false;
12736     unsigned NewOpc = 0;
12737     unsigned NumVecs = 0;
12738     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12739     switch (IntNo) {
12740     default: llvm_unreachable("unexpected intrinsic for Neon base update");
12741     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
12742       NumVecs = 2; break;
12743     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
12744       NumVecs = 3; break;
12745     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
12746       NumVecs = 4; break;
12747     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
12748       NumVecs = 2; IsStore = true; break;
12749     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
12750       NumVecs = 3; IsStore = true; break;
12751     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
12752       NumVecs = 4; IsStore = true; break;
12753     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
12754       NumVecs = 2; break;
12755     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
12756       NumVecs = 3; break;
12757     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
12758       NumVecs = 4; break;
12759     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
12760       NumVecs = 2; IsStore = true; break;
12761     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
12762       NumVecs = 3; IsStore = true; break;
12763     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
12764       NumVecs = 4; IsStore = true; break;
12765     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
12766       NumVecs = 2; IsDupOp = true; break;
12767     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
12768       NumVecs = 3; IsDupOp = true; break;
12769     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
12770       NumVecs = 4; IsDupOp = true; break;
12771     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
12772       NumVecs = 2; IsLaneOp = true; break;
12773     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
12774       NumVecs = 3; IsLaneOp = true; break;
12775     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
12776       NumVecs = 4; IsLaneOp = true; break;
12777     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
12778       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
12779     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
12780       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
12781     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
12782       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
12783     }
12784 
12785     EVT VecTy;
12786     if (IsStore)
12787       VecTy = N->getOperand(2).getValueType();
12788     else
12789       VecTy = N->getValueType(0);
12790 
12791     // If the increment is a constant, it must match the memory ref size.
12792     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12793     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12794       uint32_t IncVal = CInc->getZExtValue();
12795       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12796       if (IsLaneOp || IsDupOp)
12797         NumBytes /= VecTy.getVectorNumElements();
12798       if (IncVal != NumBytes)
12799         continue;
12800       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12801     }
12802     SmallVector<SDValue, 8> Ops;
12803     Ops.push_back(N->getOperand(0)); // Incoming chain
12804     // Load lane and store have vector list as input.
12805     if (IsLaneOp || IsStore)
12806       for (unsigned i = 2; i < AddrOpIdx; ++i)
12807         Ops.push_back(N->getOperand(i));
12808     Ops.push_back(Addr); // Base register
12809     Ops.push_back(Inc);
12810 
12811     // Return Types.
12812     EVT Tys[6];
12813     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
12814     unsigned n;
12815     for (n = 0; n < NumResultVecs; ++n)
12816       Tys[n] = VecTy;
12817     Tys[n++] = MVT::i64;  // Type of write back register
12818     Tys[n] = MVT::Other;  // Type of the chain
12819     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
12820 
12821     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
12822     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
12823                                            MemInt->getMemoryVT(),
12824                                            MemInt->getMemOperand());
12825 
12826     // Update the uses.
12827     std::vector<SDValue> NewResults;
12828     for (unsigned i = 0; i < NumResultVecs; ++i) {
12829       NewResults.push_back(SDValue(UpdN.getNode(), i));
12830     }
12831     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
12832     DCI.CombineTo(N, NewResults);
12833     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12834 
12835     break;
12836   }
12837   return SDValue();
12838 }
12839 
12840 // Checks to see if the value is the prescribed width and returns information
12841 // about its extension mode.
12842 static
12843 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
12844   ExtType = ISD::NON_EXTLOAD;
12845   switch(V.getNode()->getOpcode()) {
12846   default:
12847     return false;
12848   case ISD::LOAD: {
12849     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
12850     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
12851        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
12852       ExtType = LoadNode->getExtensionType();
12853       return true;
12854     }
12855     return false;
12856   }
12857   case ISD::AssertSext: {
12858     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12859     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12860        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12861       ExtType = ISD::SEXTLOAD;
12862       return true;
12863     }
12864     return false;
12865   }
12866   case ISD::AssertZext: {
12867     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12868     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12869        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12870       ExtType = ISD::ZEXTLOAD;
12871       return true;
12872     }
12873     return false;
12874   }
12875   case ISD::Constant:
12876   case ISD::TargetConstant: {
12877     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
12878            1LL << (width - 1);
12879   }
12880   }
12881 
12882   return true;
12883 }
12884 
12885 // This function does a whole lot of voodoo to determine if the tests are
12886 // equivalent without and with a mask. Essentially what happens is that given a
12887 // DAG resembling:
12888 //
12889 //  +-------------+ +-------------+ +-------------+ +-------------+
12890 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
12891 //  +-------------+ +-------------+ +-------------+ +-------------+
12892 //           |           |           |               |
12893 //           V           V           |    +----------+
12894 //          +-------------+  +----+  |    |
12895 //          |     ADD     |  |0xff|  |    |
12896 //          +-------------+  +----+  |    |
12897 //                  |           |    |    |
12898 //                  V           V    |    |
12899 //                 +-------------+   |    |
12900 //                 |     AND     |   |    |
12901 //                 +-------------+   |    |
12902 //                      |            |    |
12903 //                      +-----+      |    |
12904 //                            |      |    |
12905 //                            V      V    V
12906 //                           +-------------+
12907 //                           |     CMP     |
12908 //                           +-------------+
12909 //
12910 // The AND node may be safely removed for some combinations of inputs. In
12911 // particular we need to take into account the extension type of the Input,
12912 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
12913 // width of the input (this can work for any width inputs, the above graph is
12914 // specific to 8 bits.
12915 //
12916 // The specific equations were worked out by generating output tables for each
12917 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
12918 // problem was simplified by working with 4 bit inputs, which means we only
12919 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
12920 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
12921 // patterns present in both extensions (0,7). For every distinct set of
12922 // AddConstant and CompConstants bit patterns we can consider the masked and
12923 // unmasked versions to be equivalent if the result of this function is true for
12924 // all 16 distinct bit patterns of for the current extension type of Input (w0).
12925 //
12926 //   sub      w8, w0, w1
12927 //   and      w10, w8, #0x0f
12928 //   cmp      w8, w2
12929 //   cset     w9, AArch64CC
12930 //   cmp      w10, w2
12931 //   cset     w11, AArch64CC
12932 //   cmp      w9, w11
12933 //   cset     w0, eq
12934 //   ret
12935 //
12936 // Since the above function shows when the outputs are equivalent it defines
12937 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
12938 // would be expensive to run during compiles. The equations below were written
12939 // in a test harness that confirmed they gave equivalent outputs to the above
12940 // for all inputs function, so they can be used determine if the removal is
12941 // legal instead.
12942 //
12943 // isEquivalentMaskless() is the code for testing if the AND can be removed
12944 // factored out of the DAG recognition as the DAG can take several forms.
12945 
12946 static bool isEquivalentMaskless(unsigned CC, unsigned width,
12947                                  ISD::LoadExtType ExtType, int AddConstant,
12948                                  int CompConstant) {
12949   // By being careful about our equations and only writing the in term
12950   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
12951   // make them generally applicable to all bit widths.
12952   int MaxUInt = (1 << width);
12953 
12954   // For the purposes of these comparisons sign extending the type is
12955   // equivalent to zero extending the add and displacing it by half the integer
12956   // width. Provided we are careful and make sure our equations are valid over
12957   // the whole range we can just adjust the input and avoid writing equations
12958   // for sign extended inputs.
12959   if (ExtType == ISD::SEXTLOAD)
12960     AddConstant -= (1 << (width-1));
12961 
12962   switch(CC) {
12963   case AArch64CC::LE:
12964   case AArch64CC::GT:
12965     if ((AddConstant == 0) ||
12966         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
12967         (AddConstant >= 0 && CompConstant < 0) ||
12968         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
12969       return true;
12970     break;
12971   case AArch64CC::LT:
12972   case AArch64CC::GE:
12973     if ((AddConstant == 0) ||
12974         (AddConstant >= 0 && CompConstant <= 0) ||
12975         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
12976       return true;
12977     break;
12978   case AArch64CC::HI:
12979   case AArch64CC::LS:
12980     if ((AddConstant >= 0 && CompConstant < 0) ||
12981        (AddConstant <= 0 && CompConstant >= -1 &&
12982         CompConstant < AddConstant + MaxUInt))
12983       return true;
12984    break;
12985   case AArch64CC::PL:
12986   case AArch64CC::MI:
12987     if ((AddConstant == 0) ||
12988         (AddConstant > 0 && CompConstant <= 0) ||
12989         (AddConstant < 0 && CompConstant <= AddConstant))
12990       return true;
12991     break;
12992   case AArch64CC::LO:
12993   case AArch64CC::HS:
12994     if ((AddConstant >= 0 && CompConstant <= 0) ||
12995         (AddConstant <= 0 && CompConstant >= 0 &&
12996          CompConstant <= AddConstant + MaxUInt))
12997       return true;
12998     break;
12999   case AArch64CC::EQ:
13000   case AArch64CC::NE:
13001     if ((AddConstant > 0 && CompConstant < 0) ||
13002         (AddConstant < 0 && CompConstant >= 0 &&
13003          CompConstant < AddConstant + MaxUInt) ||
13004         (AddConstant >= 0 && CompConstant >= 0 &&
13005          CompConstant >= AddConstant) ||
13006         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13007       return true;
13008     break;
13009   case AArch64CC::VS:
13010   case AArch64CC::VC:
13011   case AArch64CC::AL:
13012   case AArch64CC::NV:
13013     return true;
13014   case AArch64CC::Invalid:
13015     break;
13016   }
13017 
13018   return false;
13019 }
13020 
13021 static
13022 SDValue performCONDCombine(SDNode *N,
13023                            TargetLowering::DAGCombinerInfo &DCI,
13024                            SelectionDAG &DAG, unsigned CCIndex,
13025                            unsigned CmpIndex) {
13026   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13027   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13028   unsigned CondOpcode = SubsNode->getOpcode();
13029 
13030   if (CondOpcode != AArch64ISD::SUBS)
13031     return SDValue();
13032 
13033   // There is a SUBS feeding this condition. Is it fed by a mask we can
13034   // use?
13035 
13036   SDNode *AndNode = SubsNode->getOperand(0).getNode();
13037   unsigned MaskBits = 0;
13038 
13039   if (AndNode->getOpcode() != ISD::AND)
13040     return SDValue();
13041 
13042   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13043     uint32_t CNV = CN->getZExtValue();
13044     if (CNV == 255)
13045       MaskBits = 8;
13046     else if (CNV == 65535)
13047       MaskBits = 16;
13048   }
13049 
13050   if (!MaskBits)
13051     return SDValue();
13052 
13053   SDValue AddValue = AndNode->getOperand(0);
13054 
13055   if (AddValue.getOpcode() != ISD::ADD)
13056     return SDValue();
13057 
13058   // The basic dag structure is correct, grab the inputs and validate them.
13059 
13060   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
13061   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
13062   SDValue SubsInputValue = SubsNode->getOperand(1);
13063 
13064   // The mask is present and the provenance of all the values is a smaller type,
13065   // lets see if the mask is superfluous.
13066 
13067   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
13068       !isa<ConstantSDNode>(SubsInputValue.getNode()))
13069     return SDValue();
13070 
13071   ISD::LoadExtType ExtType;
13072 
13073   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
13074       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
13075       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
13076     return SDValue();
13077 
13078   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
13079                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
13080                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
13081     return SDValue();
13082 
13083   // The AND is not necessary, remove it.
13084 
13085   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
13086                                SubsNode->getValueType(1));
13087   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
13088 
13089   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
13090   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
13091 
13092   return SDValue(N, 0);
13093 }
13094 
13095 // Optimize compare with zero and branch.
13096 static SDValue performBRCONDCombine(SDNode *N,
13097                                     TargetLowering::DAGCombinerInfo &DCI,
13098                                     SelectionDAG &DAG) {
13099   MachineFunction &MF = DAG.getMachineFunction();
13100   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
13101   // will not be produced, as they are conditional branch instructions that do
13102   // not set flags.
13103   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
13104     return SDValue();
13105 
13106   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
13107     N = NV.getNode();
13108   SDValue Chain = N->getOperand(0);
13109   SDValue Dest = N->getOperand(1);
13110   SDValue CCVal = N->getOperand(2);
13111   SDValue Cmp = N->getOperand(3);
13112 
13113   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
13114   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
13115   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
13116     return SDValue();
13117 
13118   unsigned CmpOpc = Cmp.getOpcode();
13119   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
13120     return SDValue();
13121 
13122   // Only attempt folding if there is only one use of the flag and no use of the
13123   // value.
13124   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
13125     return SDValue();
13126 
13127   SDValue LHS = Cmp.getOperand(0);
13128   SDValue RHS = Cmp.getOperand(1);
13129 
13130   assert(LHS.getValueType() == RHS.getValueType() &&
13131          "Expected the value type to be the same for both operands!");
13132   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
13133     return SDValue();
13134 
13135   if (isNullConstant(LHS))
13136     std::swap(LHS, RHS);
13137 
13138   if (!isNullConstant(RHS))
13139     return SDValue();
13140 
13141   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
13142       LHS.getOpcode() == ISD::SRL)
13143     return SDValue();
13144 
13145   // Fold the compare into the branch instruction.
13146   SDValue BR;
13147   if (CC == AArch64CC::EQ)
13148     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13149   else
13150     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13151 
13152   // Do not add new nodes to DAG combiner worklist.
13153   DCI.CombineTo(N, BR, false);
13154 
13155   return SDValue();
13156 }
13157 
13158 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
13159 // as well as whether the test should be inverted.  This code is required to
13160 // catch these cases (as opposed to standard dag combines) because
13161 // AArch64ISD::TBZ is matched during legalization.
13162 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
13163                                  SelectionDAG &DAG) {
13164 
13165   if (!Op->hasOneUse())
13166     return Op;
13167 
13168   // We don't handle undef/constant-fold cases below, as they should have
13169   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
13170   // etc.)
13171 
13172   // (tbz (trunc x), b) -> (tbz x, b)
13173   // This case is just here to enable more of the below cases to be caught.
13174   if (Op->getOpcode() == ISD::TRUNCATE &&
13175       Bit < Op->getValueType(0).getSizeInBits()) {
13176     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13177   }
13178 
13179   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
13180   if (Op->getOpcode() == ISD::ANY_EXTEND &&
13181       Bit < Op->getOperand(0).getValueSizeInBits()) {
13182     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13183   }
13184 
13185   if (Op->getNumOperands() != 2)
13186     return Op;
13187 
13188   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13189   if (!C)
13190     return Op;
13191 
13192   switch (Op->getOpcode()) {
13193   default:
13194     return Op;
13195 
13196   // (tbz (and x, m), b) -> (tbz x, b)
13197   case ISD::AND:
13198     if ((C->getZExtValue() >> Bit) & 1)
13199       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13200     return Op;
13201 
13202   // (tbz (shl x, c), b) -> (tbz x, b-c)
13203   case ISD::SHL:
13204     if (C->getZExtValue() <= Bit &&
13205         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13206       Bit = Bit - C->getZExtValue();
13207       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13208     }
13209     return Op;
13210 
13211   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
13212   case ISD::SRA:
13213     Bit = Bit + C->getZExtValue();
13214     if (Bit >= Op->getValueType(0).getSizeInBits())
13215       Bit = Op->getValueType(0).getSizeInBits() - 1;
13216     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13217 
13218   // (tbz (srl x, c), b) -> (tbz x, b+c)
13219   case ISD::SRL:
13220     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13221       Bit = Bit + C->getZExtValue();
13222       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13223     }
13224     return Op;
13225 
13226   // (tbz (xor x, -1), b) -> (tbnz x, b)
13227   case ISD::XOR:
13228     if ((C->getZExtValue() >> Bit) & 1)
13229       Invert = !Invert;
13230     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13231   }
13232 }
13233 
13234 // Optimize test single bit zero/non-zero and branch.
13235 static SDValue performTBZCombine(SDNode *N,
13236                                  TargetLowering::DAGCombinerInfo &DCI,
13237                                  SelectionDAG &DAG) {
13238   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13239   bool Invert = false;
13240   SDValue TestSrc = N->getOperand(1);
13241   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
13242 
13243   if (TestSrc == NewTestSrc)
13244     return SDValue();
13245 
13246   unsigned NewOpc = N->getOpcode();
13247   if (Invert) {
13248     if (NewOpc == AArch64ISD::TBZ)
13249       NewOpc = AArch64ISD::TBNZ;
13250     else {
13251       assert(NewOpc == AArch64ISD::TBNZ);
13252       NewOpc = AArch64ISD::TBZ;
13253     }
13254   }
13255 
13256   SDLoc DL(N);
13257   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
13258                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
13259 }
13260 
13261 // vselect (v1i1 setcc) ->
13262 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
13263 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
13264 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
13265 // such VSELECT.
13266 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
13267   SDValue N0 = N->getOperand(0);
13268   EVT CCVT = N0.getValueType();
13269 
13270   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
13271       CCVT.getVectorElementType() != MVT::i1)
13272     return SDValue();
13273 
13274   EVT ResVT = N->getValueType(0);
13275   EVT CmpVT = N0.getOperand(0).getValueType();
13276   // Only combine when the result type is of the same size as the compared
13277   // operands.
13278   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
13279     return SDValue();
13280 
13281   SDValue IfTrue = N->getOperand(1);
13282   SDValue IfFalse = N->getOperand(2);
13283   SDValue SetCC =
13284       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
13285                    N0.getOperand(0), N0.getOperand(1),
13286                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
13287   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
13288                      IfTrue, IfFalse);
13289 }
13290 
13291 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
13292 /// the compare-mask instructions rather than going via NZCV, even if LHS and
13293 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
13294 /// with a vector one followed by a DUP shuffle on the result.
13295 static SDValue performSelectCombine(SDNode *N,
13296                                     TargetLowering::DAGCombinerInfo &DCI) {
13297   SelectionDAG &DAG = DCI.DAG;
13298   SDValue N0 = N->getOperand(0);
13299   EVT ResVT = N->getValueType(0);
13300 
13301   if (N0.getOpcode() != ISD::SETCC)
13302     return SDValue();
13303 
13304   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
13305   // scalar SetCCResultType. We also don't expect vectors, because we assume
13306   // that selects fed by vector SETCCs are canonicalized to VSELECT.
13307   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
13308          "Scalar-SETCC feeding SELECT has unexpected result type!");
13309 
13310   // If NumMaskElts == 0, the comparison is larger than select result. The
13311   // largest real NEON comparison is 64-bits per lane, which means the result is
13312   // at most 32-bits and an illegal vector. Just bail out for now.
13313   EVT SrcVT = N0.getOperand(0).getValueType();
13314 
13315   // Don't try to do this optimization when the setcc itself has i1 operands.
13316   // There are no legal vectors of i1, so this would be pointless.
13317   if (SrcVT == MVT::i1)
13318     return SDValue();
13319 
13320   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
13321   if (!ResVT.isVector() || NumMaskElts == 0)
13322     return SDValue();
13323 
13324   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
13325   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
13326 
13327   // Also bail out if the vector CCVT isn't the same size as ResVT.
13328   // This can happen if the SETCC operand size doesn't divide the ResVT size
13329   // (e.g., f64 vs v3f32).
13330   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
13331     return SDValue();
13332 
13333   // Make sure we didn't create illegal types, if we're not supposed to.
13334   assert(DCI.isBeforeLegalize() ||
13335          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
13336 
13337   // First perform a vector comparison, where lane 0 is the one we're interested
13338   // in.
13339   SDLoc DL(N0);
13340   SDValue LHS =
13341       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
13342   SDValue RHS =
13343       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
13344   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
13345 
13346   // Now duplicate the comparison mask we want across all other lanes.
13347   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
13348   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
13349   Mask = DAG.getNode(ISD::BITCAST, DL,
13350                      ResVT.changeVectorElementTypeToInteger(), Mask);
13351 
13352   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
13353 }
13354 
13355 /// Get rid of unnecessary NVCASTs (that don't change the type).
13356 static SDValue performNVCASTCombine(SDNode *N) {
13357   if (N->getValueType(0) == N->getOperand(0).getValueType())
13358     return N->getOperand(0);
13359 
13360   return SDValue();
13361 }
13362 
13363 // If all users of the globaladdr are of the form (globaladdr + constant), find
13364 // the smallest constant, fold it into the globaladdr's offset and rewrite the
13365 // globaladdr as (globaladdr + constant) - constant.
13366 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
13367                                            const AArch64Subtarget *Subtarget,
13368                                            const TargetMachine &TM) {
13369   auto *GN = cast<GlobalAddressSDNode>(N);
13370   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
13371       AArch64II::MO_NO_FLAG)
13372     return SDValue();
13373 
13374   uint64_t MinOffset = -1ull;
13375   for (SDNode *N : GN->uses()) {
13376     if (N->getOpcode() != ISD::ADD)
13377       return SDValue();
13378     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
13379     if (!C)
13380       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13381     if (!C)
13382       return SDValue();
13383     MinOffset = std::min(MinOffset, C->getZExtValue());
13384   }
13385   uint64_t Offset = MinOffset + GN->getOffset();
13386 
13387   // Require that the new offset is larger than the existing one. Otherwise, we
13388   // can end up oscillating between two possible DAGs, for example,
13389   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
13390   if (Offset <= uint64_t(GN->getOffset()))
13391     return SDValue();
13392 
13393   // Check whether folding this offset is legal. It must not go out of bounds of
13394   // the referenced object to avoid violating the code model, and must be
13395   // smaller than 2^21 because this is the largest offset expressible in all
13396   // object formats.
13397   //
13398   // This check also prevents us from folding negative offsets, which will end
13399   // up being treated in the same way as large positive ones. They could also
13400   // cause code model violations, and aren't really common enough to matter.
13401   if (Offset >= (1 << 21))
13402     return SDValue();
13403 
13404   const GlobalValue *GV = GN->getGlobal();
13405   Type *T = GV->getValueType();
13406   if (!T->isSized() ||
13407       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
13408     return SDValue();
13409 
13410   SDLoc DL(GN);
13411   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
13412   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
13413                      DAG.getConstant(MinOffset, DL, MVT::i64));
13414 }
13415 
13416 // Turns the vector of indices into a vector of byte offstes by scaling Offset
13417 // by (BitWidth / 8).
13418 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
13419                                           SDLoc DL, unsigned BitWidth) {
13420   assert(Offset.getValueType().isScalableVector() &&
13421          "This method is only for scalable vectors of offsets");
13422 
13423   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
13424   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
13425 
13426   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
13427 }
13428 
13429 /// Check if the value of \p OffsetInBytes can be used as an immediate for
13430 /// the gather load/prefetch and scatter store instructions with vector base and
13431 /// immediate offset addressing mode:
13432 ///
13433 ///      [<Zn>.[S|D]{, #<imm>}]
13434 ///
13435 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13436 
13437 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
13438                                                   unsigned ScalarSizeInBytes) {
13439   // The immediate is not a multiple of the scalar size.
13440   if (OffsetInBytes % ScalarSizeInBytes)
13441     return false;
13442 
13443   // The immediate is out of range.
13444   if (OffsetInBytes / ScalarSizeInBytes > 31)
13445     return false;
13446 
13447   return true;
13448 }
13449 
13450 /// Check if the value of \p Offset represents a valid immediate for the SVE
13451 /// gather load/prefetch and scatter store instructiona with vector base and
13452 /// immediate offset addressing mode:
13453 ///
13454 ///      [<Zn>.[S|D]{, #<imm>}]
13455 ///
13456 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13457 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
13458                                            unsigned ScalarSizeInBytes) {
13459   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
13460   return OffsetConst && isValidImmForSVEVecImmAddrMode(
13461                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
13462 }
13463 
13464 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
13465                                           unsigned Opcode,
13466                                           bool OnlyPackedOffsets = true) {
13467   const SDValue Src = N->getOperand(2);
13468   const EVT SrcVT = Src->getValueType(0);
13469   assert(SrcVT.isScalableVector() &&
13470          "Scatter stores are only possible for SVE vectors");
13471 
13472   SDLoc DL(N);
13473   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
13474 
13475   // Make sure that source data will fit into an SVE register
13476   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13477     return SDValue();
13478 
13479   // For FPs, ACLE only supports _packed_ single and double precision types.
13480   if (SrcElVT.isFloatingPoint())
13481     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
13482       return SDValue();
13483 
13484   // Depending on the addressing mode, this is either a pointer or a vector of
13485   // pointers (that fits into one register)
13486   SDValue Base = N->getOperand(4);
13487   // Depending on the addressing mode, this is either a single offset or a
13488   // vector of offsets  (that fits into one register)
13489   SDValue Offset = N->getOperand(5);
13490 
13491   // For "scalar + vector of indices", just scale the indices. This only
13492   // applies to non-temporal scatters because there's no instruction that takes
13493   // indicies.
13494   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
13495     Offset =
13496         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
13497     Opcode = AArch64ISD::SSTNT1_PRED;
13498   }
13499 
13500   // In the case of non-temporal gather loads there's only one SVE instruction
13501   // per data-size: "scalar + vector", i.e.
13502   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13503   // Since we do have intrinsics that allow the arguments to be in a different
13504   // order, we may need to swap them to match the spec.
13505   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
13506     std::swap(Base, Offset);
13507 
13508   // SST1_IMM requires that the offset is an immediate that is:
13509   //    * a multiple of #SizeInBytes,
13510   //    * in the range [0, 31 x #SizeInBytes],
13511   // where #SizeInBytes is the size in bytes of the stored items. For
13512   // immediates outside that range and non-immediate scalar offsets use SST1 or
13513   // SST1_UXTW instead.
13514   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
13515     if (!isValidImmForSVEVecImmAddrMode(Offset,
13516                                         SrcVT.getScalarSizeInBits() / 8)) {
13517       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13518         Opcode = AArch64ISD::SST1_UXTW_PRED;
13519       else
13520         Opcode = AArch64ISD::SST1_PRED;
13521 
13522       std::swap(Base, Offset);
13523     }
13524   }
13525 
13526   auto &TLI = DAG.getTargetLoweringInfo();
13527   if (!TLI.isTypeLegal(Base.getValueType()))
13528     return SDValue();
13529 
13530   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
13531   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13532   // nxv2i64. Legalize accordingly.
13533   if (!OnlyPackedOffsets &&
13534       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13535     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13536 
13537   if (!TLI.isTypeLegal(Offset.getValueType()))
13538     return SDValue();
13539 
13540   // Source value type that is representable in hardware
13541   EVT HwSrcVt = getSVEContainerType(SrcVT);
13542 
13543   // Keep the original type of the input data to store - this is needed to be
13544   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
13545   // FP values we want the integer equivalent, so just use HwSrcVt.
13546   SDValue InputVT = DAG.getValueType(SrcVT);
13547   if (SrcVT.isFloatingPoint())
13548     InputVT = DAG.getValueType(HwSrcVt);
13549 
13550   SDVTList VTs = DAG.getVTList(MVT::Other);
13551   SDValue SrcNew;
13552 
13553   if (Src.getValueType().isFloatingPoint())
13554     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
13555   else
13556     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
13557 
13558   SDValue Ops[] = {N->getOperand(0), // Chain
13559                    SrcNew,
13560                    N->getOperand(3), // Pg
13561                    Base,
13562                    Offset,
13563                    InputVT};
13564 
13565   return DAG.getNode(Opcode, DL, VTs, Ops);
13566 }
13567 
13568 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
13569                                         unsigned Opcode,
13570                                         bool OnlyPackedOffsets = true) {
13571   const EVT RetVT = N->getValueType(0);
13572   assert(RetVT.isScalableVector() &&
13573          "Gather loads are only possible for SVE vectors");
13574 
13575   SDLoc DL(N);
13576 
13577   // Make sure that the loaded data will fit into an SVE register
13578   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13579     return SDValue();
13580 
13581   // Depending on the addressing mode, this is either a pointer or a vector of
13582   // pointers (that fits into one register)
13583   SDValue Base = N->getOperand(3);
13584   // Depending on the addressing mode, this is either a single offset or a
13585   // vector of offsets  (that fits into one register)
13586   SDValue Offset = N->getOperand(4);
13587 
13588   // For "scalar + vector of indices", just scale the indices. This only
13589   // applies to non-temporal gathers because there's no instruction that takes
13590   // indicies.
13591   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
13592     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
13593                                         RetVT.getScalarSizeInBits());
13594     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
13595   }
13596 
13597   // In the case of non-temporal gather loads there's only one SVE instruction
13598   // per data-size: "scalar + vector", i.e.
13599   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13600   // Since we do have intrinsics that allow the arguments to be in a different
13601   // order, we may need to swap them to match the spec.
13602   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
13603       Offset.getValueType().isVector())
13604     std::swap(Base, Offset);
13605 
13606   // GLD{FF}1_IMM requires that the offset is an immediate that is:
13607   //    * a multiple of #SizeInBytes,
13608   //    * in the range [0, 31 x #SizeInBytes],
13609   // where #SizeInBytes is the size in bytes of the loaded items. For
13610   // immediates outside that range and non-immediate scalar offsets use
13611   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
13612   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
13613       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
13614     if (!isValidImmForSVEVecImmAddrMode(Offset,
13615                                         RetVT.getScalarSizeInBits() / 8)) {
13616       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13617         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13618                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
13619                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
13620       else
13621         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13622                      ? AArch64ISD::GLD1_MERGE_ZERO
13623                      : AArch64ISD::GLDFF1_MERGE_ZERO;
13624 
13625       std::swap(Base, Offset);
13626     }
13627   }
13628 
13629   auto &TLI = DAG.getTargetLoweringInfo();
13630   if (!TLI.isTypeLegal(Base.getValueType()))
13631     return SDValue();
13632 
13633   // Some gather load variants allow unpacked offsets, but only as nxv2i32
13634   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13635   // nxv2i64. Legalize accordingly.
13636   if (!OnlyPackedOffsets &&
13637       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13638     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13639 
13640   // Return value type that is representable in hardware
13641   EVT HwRetVt = getSVEContainerType(RetVT);
13642 
13643   // Keep the original output value type around - this is needed to be able to
13644   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
13645   // values we want the integer equivalent, so just use HwRetVT.
13646   SDValue OutVT = DAG.getValueType(RetVT);
13647   if (RetVT.isFloatingPoint())
13648     OutVT = DAG.getValueType(HwRetVt);
13649 
13650   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
13651   SDValue Ops[] = {N->getOperand(0), // Chain
13652                    N->getOperand(2), // Pg
13653                    Base, Offset, OutVT};
13654 
13655   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
13656   SDValue LoadChain = SDValue(Load.getNode(), 1);
13657 
13658   if (RetVT.isInteger() && (RetVT != HwRetVt))
13659     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
13660 
13661   // If the original return value was FP, bitcast accordingly. Doing it here
13662   // means that we can avoid adding TableGen patterns for FPs.
13663   if (RetVT.isFloatingPoint())
13664     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
13665 
13666   return DAG.getMergeValues({Load, LoadChain}, DL);
13667 }
13668 
13669 static SDValue
13670 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13671                               SelectionDAG &DAG) {
13672   if (DCI.isBeforeLegalizeOps())
13673     return SDValue();
13674 
13675   SDLoc DL(N);
13676   SDValue Src = N->getOperand(0);
13677   unsigned Opc = Src->getOpcode();
13678 
13679   // Sign extend of an unsigned unpack -> signed unpack
13680   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13681 
13682     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
13683                                                : AArch64ISD::SUNPKLO;
13684 
13685     // Push the sign extend to the operand of the unpack
13686     // This is necessary where, for example, the operand of the unpack
13687     // is another unpack:
13688     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
13689     // ->
13690     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
13691     // ->
13692     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
13693     SDValue ExtOp = Src->getOperand(0);
13694     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
13695     EVT EltTy = VT.getVectorElementType();
13696     (void)EltTy;
13697 
13698     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
13699            "Sign extending from an invalid type");
13700 
13701     EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13702                                  VT.getVectorElementType(),
13703                                  VT.getVectorElementCount() * 2);
13704 
13705     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
13706                               ExtOp, DAG.getValueType(ExtVT));
13707 
13708     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
13709   }
13710 
13711   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
13712   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
13713   unsigned NewOpc;
13714   unsigned MemVTOpNum = 4;
13715   switch (Opc) {
13716   case AArch64ISD::LD1_MERGE_ZERO:
13717     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
13718     MemVTOpNum = 3;
13719     break;
13720   case AArch64ISD::LDNF1_MERGE_ZERO:
13721     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
13722     MemVTOpNum = 3;
13723     break;
13724   case AArch64ISD::LDFF1_MERGE_ZERO:
13725     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
13726     MemVTOpNum = 3;
13727     break;
13728   case AArch64ISD::GLD1_MERGE_ZERO:
13729     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
13730     break;
13731   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
13732     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
13733     break;
13734   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
13735     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
13736     break;
13737   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
13738     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
13739     break;
13740   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
13741     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
13742     break;
13743   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
13744     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
13745     break;
13746   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
13747     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
13748     break;
13749   case AArch64ISD::GLDFF1_MERGE_ZERO:
13750     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
13751     break;
13752   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
13753     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
13754     break;
13755   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
13756     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
13757     break;
13758   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
13759     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
13760     break;
13761   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
13762     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
13763     break;
13764   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
13765     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
13766     break;
13767   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
13768     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
13769     break;
13770   case AArch64ISD::GLDNT1_MERGE_ZERO:
13771     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
13772     break;
13773   default:
13774     return SDValue();
13775   }
13776 
13777   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
13778   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
13779 
13780   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
13781     return SDValue();
13782 
13783   EVT DstVT = N->getValueType(0);
13784   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
13785 
13786   SmallVector<SDValue, 5> Ops;
13787   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
13788     Ops.push_back(Src->getOperand(I));
13789 
13790   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
13791   DCI.CombineTo(N, ExtLoad);
13792   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
13793 
13794   // Return N so it doesn't get rechecked
13795   return SDValue(N, 0);
13796 }
13797 
13798 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
13799 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
13800 /// != nxv2i32) do not need legalization.
13801 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
13802   const unsigned OffsetPos = 4;
13803   SDValue Offset = N->getOperand(OffsetPos);
13804 
13805   // Not an unpacked vector, bail out.
13806   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
13807     return SDValue();
13808 
13809   // Extend the unpacked offset vector to 64-bit lanes.
13810   SDLoc DL(N);
13811   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
13812   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13813   // Replace the offset operand with the 64-bit one.
13814   Ops[OffsetPos] = Offset;
13815 
13816   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13817 }
13818 
13819 /// Combines a node carrying the intrinsic
13820 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
13821 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
13822 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
13823 /// sve gather prefetch instruction with vector plus immediate addressing mode.
13824 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
13825                                                unsigned ScalarSizeInBytes) {
13826   const unsigned ImmPos = 4, OffsetPos = 3;
13827   // No need to combine the node if the immediate is valid...
13828   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
13829     return SDValue();
13830 
13831   // ...otherwise swap the offset base with the offset...
13832   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13833   std::swap(Ops[ImmPos], Ops[OffsetPos]);
13834   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
13835   // `aarch64_sve_prfb_gather_uxtw_index`.
13836   SDLoc DL(N);
13837   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
13838                            MVT::i64);
13839 
13840   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13841 }
13842 
13843 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
13844                                                  DAGCombinerInfo &DCI) const {
13845   SelectionDAG &DAG = DCI.DAG;
13846   switch (N->getOpcode()) {
13847   default:
13848     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
13849     break;
13850   case ISD::ADD:
13851   case ISD::SUB:
13852     return performAddSubLongCombine(N, DCI, DAG);
13853   case ISD::XOR:
13854     return performXorCombine(N, DAG, DCI, Subtarget);
13855   case ISD::MUL:
13856     return performMulCombine(N, DAG, DCI, Subtarget);
13857   case ISD::SINT_TO_FP:
13858   case ISD::UINT_TO_FP:
13859     return performIntToFpCombine(N, DAG, Subtarget);
13860   case ISD::FP_TO_SINT:
13861   case ISD::FP_TO_UINT:
13862     return performFpToIntCombine(N, DAG, DCI, Subtarget);
13863   case ISD::FDIV:
13864     return performFDivCombine(N, DAG, DCI, Subtarget);
13865   case ISD::OR:
13866     return performORCombine(N, DCI, Subtarget);
13867   case ISD::AND:
13868     return performANDCombine(N, DCI);
13869   case ISD::SRL:
13870     return performSRLCombine(N, DCI);
13871   case ISD::INTRINSIC_WO_CHAIN:
13872     return performIntrinsicCombine(N, DCI, Subtarget);
13873   case ISD::ANY_EXTEND:
13874   case ISD::ZERO_EXTEND:
13875   case ISD::SIGN_EXTEND:
13876     return performExtendCombine(N, DCI, DAG);
13877   case ISD::SIGN_EXTEND_INREG:
13878     return performSignExtendInRegCombine(N, DCI, DAG);
13879   case ISD::CONCAT_VECTORS:
13880     return performConcatVectorsCombine(N, DCI, DAG);
13881   case ISD::SELECT:
13882     return performSelectCombine(N, DCI);
13883   case ISD::VSELECT:
13884     return performVSelectCombine(N, DCI.DAG);
13885   case ISD::LOAD:
13886     if (performTBISimplification(N->getOperand(1), DCI, DAG))
13887       return SDValue(N, 0);
13888     break;
13889   case ISD::STORE:
13890     return performSTORECombine(N, DCI, DAG, Subtarget);
13891   case AArch64ISD::BRCOND:
13892     return performBRCONDCombine(N, DCI, DAG);
13893   case AArch64ISD::TBNZ:
13894   case AArch64ISD::TBZ:
13895     return performTBZCombine(N, DCI, DAG);
13896   case AArch64ISD::CSEL:
13897     return performCONDCombine(N, DCI, DAG, 2, 3);
13898   case AArch64ISD::DUP:
13899     return performPostLD1Combine(N, DCI, false);
13900   case AArch64ISD::NVCAST:
13901     return performNVCASTCombine(N);
13902   case ISD::INSERT_VECTOR_ELT:
13903     return performPostLD1Combine(N, DCI, true);
13904   case ISD::INTRINSIC_VOID:
13905   case ISD::INTRINSIC_W_CHAIN:
13906     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13907     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
13908       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
13909     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
13910       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
13911     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
13912       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
13913     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
13914       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
13915     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
13916     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
13917     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
13918     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
13919     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
13920     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
13921     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
13922     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
13923       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
13924     case Intrinsic::aarch64_neon_ld2:
13925     case Intrinsic::aarch64_neon_ld3:
13926     case Intrinsic::aarch64_neon_ld4:
13927     case Intrinsic::aarch64_neon_ld1x2:
13928     case Intrinsic::aarch64_neon_ld1x3:
13929     case Intrinsic::aarch64_neon_ld1x4:
13930     case Intrinsic::aarch64_neon_ld2lane:
13931     case Intrinsic::aarch64_neon_ld3lane:
13932     case Intrinsic::aarch64_neon_ld4lane:
13933     case Intrinsic::aarch64_neon_ld2r:
13934     case Intrinsic::aarch64_neon_ld3r:
13935     case Intrinsic::aarch64_neon_ld4r:
13936     case Intrinsic::aarch64_neon_st2:
13937     case Intrinsic::aarch64_neon_st3:
13938     case Intrinsic::aarch64_neon_st4:
13939     case Intrinsic::aarch64_neon_st1x2:
13940     case Intrinsic::aarch64_neon_st1x3:
13941     case Intrinsic::aarch64_neon_st1x4:
13942     case Intrinsic::aarch64_neon_st2lane:
13943     case Intrinsic::aarch64_neon_st3lane:
13944     case Intrinsic::aarch64_neon_st4lane:
13945       return performNEONPostLDSTCombine(N, DCI, DAG);
13946     case Intrinsic::aarch64_sve_ldnt1:
13947       return performLDNT1Combine(N, DAG);
13948     case Intrinsic::aarch64_sve_ld1rq:
13949       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
13950     case Intrinsic::aarch64_sve_ld1ro:
13951       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
13952     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
13953       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13954     case Intrinsic::aarch64_sve_ldnt1_gather:
13955       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13956     case Intrinsic::aarch64_sve_ldnt1_gather_index:
13957       return performGatherLoadCombine(N, DAG,
13958                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
13959     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
13960       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13961     case Intrinsic::aarch64_sve_ld1:
13962       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
13963     case Intrinsic::aarch64_sve_ldnf1:
13964       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
13965     case Intrinsic::aarch64_sve_ldff1:
13966       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
13967     case Intrinsic::aarch64_sve_st1:
13968       return performST1Combine(N, DAG);
13969     case Intrinsic::aarch64_sve_stnt1:
13970       return performSTNT1Combine(N, DAG);
13971     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
13972       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13973     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
13974       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13975     case Intrinsic::aarch64_sve_stnt1_scatter:
13976       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13977     case Intrinsic::aarch64_sve_stnt1_scatter_index:
13978       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
13979     case Intrinsic::aarch64_sve_ld1_gather:
13980       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
13981     case Intrinsic::aarch64_sve_ld1_gather_index:
13982       return performGatherLoadCombine(N, DAG,
13983                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
13984     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
13985       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
13986                                       /*OnlyPackedOffsets=*/false);
13987     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
13988       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
13989                                       /*OnlyPackedOffsets=*/false);
13990     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
13991       return performGatherLoadCombine(N, DAG,
13992                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
13993                                       /*OnlyPackedOffsets=*/false);
13994     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
13995       return performGatherLoadCombine(N, DAG,
13996                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
13997                                       /*OnlyPackedOffsets=*/false);
13998     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
13999       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14000     case Intrinsic::aarch64_sve_ldff1_gather:
14001       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14002     case Intrinsic::aarch64_sve_ldff1_gather_index:
14003       return performGatherLoadCombine(N, DAG,
14004                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14005     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14006       return performGatherLoadCombine(N, DAG,
14007                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14008                                       /*OnlyPackedOffsets=*/false);
14009     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14010       return performGatherLoadCombine(N, DAG,
14011                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14012                                       /*OnlyPackedOffsets=*/false);
14013     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14014       return performGatherLoadCombine(N, DAG,
14015                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14016                                       /*OnlyPackedOffsets=*/false);
14017     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14018       return performGatherLoadCombine(N, DAG,
14019                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14020                                       /*OnlyPackedOffsets=*/false);
14021     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14022       return performGatherLoadCombine(N, DAG,
14023                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14024     case Intrinsic::aarch64_sve_st1_scatter:
14025       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14026     case Intrinsic::aarch64_sve_st1_scatter_index:
14027       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14028     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14029       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14030                                         /*OnlyPackedOffsets=*/false);
14031     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14032       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14033                                         /*OnlyPackedOffsets=*/false);
14034     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14035       return performScatterStoreCombine(N, DAG,
14036                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
14037                                         /*OnlyPackedOffsets=*/false);
14038     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14039       return performScatterStoreCombine(N, DAG,
14040                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
14041                                         /*OnlyPackedOffsets=*/false);
14042     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14043       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14044     case Intrinsic::aarch64_sve_tuple_get: {
14045       SDLoc DL(N);
14046       SDValue Chain = N->getOperand(0);
14047       SDValue Src1 = N->getOperand(2);
14048       SDValue Idx = N->getOperand(3);
14049 
14050       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14051       EVT ResVT = N->getValueType(0);
14052       uint64_t NumLanes = ResVT.getVectorElementCount().Min;
14053       SDValue Val =
14054           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1,
14055                       DAG.getConstant(IdxConst * NumLanes, DL, MVT::i32));
14056       return DAG.getMergeValues({Val, Chain}, DL);
14057     }
14058     case Intrinsic::aarch64_sve_tuple_set: {
14059       SDLoc DL(N);
14060       SDValue Chain = N->getOperand(0);
14061       SDValue Tuple = N->getOperand(2);
14062       SDValue Idx = N->getOperand(3);
14063       SDValue Vec = N->getOperand(4);
14064 
14065       EVT TupleVT = Tuple.getValueType();
14066       uint64_t TupleLanes = TupleVT.getVectorElementCount().Min;
14067 
14068       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14069       uint64_t NumLanes = Vec.getValueType().getVectorElementCount().Min;
14070 
14071       if ((TupleLanes % NumLanes) != 0)
14072         report_fatal_error("invalid tuple vector!");
14073 
14074       uint64_t NumVecs = TupleLanes / NumLanes;
14075 
14076       SmallVector<SDValue, 4> Opnds;
14077       for (unsigned I = 0; I < NumVecs; ++I) {
14078         if (I == IdxConst)
14079           Opnds.push_back(Vec);
14080         else {
14081           Opnds.push_back(
14082               DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Vec.getValueType(), Tuple,
14083                           DAG.getConstant(I * NumLanes, DL, MVT::i32)));
14084         }
14085       }
14086       SDValue Concat =
14087           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
14088       return DAG.getMergeValues({Concat, Chain}, DL);
14089     }
14090     case Intrinsic::aarch64_sve_tuple_create2:
14091     case Intrinsic::aarch64_sve_tuple_create3:
14092     case Intrinsic::aarch64_sve_tuple_create4: {
14093       SDLoc DL(N);
14094       SDValue Chain = N->getOperand(0);
14095 
14096       SmallVector<SDValue, 4> Opnds;
14097       for (unsigned I = 2; I < N->getNumOperands(); ++I)
14098         Opnds.push_back(N->getOperand(I));
14099 
14100       EVT VT = Opnds[0].getValueType();
14101       EVT EltVT = VT.getVectorElementType();
14102       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
14103                                     VT.getVectorElementCount() *
14104                                         (N->getNumOperands() - 2));
14105       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
14106       return DAG.getMergeValues({Concat, Chain}, DL);
14107     }
14108     case Intrinsic::aarch64_sve_ld2:
14109     case Intrinsic::aarch64_sve_ld3:
14110     case Intrinsic::aarch64_sve_ld4: {
14111       SDLoc DL(N);
14112       SDValue Chain = N->getOperand(0);
14113       SDValue Mask = N->getOperand(2);
14114       SDValue BasePtr = N->getOperand(3);
14115       SDValue LoadOps[] = {Chain, Mask, BasePtr};
14116       unsigned IntrinsicID =
14117           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14118       SDValue Result =
14119           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
14120       return DAG.getMergeValues({Result, Chain}, DL);
14121     }
14122     default:
14123       break;
14124     }
14125     break;
14126   case ISD::GlobalAddress:
14127     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
14128   }
14129   return SDValue();
14130 }
14131 
14132 // Check if the return value is used as only a return value, as otherwise
14133 // we can't perform a tail-call. In particular, we need to check for
14134 // target ISD nodes that are returns and any other "odd" constructs
14135 // that the generic analysis code won't necessarily catch.
14136 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
14137                                                SDValue &Chain) const {
14138   if (N->getNumValues() != 1)
14139     return false;
14140   if (!N->hasNUsesOfValue(1, 0))
14141     return false;
14142 
14143   SDValue TCChain = Chain;
14144   SDNode *Copy = *N->use_begin();
14145   if (Copy->getOpcode() == ISD::CopyToReg) {
14146     // If the copy has a glue operand, we conservatively assume it isn't safe to
14147     // perform a tail call.
14148     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
14149         MVT::Glue)
14150       return false;
14151     TCChain = Copy->getOperand(0);
14152   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
14153     return false;
14154 
14155   bool HasRet = false;
14156   for (SDNode *Node : Copy->uses()) {
14157     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
14158       return false;
14159     HasRet = true;
14160   }
14161 
14162   if (!HasRet)
14163     return false;
14164 
14165   Chain = TCChain;
14166   return true;
14167 }
14168 
14169 // Return whether the an instruction can potentially be optimized to a tail
14170 // call. This will cause the optimizers to attempt to move, or duplicate,
14171 // return instructions to help enable tail call optimizations for this
14172 // instruction.
14173 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14174   return CI->isTailCall();
14175 }
14176 
14177 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
14178                                                    SDValue &Offset,
14179                                                    ISD::MemIndexedMode &AM,
14180                                                    bool &IsInc,
14181                                                    SelectionDAG &DAG) const {
14182   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
14183     return false;
14184 
14185   Base = Op->getOperand(0);
14186   // All of the indexed addressing mode instructions take a signed
14187   // 9 bit immediate offset.
14188   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
14189     int64_t RHSC = RHS->getSExtValue();
14190     if (Op->getOpcode() == ISD::SUB)
14191       RHSC = -(uint64_t)RHSC;
14192     if (!isInt<9>(RHSC))
14193       return false;
14194     IsInc = (Op->getOpcode() == ISD::ADD);
14195     Offset = Op->getOperand(1);
14196     return true;
14197   }
14198   return false;
14199 }
14200 
14201 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14202                                                       SDValue &Offset,
14203                                                       ISD::MemIndexedMode &AM,
14204                                                       SelectionDAG &DAG) const {
14205   EVT VT;
14206   SDValue Ptr;
14207   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14208     VT = LD->getMemoryVT();
14209     Ptr = LD->getBasePtr();
14210   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14211     VT = ST->getMemoryVT();
14212     Ptr = ST->getBasePtr();
14213   } else
14214     return false;
14215 
14216   bool IsInc;
14217   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
14218     return false;
14219   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
14220   return true;
14221 }
14222 
14223 bool AArch64TargetLowering::getPostIndexedAddressParts(
14224     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
14225     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
14226   EVT VT;
14227   SDValue Ptr;
14228   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14229     VT = LD->getMemoryVT();
14230     Ptr = LD->getBasePtr();
14231   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14232     VT = ST->getMemoryVT();
14233     Ptr = ST->getBasePtr();
14234   } else
14235     return false;
14236 
14237   bool IsInc;
14238   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
14239     return false;
14240   // Post-indexing updates the base, so it's not a valid transform
14241   // if that's not the same as the load's pointer.
14242   if (Ptr != Base)
14243     return false;
14244   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
14245   return true;
14246 }
14247 
14248 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
14249                                   SelectionDAG &DAG) {
14250   SDLoc DL(N);
14251   SDValue Op = N->getOperand(0);
14252 
14253   if (N->getValueType(0) != MVT::i16 ||
14254       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
14255     return;
14256 
14257   Op = SDValue(
14258       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
14259                          DAG.getUNDEF(MVT::i32), Op,
14260                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
14261       0);
14262   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
14263   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
14264 }
14265 
14266 static void ReplaceReductionResults(SDNode *N,
14267                                     SmallVectorImpl<SDValue> &Results,
14268                                     SelectionDAG &DAG, unsigned InterOp,
14269                                     unsigned AcrossOp) {
14270   EVT LoVT, HiVT;
14271   SDValue Lo, Hi;
14272   SDLoc dl(N);
14273   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
14274   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
14275   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
14276   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
14277   Results.push_back(SplitVal);
14278 }
14279 
14280 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
14281   SDLoc DL(N);
14282   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
14283   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
14284                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
14285                                        DAG.getConstant(64, DL, MVT::i64)));
14286   return std::make_pair(Lo, Hi);
14287 }
14288 
14289 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
14290     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14291   SDValue In = N->getOperand(0);
14292   EVT InVT = In.getValueType();
14293 
14294   // Common code will handle these just fine.
14295   if (!InVT.isScalableVector() || !InVT.isInteger())
14296     return;
14297 
14298   SDLoc DL(N);
14299   EVT VT = N->getValueType(0);
14300 
14301   // The following checks bail if this is not a halving operation.
14302 
14303   ElementCount ResEC = VT.getVectorElementCount();
14304 
14305   if (InVT.getVectorElementCount().Min != (ResEC.Min * 2))
14306     return;
14307 
14308   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
14309   if (!CIndex)
14310     return;
14311 
14312   unsigned Index = CIndex->getZExtValue();
14313   if ((Index != 0) && (Index != ResEC.Min))
14314     return;
14315 
14316   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
14317   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
14318 
14319   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
14320   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
14321 }
14322 
14323 // Create an even/odd pair of X registers holding integer value V.
14324 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
14325   SDLoc dl(V.getNode());
14326   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
14327   SDValue VHi = DAG.getAnyExtOrTrunc(
14328       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
14329       dl, MVT::i64);
14330   if (DAG.getDataLayout().isBigEndian())
14331     std::swap (VLo, VHi);
14332   SDValue RegClass =
14333       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
14334   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
14335   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
14336   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
14337   return SDValue(
14338       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
14339 }
14340 
14341 static void ReplaceCMP_SWAP_128Results(SDNode *N,
14342                                        SmallVectorImpl<SDValue> &Results,
14343                                        SelectionDAG &DAG,
14344                                        const AArch64Subtarget *Subtarget) {
14345   assert(N->getValueType(0) == MVT::i128 &&
14346          "AtomicCmpSwap on types less than 128 should be legal");
14347 
14348   if (Subtarget->hasLSE()) {
14349     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
14350     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
14351     SDValue Ops[] = {
14352         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
14353         createGPRPairNode(DAG, N->getOperand(3)), // Store value
14354         N->getOperand(1), // Ptr
14355         N->getOperand(0), // Chain in
14356     };
14357 
14358     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14359 
14360     unsigned Opcode;
14361     switch (MemOp->getOrdering()) {
14362     case AtomicOrdering::Monotonic:
14363       Opcode = AArch64::CASPX;
14364       break;
14365     case AtomicOrdering::Acquire:
14366       Opcode = AArch64::CASPAX;
14367       break;
14368     case AtomicOrdering::Release:
14369       Opcode = AArch64::CASPLX;
14370       break;
14371     case AtomicOrdering::AcquireRelease:
14372     case AtomicOrdering::SequentiallyConsistent:
14373       Opcode = AArch64::CASPALX;
14374       break;
14375     default:
14376       llvm_unreachable("Unexpected ordering!");
14377     }
14378 
14379     MachineSDNode *CmpSwap = DAG.getMachineNode(
14380         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
14381     DAG.setNodeMemRefs(CmpSwap, {MemOp});
14382 
14383     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
14384     if (DAG.getDataLayout().isBigEndian())
14385       std::swap(SubReg1, SubReg2);
14386     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
14387                                             SDValue(CmpSwap, 0));
14388     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
14389                                             SDValue(CmpSwap, 0));
14390     Results.push_back(
14391         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
14392     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
14393     return;
14394   }
14395 
14396   auto Desired = splitInt128(N->getOperand(2), DAG);
14397   auto New = splitInt128(N->getOperand(3), DAG);
14398   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
14399                    New.first,        New.second,    N->getOperand(0)};
14400   SDNode *CmpSwap = DAG.getMachineNode(
14401       AArch64::CMP_SWAP_128, SDLoc(N),
14402       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
14403 
14404   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14405   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
14406 
14407   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14408                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
14409   Results.push_back(SDValue(CmpSwap, 3));
14410 }
14411 
14412 void AArch64TargetLowering::ReplaceNodeResults(
14413     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14414   switch (N->getOpcode()) {
14415   default:
14416     llvm_unreachable("Don't know how to custom expand this");
14417   case ISD::BITCAST:
14418     ReplaceBITCASTResults(N, Results, DAG);
14419     return;
14420   case ISD::VECREDUCE_ADD:
14421   case ISD::VECREDUCE_SMAX:
14422   case ISD::VECREDUCE_SMIN:
14423   case ISD::VECREDUCE_UMAX:
14424   case ISD::VECREDUCE_UMIN:
14425     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
14426     return;
14427 
14428   case ISD::CTPOP:
14429     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
14430     return;
14431   case AArch64ISD::SADDV:
14432     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
14433     return;
14434   case AArch64ISD::UADDV:
14435     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
14436     return;
14437   case AArch64ISD::SMINV:
14438     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
14439     return;
14440   case AArch64ISD::UMINV:
14441     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
14442     return;
14443   case AArch64ISD::SMAXV:
14444     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
14445     return;
14446   case AArch64ISD::UMAXV:
14447     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
14448     return;
14449   case ISD::FP_TO_UINT:
14450   case ISD::FP_TO_SINT:
14451     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
14452     // Let normal code take care of it by not adding anything to Results.
14453     return;
14454   case ISD::ATOMIC_CMP_SWAP:
14455     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
14456     return;
14457   case ISD::LOAD: {
14458     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
14459            "unexpected load's value type");
14460     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
14461     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
14462       // Non-volatile loads are optimized later in AArch64's load/store
14463       // optimizer.
14464       return;
14465     }
14466 
14467     SDValue Result = DAG.getMemIntrinsicNode(
14468         AArch64ISD::LDP, SDLoc(N),
14469         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
14470         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
14471         LoadNode->getMemOperand());
14472 
14473     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14474                                Result.getValue(0), Result.getValue(1));
14475     Results.append({Pair, Result.getValue(2) /* Chain */});
14476     return;
14477   }
14478   case ISD::EXTRACT_SUBVECTOR:
14479     ReplaceExtractSubVectorResults(N, Results, DAG);
14480     return;
14481   case ISD::INTRINSIC_WO_CHAIN: {
14482     EVT VT = N->getValueType(0);
14483     assert((VT == MVT::i8 || VT == MVT::i16) &&
14484            "custom lowering for unexpected type");
14485 
14486     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
14487     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14488     switch (IntID) {
14489     default:
14490       return;
14491     case Intrinsic::aarch64_sve_clasta_n: {
14492       SDLoc DL(N);
14493       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14494       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
14495                            N->getOperand(1), Op2, N->getOperand(3));
14496       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14497       return;
14498     }
14499     case Intrinsic::aarch64_sve_clastb_n: {
14500       SDLoc DL(N);
14501       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14502       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
14503                            N->getOperand(1), Op2, N->getOperand(3));
14504       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14505       return;
14506     }
14507     case Intrinsic::aarch64_sve_lasta: {
14508       SDLoc DL(N);
14509       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
14510                            N->getOperand(1), N->getOperand(2));
14511       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14512       return;
14513     }
14514     case Intrinsic::aarch64_sve_lastb: {
14515       SDLoc DL(N);
14516       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
14517                            N->getOperand(1), N->getOperand(2));
14518       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14519       return;
14520     }
14521     }
14522   }
14523   }
14524 }
14525 
14526 bool AArch64TargetLowering::useLoadStackGuardNode() const {
14527   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
14528     return TargetLowering::useLoadStackGuardNode();
14529   return true;
14530 }
14531 
14532 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
14533   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
14534   // reciprocal if there are three or more FDIVs.
14535   return 3;
14536 }
14537 
14538 TargetLoweringBase::LegalizeTypeAction
14539 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
14540   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
14541   // v4i16, v2i32 instead of to promote.
14542   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
14543       VT == MVT::v1f32)
14544     return TypeWidenVector;
14545 
14546   return TargetLoweringBase::getPreferredVectorAction(VT);
14547 }
14548 
14549 // Loads and stores less than 128-bits are already atomic; ones above that
14550 // are doomed anyway, so defer to the default libcall and blame the OS when
14551 // things go wrong.
14552 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14553   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14554   return Size == 128;
14555 }
14556 
14557 // Loads and stores less than 128-bits are already atomic; ones above that
14558 // are doomed anyway, so defer to the default libcall and blame the OS when
14559 // things go wrong.
14560 TargetLowering::AtomicExpansionKind
14561 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14562   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14563   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
14564 }
14565 
14566 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
14567 TargetLowering::AtomicExpansionKind
14568 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14569   if (AI->isFloatingPointOperation())
14570     return AtomicExpansionKind::CmpXChg;
14571 
14572   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14573   if (Size > 128) return AtomicExpansionKind::None;
14574   // Nand not supported in LSE.
14575   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
14576   // Leave 128 bits to LLSC.
14577   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
14578 }
14579 
14580 TargetLowering::AtomicExpansionKind
14581 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
14582     AtomicCmpXchgInst *AI) const {
14583   // If subtarget has LSE, leave cmpxchg intact for codegen.
14584   if (Subtarget->hasLSE())
14585     return AtomicExpansionKind::None;
14586   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14587   // implement cmpxchg without spilling. If the address being exchanged is also
14588   // on the stack and close enough to the spill slot, this can lead to a
14589   // situation where the monitor always gets cleared and the atomic operation
14590   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14591   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
14592     return AtomicExpansionKind::None;
14593   return AtomicExpansionKind::LLSC;
14594 }
14595 
14596 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14597                                              AtomicOrdering Ord) const {
14598   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14599   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14600   bool IsAcquire = isAcquireOrStronger(Ord);
14601 
14602   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
14603   // intrinsic must return {i64, i64} and we have to recombine them into a
14604   // single i128 here.
14605   if (ValTy->getPrimitiveSizeInBits() == 128) {
14606     Intrinsic::ID Int =
14607         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
14608     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
14609 
14610     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14611     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
14612 
14613     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14614     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14615     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14616     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14617     return Builder.CreateOr(
14618         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
14619   }
14620 
14621   Type *Tys[] = { Addr->getType() };
14622   Intrinsic::ID Int =
14623       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
14624   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
14625 
14626   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
14627 
14628   const DataLayout &DL = M->getDataLayout();
14629   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
14630   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
14631 
14632   return Builder.CreateBitCast(Trunc, EltTy);
14633 }
14634 
14635 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14636     IRBuilder<> &Builder) const {
14637   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14638   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
14639 }
14640 
14641 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
14642                                                    Value *Val, Value *Addr,
14643                                                    AtomicOrdering Ord) const {
14644   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14645   bool IsRelease = isReleaseOrStronger(Ord);
14646 
14647   // Since the intrinsics must have legal type, the i128 intrinsics take two
14648   // parameters: "i64, i64". We must marshal Val into the appropriate form
14649   // before the call.
14650   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
14651     Intrinsic::ID Int =
14652         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
14653     Function *Stxr = Intrinsic::getDeclaration(M, Int);
14654     Type *Int64Ty = Type::getInt64Ty(M->getContext());
14655 
14656     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
14657     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
14658     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14659     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
14660   }
14661 
14662   Intrinsic::ID Int =
14663       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
14664   Type *Tys[] = { Addr->getType() };
14665   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
14666 
14667   const DataLayout &DL = M->getDataLayout();
14668   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
14669   Val = Builder.CreateBitCast(Val, IntValTy);
14670 
14671   return Builder.CreateCall(Stxr,
14672                             {Builder.CreateZExtOrBitCast(
14673                                  Val, Stxr->getFunctionType()->getParamType(0)),
14674                              Addr});
14675 }
14676 
14677 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
14678     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14679   return Ty->isArrayTy();
14680 }
14681 
14682 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
14683                                                             EVT) const {
14684   return false;
14685 }
14686 
14687 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
14688   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
14689   Function *ThreadPointerFunc =
14690       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
14691   return IRB.CreatePointerCast(
14692       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
14693                              Offset),
14694       IRB.getInt8PtrTy()->getPointerTo(0));
14695 }
14696 
14697 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
14698   // Android provides a fixed TLS slot for the stack cookie. See the definition
14699   // of TLS_SLOT_STACK_GUARD in
14700   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14701   if (Subtarget->isTargetAndroid())
14702     return UseTlsOffset(IRB, 0x28);
14703 
14704   // Fuchsia is similar.
14705   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
14706   if (Subtarget->isTargetFuchsia())
14707     return UseTlsOffset(IRB, -0x10);
14708 
14709   return TargetLowering::getIRStackGuard(IRB);
14710 }
14711 
14712 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
14713   // MSVC CRT provides functionalities for stack protection.
14714   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
14715     // MSVC CRT has a global variable holding security cookie.
14716     M.getOrInsertGlobal("__security_cookie",
14717                         Type::getInt8PtrTy(M.getContext()));
14718 
14719     // MSVC CRT has a function to validate security cookie.
14720     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
14721         "__security_check_cookie", Type::getVoidTy(M.getContext()),
14722         Type::getInt8PtrTy(M.getContext()));
14723     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
14724       F->setCallingConv(CallingConv::Win64);
14725       F->addAttribute(1, Attribute::AttrKind::InReg);
14726     }
14727     return;
14728   }
14729   TargetLowering::insertSSPDeclarations(M);
14730 }
14731 
14732 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
14733   // MSVC CRT has a global variable holding security cookie.
14734   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14735     return M.getGlobalVariable("__security_cookie");
14736   return TargetLowering::getSDagStackGuard(M);
14737 }
14738 
14739 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
14740   // MSVC CRT has a function to validate security cookie.
14741   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14742     return M.getFunction("__security_check_cookie");
14743   return TargetLowering::getSSPStackGuardCheck(M);
14744 }
14745 
14746 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
14747   // Android provides a fixed TLS slot for the SafeStack pointer. See the
14748   // definition of TLS_SLOT_SAFESTACK in
14749   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14750   if (Subtarget->isTargetAndroid())
14751     return UseTlsOffset(IRB, 0x48);
14752 
14753   // Fuchsia is similar.
14754   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
14755   if (Subtarget->isTargetFuchsia())
14756     return UseTlsOffset(IRB, -0x8);
14757 
14758   return TargetLowering::getSafeStackPointerLocation(IRB);
14759 }
14760 
14761 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
14762     const Instruction &AndI) const {
14763   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
14764   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
14765   // may be beneficial to sink in other cases, but we would have to check that
14766   // the cmp would not get folded into the br to form a cbz for these to be
14767   // beneficial.
14768   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
14769   if (!Mask)
14770     return false;
14771   return Mask->getValue().isPowerOf2();
14772 }
14773 
14774 bool AArch64TargetLowering::
14775     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14776         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
14777         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
14778         SelectionDAG &DAG) const {
14779   // Does baseline recommend not to perform the fold by default?
14780   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14781           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
14782     return false;
14783   // Else, if this is a vector shift, prefer 'shl'.
14784   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
14785 }
14786 
14787 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
14788                                               SDNode *N) const {
14789   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14790       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
14791     return false;
14792   return true;
14793 }
14794 
14795 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14796   // Update IsSplitCSR in AArch64unctionInfo.
14797   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
14798   AFI->setIsSplitCSR(true);
14799 }
14800 
14801 void AArch64TargetLowering::insertCopiesSplitCSR(
14802     MachineBasicBlock *Entry,
14803     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14804   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
14805   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14806   if (!IStart)
14807     return;
14808 
14809   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14810   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14811   MachineBasicBlock::iterator MBBI = Entry->begin();
14812   for (const MCPhysReg *I = IStart; *I; ++I) {
14813     const TargetRegisterClass *RC = nullptr;
14814     if (AArch64::GPR64RegClass.contains(*I))
14815       RC = &AArch64::GPR64RegClass;
14816     else if (AArch64::FPR64RegClass.contains(*I))
14817       RC = &AArch64::FPR64RegClass;
14818     else
14819       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14820 
14821     Register NewVR = MRI->createVirtualRegister(RC);
14822     // Create copy from CSR to a virtual register.
14823     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14824     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14825     // nounwind. If we want to generalize this later, we may need to emit
14826     // CFI pseudo-instructions.
14827     assert(Entry->getParent()->getFunction().hasFnAttribute(
14828                Attribute::NoUnwind) &&
14829            "Function should be nounwind in insertCopiesSplitCSR!");
14830     Entry->addLiveIn(*I);
14831     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14832         .addReg(*I);
14833 
14834     // Insert the copy-back instructions right before the terminator.
14835     for (auto *Exit : Exits)
14836       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14837               TII->get(TargetOpcode::COPY), *I)
14838           .addReg(NewVR);
14839   }
14840 }
14841 
14842 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
14843   // Integer division on AArch64 is expensive. However, when aggressively
14844   // optimizing for code size, we prefer to use a div instruction, as it is
14845   // usually smaller than the alternative sequence.
14846   // The exception to this is vector division. Since AArch64 doesn't have vector
14847   // integer division, leaving the division as-is is a loss even in terms of
14848   // size, because it will have to be scalarized, while the alternative code
14849   // sequence can be performed in vector form.
14850   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
14851   return OptSize && !VT.isVector();
14852 }
14853 
14854 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
14855   // We want inc-of-add for scalars and sub-of-not for vectors.
14856   return VT.isScalarInteger();
14857 }
14858 
14859 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
14860   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
14861 }
14862 
14863 unsigned
14864 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
14865   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
14866     return getPointerTy(DL).getSizeInBits();
14867 
14868   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
14869 }
14870 
14871 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
14872   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14873   TargetLoweringBase::finalizeLowering(MF);
14874 }
14875 
14876 // Unlike X86, we let frame lowering assign offsets to all catch objects.
14877 bool AArch64TargetLowering::needsFixedCatchObjects() const {
14878   return false;
14879 }
14880 
14881 bool AArch64TargetLowering::shouldLocalize(
14882     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
14883   switch (MI.getOpcode()) {
14884   case TargetOpcode::G_GLOBAL_VALUE: {
14885     // On Darwin, TLS global vars get selected into function calls, which
14886     // we don't want localized, as they can get moved into the middle of a
14887     // another call sequence.
14888     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
14889     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
14890       return false;
14891     break;
14892   }
14893   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
14894   // localizable.
14895   case AArch64::ADRP:
14896   case AArch64::G_ADD_LOW:
14897     return true;
14898   default:
14899     break;
14900   }
14901   return TargetLoweringBase::shouldLocalize(MI, TTI);
14902 }
14903 
14904 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
14905   if (isa<ScalableVectorType>(Inst.getType()))
14906     return true;
14907 
14908   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
14909     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
14910       return true;
14911 
14912   return false;
14913 }
14914 
14915 // Return the largest legal scalable vector type that matches VT's element type.
14916 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
14917   assert(VT.isFixedLengthVector() &&
14918          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14919          "Expected legal fixed length vector!");
14920   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
14921   default:
14922     llvm_unreachable("unexpected element type for SVE container");
14923   case MVT::i8:
14924     return EVT(MVT::nxv16i8);
14925   case MVT::i16:
14926     return EVT(MVT::nxv8i16);
14927   case MVT::i32:
14928     return EVT(MVT::nxv4i32);
14929   case MVT::i64:
14930     return EVT(MVT::nxv2i64);
14931   case MVT::f16:
14932     return EVT(MVT::nxv8f16);
14933   case MVT::f32:
14934     return EVT(MVT::nxv4f32);
14935   case MVT::f64:
14936     return EVT(MVT::nxv2f64);
14937   }
14938 }
14939 
14940 // Return a PTRUE with active lanes corresponding to the extent of VT.
14941 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
14942                                                 EVT VT) {
14943   assert(VT.isFixedLengthVector() &&
14944          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14945          "Expected legal fixed length vector!");
14946 
14947   int PgPattern;
14948   switch (VT.getVectorNumElements()) {
14949   default:
14950     llvm_unreachable("unexpected element count for SVE predicate");
14951   case 1:
14952     PgPattern = AArch64SVEPredPattern::vl1;
14953     break;
14954   case 2:
14955     PgPattern = AArch64SVEPredPattern::vl2;
14956     break;
14957   case 4:
14958     PgPattern = AArch64SVEPredPattern::vl4;
14959     break;
14960   case 8:
14961     PgPattern = AArch64SVEPredPattern::vl8;
14962     break;
14963   case 16:
14964     PgPattern = AArch64SVEPredPattern::vl16;
14965     break;
14966   case 32:
14967     PgPattern = AArch64SVEPredPattern::vl32;
14968     break;
14969   case 64:
14970     PgPattern = AArch64SVEPredPattern::vl64;
14971     break;
14972   case 128:
14973     PgPattern = AArch64SVEPredPattern::vl128;
14974     break;
14975   case 256:
14976     PgPattern = AArch64SVEPredPattern::vl256;
14977     break;
14978   }
14979 
14980   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
14981   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
14982   // variants of instructions when available.
14983 
14984   MVT MaskVT;
14985   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
14986   default:
14987     llvm_unreachable("unexpected element type for SVE predicate");
14988   case MVT::i8:
14989     MaskVT = MVT::nxv16i1;
14990     break;
14991   case MVT::i16:
14992   case MVT::f16:
14993     MaskVT = MVT::nxv8i1;
14994     break;
14995   case MVT::i32:
14996   case MVT::f32:
14997     MaskVT = MVT::nxv4i1;
14998     break;
14999   case MVT::i64:
15000   case MVT::f64:
15001     MaskVT = MVT::nxv2i1;
15002     break;
15003   }
15004 
15005   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15006                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15007 }
15008 
15009 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15010                                              EVT VT) {
15011   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15012          "Expected legal scalable vector!");
15013   auto PredTy = VT.changeVectorElementType(MVT::i1);
15014   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15015 }
15016 
15017 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15018   if (VT.isFixedLengthVector())
15019     return getPredicateForFixedLengthVector(DAG, DL, VT);
15020 
15021   return getPredicateForScalableVector(DAG, DL, VT);
15022 }
15023 
15024 // Grow V to consume an entire SVE register.
15025 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15026   assert(VT.isScalableVector() &&
15027          "Expected to convert into a scalable vector!");
15028   assert(V.getValueType().isFixedLengthVector() &&
15029          "Expected a fixed length vector operand!");
15030   SDLoc DL(V);
15031   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15032   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
15033 }
15034 
15035 // Shrink V so it's just big enough to maintain a VT's worth of data.
15036 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15037   assert(VT.isFixedLengthVector() &&
15038          "Expected to convert into a fixed length vector!");
15039   assert(V.getValueType().isScalableVector() &&
15040          "Expected a scalable vector operand!");
15041   SDLoc DL(V);
15042   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15043   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
15044 }
15045 
15046 // Convert all fixed length vector loads larger than NEON to masked_loads.
15047 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
15048     SDValue Op, SelectionDAG &DAG) const {
15049   auto Load = cast<LoadSDNode>(Op);
15050 
15051   SDLoc DL(Op);
15052   EVT VT = Op.getValueType();
15053   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15054 
15055   auto NewLoad = DAG.getMaskedLoad(
15056       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
15057       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
15058       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
15059       Load->getExtensionType());
15060 
15061   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
15062   SDValue MergedValues[2] = {Result, Load->getChain()};
15063   return DAG.getMergeValues(MergedValues, DL);
15064 }
15065 
15066 // Convert all fixed length vector stores larger than NEON to masked_stores.
15067 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
15068     SDValue Op, SelectionDAG &DAG) const {
15069   auto Store = cast<StoreSDNode>(Op);
15070 
15071   SDLoc DL(Op);
15072   EVT VT = Store->getValue().getValueType();
15073   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15074 
15075   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
15076   return DAG.getMaskedStore(
15077       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
15078       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
15079       Store->getMemOperand(), Store->getAddressingMode(),
15080       Store->isTruncatingStore());
15081 }
15082 
15083 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
15084     SDValue Op, SelectionDAG &DAG) const {
15085   EVT VT = Op.getValueType();
15086   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
15087 
15088   SDLoc DL(Op);
15089   SDValue Val = Op.getOperand(0);
15090   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
15091   Val = convertToScalableVector(DAG, ContainerVT, Val);
15092 
15093   // Repeatedly truncate Val until the result is of the desired element type.
15094   switch (ContainerVT.getSimpleVT().SimpleTy) {
15095   default:
15096     llvm_unreachable("unimplemented container type");
15097   case MVT::nxv2i64:
15098     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
15099     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
15100     if (VT.getVectorElementType() == MVT::i32)
15101       break;
15102     LLVM_FALLTHROUGH;
15103   case MVT::nxv4i32:
15104     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
15105     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
15106     if (VT.getVectorElementType() == MVT::i16)
15107       break;
15108     LLVM_FALLTHROUGH;
15109   case MVT::nxv8i16:
15110     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
15111     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
15112     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
15113     break;
15114   }
15115 
15116   return convertFromScalableVector(DAG, VT, Val);
15117 }
15118 
15119 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
15120                                                    SelectionDAG &DAG,
15121                                                    unsigned NewOp) const {
15122   EVT VT = Op.getValueType();
15123   SDLoc DL(Op);
15124   auto Pg = getPredicateForVector(DAG, DL, VT);
15125 
15126   if (useSVEForFixedLengthVectorVT(VT)) {
15127     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15128 
15129     // Create list of operands by convereting existing ones to scalable types.
15130     SmallVector<SDValue, 4> Operands = {Pg};
15131     for (const SDValue &V : Op->op_values()) {
15132       if (isa<CondCodeSDNode>(V)) {
15133         Operands.push_back(V);
15134         continue;
15135       }
15136 
15137       assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
15138              "Only fixed length vectors are supported!");
15139       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
15140     }
15141 
15142     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
15143     return convertFromScalableVector(DAG, VT, ScalableRes);
15144   }
15145 
15146   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
15147 
15148   SmallVector<SDValue, 4> Operands = {Pg};
15149   for (const SDValue &V : Op->op_values()) {
15150     assert((isa<CondCodeSDNode>(V) || V.getValueType().isScalableVector()) &&
15151            "Only scalable vectors are supported!");
15152     Operands.push_back(V);
15153   }
15154 
15155   return DAG.getNode(NewOp, DL, VT, Operands);
15156 }
15157