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 static cl::opt<bool>
103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
104                            cl::desc("Allow AArch64 SLI/SRI formation"),
105                            cl::init(false));
106 
107 // FIXME: The necessary dtprel relocations don't seem to be supported
108 // well in the GNU bfd and gold linkers at the moment. Therefore, by
109 // default, for now, fall back to GeneralDynamic code generation.
110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
111     "aarch64-elf-ldtls-generation", cl::Hidden,
112     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113     cl::init(false));
114 
115 static cl::opt<bool>
116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
117                          cl::desc("Enable AArch64 logical imm instruction "
118                                   "optimization"),
119                          cl::init(true));
120 
121 /// Value type used for condition codes.
122 static const MVT MVT_CC = MVT::i32;
123 
124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
125                                              const AArch64Subtarget &STI)
126     : TargetLowering(TM), Subtarget(&STI) {
127   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
128   // we have to make something up. Arbitrarily, choose ZeroOrOne.
129   setBooleanContents(ZeroOrOneBooleanContent);
130   // When comparing vectors the result sets the different elements in the
131   // vector to all-one or all-zero.
132   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
133 
134   // Set up the register classes.
135   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
136   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
137 
138   if (Subtarget->hasFPARMv8()) {
139     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
140     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
141     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
142     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
143   }
144 
145   if (Subtarget->hasNEON()) {
146     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
147     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
148     // Someone set us up the NEON.
149     addDRTypeForNEON(MVT::v2f32);
150     addDRTypeForNEON(MVT::v8i8);
151     addDRTypeForNEON(MVT::v4i16);
152     addDRTypeForNEON(MVT::v2i32);
153     addDRTypeForNEON(MVT::v1i64);
154     addDRTypeForNEON(MVT::v1f64);
155     addDRTypeForNEON(MVT::v4f16);
156 
157     addQRTypeForNEON(MVT::v4f32);
158     addQRTypeForNEON(MVT::v2f64);
159     addQRTypeForNEON(MVT::v16i8);
160     addQRTypeForNEON(MVT::v8i16);
161     addQRTypeForNEON(MVT::v4i32);
162     addQRTypeForNEON(MVT::v2i64);
163     addQRTypeForNEON(MVT::v8f16);
164   }
165 
166   if (Subtarget->hasSVE()) {
167     // Add legal sve predicate types
168     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
169     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
170     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
171     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
172 
173     // Add legal sve data types
174     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
175     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
176     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
177     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
178 
179     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
180     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
181     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
182     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185 
186     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
187       setOperationAction(ISD::SADDSAT, VT, Legal);
188       setOperationAction(ISD::UADDSAT, VT, Legal);
189       setOperationAction(ISD::SSUBSAT, VT, Legal);
190       setOperationAction(ISD::USUBSAT, VT, Legal);
191       setOperationAction(ISD::SMAX, VT, Legal);
192       setOperationAction(ISD::UMAX, VT, Legal);
193       setOperationAction(ISD::SMIN, VT, Legal);
194       setOperationAction(ISD::UMIN, VT, Legal);
195     }
196 
197     for (auto VT :
198          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
199            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
200       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
201 
202     for (auto VT :
203          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
204            MVT::nxv2f64 }) {
205       setCondCodeAction(ISD::SETO, VT, Expand);
206       setCondCodeAction(ISD::SETOLT, VT, Expand);
207       setCondCodeAction(ISD::SETOLE, VT, Expand);
208       setCondCodeAction(ISD::SETULT, VT, Expand);
209       setCondCodeAction(ISD::SETULE, VT, Expand);
210       setCondCodeAction(ISD::SETUGE, VT, Expand);
211       setCondCodeAction(ISD::SETUGT, VT, Expand);
212       setCondCodeAction(ISD::SETUEQ, VT, Expand);
213       setCondCodeAction(ISD::SETUNE, VT, Expand);
214     }
215   }
216 
217   // Compute derived properties from the register classes
218   computeRegisterProperties(Subtarget->getRegisterInfo());
219 
220   // Provide all sorts of operation actions
221   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
222   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
223   setOperationAction(ISD::SETCC, MVT::i32, Custom);
224   setOperationAction(ISD::SETCC, MVT::i64, Custom);
225   setOperationAction(ISD::SETCC, MVT::f16, Custom);
226   setOperationAction(ISD::SETCC, MVT::f32, Custom);
227   setOperationAction(ISD::SETCC, MVT::f64, Custom);
228   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
229   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
230   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
231   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
232   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
233   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
234   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
235   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
236   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
237   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
238   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
239   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
240   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
241   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
242   setOperationAction(ISD::SELECT, MVT::i32, Custom);
243   setOperationAction(ISD::SELECT, MVT::i64, Custom);
244   setOperationAction(ISD::SELECT, MVT::f16, Custom);
245   setOperationAction(ISD::SELECT, MVT::f32, Custom);
246   setOperationAction(ISD::SELECT, MVT::f64, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
248   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
249   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
250   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
251   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
252   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
253   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
254 
255   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
256   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
257   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
258 
259   setOperationAction(ISD::FREM, MVT::f32, Expand);
260   setOperationAction(ISD::FREM, MVT::f64, Expand);
261   setOperationAction(ISD::FREM, MVT::f80, Expand);
262 
263   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
264 
265   // Custom lowering hooks are needed for XOR
266   // to fold it into CSINC/CSINV.
267   setOperationAction(ISD::XOR, MVT::i32, Custom);
268   setOperationAction(ISD::XOR, MVT::i64, Custom);
269 
270   // Virtually no operation on f128 is legal, but LLVM can't expand them when
271   // there's a valid register class, so we need custom operations in most cases.
272   setOperationAction(ISD::FABS, MVT::f128, Expand);
273   setOperationAction(ISD::FADD, MVT::f128, Custom);
274   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
275   setOperationAction(ISD::FCOS, MVT::f128, Expand);
276   setOperationAction(ISD::FDIV, MVT::f128, Custom);
277   setOperationAction(ISD::FMA, MVT::f128, Expand);
278   setOperationAction(ISD::FMUL, MVT::f128, Custom);
279   setOperationAction(ISD::FNEG, MVT::f128, Expand);
280   setOperationAction(ISD::FPOW, MVT::f128, Expand);
281   setOperationAction(ISD::FREM, MVT::f128, Expand);
282   setOperationAction(ISD::FRINT, MVT::f128, Expand);
283   setOperationAction(ISD::FSIN, MVT::f128, Expand);
284   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
285   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
286   setOperationAction(ISD::FSUB, MVT::f128, Custom);
287   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
288   setOperationAction(ISD::SETCC, MVT::f128, Custom);
289   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
290   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
291   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
292   setOperationAction(ISD::SELECT, MVT::f128, Custom);
293   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
294   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
295 
296   // Lowering for many of the conversions is actually specified by the non-f128
297   // type. The LowerXXX function will be trivial when f128 isn't involved.
298   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
299   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
300   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
301   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
302   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
303   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
304   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
305   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
306   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
307   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
308   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
309   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
310   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
311   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
312   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
313   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
314   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
315   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
316   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
317   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
318   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
319   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
320   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
321   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
322   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
323   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
324   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
325   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
326 
327   // Variable arguments.
328   setOperationAction(ISD::VASTART, MVT::Other, Custom);
329   setOperationAction(ISD::VAARG, MVT::Other, Custom);
330   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
331   setOperationAction(ISD::VAEND, MVT::Other, Expand);
332 
333   // Variable-sized objects.
334   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
335   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
336 
337   if (Subtarget->isTargetWindows())
338     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
339   else
340     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
341 
342   // Constant pool entries
343   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
344 
345   // BlockAddress
346   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
347 
348   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
349   setOperationAction(ISD::ADDC, MVT::i32, Custom);
350   setOperationAction(ISD::ADDE, MVT::i32, Custom);
351   setOperationAction(ISD::SUBC, MVT::i32, Custom);
352   setOperationAction(ISD::SUBE, MVT::i32, Custom);
353   setOperationAction(ISD::ADDC, MVT::i64, Custom);
354   setOperationAction(ISD::ADDE, MVT::i64, Custom);
355   setOperationAction(ISD::SUBC, MVT::i64, Custom);
356   setOperationAction(ISD::SUBE, MVT::i64, Custom);
357 
358   // AArch64 lacks both left-rotate and popcount instructions.
359   setOperationAction(ISD::ROTL, MVT::i32, Expand);
360   setOperationAction(ISD::ROTL, MVT::i64, Expand);
361   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
362     setOperationAction(ISD::ROTL, VT, Expand);
363     setOperationAction(ISD::ROTR, VT, Expand);
364   }
365 
366   // AArch64 doesn't have {U|S}MUL_LOHI.
367   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
368   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
369 
370   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
371   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
372 
373   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
374   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
375   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
376     setOperationAction(ISD::SDIVREM, VT, Expand);
377     setOperationAction(ISD::UDIVREM, VT, Expand);
378   }
379   setOperationAction(ISD::SREM, MVT::i32, Expand);
380   setOperationAction(ISD::SREM, MVT::i64, Expand);
381   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
382   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
383   setOperationAction(ISD::UREM, MVT::i32, Expand);
384   setOperationAction(ISD::UREM, MVT::i64, Expand);
385 
386   // Custom lower Add/Sub/Mul with overflow.
387   setOperationAction(ISD::SADDO, MVT::i32, Custom);
388   setOperationAction(ISD::SADDO, MVT::i64, Custom);
389   setOperationAction(ISD::UADDO, MVT::i32, Custom);
390   setOperationAction(ISD::UADDO, MVT::i64, Custom);
391   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
392   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
393   setOperationAction(ISD::USUBO, MVT::i32, Custom);
394   setOperationAction(ISD::USUBO, MVT::i64, Custom);
395   setOperationAction(ISD::SMULO, MVT::i32, Custom);
396   setOperationAction(ISD::SMULO, MVT::i64, Custom);
397   setOperationAction(ISD::UMULO, MVT::i32, Custom);
398   setOperationAction(ISD::UMULO, MVT::i64, Custom);
399 
400   setOperationAction(ISD::FSIN, MVT::f32, Expand);
401   setOperationAction(ISD::FSIN, MVT::f64, Expand);
402   setOperationAction(ISD::FCOS, MVT::f32, Expand);
403   setOperationAction(ISD::FCOS, MVT::f64, Expand);
404   setOperationAction(ISD::FPOW, MVT::f32, Expand);
405   setOperationAction(ISD::FPOW, MVT::f64, Expand);
406   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
407   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
408   if (Subtarget->hasFullFP16())
409     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
410   else
411     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
412 
413   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
414   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
415   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
416   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
417   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
418   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
419   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
420   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
421   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
422   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
423   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
424   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
425   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
426   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
427   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
428   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
429   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
430   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
431   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
432   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
433   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
434   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
435   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
436   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
437   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
438   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
439   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
440   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
441   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
442   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
443   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
444   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
445   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
446 
447   if (!Subtarget->hasFullFP16()) {
448     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
449     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
450     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
451     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
452     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
453     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
454     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
455     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
456     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
457     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
458     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
459     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
460     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
461     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
462     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
463     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
464     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
465     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
466     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
467     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
468     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
469     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
470 
471     // promote v4f16 to v4f32 when that is known to be safe.
472     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
473     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
474     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
475     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
476     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
477     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
478     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
479     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
480 
481     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
482     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
483     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
484     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
485     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
486     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
487     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
488     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
489     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
490     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
491     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
492     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
493     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
494     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
495     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
496 
497     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
498     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
499     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
500     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
501     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
502     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
503     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
504     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
505     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
506     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
507     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
508     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
509     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
510     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
511     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
512     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
513     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
514     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
515     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
516     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
517   }
518 
519   // AArch64 has implementations of a lot of rounding-like FP operations.
520   for (MVT Ty : {MVT::f32, MVT::f64}) {
521     setOperationAction(ISD::FFLOOR, Ty, Legal);
522     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
523     setOperationAction(ISD::FCEIL, Ty, Legal);
524     setOperationAction(ISD::FRINT, Ty, Legal);
525     setOperationAction(ISD::FTRUNC, Ty, Legal);
526     setOperationAction(ISD::FROUND, Ty, Legal);
527     setOperationAction(ISD::FMINNUM, Ty, Legal);
528     setOperationAction(ISD::FMAXNUM, Ty, Legal);
529     setOperationAction(ISD::FMINIMUM, Ty, Legal);
530     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
531     setOperationAction(ISD::LROUND, Ty, Legal);
532     setOperationAction(ISD::LLROUND, Ty, Legal);
533     setOperationAction(ISD::LRINT, Ty, Legal);
534     setOperationAction(ISD::LLRINT, Ty, Legal);
535   }
536 
537   if (Subtarget->hasFullFP16()) {
538     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
539     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
540     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
541     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
542     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
543     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
544     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
545     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
546     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
547     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
548   }
549 
550   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
551 
552   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
553 
554   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
555   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
556   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
557   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
558   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
559 
560   // 128-bit loads and stores can be done without expanding
561   setOperationAction(ISD::LOAD, MVT::i128, Custom);
562   setOperationAction(ISD::STORE, MVT::i128, Custom);
563 
564   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
565   // custom lowering, as there are no un-paired non-temporal stores and
566   // legalization will break up 256 bit inputs.
567   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
568   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
569   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
570   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
571   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
572   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
573   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
574 
575   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
576   // This requires the Performance Monitors extension.
577   if (Subtarget->hasPerfMon())
578     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
579 
580   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
581       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
582     // Issue __sincos_stret if available.
583     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
584     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
585   } else {
586     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
587     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
588   }
589 
590   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
591     // MSVCRT doesn't have powi; fall back to pow
592     setLibcallName(RTLIB::POWI_F32, nullptr);
593     setLibcallName(RTLIB::POWI_F64, nullptr);
594   }
595 
596   // Make floating-point constants legal for the large code model, so they don't
597   // become loads from the constant pool.
598   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
599     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
600     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
601   }
602 
603   // AArch64 does not have floating-point extending loads, i1 sign-extending
604   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
605   for (MVT VT : MVT::fp_valuetypes()) {
606     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
607     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
608     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
609     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
610   }
611   for (MVT VT : MVT::integer_valuetypes())
612     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
613 
614   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
615   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
616   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
617   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
618   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
619   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
620   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
621 
622   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
623   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
624 
625   // Indexed loads and stores are supported.
626   for (unsigned im = (unsigned)ISD::PRE_INC;
627        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
628     setIndexedLoadAction(im, MVT::i8, Legal);
629     setIndexedLoadAction(im, MVT::i16, Legal);
630     setIndexedLoadAction(im, MVT::i32, Legal);
631     setIndexedLoadAction(im, MVT::i64, Legal);
632     setIndexedLoadAction(im, MVT::f64, Legal);
633     setIndexedLoadAction(im, MVT::f32, Legal);
634     setIndexedLoadAction(im, MVT::f16, Legal);
635     setIndexedStoreAction(im, MVT::i8, Legal);
636     setIndexedStoreAction(im, MVT::i16, Legal);
637     setIndexedStoreAction(im, MVT::i32, Legal);
638     setIndexedStoreAction(im, MVT::i64, Legal);
639     setIndexedStoreAction(im, MVT::f64, Legal);
640     setIndexedStoreAction(im, MVT::f32, Legal);
641     setIndexedStoreAction(im, MVT::f16, Legal);
642   }
643 
644   // Trap.
645   setOperationAction(ISD::TRAP, MVT::Other, Legal);
646   if (Subtarget->isTargetWindows())
647     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
648 
649   // We combine OR nodes for bitfield operations.
650   setTargetDAGCombine(ISD::OR);
651   // Try to create BICs for vector ANDs.
652   setTargetDAGCombine(ISD::AND);
653 
654   // Vector add and sub nodes may conceal a high-half opportunity.
655   // Also, try to fold ADD into CSINC/CSINV..
656   setTargetDAGCombine(ISD::ADD);
657   setTargetDAGCombine(ISD::SUB);
658   setTargetDAGCombine(ISD::SRL);
659   setTargetDAGCombine(ISD::XOR);
660   setTargetDAGCombine(ISD::SINT_TO_FP);
661   setTargetDAGCombine(ISD::UINT_TO_FP);
662 
663   setTargetDAGCombine(ISD::FP_TO_SINT);
664   setTargetDAGCombine(ISD::FP_TO_UINT);
665   setTargetDAGCombine(ISD::FDIV);
666 
667   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
668 
669   setTargetDAGCombine(ISD::ANY_EXTEND);
670   setTargetDAGCombine(ISD::ZERO_EXTEND);
671   setTargetDAGCombine(ISD::SIGN_EXTEND);
672   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
673   setTargetDAGCombine(ISD::CONCAT_VECTORS);
674   setTargetDAGCombine(ISD::STORE);
675   if (Subtarget->supportsAddressTopByteIgnored())
676     setTargetDAGCombine(ISD::LOAD);
677 
678   setTargetDAGCombine(ISD::MUL);
679 
680   setTargetDAGCombine(ISD::SELECT);
681   setTargetDAGCombine(ISD::VSELECT);
682 
683   setTargetDAGCombine(ISD::INTRINSIC_VOID);
684   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
685   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
686 
687   setTargetDAGCombine(ISD::GlobalAddress);
688 
689   // In case of strict alignment, avoid an excessive number of byte wide stores.
690   MaxStoresPerMemsetOptSize = 8;
691   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
692                        ? MaxStoresPerMemsetOptSize : 32;
693 
694   MaxGluedStoresPerMemcpy = 4;
695   MaxStoresPerMemcpyOptSize = 4;
696   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
697                        ? MaxStoresPerMemcpyOptSize : 16;
698 
699   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
700 
701   MaxLoadsPerMemcmpOptSize = 4;
702   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
703                       ? MaxLoadsPerMemcmpOptSize : 8;
704 
705   setStackPointerRegisterToSaveRestore(AArch64::SP);
706 
707   setSchedulingPreference(Sched::Hybrid);
708 
709   EnableExtLdPromotion = true;
710 
711   // Set required alignment.
712   setMinFunctionAlignment(Align(4));
713   // Set preferred alignments.
714   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
715   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
716 
717   // Only change the limit for entries in a jump table if specified by
718   // the sub target, but not at the command line.
719   unsigned MaxJT = STI.getMaximumJumpTableSize();
720   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
721     setMaximumJumpTableSize(MaxJT);
722 
723   setHasExtractBitsInsn(true);
724 
725   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
726 
727   if (Subtarget->hasNEON()) {
728     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
729     // silliness like this:
730     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
731     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
732     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
734     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
735     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
736     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
737     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
738     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
739     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
740     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
741     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
742     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
743     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
744     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
745     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
746     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
747     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
748     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
749     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
750     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
751     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
752     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
753     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
754     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
755 
756     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
757     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
758     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
759     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
760     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
761 
762     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
763 
764     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
765     // elements smaller than i32, so promote the input to i32 first.
766     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
767     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
768     // i8 vector elements also need promotion to i32 for v8i8
769     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
770     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
771     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
772     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
773     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
774     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
775     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
776     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
777     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
778     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
779     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
780 
781     if (Subtarget->hasFullFP16()) {
782       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
783       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
784       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
785       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
786     } else {
787       // when AArch64 doesn't have fullfp16 support, promote the input
788       // to i32 first.
789       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
790       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
791       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
792       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
793     }
794 
795     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
796     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
797 
798     // AArch64 doesn't have MUL.2d:
799     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
800     // Custom handling for some quad-vector types to detect MULL.
801     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
802     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
803     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
804 
805     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
806                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
807       // Vector reductions
808       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
809       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
810       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
811       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
812       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
813 
814       // Saturates
815       setOperationAction(ISD::SADDSAT, VT, Legal);
816       setOperationAction(ISD::UADDSAT, VT, Legal);
817       setOperationAction(ISD::SSUBSAT, VT, Legal);
818       setOperationAction(ISD::USUBSAT, VT, Legal);
819     }
820     for (MVT VT : { MVT::v4f16, MVT::v2f32,
821                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
822       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
823       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
824     }
825 
826     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
827     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
828     // Likewise, narrowing and extending vector loads/stores aren't handled
829     // directly.
830     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
831       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
832 
833       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
834         setOperationAction(ISD::MULHS, VT, Legal);
835         setOperationAction(ISD::MULHU, VT, Legal);
836       } else {
837         setOperationAction(ISD::MULHS, VT, Expand);
838         setOperationAction(ISD::MULHU, VT, Expand);
839       }
840       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
842 
843       setOperationAction(ISD::BSWAP, VT, Expand);
844       setOperationAction(ISD::CTTZ, VT, Expand);
845 
846       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
847         setTruncStoreAction(VT, InnerVT, Expand);
848         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
849         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
850         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
851       }
852     }
853 
854     // AArch64 has implementations of a lot of rounding-like FP operations.
855     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
856       setOperationAction(ISD::FFLOOR, Ty, Legal);
857       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
858       setOperationAction(ISD::FCEIL, Ty, Legal);
859       setOperationAction(ISD::FRINT, Ty, Legal);
860       setOperationAction(ISD::FTRUNC, Ty, Legal);
861       setOperationAction(ISD::FROUND, Ty, Legal);
862     }
863 
864     if (Subtarget->hasFullFP16()) {
865       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
866         setOperationAction(ISD::FFLOOR, Ty, Legal);
867         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
868         setOperationAction(ISD::FCEIL, Ty, Legal);
869         setOperationAction(ISD::FRINT, Ty, Legal);
870         setOperationAction(ISD::FTRUNC, Ty, Legal);
871         setOperationAction(ISD::FROUND, Ty, Legal);
872       }
873     }
874 
875     if (Subtarget->hasSVE())
876       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
877 
878     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
879   }
880 
881   if (Subtarget->hasSVE()) {
882     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
883     // splat of 0 or undef) once vector selects supported in SVE codegen. See
884     // D68877 for more details.
885     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
886       if (isTypeLegal(VT))
887         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
888     }
889     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
890     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
891 
892     for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
893       if (isTypeLegal(VT)) {
894         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
895       }
896     }
897   }
898 
899   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
900 }
901 
902 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
903   assert(VT.isVector() && "VT should be a vector type");
904 
905   if (VT.isFloatingPoint()) {
906     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
907     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
908     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
909   }
910 
911   // Mark vector float intrinsics as expand.
912   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
913     setOperationAction(ISD::FSIN, VT, Expand);
914     setOperationAction(ISD::FCOS, VT, Expand);
915     setOperationAction(ISD::FPOW, VT, Expand);
916     setOperationAction(ISD::FLOG, VT, Expand);
917     setOperationAction(ISD::FLOG2, VT, Expand);
918     setOperationAction(ISD::FLOG10, VT, Expand);
919     setOperationAction(ISD::FEXP, VT, Expand);
920     setOperationAction(ISD::FEXP2, VT, Expand);
921 
922     // But we do support custom-lowering for FCOPYSIGN.
923     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
924   }
925 
926   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
927   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
928   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
929   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
930   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
931   setOperationAction(ISD::SRA, VT, Custom);
932   setOperationAction(ISD::SRL, VT, Custom);
933   setOperationAction(ISD::SHL, VT, Custom);
934   setOperationAction(ISD::OR, VT, Custom);
935   setOperationAction(ISD::SETCC, VT, Custom);
936   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
937 
938   setOperationAction(ISD::SELECT, VT, Expand);
939   setOperationAction(ISD::SELECT_CC, VT, Expand);
940   setOperationAction(ISD::VSELECT, VT, Expand);
941   for (MVT InnerVT : MVT::all_valuetypes())
942     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
943 
944   // CNT supports only B element sizes, then use UADDLP to widen.
945   if (VT != MVT::v8i8 && VT != MVT::v16i8)
946     setOperationAction(ISD::CTPOP, VT, Custom);
947 
948   setOperationAction(ISD::UDIV, VT, Expand);
949   setOperationAction(ISD::SDIV, VT, Expand);
950   setOperationAction(ISD::UREM, VT, Expand);
951   setOperationAction(ISD::SREM, VT, Expand);
952   setOperationAction(ISD::FREM, VT, Expand);
953 
954   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
955   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
956 
957   if (!VT.isFloatingPoint())
958     setOperationAction(ISD::ABS, VT, Legal);
959 
960   // [SU][MIN|MAX] are available for all NEON types apart from i64.
961   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
962     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
963       setOperationAction(Opcode, VT, Legal);
964 
965   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
966   if (VT.isFloatingPoint() &&
967       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
968     for (unsigned Opcode :
969          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
970       setOperationAction(Opcode, VT, Legal);
971 
972   if (Subtarget->isLittleEndian()) {
973     for (unsigned im = (unsigned)ISD::PRE_INC;
974          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
975       setIndexedLoadAction(im, VT, Legal);
976       setIndexedStoreAction(im, VT, Legal);
977     }
978   }
979 }
980 
981 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
982   addRegisterClass(VT, &AArch64::FPR64RegClass);
983   addTypeForNEON(VT, MVT::v2i32);
984 }
985 
986 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
987   addRegisterClass(VT, &AArch64::FPR128RegClass);
988   addTypeForNEON(VT, MVT::v4i32);
989 }
990 
991 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
992                                               EVT VT) const {
993   if (!VT.isVector())
994     return MVT::i32;
995   return VT.changeVectorElementTypeToInteger();
996 }
997 
998 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
999                                const APInt &Demanded,
1000                                TargetLowering::TargetLoweringOpt &TLO,
1001                                unsigned NewOpc) {
1002   uint64_t OldImm = Imm, NewImm, Enc;
1003   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1004 
1005   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1006   // bimm64.
1007   if (Imm == 0 || Imm == Mask ||
1008       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1009     return false;
1010 
1011   unsigned EltSize = Size;
1012   uint64_t DemandedBits = Demanded.getZExtValue();
1013 
1014   // Clear bits that are not demanded.
1015   Imm &= DemandedBits;
1016 
1017   while (true) {
1018     // The goal here is to set the non-demanded bits in a way that minimizes
1019     // the number of switching between 0 and 1. In order to achieve this goal,
1020     // we set the non-demanded bits to the value of the preceding demanded bits.
1021     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1022     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1023     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1024     // The final result is 0b11000011.
1025     uint64_t NonDemandedBits = ~DemandedBits;
1026     uint64_t InvertedImm = ~Imm & DemandedBits;
1027     uint64_t RotatedImm =
1028         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1029         NonDemandedBits;
1030     uint64_t Sum = RotatedImm + NonDemandedBits;
1031     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1032     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1033     NewImm = (Imm | Ones) & Mask;
1034 
1035     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1036     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1037     // we halve the element size and continue the search.
1038     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1039       break;
1040 
1041     // We cannot shrink the element size any further if it is 2-bits.
1042     if (EltSize == 2)
1043       return false;
1044 
1045     EltSize /= 2;
1046     Mask >>= EltSize;
1047     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1048 
1049     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1050     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1051       return false;
1052 
1053     // Merge the upper and lower halves of Imm and DemandedBits.
1054     Imm |= Hi;
1055     DemandedBits |= DemandedBitsHi;
1056   }
1057 
1058   ++NumOptimizedImms;
1059 
1060   // Replicate the element across the register width.
1061   while (EltSize < Size) {
1062     NewImm |= NewImm << EltSize;
1063     EltSize *= 2;
1064   }
1065 
1066   (void)OldImm;
1067   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1068          "demanded bits should never be altered");
1069   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1070 
1071   // Create the new constant immediate node.
1072   EVT VT = Op.getValueType();
1073   SDLoc DL(Op);
1074   SDValue New;
1075 
1076   // If the new constant immediate is all-zeros or all-ones, let the target
1077   // independent DAG combine optimize this node.
1078   if (NewImm == 0 || NewImm == OrigMask) {
1079     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1080                           TLO.DAG.getConstant(NewImm, DL, VT));
1081   // Otherwise, create a machine node so that target independent DAG combine
1082   // doesn't undo this optimization.
1083   } else {
1084     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1085     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1086     New = SDValue(
1087         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1088   }
1089 
1090   return TLO.CombineTo(Op, New);
1091 }
1092 
1093 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1094     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1095   // Delay this optimization to as late as possible.
1096   if (!TLO.LegalOps)
1097     return false;
1098 
1099   if (!EnableOptimizeLogicalImm)
1100     return false;
1101 
1102   EVT VT = Op.getValueType();
1103   if (VT.isVector())
1104     return false;
1105 
1106   unsigned Size = VT.getSizeInBits();
1107   assert((Size == 32 || Size == 64) &&
1108          "i32 or i64 is expected after legalization.");
1109 
1110   // Exit early if we demand all bits.
1111   if (Demanded.countPopulation() == Size)
1112     return false;
1113 
1114   unsigned NewOpc;
1115   switch (Op.getOpcode()) {
1116   default:
1117     return false;
1118   case ISD::AND:
1119     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1120     break;
1121   case ISD::OR:
1122     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1123     break;
1124   case ISD::XOR:
1125     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1126     break;
1127   }
1128   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1129   if (!C)
1130     return false;
1131   uint64_t Imm = C->getZExtValue();
1132   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1133 }
1134 
1135 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1136 /// Mask are known to be either zero or one and return them Known.
1137 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1138     const SDValue Op, KnownBits &Known,
1139     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1140   switch (Op.getOpcode()) {
1141   default:
1142     break;
1143   case AArch64ISD::CSEL: {
1144     KnownBits Known2;
1145     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1146     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1147     Known.Zero &= Known2.Zero;
1148     Known.One &= Known2.One;
1149     break;
1150   }
1151   case AArch64ISD::LOADgot:
1152   case AArch64ISD::ADDlow: {
1153     if (!Subtarget->isTargetILP32())
1154       break;
1155     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1156     Known.Zero = APInt::getHighBitsSet(64, 32);
1157     break;
1158   }
1159   case ISD::INTRINSIC_W_CHAIN: {
1160     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1161     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1162     switch (IntID) {
1163     default: return;
1164     case Intrinsic::aarch64_ldaxr:
1165     case Intrinsic::aarch64_ldxr: {
1166       unsigned BitWidth = Known.getBitWidth();
1167       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1168       unsigned MemBits = VT.getScalarSizeInBits();
1169       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1170       return;
1171     }
1172     }
1173     break;
1174   }
1175   case ISD::INTRINSIC_WO_CHAIN:
1176   case ISD::INTRINSIC_VOID: {
1177     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1178     switch (IntNo) {
1179     default:
1180       break;
1181     case Intrinsic::aarch64_neon_umaxv:
1182     case Intrinsic::aarch64_neon_uminv: {
1183       // Figure out the datatype of the vector operand. The UMINV instruction
1184       // will zero extend the result, so we can mark as known zero all the
1185       // bits larger than the element datatype. 32-bit or larget doesn't need
1186       // this as those are legal types and will be handled by isel directly.
1187       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1188       unsigned BitWidth = Known.getBitWidth();
1189       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1190         assert(BitWidth >= 8 && "Unexpected width!");
1191         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1192         Known.Zero |= Mask;
1193       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1194         assert(BitWidth >= 16 && "Unexpected width!");
1195         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1196         Known.Zero |= Mask;
1197       }
1198       break;
1199     } break;
1200     }
1201   }
1202   }
1203 }
1204 
1205 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1206                                                   EVT) const {
1207   return MVT::i64;
1208 }
1209 
1210 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1211     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1212     bool *Fast) const {
1213   if (Subtarget->requiresStrictAlign())
1214     return false;
1215 
1216   if (Fast) {
1217     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1218     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1219             // See comments in performSTORECombine() for more details about
1220             // these conditions.
1221 
1222             // Code that uses clang vector extensions can mark that it
1223             // wants unaligned accesses to be treated as fast by
1224             // underspecifying alignment to be 1 or 2.
1225             Align <= 2 ||
1226 
1227             // Disregard v2i64. Memcpy lowering produces those and splitting
1228             // them regresses performance on micro-benchmarks and olden/bh.
1229             VT == MVT::v2i64;
1230   }
1231   return true;
1232 }
1233 
1234 // Same as above but handling LLTs instead.
1235 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1236     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1237     bool *Fast) const {
1238   if (Subtarget->requiresStrictAlign())
1239     return false;
1240 
1241   if (Fast) {
1242     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1243     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1244             Ty.getSizeInBytes() != 16 ||
1245             // See comments in performSTORECombine() for more details about
1246             // these conditions.
1247 
1248             // Code that uses clang vector extensions can mark that it
1249             // wants unaligned accesses to be treated as fast by
1250             // underspecifying alignment to be 1 or 2.
1251             Align <= 2 ||
1252 
1253             // Disregard v2i64. Memcpy lowering produces those and splitting
1254             // them regresses performance on micro-benchmarks and olden/bh.
1255             Ty == LLT::vector(2, 64);
1256   }
1257   return true;
1258 }
1259 
1260 FastISel *
1261 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1262                                       const TargetLibraryInfo *libInfo) const {
1263   return AArch64::createFastISel(funcInfo, libInfo);
1264 }
1265 
1266 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1267   switch ((AArch64ISD::NodeType)Opcode) {
1268   case AArch64ISD::FIRST_NUMBER:      break;
1269   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1270   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1271   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1272   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1273   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1274   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1275   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1276   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1277   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1278   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1279   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1280   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1281   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1282   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1283   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1284   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1285   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1286   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1287   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1288   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1289   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1290   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1291   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1292   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1293   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1294   case AArch64ISD::STRICT_FCMP:       return "AArch64ISD::STRICT_FCMP";
1295   case AArch64ISD::STRICT_FCMPE:      return "AArch64ISD::STRICT_FCMPE";
1296   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1297   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1298   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1299   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1300   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1301   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1302   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1303   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1304   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1305   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1306   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1307   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1308   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1309   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1310   case AArch64ISD::BSP:               return "AArch64ISD::BSP";
1311   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1312   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1313   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1314   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1315   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1316   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1317   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1318   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1319   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1320   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1321   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1322   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1323   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1324   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1325   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1326   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1327   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1328   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1329   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1330   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1331   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1332   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1333   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1334   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1335   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1336   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1337   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1338   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1339   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1340   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1341   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1342   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1343   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1344   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1345   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1346   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1347   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1348   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1349   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1350   case AArch64ISD::SMAXV_PRED:        return "AArch64ISD::SMAXV_PRED";
1351   case AArch64ISD::UMAXV_PRED:        return "AArch64ISD::UMAXV_PRED";
1352   case AArch64ISD::SMINV_PRED:        return "AArch64ISD::SMINV_PRED";
1353   case AArch64ISD::UMINV_PRED:        return "AArch64ISD::UMINV_PRED";
1354   case AArch64ISD::ORV_PRED:          return "AArch64ISD::ORV_PRED";
1355   case AArch64ISD::EORV_PRED:         return "AArch64ISD::EORV_PRED";
1356   case AArch64ISD::ANDV_PRED:         return "AArch64ISD::ANDV_PRED";
1357   case AArch64ISD::CLASTA_N:          return "AArch64ISD::CLASTA_N";
1358   case AArch64ISD::CLASTB_N:          return "AArch64ISD::CLASTB_N";
1359   case AArch64ISD::LASTA:             return "AArch64ISD::LASTA";
1360   case AArch64ISD::LASTB:             return "AArch64ISD::LASTB";
1361   case AArch64ISD::REV:               return "AArch64ISD::REV";
1362   case AArch64ISD::REINTERPRET_CAST:  return "AArch64ISD::REINTERPRET_CAST";
1363   case AArch64ISD::TBL:               return "AArch64ISD::TBL";
1364   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1365   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1366   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1367   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1368   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1369   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1370   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1371   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1372   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1373   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1374   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1375   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1376   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1377   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1378   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1379   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1380   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1381   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1382   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1383   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1384   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1385   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1386   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1387   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1388   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1389   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1390   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1391   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1392   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1393   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1394   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1395   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1396   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1397   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1398   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1399   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1400   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1401   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1402   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1403   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1404   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1405   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1406   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1407   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1408   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1409   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1410   case AArch64ISD::STG:               return "AArch64ISD::STG";
1411   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1412   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1413   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1414   case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1415   case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1416   case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1417   case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1418   case AArch64ISD::INSR:              return "AArch64ISD::INSR";
1419   case AArch64ISD::PTEST:             return "AArch64ISD::PTEST";
1420   case AArch64ISD::PTRUE:             return "AArch64ISD::PTRUE";
1421   case AArch64ISD::LDNF1:             return "AArch64ISD::LDNF1";
1422   case AArch64ISD::LDNF1S:            return "AArch64ISD::LDNF1S";
1423   case AArch64ISD::LDFF1:             return "AArch64ISD::LDFF1";
1424   case AArch64ISD::LDFF1S:            return "AArch64ISD::LDFF1S";
1425   case AArch64ISD::GLD1:              return "AArch64ISD::GLD1";
1426   case AArch64ISD::GLD1_SCALED:       return "AArch64ISD::GLD1_SCALED";
1427   case AArch64ISD::GLD1_SXTW:         return "AArch64ISD::GLD1_SXTW";
1428   case AArch64ISD::GLD1_UXTW:         return "AArch64ISD::GLD1_UXTW";
1429   case AArch64ISD::GLD1_SXTW_SCALED:  return "AArch64ISD::GLD1_SXTW_SCALED";
1430   case AArch64ISD::GLD1_UXTW_SCALED:  return "AArch64ISD::GLD1_UXTW_SCALED";
1431   case AArch64ISD::GLD1_IMM:          return "AArch64ISD::GLD1_IMM";
1432   case AArch64ISD::GLD1S:             return "AArch64ISD::GLD1S";
1433   case AArch64ISD::GLD1S_SCALED:      return "AArch64ISD::GLD1S_SCALED";
1434   case AArch64ISD::GLD1S_SXTW:        return "AArch64ISD::GLD1S_SXTW";
1435   case AArch64ISD::GLD1S_UXTW:        return "AArch64ISD::GLD1S_UXTW";
1436   case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1437   case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1438   case AArch64ISD::GLD1S_IMM:         return "AArch64ISD::GLD1S_IMM";
1439   case AArch64ISD::GLDFF1:            return "AArch64ISD::GLDFF1";
1440   case AArch64ISD::GLDFF1_SCALED:     return "AArch64ISD::GLDFF1_SCALED";
1441   case AArch64ISD::GLDFF1_SXTW:       return "AArch64ISD::GLDFF1_SXTW";
1442   case AArch64ISD::GLDFF1_UXTW:       return "AArch64ISD::GLDFF1_UXTW";
1443   case AArch64ISD::GLDFF1_SXTW_SCALED:return "AArch64ISD::GLDFF1_SXTW_SCALED";
1444   case AArch64ISD::GLDFF1_UXTW_SCALED:return "AArch64ISD::GLDFF1_UXTW_SCALED";
1445   case AArch64ISD::GLDFF1_IMM:        return "AArch64ISD::GLDFF1_IMM";
1446   case AArch64ISD::GLDFF1S:           return "AArch64ISD::GLDFF1S";
1447   case AArch64ISD::GLDFF1S_SCALED:    return "AArch64ISD::GLDFF1S_SCALED";
1448   case AArch64ISD::GLDFF1S_SXTW:      return "AArch64ISD::GLDFF1S_SXTW";
1449   case AArch64ISD::GLDFF1S_UXTW:      return "AArch64ISD::GLDFF1S_UXTW";
1450   case AArch64ISD::GLDFF1S_SXTW_SCALED:
1451     return "AArch64ISD::GLDFF1S_SXTW_SCALED";
1452   case AArch64ISD::GLDFF1S_UXTW_SCALED:
1453     return "AArch64ISD::GLDFF1S_UXTW_SCALED";
1454   case AArch64ISD::GLDFF1S_IMM:       return "AArch64ISD::GLDFF1S_IMM";
1455 
1456   case AArch64ISD::GLDNT1:            return "AArch64ISD::GLDNT1";
1457   case AArch64ISD::GLDNT1_INDEX:      return "AArch64ISD::GLDNT1_INDEX";
1458   case AArch64ISD::GLDNT1S:           return "AArch64ISD::GLDNT1S";
1459 
1460   case AArch64ISD::SST1:              return "AArch64ISD::SST1";
1461   case AArch64ISD::SST1_SCALED:       return "AArch64ISD::SST1_SCALED";
1462   case AArch64ISD::SST1_SXTW:         return "AArch64ISD::SST1_SXTW";
1463   case AArch64ISD::SST1_UXTW:         return "AArch64ISD::SST1_UXTW";
1464   case AArch64ISD::SST1_SXTW_SCALED:  return "AArch64ISD::SST1_SXTW_SCALED";
1465   case AArch64ISD::SST1_UXTW_SCALED:  return "AArch64ISD::SST1_UXTW_SCALED";
1466   case AArch64ISD::SST1_IMM:          return "AArch64ISD::SST1_IMM";
1467 
1468   case AArch64ISD::SSTNT1:            return "AArch64ISD::SSTNT1";
1469   case AArch64ISD::SSTNT1_INDEX:      return "AArch64ISD::SSTNT1_INDEX";
1470 
1471   case AArch64ISD::LDP:               return "AArch64ISD::LDP";
1472   case AArch64ISD::STP:               return "AArch64ISD::STP";
1473   case AArch64ISD::STNP:              return "AArch64ISD::STNP";
1474   case AArch64ISD::DUP_PRED:          return "AArch64ISD::DUP_PRED";
1475   case AArch64ISD::INDEX_VECTOR:      return "AArch64ISD::INDEX_VECTOR";
1476   }
1477   return nullptr;
1478 }
1479 
1480 MachineBasicBlock *
1481 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1482                                     MachineBasicBlock *MBB) const {
1483   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1484   // phi node:
1485 
1486   // OrigBB:
1487   //     [... previous instrs leading to comparison ...]
1488   //     b.ne TrueBB
1489   //     b EndBB
1490   // TrueBB:
1491   //     ; Fallthrough
1492   // EndBB:
1493   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1494 
1495   MachineFunction *MF = MBB->getParent();
1496   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1497   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1498   DebugLoc DL = MI.getDebugLoc();
1499   MachineFunction::iterator It = ++MBB->getIterator();
1500 
1501   Register DestReg = MI.getOperand(0).getReg();
1502   Register IfTrueReg = MI.getOperand(1).getReg();
1503   Register IfFalseReg = MI.getOperand(2).getReg();
1504   unsigned CondCode = MI.getOperand(3).getImm();
1505   bool NZCVKilled = MI.getOperand(4).isKill();
1506 
1507   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1508   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1509   MF->insert(It, TrueBB);
1510   MF->insert(It, EndBB);
1511 
1512   // Transfer rest of current basic-block to EndBB
1513   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1514                 MBB->end());
1515   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1516 
1517   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1518   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1519   MBB->addSuccessor(TrueBB);
1520   MBB->addSuccessor(EndBB);
1521 
1522   // TrueBB falls through to the end.
1523   TrueBB->addSuccessor(EndBB);
1524 
1525   if (!NZCVKilled) {
1526     TrueBB->addLiveIn(AArch64::NZCV);
1527     EndBB->addLiveIn(AArch64::NZCV);
1528   }
1529 
1530   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1531       .addReg(IfTrueReg)
1532       .addMBB(TrueBB)
1533       .addReg(IfFalseReg)
1534       .addMBB(MBB);
1535 
1536   MI.eraseFromParent();
1537   return EndBB;
1538 }
1539 
1540 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1541        MachineInstr &MI, MachineBasicBlock *BB) const {
1542   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1543              BB->getParent()->getFunction().getPersonalityFn())) &&
1544          "SEH does not use catchret!");
1545   return BB;
1546 }
1547 
1548 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1549     MachineInstr &MI, MachineBasicBlock *BB) const {
1550   switch (MI.getOpcode()) {
1551   default:
1552 #ifndef NDEBUG
1553     MI.dump();
1554 #endif
1555     llvm_unreachable("Unexpected instruction for custom inserter!");
1556 
1557   case AArch64::F128CSEL:
1558     return EmitF128CSEL(MI, BB);
1559 
1560   case TargetOpcode::STACKMAP:
1561   case TargetOpcode::PATCHPOINT:
1562     return emitPatchPoint(MI, BB);
1563 
1564   case AArch64::CATCHRET:
1565     return EmitLoweredCatchRet(MI, BB);
1566   }
1567 }
1568 
1569 //===----------------------------------------------------------------------===//
1570 // AArch64 Lowering private implementation.
1571 //===----------------------------------------------------------------------===//
1572 
1573 //===----------------------------------------------------------------------===//
1574 // Lowering Code
1575 //===----------------------------------------------------------------------===//
1576 
1577 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1578 /// CC
1579 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1580   switch (CC) {
1581   default:
1582     llvm_unreachable("Unknown condition code!");
1583   case ISD::SETNE:
1584     return AArch64CC::NE;
1585   case ISD::SETEQ:
1586     return AArch64CC::EQ;
1587   case ISD::SETGT:
1588     return AArch64CC::GT;
1589   case ISD::SETGE:
1590     return AArch64CC::GE;
1591   case ISD::SETLT:
1592     return AArch64CC::LT;
1593   case ISD::SETLE:
1594     return AArch64CC::LE;
1595   case ISD::SETUGT:
1596     return AArch64CC::HI;
1597   case ISD::SETUGE:
1598     return AArch64CC::HS;
1599   case ISD::SETULT:
1600     return AArch64CC::LO;
1601   case ISD::SETULE:
1602     return AArch64CC::LS;
1603   }
1604 }
1605 
1606 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1607 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1608                                   AArch64CC::CondCode &CondCode,
1609                                   AArch64CC::CondCode &CondCode2) {
1610   CondCode2 = AArch64CC::AL;
1611   switch (CC) {
1612   default:
1613     llvm_unreachable("Unknown FP condition!");
1614   case ISD::SETEQ:
1615   case ISD::SETOEQ:
1616     CondCode = AArch64CC::EQ;
1617     break;
1618   case ISD::SETGT:
1619   case ISD::SETOGT:
1620     CondCode = AArch64CC::GT;
1621     break;
1622   case ISD::SETGE:
1623   case ISD::SETOGE:
1624     CondCode = AArch64CC::GE;
1625     break;
1626   case ISD::SETOLT:
1627     CondCode = AArch64CC::MI;
1628     break;
1629   case ISD::SETOLE:
1630     CondCode = AArch64CC::LS;
1631     break;
1632   case ISD::SETONE:
1633     CondCode = AArch64CC::MI;
1634     CondCode2 = AArch64CC::GT;
1635     break;
1636   case ISD::SETO:
1637     CondCode = AArch64CC::VC;
1638     break;
1639   case ISD::SETUO:
1640     CondCode = AArch64CC::VS;
1641     break;
1642   case ISD::SETUEQ:
1643     CondCode = AArch64CC::EQ;
1644     CondCode2 = AArch64CC::VS;
1645     break;
1646   case ISD::SETUGT:
1647     CondCode = AArch64CC::HI;
1648     break;
1649   case ISD::SETUGE:
1650     CondCode = AArch64CC::PL;
1651     break;
1652   case ISD::SETLT:
1653   case ISD::SETULT:
1654     CondCode = AArch64CC::LT;
1655     break;
1656   case ISD::SETLE:
1657   case ISD::SETULE:
1658     CondCode = AArch64CC::LE;
1659     break;
1660   case ISD::SETNE:
1661   case ISD::SETUNE:
1662     CondCode = AArch64CC::NE;
1663     break;
1664   }
1665 }
1666 
1667 /// Convert a DAG fp condition code to an AArch64 CC.
1668 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1669 /// should be AND'ed instead of OR'ed.
1670 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1671                                      AArch64CC::CondCode &CondCode,
1672                                      AArch64CC::CondCode &CondCode2) {
1673   CondCode2 = AArch64CC::AL;
1674   switch (CC) {
1675   default:
1676     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1677     assert(CondCode2 == AArch64CC::AL);
1678     break;
1679   case ISD::SETONE:
1680     // (a one b)
1681     // == ((a olt b) || (a ogt b))
1682     // == ((a ord b) && (a une b))
1683     CondCode = AArch64CC::VC;
1684     CondCode2 = AArch64CC::NE;
1685     break;
1686   case ISD::SETUEQ:
1687     // (a ueq b)
1688     // == ((a uno b) || (a oeq b))
1689     // == ((a ule b) && (a uge b))
1690     CondCode = AArch64CC::PL;
1691     CondCode2 = AArch64CC::LE;
1692     break;
1693   }
1694 }
1695 
1696 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1697 /// CC usable with the vector instructions. Fewer operations are available
1698 /// without a real NZCV register, so we have to use less efficient combinations
1699 /// to get the same effect.
1700 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1701                                         AArch64CC::CondCode &CondCode,
1702                                         AArch64CC::CondCode &CondCode2,
1703                                         bool &Invert) {
1704   Invert = false;
1705   switch (CC) {
1706   default:
1707     // Mostly the scalar mappings work fine.
1708     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1709     break;
1710   case ISD::SETUO:
1711     Invert = true;
1712     LLVM_FALLTHROUGH;
1713   case ISD::SETO:
1714     CondCode = AArch64CC::MI;
1715     CondCode2 = AArch64CC::GE;
1716     break;
1717   case ISD::SETUEQ:
1718   case ISD::SETULT:
1719   case ISD::SETULE:
1720   case ISD::SETUGT:
1721   case ISD::SETUGE:
1722     // All of the compare-mask comparisons are ordered, but we can switch
1723     // between the two by a double inversion. E.g. ULE == !OGT.
1724     Invert = true;
1725     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1726                           CondCode, CondCode2);
1727     break;
1728   }
1729 }
1730 
1731 static bool isLegalArithImmed(uint64_t C) {
1732   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1733   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1734   LLVM_DEBUG(dbgs() << "Is imm " << C
1735                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1736   return IsLegal;
1737 }
1738 
1739 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1740 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1741 // can be set differently by this operation. It comes down to whether
1742 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1743 // everything is fine. If not then the optimization is wrong. Thus general
1744 // comparisons are only valid if op2 != 0.
1745 //
1746 // So, finally, the only LLVM-native comparisons that don't mention C and V
1747 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1748 // the absence of information about op2.
1749 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1750   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1751          (CC == ISD::SETEQ || CC == ISD::SETNE);
1752 }
1753 
1754 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1755                                       SelectionDAG &DAG, SDValue Chain,
1756                                       bool IsSignaling) {
1757   EVT VT = LHS.getValueType();
1758   assert(VT != MVT::f128);
1759   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1760   unsigned Opcode =
1761       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1762   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1763 }
1764 
1765 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1766                               const SDLoc &dl, SelectionDAG &DAG) {
1767   EVT VT = LHS.getValueType();
1768   const bool FullFP16 =
1769     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1770 
1771   if (VT.isFloatingPoint()) {
1772     assert(VT != MVT::f128);
1773     if (VT == MVT::f16 && !FullFP16) {
1774       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1775       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1776       VT = MVT::f32;
1777     }
1778     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1779   }
1780 
1781   // The CMP instruction is just an alias for SUBS, and representing it as
1782   // SUBS means that it's possible to get CSE with subtract operations.
1783   // A later phase can perform the optimization of setting the destination
1784   // register to WZR/XZR if it ends up being unused.
1785   unsigned Opcode = AArch64ISD::SUBS;
1786 
1787   if (isCMN(RHS, CC)) {
1788     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1789     Opcode = AArch64ISD::ADDS;
1790     RHS = RHS.getOperand(1);
1791   } else if (isCMN(LHS, CC)) {
1792     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1793     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1794     Opcode = AArch64ISD::ADDS;
1795     LHS = LHS.getOperand(1);
1796   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
1797     if (LHS.getOpcode() == ISD::AND) {
1798       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1799       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1800       // of the signed comparisons.
1801       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
1802                                            DAG.getVTList(VT, MVT_CC),
1803                                            LHS.getOperand(0),
1804                                            LHS.getOperand(1));
1805       // Replace all users of (and X, Y) with newly generated (ands X, Y)
1806       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
1807       return ANDSNode.getValue(1);
1808     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
1809       // Use result of ANDS
1810       return LHS.getValue(1);
1811     }
1812   }
1813 
1814   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1815       .getValue(1);
1816 }
1817 
1818 /// \defgroup AArch64CCMP CMP;CCMP matching
1819 ///
1820 /// These functions deal with the formation of CMP;CCMP;... sequences.
1821 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1822 /// a comparison. They set the NZCV flags to a predefined value if their
1823 /// predicate is false. This allows to express arbitrary conjunctions, for
1824 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1825 /// expressed as:
1826 ///   cmp A
1827 ///   ccmp B, inv(CB), CA
1828 ///   check for CB flags
1829 ///
1830 /// This naturally lets us implement chains of AND operations with SETCC
1831 /// operands. And we can even implement some other situations by transforming
1832 /// them:
1833 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1834 ///     negating the flags used in a CCMP/FCCMP operations.
1835 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1836 ///     by negating the flags we test for afterwards. i.e.
1837 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1838 ///   - Note that we can only ever negate all previously processed results.
1839 ///     What we can not implement by flipping the flags to test is a negation
1840 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1841 ///     far, so the 2nd sub-tree we emit would also affect the first).
1842 /// With those tools we can implement some OR operations:
1843 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1844 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1845 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1846 ///     elimination rules from earlier to implement the whole thing as a
1847 ///     CCMP/FCCMP chain.
1848 ///
1849 /// As complete example:
1850 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1851 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1852 /// can be reassociated to:
1853 ///     or (and (setCC (cmp C)) setCD (cmp D))
1854 //         (or (setCA (cmp A)) (setCB (cmp B)))
1855 /// can be transformed to:
1856 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1857 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1858 /// which can be implemented as:
1859 ///   cmp C
1860 ///   ccmp D, inv(CD), CC
1861 ///   ccmp A, CA, inv(CD)
1862 ///   ccmp B, CB, inv(CA)
1863 ///   check for CB flags
1864 ///
1865 /// A counterexample is "or (and A B) (and C D)" which translates to
1866 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1867 /// can only implement 1 of the inner (not) operations, but not both!
1868 /// @{
1869 
1870 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1871 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1872                                          ISD::CondCode CC, SDValue CCOp,
1873                                          AArch64CC::CondCode Predicate,
1874                                          AArch64CC::CondCode OutCC,
1875                                          const SDLoc &DL, SelectionDAG &DAG) {
1876   unsigned Opcode = 0;
1877   const bool FullFP16 =
1878     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1879 
1880   if (LHS.getValueType().isFloatingPoint()) {
1881     assert(LHS.getValueType() != MVT::f128);
1882     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1883       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1884       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1885     }
1886     Opcode = AArch64ISD::FCCMP;
1887   } else if (RHS.getOpcode() == ISD::SUB) {
1888     SDValue SubOp0 = RHS.getOperand(0);
1889     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1890       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1891       Opcode = AArch64ISD::CCMN;
1892       RHS = RHS.getOperand(1);
1893     }
1894   }
1895   if (Opcode == 0)
1896     Opcode = AArch64ISD::CCMP;
1897 
1898   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1899   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1900   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1901   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1902   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1903 }
1904 
1905 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1906 /// expressed as a conjunction. See \ref AArch64CCMP.
1907 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1908 ///                     changing the conditions on the SETCC tests.
1909 ///                     (this means we can call emitConjunctionRec() with
1910 ///                      Negate==true on this sub-tree)
1911 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1912 ///                     cannot do the negation naturally. We are required to
1913 ///                     emit the subtree first in this case.
1914 /// \param WillNegate   Is true if are called when the result of this
1915 ///                     subexpression must be negated. This happens when the
1916 ///                     outer expression is an OR. We can use this fact to know
1917 ///                     that we have a double negation (or (or ...) ...) that
1918 ///                     can be implemented for free.
1919 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1920                                bool &MustBeFirst, bool WillNegate,
1921                                unsigned Depth = 0) {
1922   if (!Val.hasOneUse())
1923     return false;
1924   unsigned Opcode = Val->getOpcode();
1925   if (Opcode == ISD::SETCC) {
1926     if (Val->getOperand(0).getValueType() == MVT::f128)
1927       return false;
1928     CanNegate = true;
1929     MustBeFirst = false;
1930     return true;
1931   }
1932   // Protect against exponential runtime and stack overflow.
1933   if (Depth > 6)
1934     return false;
1935   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1936     bool IsOR = Opcode == ISD::OR;
1937     SDValue O0 = Val->getOperand(0);
1938     SDValue O1 = Val->getOperand(1);
1939     bool CanNegateL;
1940     bool MustBeFirstL;
1941     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1942       return false;
1943     bool CanNegateR;
1944     bool MustBeFirstR;
1945     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1946       return false;
1947 
1948     if (MustBeFirstL && MustBeFirstR)
1949       return false;
1950 
1951     if (IsOR) {
1952       // For an OR expression we need to be able to naturally negate at least
1953       // one side or we cannot do the transformation at all.
1954       if (!CanNegateL && !CanNegateR)
1955         return false;
1956       // If we the result of the OR will be negated and we can naturally negate
1957       // the leafs, then this sub-tree as a whole negates naturally.
1958       CanNegate = WillNegate && CanNegateL && CanNegateR;
1959       // If we cannot naturally negate the whole sub-tree, then this must be
1960       // emitted first.
1961       MustBeFirst = !CanNegate;
1962     } else {
1963       assert(Opcode == ISD::AND && "Must be OR or AND");
1964       // We cannot naturally negate an AND operation.
1965       CanNegate = false;
1966       MustBeFirst = MustBeFirstL || MustBeFirstR;
1967     }
1968     return true;
1969   }
1970   return false;
1971 }
1972 
1973 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1974 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1975 /// Tries to transform the given i1 producing node @p Val to a series compare
1976 /// and conditional compare operations. @returns an NZCV flags producing node
1977 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1978 /// transformation was not possible.
1979 /// \p Negate is true if we want this sub-tree being negated just by changing
1980 /// SETCC conditions.
1981 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1982     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1983     AArch64CC::CondCode Predicate) {
1984   // We're at a tree leaf, produce a conditional comparison operation.
1985   unsigned Opcode = Val->getOpcode();
1986   if (Opcode == ISD::SETCC) {
1987     SDValue LHS = Val->getOperand(0);
1988     SDValue RHS = Val->getOperand(1);
1989     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1990     bool isInteger = LHS.getValueType().isInteger();
1991     if (Negate)
1992       CC = getSetCCInverse(CC, LHS.getValueType());
1993     SDLoc DL(Val);
1994     // Determine OutCC and handle FP special case.
1995     if (isInteger) {
1996       OutCC = changeIntCCToAArch64CC(CC);
1997     } else {
1998       assert(LHS.getValueType().isFloatingPoint());
1999       AArch64CC::CondCode ExtraCC;
2000       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2001       // Some floating point conditions can't be tested with a single condition
2002       // code. Construct an additional comparison in this case.
2003       if (ExtraCC != AArch64CC::AL) {
2004         SDValue ExtraCmp;
2005         if (!CCOp.getNode())
2006           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2007         else
2008           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2009                                                ExtraCC, DL, DAG);
2010         CCOp = ExtraCmp;
2011         Predicate = ExtraCC;
2012       }
2013     }
2014 
2015     // Produce a normal comparison if we are first in the chain
2016     if (!CCOp)
2017       return emitComparison(LHS, RHS, CC, DL, DAG);
2018     // Otherwise produce a ccmp.
2019     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2020                                      DAG);
2021   }
2022   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2023 
2024   bool IsOR = Opcode == ISD::OR;
2025 
2026   SDValue LHS = Val->getOperand(0);
2027   bool CanNegateL;
2028   bool MustBeFirstL;
2029   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2030   assert(ValidL && "Valid conjunction/disjunction tree");
2031   (void)ValidL;
2032 
2033   SDValue RHS = Val->getOperand(1);
2034   bool CanNegateR;
2035   bool MustBeFirstR;
2036   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2037   assert(ValidR && "Valid conjunction/disjunction tree");
2038   (void)ValidR;
2039 
2040   // Swap sub-tree that must come first to the right side.
2041   if (MustBeFirstL) {
2042     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2043     std::swap(LHS, RHS);
2044     std::swap(CanNegateL, CanNegateR);
2045     std::swap(MustBeFirstL, MustBeFirstR);
2046   }
2047 
2048   bool NegateR;
2049   bool NegateAfterR;
2050   bool NegateL;
2051   bool NegateAfterAll;
2052   if (Opcode == ISD::OR) {
2053     // Swap the sub-tree that we can negate naturally to the left.
2054     if (!CanNegateL) {
2055       assert(CanNegateR && "at least one side must be negatable");
2056       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2057       assert(!Negate);
2058       std::swap(LHS, RHS);
2059       NegateR = false;
2060       NegateAfterR = true;
2061     } else {
2062       // Negate the left sub-tree if possible, otherwise negate the result.
2063       NegateR = CanNegateR;
2064       NegateAfterR = !CanNegateR;
2065     }
2066     NegateL = true;
2067     NegateAfterAll = !Negate;
2068   } else {
2069     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2070     assert(!Negate && "Valid conjunction/disjunction tree");
2071 
2072     NegateL = false;
2073     NegateR = false;
2074     NegateAfterR = false;
2075     NegateAfterAll = false;
2076   }
2077 
2078   // Emit sub-trees.
2079   AArch64CC::CondCode RHSCC;
2080   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2081   if (NegateAfterR)
2082     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2083   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2084   if (NegateAfterAll)
2085     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2086   return CmpL;
2087 }
2088 
2089 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2090 /// In some cases this is even possible with OR operations in the expression.
2091 /// See \ref AArch64CCMP.
2092 /// \see emitConjunctionRec().
2093 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2094                                AArch64CC::CondCode &OutCC) {
2095   bool DummyCanNegate;
2096   bool DummyMustBeFirst;
2097   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2098     return SDValue();
2099 
2100   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2101 }
2102 
2103 /// @}
2104 
2105 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2106 /// extension operations.
2107 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2108   auto isSupportedExtend = [&](SDValue V) {
2109     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2110       return true;
2111 
2112     if (V.getOpcode() == ISD::AND)
2113       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2114         uint64_t Mask = MaskCst->getZExtValue();
2115         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2116       }
2117 
2118     return false;
2119   };
2120 
2121   if (!Op.hasOneUse())
2122     return 0;
2123 
2124   if (isSupportedExtend(Op))
2125     return 1;
2126 
2127   unsigned Opc = Op.getOpcode();
2128   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2129     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2130       uint64_t Shift = ShiftCst->getZExtValue();
2131       if (isSupportedExtend(Op.getOperand(0)))
2132         return (Shift <= 4) ? 2 : 1;
2133       EVT VT = Op.getValueType();
2134       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2135         return 1;
2136     }
2137 
2138   return 0;
2139 }
2140 
2141 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2142                              SDValue &AArch64cc, SelectionDAG &DAG,
2143                              const SDLoc &dl) {
2144   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2145     EVT VT = RHS.getValueType();
2146     uint64_t C = RHSC->getZExtValue();
2147     if (!isLegalArithImmed(C)) {
2148       // Constant does not fit, try adjusting it by one?
2149       switch (CC) {
2150       default:
2151         break;
2152       case ISD::SETLT:
2153       case ISD::SETGE:
2154         if ((VT == MVT::i32 && C != 0x80000000 &&
2155              isLegalArithImmed((uint32_t)(C - 1))) ||
2156             (VT == MVT::i64 && C != 0x80000000ULL &&
2157              isLegalArithImmed(C - 1ULL))) {
2158           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2159           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2160           RHS = DAG.getConstant(C, dl, VT);
2161         }
2162         break;
2163       case ISD::SETULT:
2164       case ISD::SETUGE:
2165         if ((VT == MVT::i32 && C != 0 &&
2166              isLegalArithImmed((uint32_t)(C - 1))) ||
2167             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2168           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2169           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2170           RHS = DAG.getConstant(C, dl, VT);
2171         }
2172         break;
2173       case ISD::SETLE:
2174       case ISD::SETGT:
2175         if ((VT == MVT::i32 && C != INT32_MAX &&
2176              isLegalArithImmed((uint32_t)(C + 1))) ||
2177             (VT == MVT::i64 && C != INT64_MAX &&
2178              isLegalArithImmed(C + 1ULL))) {
2179           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2180           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2181           RHS = DAG.getConstant(C, dl, VT);
2182         }
2183         break;
2184       case ISD::SETULE:
2185       case ISD::SETUGT:
2186         if ((VT == MVT::i32 && C != UINT32_MAX &&
2187              isLegalArithImmed((uint32_t)(C + 1))) ||
2188             (VT == MVT::i64 && C != UINT64_MAX &&
2189              isLegalArithImmed(C + 1ULL))) {
2190           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2191           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2192           RHS = DAG.getConstant(C, dl, VT);
2193         }
2194         break;
2195       }
2196     }
2197   }
2198 
2199   // Comparisons are canonicalized so that the RHS operand is simpler than the
2200   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2201   // can fold some shift+extend operations on the RHS operand, so swap the
2202   // operands if that can be done.
2203   //
2204   // For example:
2205   //    lsl     w13, w11, #1
2206   //    cmp     w13, w12
2207   // can be turned into:
2208   //    cmp     w12, w11, lsl #1
2209   if (!isa<ConstantSDNode>(RHS) ||
2210       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2211     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2212 
2213     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2214       std::swap(LHS, RHS);
2215       CC = ISD::getSetCCSwappedOperands(CC);
2216     }
2217   }
2218 
2219   SDValue Cmp;
2220   AArch64CC::CondCode AArch64CC;
2221   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2222     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2223 
2224     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2225     // For the i8 operand, the largest immediate is 255, so this can be easily
2226     // encoded in the compare instruction. For the i16 operand, however, the
2227     // largest immediate cannot be encoded in the compare.
2228     // Therefore, use a sign extending load and cmn to avoid materializing the
2229     // -1 constant. For example,
2230     // movz w1, #65535
2231     // ldrh w0, [x0, #0]
2232     // cmp w0, w1
2233     // >
2234     // ldrsh w0, [x0, #0]
2235     // cmn w0, #1
2236     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2237     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2238     // ensure both the LHS and RHS are truly zero extended and to make sure the
2239     // transformation is profitable.
2240     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2241         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2242         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2243         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2244       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2245       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2246         SDValue SExt =
2247             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2248                         DAG.getValueType(MVT::i16));
2249         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2250                                                    RHS.getValueType()),
2251                              CC, dl, DAG);
2252         AArch64CC = changeIntCCToAArch64CC(CC);
2253       }
2254     }
2255 
2256     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2257       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2258         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2259           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2260       }
2261     }
2262   }
2263 
2264   if (!Cmp) {
2265     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2266     AArch64CC = changeIntCCToAArch64CC(CC);
2267   }
2268   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2269   return Cmp;
2270 }
2271 
2272 static std::pair<SDValue, SDValue>
2273 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2274   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2275          "Unsupported value type");
2276   SDValue Value, Overflow;
2277   SDLoc DL(Op);
2278   SDValue LHS = Op.getOperand(0);
2279   SDValue RHS = Op.getOperand(1);
2280   unsigned Opc = 0;
2281   switch (Op.getOpcode()) {
2282   default:
2283     llvm_unreachable("Unknown overflow instruction!");
2284   case ISD::SADDO:
2285     Opc = AArch64ISD::ADDS;
2286     CC = AArch64CC::VS;
2287     break;
2288   case ISD::UADDO:
2289     Opc = AArch64ISD::ADDS;
2290     CC = AArch64CC::HS;
2291     break;
2292   case ISD::SSUBO:
2293     Opc = AArch64ISD::SUBS;
2294     CC = AArch64CC::VS;
2295     break;
2296   case ISD::USUBO:
2297     Opc = AArch64ISD::SUBS;
2298     CC = AArch64CC::LO;
2299     break;
2300   // Multiply needs a little bit extra work.
2301   case ISD::SMULO:
2302   case ISD::UMULO: {
2303     CC = AArch64CC::NE;
2304     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2305     if (Op.getValueType() == MVT::i32) {
2306       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2307       // For a 32 bit multiply with overflow check we want the instruction
2308       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2309       // need to generate the following pattern:
2310       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2311       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2312       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2313       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2314       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2315                                 DAG.getConstant(0, DL, MVT::i64));
2316       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2317       // operation. We need to clear out the upper 32 bits, because we used a
2318       // widening multiply that wrote all 64 bits. In the end this should be a
2319       // noop.
2320       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2321       if (IsSigned) {
2322         // The signed overflow check requires more than just a simple check for
2323         // any bit set in the upper 32 bits of the result. These bits could be
2324         // just the sign bits of a negative number. To perform the overflow
2325         // check we have to arithmetic shift right the 32nd bit of the result by
2326         // 31 bits. Then we compare the result to the upper 32 bits.
2327         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2328                                         DAG.getConstant(32, DL, MVT::i64));
2329         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2330         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2331                                         DAG.getConstant(31, DL, MVT::i64));
2332         // It is important that LowerBits is last, otherwise the arithmetic
2333         // shift will not be folded into the compare (SUBS).
2334         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2335         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2336                        .getValue(1);
2337       } else {
2338         // The overflow check for unsigned multiply is easy. We only need to
2339         // check if any of the upper 32 bits are set. This can be done with a
2340         // CMP (shifted register). For that we need to generate the following
2341         // pattern:
2342         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2343         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2344                                         DAG.getConstant(32, DL, MVT::i64));
2345         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2346         Overflow =
2347             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2348                         DAG.getConstant(0, DL, MVT::i64),
2349                         UpperBits).getValue(1);
2350       }
2351       break;
2352     }
2353     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2354     // For the 64 bit multiply
2355     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2356     if (IsSigned) {
2357       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2358       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2359                                       DAG.getConstant(63, DL, MVT::i64));
2360       // It is important that LowerBits is last, otherwise the arithmetic
2361       // shift will not be folded into the compare (SUBS).
2362       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2363       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2364                      .getValue(1);
2365     } else {
2366       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2367       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2368       Overflow =
2369           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2370                       DAG.getConstant(0, DL, MVT::i64),
2371                       UpperBits).getValue(1);
2372     }
2373     break;
2374   }
2375   } // switch (...)
2376 
2377   if (Opc) {
2378     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2379 
2380     // Emit the AArch64 operation with overflow check.
2381     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2382     Overflow = Value.getValue(1);
2383   }
2384   return std::make_pair(Value, Overflow);
2385 }
2386 
2387 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2388                                              RTLIB::Libcall Call) const {
2389   bool IsStrict = Op->isStrictFPOpcode();
2390   unsigned Offset = IsStrict ? 1 : 0;
2391   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2392   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2393   MakeLibCallOptions CallOptions;
2394   SDValue Result;
2395   SDLoc dl(Op);
2396   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2397                                         CallOptions, dl, Chain);
2398   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2399 }
2400 
2401 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2402   SDValue Sel = Op.getOperand(0);
2403   SDValue Other = Op.getOperand(1);
2404   SDLoc dl(Sel);
2405 
2406   // If the operand is an overflow checking operation, invert the condition
2407   // code and kill the Not operation. I.e., transform:
2408   // (xor (overflow_op_bool, 1))
2409   //   -->
2410   // (csel 1, 0, invert(cc), overflow_op_bool)
2411   // ... which later gets transformed to just a cset instruction with an
2412   // inverted condition code, rather than a cset + eor sequence.
2413   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2414     // Only lower legal XALUO ops.
2415     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2416       return SDValue();
2417 
2418     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2419     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2420     AArch64CC::CondCode CC;
2421     SDValue Value, Overflow;
2422     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2423     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2424     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2425                        CCVal, Overflow);
2426   }
2427   // If neither operand is a SELECT_CC, give up.
2428   if (Sel.getOpcode() != ISD::SELECT_CC)
2429     std::swap(Sel, Other);
2430   if (Sel.getOpcode() != ISD::SELECT_CC)
2431     return Op;
2432 
2433   // The folding we want to perform is:
2434   // (xor x, (select_cc a, b, cc, 0, -1) )
2435   //   -->
2436   // (csel x, (xor x, -1), cc ...)
2437   //
2438   // The latter will get matched to a CSINV instruction.
2439 
2440   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2441   SDValue LHS = Sel.getOperand(0);
2442   SDValue RHS = Sel.getOperand(1);
2443   SDValue TVal = Sel.getOperand(2);
2444   SDValue FVal = Sel.getOperand(3);
2445 
2446   // FIXME: This could be generalized to non-integer comparisons.
2447   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2448     return Op;
2449 
2450   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2451   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2452 
2453   // The values aren't constants, this isn't the pattern we're looking for.
2454   if (!CFVal || !CTVal)
2455     return Op;
2456 
2457   // We can commute the SELECT_CC by inverting the condition.  This
2458   // might be needed to make this fit into a CSINV pattern.
2459   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2460     std::swap(TVal, FVal);
2461     std::swap(CTVal, CFVal);
2462     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2463   }
2464 
2465   // If the constants line up, perform the transform!
2466   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2467     SDValue CCVal;
2468     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2469 
2470     FVal = Other;
2471     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2472                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2473 
2474     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2475                        CCVal, Cmp);
2476   }
2477 
2478   return Op;
2479 }
2480 
2481 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2482   EVT VT = Op.getValueType();
2483 
2484   // Let legalize expand this if it isn't a legal type yet.
2485   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2486     return SDValue();
2487 
2488   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2489 
2490   unsigned Opc;
2491   bool ExtraOp = false;
2492   switch (Op.getOpcode()) {
2493   default:
2494     llvm_unreachable("Invalid code");
2495   case ISD::ADDC:
2496     Opc = AArch64ISD::ADDS;
2497     break;
2498   case ISD::SUBC:
2499     Opc = AArch64ISD::SUBS;
2500     break;
2501   case ISD::ADDE:
2502     Opc = AArch64ISD::ADCS;
2503     ExtraOp = true;
2504     break;
2505   case ISD::SUBE:
2506     Opc = AArch64ISD::SBCS;
2507     ExtraOp = true;
2508     break;
2509   }
2510 
2511   if (!ExtraOp)
2512     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2513   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2514                      Op.getOperand(2));
2515 }
2516 
2517 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2518   // Let legalize expand this if it isn't a legal type yet.
2519   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2520     return SDValue();
2521 
2522   SDLoc dl(Op);
2523   AArch64CC::CondCode CC;
2524   // The actual operation that sets the overflow or carry flag.
2525   SDValue Value, Overflow;
2526   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2527 
2528   // We use 0 and 1 as false and true values.
2529   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2530   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2531 
2532   // We use an inverted condition, because the conditional select is inverted
2533   // too. This will allow it to be selected to a single instruction:
2534   // CSINC Wd, WZR, WZR, invert(cond).
2535   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2536   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2537                          CCVal, Overflow);
2538 
2539   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2540   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2541 }
2542 
2543 // Prefetch operands are:
2544 // 1: Address to prefetch
2545 // 2: bool isWrite
2546 // 3: int locality (0 = no locality ... 3 = extreme locality)
2547 // 4: bool isDataCache
2548 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2549   SDLoc DL(Op);
2550   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2551   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2552   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2553 
2554   bool IsStream = !Locality;
2555   // When the locality number is set
2556   if (Locality) {
2557     // The front-end should have filtered out the out-of-range values
2558     assert(Locality <= 3 && "Prefetch locality out-of-range");
2559     // The locality degree is the opposite of the cache speed.
2560     // Put the number the other way around.
2561     // The encoding starts at 0 for level 1
2562     Locality = 3 - Locality;
2563   }
2564 
2565   // built the mask value encoding the expected behavior.
2566   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2567                    (!IsData << 3) |     // IsDataCache bit
2568                    (Locality << 1) |    // Cache level bits
2569                    (unsigned)IsStream;  // Stream bit
2570   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2571                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2572 }
2573 
2574 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2575                                               SelectionDAG &DAG) const {
2576   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2577 
2578   RTLIB::Libcall LC;
2579   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2580 
2581   return LowerF128Call(Op, DAG, LC);
2582 }
2583 
2584 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2585                                              SelectionDAG &DAG) const {
2586   bool IsStrict = Op->isStrictFPOpcode();
2587   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2588   if (SrcVal.getValueType() != MVT::f128) {
2589     // It's legal except when f128 is involved
2590     return Op;
2591   }
2592 
2593   RTLIB::Libcall LC;
2594   LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType());
2595 
2596   // FP_ROUND node has a second operand indicating whether it is known to be
2597   // precise. That doesn't take part in the LibCall so we can't directly use
2598   // LowerF128Call.
2599   MakeLibCallOptions CallOptions;
2600   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2601   SDValue Result;
2602   SDLoc dl(Op);
2603   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2604                                         CallOptions, dl, Chain);
2605   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2606 }
2607 
2608 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2609                                                     SelectionDAG &DAG) const {
2610   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2611   // Any additional optimization in this function should be recorded
2612   // in the cost tables.
2613   EVT InVT = Op.getOperand(0).getValueType();
2614   EVT VT = Op.getValueType();
2615   unsigned NumElts = InVT.getVectorNumElements();
2616 
2617   // f16 conversions are promoted to f32 when full fp16 is not supported.
2618   if (InVT.getVectorElementType() == MVT::f16 &&
2619       !Subtarget->hasFullFP16()) {
2620     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2621     SDLoc dl(Op);
2622     return DAG.getNode(
2623         Op.getOpcode(), dl, Op.getValueType(),
2624         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2625   }
2626 
2627   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2628     SDLoc dl(Op);
2629     SDValue Cv =
2630         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2631                     Op.getOperand(0));
2632     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2633   }
2634 
2635   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2636     SDLoc dl(Op);
2637     MVT ExtVT =
2638         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2639                          VT.getVectorNumElements());
2640     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2641     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2642   }
2643 
2644   // Type changing conversions are illegal.
2645   return Op;
2646 }
2647 
2648 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2649                                               SelectionDAG &DAG) const {
2650   bool IsStrict = Op->isStrictFPOpcode();
2651   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2652 
2653   if (SrcVal.getValueType().isVector())
2654     return LowerVectorFP_TO_INT(Op, DAG);
2655 
2656   // f16 conversions are promoted to f32 when full fp16 is not supported.
2657   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2658     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2659     SDLoc dl(Op);
2660     return DAG.getNode(
2661         Op.getOpcode(), dl, Op.getValueType(),
2662         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2663   }
2664 
2665   if (SrcVal.getValueType() != MVT::f128) {
2666     // It's legal except when f128 is involved
2667     return Op;
2668   }
2669 
2670   RTLIB::Libcall LC;
2671   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2672       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2673     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2674   else
2675     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2676 
2677   return LowerF128Call(Op, DAG, LC);
2678 }
2679 
2680 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2681   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2682   // Any additional optimization in this function should be recorded
2683   // in the cost tables.
2684   EVT VT = Op.getValueType();
2685   SDLoc dl(Op);
2686   SDValue In = Op.getOperand(0);
2687   EVT InVT = In.getValueType();
2688 
2689   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2690     MVT CastVT =
2691         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2692                          InVT.getVectorNumElements());
2693     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2694     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2695   }
2696 
2697   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2698     unsigned CastOpc =
2699         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2700     EVT CastVT = VT.changeVectorElementTypeToInteger();
2701     In = DAG.getNode(CastOpc, dl, CastVT, In);
2702     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2703   }
2704 
2705   return Op;
2706 }
2707 
2708 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2709                                             SelectionDAG &DAG) const {
2710   if (Op.getValueType().isVector())
2711     return LowerVectorINT_TO_FP(Op, DAG);
2712 
2713   bool IsStrict = Op->isStrictFPOpcode();
2714   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2715 
2716   // f16 conversions are promoted to f32 when full fp16 is not supported.
2717   if (Op.getValueType() == MVT::f16 &&
2718       !Subtarget->hasFullFP16()) {
2719     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2720     SDLoc dl(Op);
2721     return DAG.getNode(
2722         ISD::FP_ROUND, dl, MVT::f16,
2723         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2724         DAG.getIntPtrConstant(0, dl));
2725   }
2726 
2727   // i128 conversions are libcalls.
2728   if (SrcVal.getValueType() == MVT::i128)
2729     return SDValue();
2730 
2731   // Other conversions are legal, unless it's to the completely software-based
2732   // fp128.
2733   if (Op.getValueType() != MVT::f128)
2734     return Op;
2735 
2736   RTLIB::Libcall LC;
2737   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2738       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2739     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2740   else
2741     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2742 
2743   return LowerF128Call(Op, DAG, LC);
2744 }
2745 
2746 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2747                                             SelectionDAG &DAG) const {
2748   // For iOS, we want to call an alternative entry point: __sincos_stret,
2749   // which returns the values in two S / D registers.
2750   SDLoc dl(Op);
2751   SDValue Arg = Op.getOperand(0);
2752   EVT ArgVT = Arg.getValueType();
2753   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2754 
2755   ArgListTy Args;
2756   ArgListEntry Entry;
2757 
2758   Entry.Node = Arg;
2759   Entry.Ty = ArgTy;
2760   Entry.IsSExt = false;
2761   Entry.IsZExt = false;
2762   Args.push_back(Entry);
2763 
2764   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2765                                         : RTLIB::SINCOS_STRET_F32;
2766   const char *LibcallName = getLibcallName(LC);
2767   SDValue Callee =
2768       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2769 
2770   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2771   TargetLowering::CallLoweringInfo CLI(DAG);
2772   CLI.setDebugLoc(dl)
2773       .setChain(DAG.getEntryNode())
2774       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2775 
2776   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2777   return CallResult.first;
2778 }
2779 
2780 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2781   if (Op.getValueType() != MVT::f16)
2782     return SDValue();
2783 
2784   assert(Op.getOperand(0).getValueType() == MVT::i16);
2785   SDLoc DL(Op);
2786 
2787   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2788   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2789   return SDValue(
2790       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2791                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2792       0);
2793 }
2794 
2795 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2796   if (OrigVT.getSizeInBits() >= 64)
2797     return OrigVT;
2798 
2799   assert(OrigVT.isSimple() && "Expecting a simple value type");
2800 
2801   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2802   switch (OrigSimpleTy) {
2803   default: llvm_unreachable("Unexpected Vector Type");
2804   case MVT::v2i8:
2805   case MVT::v2i16:
2806      return MVT::v2i32;
2807   case MVT::v4i8:
2808     return  MVT::v4i16;
2809   }
2810 }
2811 
2812 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2813                                                  const EVT &OrigTy,
2814                                                  const EVT &ExtTy,
2815                                                  unsigned ExtOpcode) {
2816   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2817   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2818   // 64-bits we need to insert a new extension so that it will be 64-bits.
2819   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2820   if (OrigTy.getSizeInBits() >= 64)
2821     return N;
2822 
2823   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2824   EVT NewVT = getExtensionTo64Bits(OrigTy);
2825 
2826   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2827 }
2828 
2829 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2830                                    bool isSigned) {
2831   EVT VT = N->getValueType(0);
2832 
2833   if (N->getOpcode() != ISD::BUILD_VECTOR)
2834     return false;
2835 
2836   for (const SDValue &Elt : N->op_values()) {
2837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2838       unsigned EltSize = VT.getScalarSizeInBits();
2839       unsigned HalfSize = EltSize / 2;
2840       if (isSigned) {
2841         if (!isIntN(HalfSize, C->getSExtValue()))
2842           return false;
2843       } else {
2844         if (!isUIntN(HalfSize, C->getZExtValue()))
2845           return false;
2846       }
2847       continue;
2848     }
2849     return false;
2850   }
2851 
2852   return true;
2853 }
2854 
2855 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2856   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2857     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2858                                              N->getOperand(0)->getValueType(0),
2859                                              N->getValueType(0),
2860                                              N->getOpcode());
2861 
2862   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2863   EVT VT = N->getValueType(0);
2864   SDLoc dl(N);
2865   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2866   unsigned NumElts = VT.getVectorNumElements();
2867   MVT TruncVT = MVT::getIntegerVT(EltSize);
2868   SmallVector<SDValue, 8> Ops;
2869   for (unsigned i = 0; i != NumElts; ++i) {
2870     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2871     const APInt &CInt = C->getAPIntValue();
2872     // Element types smaller than 32 bits are not legal, so use i32 elements.
2873     // The values are implicitly truncated so sext vs. zext doesn't matter.
2874     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2875   }
2876   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2877 }
2878 
2879 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2880   return N->getOpcode() == ISD::SIGN_EXTEND ||
2881          isExtendedBUILD_VECTOR(N, DAG, true);
2882 }
2883 
2884 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2885   return N->getOpcode() == ISD::ZERO_EXTEND ||
2886          isExtendedBUILD_VECTOR(N, DAG, false);
2887 }
2888 
2889 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2890   unsigned Opcode = N->getOpcode();
2891   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2892     SDNode *N0 = N->getOperand(0).getNode();
2893     SDNode *N1 = N->getOperand(1).getNode();
2894     return N0->hasOneUse() && N1->hasOneUse() &&
2895       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2896   }
2897   return false;
2898 }
2899 
2900 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2901   unsigned Opcode = N->getOpcode();
2902   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2903     SDNode *N0 = N->getOperand(0).getNode();
2904     SDNode *N1 = N->getOperand(1).getNode();
2905     return N0->hasOneUse() && N1->hasOneUse() &&
2906       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2907   }
2908   return false;
2909 }
2910 
2911 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2912                                                 SelectionDAG &DAG) const {
2913   // The rounding mode is in bits 23:22 of the FPSCR.
2914   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2915   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2916   // so that the shift + and get folded into a bitfield extract.
2917   SDLoc dl(Op);
2918 
2919   SDValue Chain = Op.getOperand(0);
2920   SDValue FPCR_64 = DAG.getNode(
2921       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
2922       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
2923   Chain = FPCR_64.getValue(1);
2924   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2925   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2926                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2927   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2928                               DAG.getConstant(22, dl, MVT::i32));
2929   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2930                             DAG.getConstant(3, dl, MVT::i32));
2931   return DAG.getMergeValues({AND, Chain}, dl);
2932 }
2933 
2934 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2935   // Multiplications are only custom-lowered for 128-bit vectors so that
2936   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2937   EVT VT = Op.getValueType();
2938   assert(VT.is128BitVector() && VT.isInteger() &&
2939          "unexpected type for custom-lowering ISD::MUL");
2940   SDNode *N0 = Op.getOperand(0).getNode();
2941   SDNode *N1 = Op.getOperand(1).getNode();
2942   unsigned NewOpc = 0;
2943   bool isMLA = false;
2944   bool isN0SExt = isSignExtended(N0, DAG);
2945   bool isN1SExt = isSignExtended(N1, DAG);
2946   if (isN0SExt && isN1SExt)
2947     NewOpc = AArch64ISD::SMULL;
2948   else {
2949     bool isN0ZExt = isZeroExtended(N0, DAG);
2950     bool isN1ZExt = isZeroExtended(N1, DAG);
2951     if (isN0ZExt && isN1ZExt)
2952       NewOpc = AArch64ISD::UMULL;
2953     else if (isN1SExt || isN1ZExt) {
2954       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2955       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2956       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2957         NewOpc = AArch64ISD::SMULL;
2958         isMLA = true;
2959       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2960         NewOpc =  AArch64ISD::UMULL;
2961         isMLA = true;
2962       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2963         std::swap(N0, N1);
2964         NewOpc =  AArch64ISD::UMULL;
2965         isMLA = true;
2966       }
2967     }
2968 
2969     if (!NewOpc) {
2970       if (VT == MVT::v2i64)
2971         // Fall through to expand this.  It is not legal.
2972         return SDValue();
2973       else
2974         // Other vector multiplications are legal.
2975         return Op;
2976     }
2977   }
2978 
2979   // Legalize to a S/UMULL instruction
2980   SDLoc DL(Op);
2981   SDValue Op0;
2982   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2983   if (!isMLA) {
2984     Op0 = skipExtensionForVectorMULL(N0, DAG);
2985     assert(Op0.getValueType().is64BitVector() &&
2986            Op1.getValueType().is64BitVector() &&
2987            "unexpected types for extended operands to VMULL");
2988     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2989   }
2990   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2991   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2992   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2993   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2994   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2995   EVT Op1VT = Op1.getValueType();
2996   return DAG.getNode(N0->getOpcode(), DL, VT,
2997                      DAG.getNode(NewOpc, DL, VT,
2998                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2999                      DAG.getNode(NewOpc, DL, VT,
3000                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3001 }
3002 
3003 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3004                                int Pattern) {
3005   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3006                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3007 }
3008 
3009 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3010                                                      SelectionDAG &DAG) const {
3011   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3012   SDLoc dl(Op);
3013   switch (IntNo) {
3014   default: return SDValue();    // Don't custom lower most intrinsics.
3015   case Intrinsic::thread_pointer: {
3016     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3017     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3018   }
3019   case Intrinsic::aarch64_neon_abs: {
3020     EVT Ty = Op.getValueType();
3021     if (Ty == MVT::i64) {
3022       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3023                                    Op.getOperand(1));
3024       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3025       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3026     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3027       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3028     } else {
3029       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3030     }
3031   }
3032   case Intrinsic::aarch64_neon_smax:
3033     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3034                        Op.getOperand(1), Op.getOperand(2));
3035   case Intrinsic::aarch64_neon_umax:
3036     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3037                        Op.getOperand(1), Op.getOperand(2));
3038   case Intrinsic::aarch64_neon_smin:
3039     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3040                        Op.getOperand(1), Op.getOperand(2));
3041   case Intrinsic::aarch64_neon_umin:
3042     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3043                        Op.getOperand(1), Op.getOperand(2));
3044 
3045   case Intrinsic::aarch64_sve_sunpkhi:
3046     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3047                        Op.getOperand(1));
3048   case Intrinsic::aarch64_sve_sunpklo:
3049     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3050                        Op.getOperand(1));
3051   case Intrinsic::aarch64_sve_uunpkhi:
3052     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3053                        Op.getOperand(1));
3054   case Intrinsic::aarch64_sve_uunpklo:
3055     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3056                        Op.getOperand(1));
3057   case Intrinsic::aarch64_sve_clasta_n:
3058     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3059                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3060   case Intrinsic::aarch64_sve_clastb_n:
3061     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3062                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3063   case Intrinsic::aarch64_sve_lasta:
3064     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3065                        Op.getOperand(1), Op.getOperand(2));
3066   case Intrinsic::aarch64_sve_lastb:
3067     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3068                        Op.getOperand(1), Op.getOperand(2));
3069   case Intrinsic::aarch64_sve_rev:
3070     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3071                        Op.getOperand(1));
3072   case Intrinsic::aarch64_sve_tbl:
3073     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3074                        Op.getOperand(1), Op.getOperand(2));
3075   case Intrinsic::aarch64_sve_trn1:
3076     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3077                        Op.getOperand(1), Op.getOperand(2));
3078   case Intrinsic::aarch64_sve_trn2:
3079     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3080                        Op.getOperand(1), Op.getOperand(2));
3081   case Intrinsic::aarch64_sve_uzp1:
3082     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3083                        Op.getOperand(1), Op.getOperand(2));
3084   case Intrinsic::aarch64_sve_uzp2:
3085     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3086                        Op.getOperand(1), Op.getOperand(2));
3087   case Intrinsic::aarch64_sve_zip1:
3088     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3089                        Op.getOperand(1), Op.getOperand(2));
3090   case Intrinsic::aarch64_sve_zip2:
3091     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3092                        Op.getOperand(1), Op.getOperand(2));
3093   case Intrinsic::aarch64_sve_ptrue:
3094     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3095                        Op.getOperand(1));
3096   case Intrinsic::aarch64_sve_dupq_lane:
3097     return LowerDUPQLane(Op, DAG);
3098   case Intrinsic::aarch64_sve_convert_from_svbool:
3099     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3100                        Op.getOperand(1));
3101   case Intrinsic::aarch64_sve_convert_to_svbool: {
3102     EVT OutVT = Op.getValueType();
3103     EVT InVT = Op.getOperand(1).getValueType();
3104     // Return the operand if the cast isn't changing type,
3105     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3106     if (InVT == OutVT)
3107       return Op.getOperand(1);
3108     // Otherwise, zero the newly introduced lanes.
3109     SDValue Reinterpret =
3110         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3111     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3112     SDValue MaskReinterpret =
3113         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3114     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3115   }
3116 
3117   case Intrinsic::aarch64_sve_insr: {
3118     SDValue Scalar = Op.getOperand(2);
3119     EVT ScalarTy = Scalar.getValueType();
3120     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3121       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3122 
3123     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3124                        Op.getOperand(1), Scalar);
3125   }
3126 
3127   case Intrinsic::localaddress: {
3128     const auto &MF = DAG.getMachineFunction();
3129     const auto *RegInfo = Subtarget->getRegisterInfo();
3130     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3131     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3132                               Op.getSimpleValueType());
3133   }
3134 
3135   case Intrinsic::eh_recoverfp: {
3136     // FIXME: This needs to be implemented to correctly handle highly aligned
3137     // stack objects. For now we simply return the incoming FP. Refer D53541
3138     // for more details.
3139     SDValue FnOp = Op.getOperand(1);
3140     SDValue IncomingFPOp = Op.getOperand(2);
3141     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3142     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3143     if (!Fn)
3144       report_fatal_error(
3145           "llvm.eh.recoverfp must take a function as the first argument");
3146     return IncomingFPOp;
3147   }
3148   }
3149 }
3150 
3151 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3152   return ExtVal.getValueType().isScalableVector();
3153 }
3154 
3155 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3156 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3157                                         EVT VT, EVT MemVT,
3158                                         SelectionDAG &DAG) {
3159   assert(VT.isVector() && "VT should be a vector type");
3160   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3161 
3162   SDValue Value = ST->getValue();
3163 
3164   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3165   // the word lane which represent the v4i8 subvector.  It optimizes the store
3166   // to:
3167   //
3168   //   xtn  v0.8b, v0.8h
3169   //   str  s0, [x0]
3170 
3171   SDValue Undef = DAG.getUNDEF(MVT::i16);
3172   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3173                                         {Undef, Undef, Undef, Undef});
3174 
3175   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3176                                  Value, UndefVec);
3177   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3178 
3179   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3180   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3181                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3182 
3183   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3184                       ST->getBasePtr(), ST->getMemOperand());
3185 }
3186 
3187 // Custom lowering for any store, vector or scalar and/or default or with
3188 // a truncate operations.  Currently only custom lower truncate operation
3189 // from vector v4i16 to v4i8 or volatile stores of i128.
3190 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3191                                           SelectionDAG &DAG) const {
3192   SDLoc Dl(Op);
3193   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3194   assert (StoreNode && "Can only custom lower store nodes");
3195 
3196   SDValue Value = StoreNode->getValue();
3197 
3198   EVT VT = Value.getValueType();
3199   EVT MemVT = StoreNode->getMemoryVT();
3200 
3201   if (VT.isVector()) {
3202     unsigned AS = StoreNode->getAddressSpace();
3203     unsigned Align = StoreNode->getAlignment();
3204     if (Align < MemVT.getStoreSize() &&
3205         !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3206                                         StoreNode->getMemOperand()->getFlags(),
3207                                         nullptr)) {
3208       return scalarizeVectorStore(StoreNode, DAG);
3209     }
3210 
3211     if (StoreNode->isTruncatingStore()) {
3212       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3213     }
3214     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3215     // the custom lowering, as there are no un-paired non-temporal stores and
3216     // legalization will break up 256 bit inputs.
3217     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3218         MemVT.getVectorElementCount().Min % 2u == 0 &&
3219         ((MemVT.getScalarSizeInBits() == 8u ||
3220           MemVT.getScalarSizeInBits() == 16u ||
3221           MemVT.getScalarSizeInBits() == 32u ||
3222           MemVT.getScalarSizeInBits() == 64u))) {
3223       SDValue Lo =
3224           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3225                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3226                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3227       SDValue Hi = DAG.getNode(
3228           ISD::EXTRACT_SUBVECTOR, Dl,
3229           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3230           StoreNode->getValue(),
3231           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3232       SDValue Result = DAG.getMemIntrinsicNode(
3233           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3234           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3235           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3236       return Result;
3237     }
3238   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3239     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3240     SDValue Lo =
3241         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3242                     DAG.getConstant(0, Dl, MVT::i64));
3243     SDValue Hi =
3244         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3245                     DAG.getConstant(1, Dl, MVT::i64));
3246     SDValue Result = DAG.getMemIntrinsicNode(
3247         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3248         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3249         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3250     return Result;
3251   }
3252 
3253   return SDValue();
3254 }
3255 
3256 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3257                                               SelectionDAG &DAG) const {
3258   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3259   LLVM_DEBUG(Op.dump());
3260 
3261   switch (Op.getOpcode()) {
3262   default:
3263     llvm_unreachable("unimplemented operand");
3264     return SDValue();
3265   case ISD::BITCAST:
3266     return LowerBITCAST(Op, DAG);
3267   case ISD::GlobalAddress:
3268     return LowerGlobalAddress(Op, DAG);
3269   case ISD::GlobalTLSAddress:
3270     return LowerGlobalTLSAddress(Op, DAG);
3271   case ISD::SETCC:
3272   case ISD::STRICT_FSETCC:
3273   case ISD::STRICT_FSETCCS:
3274     return LowerSETCC(Op, DAG);
3275   case ISD::BR_CC:
3276     return LowerBR_CC(Op, DAG);
3277   case ISD::SELECT:
3278     return LowerSELECT(Op, DAG);
3279   case ISD::SELECT_CC:
3280     return LowerSELECT_CC(Op, DAG);
3281   case ISD::JumpTable:
3282     return LowerJumpTable(Op, DAG);
3283   case ISD::BR_JT:
3284     return LowerBR_JT(Op, DAG);
3285   case ISD::ConstantPool:
3286     return LowerConstantPool(Op, DAG);
3287   case ISD::BlockAddress:
3288     return LowerBlockAddress(Op, DAG);
3289   case ISD::VASTART:
3290     return LowerVASTART(Op, DAG);
3291   case ISD::VACOPY:
3292     return LowerVACOPY(Op, DAG);
3293   case ISD::VAARG:
3294     return LowerVAARG(Op, DAG);
3295   case ISD::ADDC:
3296   case ISD::ADDE:
3297   case ISD::SUBC:
3298   case ISD::SUBE:
3299     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3300   case ISD::SADDO:
3301   case ISD::UADDO:
3302   case ISD::SSUBO:
3303   case ISD::USUBO:
3304   case ISD::SMULO:
3305   case ISD::UMULO:
3306     return LowerXALUO(Op, DAG);
3307   case ISD::FADD:
3308     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3309   case ISD::FSUB:
3310     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3311   case ISD::FMUL:
3312     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3313   case ISD::FDIV:
3314     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3315   case ISD::FP_ROUND:
3316   case ISD::STRICT_FP_ROUND:
3317     return LowerFP_ROUND(Op, DAG);
3318   case ISD::FP_EXTEND:
3319     return LowerFP_EXTEND(Op, DAG);
3320   case ISD::FRAMEADDR:
3321     return LowerFRAMEADDR(Op, DAG);
3322   case ISD::SPONENTRY:
3323     return LowerSPONENTRY(Op, DAG);
3324   case ISD::RETURNADDR:
3325     return LowerRETURNADDR(Op, DAG);
3326   case ISD::ADDROFRETURNADDR:
3327     return LowerADDROFRETURNADDR(Op, DAG);
3328   case ISD::INSERT_VECTOR_ELT:
3329     return LowerINSERT_VECTOR_ELT(Op, DAG);
3330   case ISD::EXTRACT_VECTOR_ELT:
3331     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3332   case ISD::BUILD_VECTOR:
3333     return LowerBUILD_VECTOR(Op, DAG);
3334   case ISD::VECTOR_SHUFFLE:
3335     return LowerVECTOR_SHUFFLE(Op, DAG);
3336   case ISD::SPLAT_VECTOR:
3337     return LowerSPLAT_VECTOR(Op, DAG);
3338   case ISD::EXTRACT_SUBVECTOR:
3339     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3340   case ISD::SRA:
3341   case ISD::SRL:
3342   case ISD::SHL:
3343     return LowerVectorSRA_SRL_SHL(Op, DAG);
3344   case ISD::SHL_PARTS:
3345     return LowerShiftLeftParts(Op, DAG);
3346   case ISD::SRL_PARTS:
3347   case ISD::SRA_PARTS:
3348     return LowerShiftRightParts(Op, DAG);
3349   case ISD::CTPOP:
3350     return LowerCTPOP(Op, DAG);
3351   case ISD::FCOPYSIGN:
3352     return LowerFCOPYSIGN(Op, DAG);
3353   case ISD::OR:
3354     return LowerVectorOR(Op, DAG);
3355   case ISD::XOR:
3356     return LowerXOR(Op, DAG);
3357   case ISD::PREFETCH:
3358     return LowerPREFETCH(Op, DAG);
3359   case ISD::SINT_TO_FP:
3360   case ISD::UINT_TO_FP:
3361   case ISD::STRICT_SINT_TO_FP:
3362   case ISD::STRICT_UINT_TO_FP:
3363     return LowerINT_TO_FP(Op, DAG);
3364   case ISD::FP_TO_SINT:
3365   case ISD::FP_TO_UINT:
3366   case ISD::STRICT_FP_TO_SINT:
3367   case ISD::STRICT_FP_TO_UINT:
3368     return LowerFP_TO_INT(Op, DAG);
3369   case ISD::FSINCOS:
3370     return LowerFSINCOS(Op, DAG);
3371   case ISD::FLT_ROUNDS_:
3372     return LowerFLT_ROUNDS_(Op, DAG);
3373   case ISD::MUL:
3374     return LowerMUL(Op, DAG);
3375   case ISD::INTRINSIC_WO_CHAIN:
3376     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3377   case ISD::STORE:
3378     return LowerSTORE(Op, DAG);
3379   case ISD::VECREDUCE_ADD:
3380   case ISD::VECREDUCE_SMAX:
3381   case ISD::VECREDUCE_SMIN:
3382   case ISD::VECREDUCE_UMAX:
3383   case ISD::VECREDUCE_UMIN:
3384   case ISD::VECREDUCE_FMAX:
3385   case ISD::VECREDUCE_FMIN:
3386     return LowerVECREDUCE(Op, DAG);
3387   case ISD::ATOMIC_LOAD_SUB:
3388     return LowerATOMIC_LOAD_SUB(Op, DAG);
3389   case ISD::ATOMIC_LOAD_AND:
3390     return LowerATOMIC_LOAD_AND(Op, DAG);
3391   case ISD::DYNAMIC_STACKALLOC:
3392     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3393   case ISD::VSCALE:
3394     return LowerVSCALE(Op, DAG);
3395   }
3396 }
3397 
3398 //===----------------------------------------------------------------------===//
3399 //                      Calling Convention Implementation
3400 //===----------------------------------------------------------------------===//
3401 
3402 /// Selects the correct CCAssignFn for a given CallingConvention value.
3403 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3404                                                      bool IsVarArg) const {
3405   switch (CC) {
3406   default:
3407     report_fatal_error("Unsupported calling convention.");
3408   case CallingConv::WebKit_JS:
3409     return CC_AArch64_WebKit_JS;
3410   case CallingConv::GHC:
3411     return CC_AArch64_GHC;
3412   case CallingConv::C:
3413   case CallingConv::Fast:
3414   case CallingConv::PreserveMost:
3415   case CallingConv::CXX_FAST_TLS:
3416   case CallingConv::Swift:
3417     if (Subtarget->isTargetWindows() && IsVarArg)
3418       return CC_AArch64_Win64_VarArg;
3419     if (!Subtarget->isTargetDarwin())
3420       return CC_AArch64_AAPCS;
3421     if (!IsVarArg)
3422       return CC_AArch64_DarwinPCS;
3423     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3424                                       : CC_AArch64_DarwinPCS_VarArg;
3425    case CallingConv::Win64:
3426     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3427    case CallingConv::CFGuard_Check:
3428      return CC_AArch64_Win64_CFGuard_Check;
3429    case CallingConv::AArch64_VectorCall:
3430    case CallingConv::AArch64_SVE_VectorCall:
3431      return CC_AArch64_AAPCS;
3432   }
3433 }
3434 
3435 CCAssignFn *
3436 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3437   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3438                                       : RetCC_AArch64_AAPCS;
3439 }
3440 
3441 SDValue AArch64TargetLowering::LowerFormalArguments(
3442     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3443     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3444     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3445   MachineFunction &MF = DAG.getMachineFunction();
3446   MachineFrameInfo &MFI = MF.getFrameInfo();
3447   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3448 
3449   // Assign locations to all of the incoming arguments.
3450   SmallVector<CCValAssign, 16> ArgLocs;
3451   DenseMap<unsigned, SDValue> CopiedRegs;
3452   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3453                  *DAG.getContext());
3454 
3455   // At this point, Ins[].VT may already be promoted to i32. To correctly
3456   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3457   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3458   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3459   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3460   // LocVT.
3461   unsigned NumArgs = Ins.size();
3462   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3463   unsigned CurArgIdx = 0;
3464   for (unsigned i = 0; i != NumArgs; ++i) {
3465     MVT ValVT = Ins[i].VT;
3466     if (Ins[i].isOrigArg()) {
3467       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3468       CurArgIdx = Ins[i].getOrigArgIndex();
3469 
3470       // Get type of the original argument.
3471       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3472                                   /*AllowUnknown*/ true);
3473       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3474       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3475       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3476         ValVT = MVT::i8;
3477       else if (ActualMVT == MVT::i16)
3478         ValVT = MVT::i16;
3479     }
3480     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3481     bool Res =
3482         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3483     assert(!Res && "Call operand has unhandled type");
3484     (void)Res;
3485   }
3486   assert(ArgLocs.size() == Ins.size());
3487   SmallVector<SDValue, 16> ArgValues;
3488   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3489     CCValAssign &VA = ArgLocs[i];
3490 
3491     if (Ins[i].Flags.isByVal()) {
3492       // Byval is used for HFAs in the PCS, but the system should work in a
3493       // non-compliant manner for larger structs.
3494       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3495       int Size = Ins[i].Flags.getByValSize();
3496       unsigned NumRegs = (Size + 7) / 8;
3497 
3498       // FIXME: This works on big-endian for composite byvals, which are the common
3499       // case. It should also work for fundamental types too.
3500       unsigned FrameIdx =
3501         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3502       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3503       InVals.push_back(FrameIdxN);
3504 
3505       continue;
3506     }
3507 
3508     SDValue ArgValue;
3509     if (VA.isRegLoc()) {
3510       // Arguments stored in registers.
3511       EVT RegVT = VA.getLocVT();
3512       const TargetRegisterClass *RC;
3513 
3514       if (RegVT == MVT::i32)
3515         RC = &AArch64::GPR32RegClass;
3516       else if (RegVT == MVT::i64)
3517         RC = &AArch64::GPR64RegClass;
3518       else if (RegVT == MVT::f16)
3519         RC = &AArch64::FPR16RegClass;
3520       else if (RegVT == MVT::f32)
3521         RC = &AArch64::FPR32RegClass;
3522       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3523         RC = &AArch64::FPR64RegClass;
3524       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3525         RC = &AArch64::FPR128RegClass;
3526       else if (RegVT.isScalableVector() &&
3527                RegVT.getVectorElementType() == MVT::i1)
3528         RC = &AArch64::PPRRegClass;
3529       else if (RegVT.isScalableVector())
3530         RC = &AArch64::ZPRRegClass;
3531       else
3532         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3533 
3534       // Transform the arguments in physical registers into virtual ones.
3535       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3536       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3537 
3538       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3539       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3540       // truncate to the right size.
3541       switch (VA.getLocInfo()) {
3542       default:
3543         llvm_unreachable("Unknown loc info!");
3544       case CCValAssign::Full:
3545         break;
3546       case CCValAssign::Indirect:
3547         assert(VA.getValVT().isScalableVector() &&
3548                "Only scalable vectors can be passed indirectly");
3549         break;
3550       case CCValAssign::BCvt:
3551         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3552         break;
3553       case CCValAssign::AExt:
3554       case CCValAssign::SExt:
3555       case CCValAssign::ZExt:
3556         break;
3557       case CCValAssign::AExtUpper:
3558         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3559                                DAG.getConstant(32, DL, RegVT));
3560         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3561         break;
3562       }
3563     } else { // VA.isRegLoc()
3564       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3565       unsigned ArgOffset = VA.getLocMemOffset();
3566       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3567                               ? VA.getLocVT().getSizeInBits()
3568                               : VA.getValVT().getSizeInBits()) / 8;
3569 
3570       uint32_t BEAlign = 0;
3571       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3572           !Ins[i].Flags.isInConsecutiveRegs())
3573         BEAlign = 8 - ArgSize;
3574 
3575       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3576 
3577       // Create load nodes to retrieve arguments from the stack.
3578       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3579 
3580       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3581       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3582       MVT MemVT = VA.getValVT();
3583 
3584       switch (VA.getLocInfo()) {
3585       default:
3586         break;
3587       case CCValAssign::Trunc:
3588       case CCValAssign::BCvt:
3589         MemVT = VA.getLocVT();
3590         break;
3591       case CCValAssign::Indirect:
3592         assert(VA.getValVT().isScalableVector() &&
3593                "Only scalable vectors can be passed indirectly");
3594         MemVT = VA.getLocVT();
3595         break;
3596       case CCValAssign::SExt:
3597         ExtType = ISD::SEXTLOAD;
3598         break;
3599       case CCValAssign::ZExt:
3600         ExtType = ISD::ZEXTLOAD;
3601         break;
3602       case CCValAssign::AExt:
3603         ExtType = ISD::EXTLOAD;
3604         break;
3605       }
3606 
3607       ArgValue = DAG.getExtLoad(
3608           ExtType, DL, VA.getLocVT(), Chain, FIN,
3609           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3610           MemVT);
3611 
3612     }
3613 
3614     if (VA.getLocInfo() == CCValAssign::Indirect) {
3615       assert(VA.getValVT().isScalableVector() &&
3616            "Only scalable vectors can be passed indirectly");
3617       // If value is passed via pointer - do a load.
3618       ArgValue =
3619           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
3620     }
3621 
3622     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3623       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3624                              ArgValue, DAG.getValueType(MVT::i32));
3625     InVals.push_back(ArgValue);
3626   }
3627 
3628   // varargs
3629   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3630   if (isVarArg) {
3631     if (!Subtarget->isTargetDarwin() || IsWin64) {
3632       // The AAPCS variadic function ABI is identical to the non-variadic
3633       // one. As a result there may be more arguments in registers and we should
3634       // save them for future reference.
3635       // Win64 variadic functions also pass arguments in registers, but all float
3636       // arguments are passed in integer registers.
3637       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3638     }
3639 
3640     // This will point to the next argument passed via stack.
3641     unsigned StackOffset = CCInfo.getNextStackOffset();
3642     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3643     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3644     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3645 
3646     if (MFI.hasMustTailInVarArgFunc()) {
3647       SmallVector<MVT, 2> RegParmTypes;
3648       RegParmTypes.push_back(MVT::i64);
3649       RegParmTypes.push_back(MVT::f128);
3650       // Compute the set of forwarded registers. The rest are scratch.
3651       SmallVectorImpl<ForwardedRegister> &Forwards =
3652                                        FuncInfo->getForwardedMustTailRegParms();
3653       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3654                                                CC_AArch64_AAPCS);
3655 
3656       // Conservatively forward X8, since it might be used for aggregate return.
3657       if (!CCInfo.isAllocated(AArch64::X8)) {
3658         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3659         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3660       }
3661     }
3662   }
3663 
3664   // On Windows, InReg pointers must be returned, so record the pointer in a
3665   // virtual register at the start of the function so it can be returned in the
3666   // epilogue.
3667   if (IsWin64) {
3668     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3669       if (Ins[I].Flags.isInReg()) {
3670         assert(!FuncInfo->getSRetReturnReg());
3671 
3672         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3673         Register Reg =
3674             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3675         FuncInfo->setSRetReturnReg(Reg);
3676 
3677         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3678         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3679         break;
3680       }
3681     }
3682   }
3683 
3684   unsigned StackArgSize = CCInfo.getNextStackOffset();
3685   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3686   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3687     // This is a non-standard ABI so by fiat I say we're allowed to make full
3688     // use of the stack area to be popped, which must be aligned to 16 bytes in
3689     // any case:
3690     StackArgSize = alignTo(StackArgSize, 16);
3691 
3692     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3693     // a multiple of 16.
3694     FuncInfo->setArgumentStackToRestore(StackArgSize);
3695 
3696     // This realignment carries over to the available bytes below. Our own
3697     // callers will guarantee the space is free by giving an aligned value to
3698     // CALLSEQ_START.
3699   }
3700   // Even if we're not expected to free up the space, it's useful to know how
3701   // much is there while considering tail calls (because we can reuse it).
3702   FuncInfo->setBytesInStackArgArea(StackArgSize);
3703 
3704   if (Subtarget->hasCustomCallingConv())
3705     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3706 
3707   return Chain;
3708 }
3709 
3710 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3711                                                 SelectionDAG &DAG,
3712                                                 const SDLoc &DL,
3713                                                 SDValue &Chain) const {
3714   MachineFunction &MF = DAG.getMachineFunction();
3715   MachineFrameInfo &MFI = MF.getFrameInfo();
3716   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3717   auto PtrVT = getPointerTy(DAG.getDataLayout());
3718   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3719 
3720   SmallVector<SDValue, 8> MemOps;
3721 
3722   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3723                                           AArch64::X3, AArch64::X4, AArch64::X5,
3724                                           AArch64::X6, AArch64::X7 };
3725   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3726   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3727 
3728   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3729   int GPRIdx = 0;
3730   if (GPRSaveSize != 0) {
3731     if (IsWin64) {
3732       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3733       if (GPRSaveSize & 15)
3734         // The extra size here, if triggered, will always be 8.
3735         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3736     } else
3737       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3738 
3739     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3740 
3741     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3742       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3743       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3744       SDValue Store = DAG.getStore(
3745           Val.getValue(1), DL, Val, FIN,
3746           IsWin64
3747               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3748                                                   GPRIdx,
3749                                                   (i - FirstVariadicGPR) * 8)
3750               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3751       MemOps.push_back(Store);
3752       FIN =
3753           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3754     }
3755   }
3756   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3757   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3758 
3759   if (Subtarget->hasFPARMv8() && !IsWin64) {
3760     static const MCPhysReg FPRArgRegs[] = {
3761         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3762         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3763     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3764     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3765 
3766     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3767     int FPRIdx = 0;
3768     if (FPRSaveSize != 0) {
3769       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3770 
3771       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3772 
3773       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3774         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3775         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3776 
3777         SDValue Store = DAG.getStore(
3778             Val.getValue(1), DL, Val, FIN,
3779             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3780         MemOps.push_back(Store);
3781         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3782                           DAG.getConstant(16, DL, PtrVT));
3783       }
3784     }
3785     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3786     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3787   }
3788 
3789   if (!MemOps.empty()) {
3790     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3791   }
3792 }
3793 
3794 /// LowerCallResult - Lower the result values of a call into the
3795 /// appropriate copies out of appropriate physical registers.
3796 SDValue AArch64TargetLowering::LowerCallResult(
3797     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3798     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3799     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3800     SDValue ThisVal) const {
3801   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3802                           ? RetCC_AArch64_WebKit_JS
3803                           : RetCC_AArch64_AAPCS;
3804   // Assign locations to each value returned by this call.
3805   SmallVector<CCValAssign, 16> RVLocs;
3806   DenseMap<unsigned, SDValue> CopiedRegs;
3807   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3808                  *DAG.getContext());
3809   CCInfo.AnalyzeCallResult(Ins, RetCC);
3810 
3811   // Copy all of the result registers out of their specified physreg.
3812   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3813     CCValAssign VA = RVLocs[i];
3814 
3815     // Pass 'this' value directly from the argument to return value, to avoid
3816     // reg unit interference
3817     if (i == 0 && isThisReturn) {
3818       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3819              "unexpected return calling convention register assignment");
3820       InVals.push_back(ThisVal);
3821       continue;
3822     }
3823 
3824     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3825     // allows one use of a physreg per block.
3826     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3827     if (!Val) {
3828       Val =
3829           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3830       Chain = Val.getValue(1);
3831       InFlag = Val.getValue(2);
3832       CopiedRegs[VA.getLocReg()] = Val;
3833     }
3834 
3835     switch (VA.getLocInfo()) {
3836     default:
3837       llvm_unreachable("Unknown loc info!");
3838     case CCValAssign::Full:
3839       break;
3840     case CCValAssign::BCvt:
3841       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3842       break;
3843     case CCValAssign::AExtUpper:
3844       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3845                         DAG.getConstant(32, DL, VA.getLocVT()));
3846       LLVM_FALLTHROUGH;
3847     case CCValAssign::AExt:
3848       LLVM_FALLTHROUGH;
3849     case CCValAssign::ZExt:
3850       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3851       break;
3852     }
3853 
3854     InVals.push_back(Val);
3855   }
3856 
3857   return Chain;
3858 }
3859 
3860 /// Return true if the calling convention is one that we can guarantee TCO for.
3861 static bool canGuaranteeTCO(CallingConv::ID CC) {
3862   return CC == CallingConv::Fast;
3863 }
3864 
3865 /// Return true if we might ever do TCO for calls with this calling convention.
3866 static bool mayTailCallThisCC(CallingConv::ID CC) {
3867   switch (CC) {
3868   case CallingConv::C:
3869   case CallingConv::PreserveMost:
3870   case CallingConv::Swift:
3871     return true;
3872   default:
3873     return canGuaranteeTCO(CC);
3874   }
3875 }
3876 
3877 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3878     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3879     const SmallVectorImpl<ISD::OutputArg> &Outs,
3880     const SmallVectorImpl<SDValue> &OutVals,
3881     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3882   if (!mayTailCallThisCC(CalleeCC))
3883     return false;
3884 
3885   MachineFunction &MF = DAG.getMachineFunction();
3886   const Function &CallerF = MF.getFunction();
3887   CallingConv::ID CallerCC = CallerF.getCallingConv();
3888   bool CCMatch = CallerCC == CalleeCC;
3889 
3890   // Byval parameters hand the function a pointer directly into the stack area
3891   // we want to reuse during a tail call. Working around this *is* possible (see
3892   // X86) but less efficient and uglier in LowerCall.
3893   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3894                                     e = CallerF.arg_end();
3895        i != e; ++i) {
3896     if (i->hasByValAttr())
3897       return false;
3898 
3899     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3900     // In this case, it is necessary to save/restore X0 in the callee. Tail
3901     // call opt interferes with this. So we disable tail call opt when the
3902     // caller has an argument with "inreg" attribute.
3903 
3904     // FIXME: Check whether the callee also has an "inreg" argument.
3905     if (i->hasInRegAttr())
3906       return false;
3907   }
3908 
3909   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3910     return canGuaranteeTCO(CalleeCC) && CCMatch;
3911 
3912   // Externally-defined functions with weak linkage should not be
3913   // tail-called on AArch64 when the OS does not support dynamic
3914   // pre-emption of symbols, as the AAELF spec requires normal calls
3915   // to undefined weak functions to be replaced with a NOP or jump to the
3916   // next instruction. The behaviour of branch instructions in this
3917   // situation (as used for tail calls) is implementation-defined, so we
3918   // cannot rely on the linker replacing the tail call with a return.
3919   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3920     const GlobalValue *GV = G->getGlobal();
3921     const Triple &TT = getTargetMachine().getTargetTriple();
3922     if (GV->hasExternalWeakLinkage() &&
3923         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3924       return false;
3925   }
3926 
3927   // Now we search for cases where we can use a tail call without changing the
3928   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3929   // concept.
3930 
3931   // I want anyone implementing a new calling convention to think long and hard
3932   // about this assert.
3933   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3934          "Unexpected variadic calling convention");
3935 
3936   LLVMContext &C = *DAG.getContext();
3937   if (isVarArg && !Outs.empty()) {
3938     // At least two cases here: if caller is fastcc then we can't have any
3939     // memory arguments (we'd be expected to clean up the stack afterwards). If
3940     // caller is C then we could potentially use its argument area.
3941 
3942     // FIXME: for now we take the most conservative of these in both cases:
3943     // disallow all variadic memory operands.
3944     SmallVector<CCValAssign, 16> ArgLocs;
3945     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3946 
3947     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3948     for (const CCValAssign &ArgLoc : ArgLocs)
3949       if (!ArgLoc.isRegLoc())
3950         return false;
3951   }
3952 
3953   // Check that the call results are passed in the same way.
3954   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3955                                   CCAssignFnForCall(CalleeCC, isVarArg),
3956                                   CCAssignFnForCall(CallerCC, isVarArg)))
3957     return false;
3958   // The callee has to preserve all registers the caller needs to preserve.
3959   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3960   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3961   if (!CCMatch) {
3962     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3963     if (Subtarget->hasCustomCallingConv()) {
3964       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3965       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3966     }
3967     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3968       return false;
3969   }
3970 
3971   // Nothing more to check if the callee is taking no arguments
3972   if (Outs.empty())
3973     return true;
3974 
3975   SmallVector<CCValAssign, 16> ArgLocs;
3976   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3977 
3978   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3979 
3980   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3981 
3982   // If any of the arguments is passed indirectly, it must be SVE, so the
3983   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
3984   // allocate space on the stack. That is why we determine this explicitly here
3985   // the call cannot be a tailcall.
3986   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
3987         assert((A.getLocInfo() != CCValAssign::Indirect ||
3988                 A.getValVT().isScalableVector()) &&
3989                "Expected value to be scalable");
3990         return A.getLocInfo() == CCValAssign::Indirect;
3991       }))
3992     return false;
3993 
3994   // If the stack arguments for this call do not fit into our own save area then
3995   // the call cannot be made tail.
3996   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3997     return false;
3998 
3999   const MachineRegisterInfo &MRI = MF.getRegInfo();
4000   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4001     return false;
4002 
4003   return true;
4004 }
4005 
4006 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4007                                                    SelectionDAG &DAG,
4008                                                    MachineFrameInfo &MFI,
4009                                                    int ClobberedFI) const {
4010   SmallVector<SDValue, 8> ArgChains;
4011   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4012   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4013 
4014   // Include the original chain at the beginning of the list. When this is
4015   // used by target LowerCall hooks, this helps legalize find the
4016   // CALLSEQ_BEGIN node.
4017   ArgChains.push_back(Chain);
4018 
4019   // Add a chain value for each stack argument corresponding
4020   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4021                             UE = DAG.getEntryNode().getNode()->use_end();
4022        U != UE; ++U)
4023     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4024       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4025         if (FI->getIndex() < 0) {
4026           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4027           int64_t InLastByte = InFirstByte;
4028           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4029 
4030           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4031               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4032             ArgChains.push_back(SDValue(L, 1));
4033         }
4034 
4035   // Build a tokenfactor for all the chains.
4036   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4037 }
4038 
4039 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4040                                                    bool TailCallOpt) const {
4041   return CallCC == CallingConv::Fast && TailCallOpt;
4042 }
4043 
4044 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4045 /// and add input and output parameter nodes.
4046 SDValue
4047 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4048                                  SmallVectorImpl<SDValue> &InVals) const {
4049   SelectionDAG &DAG = CLI.DAG;
4050   SDLoc &DL = CLI.DL;
4051   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4052   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4053   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4054   SDValue Chain = CLI.Chain;
4055   SDValue Callee = CLI.Callee;
4056   bool &IsTailCall = CLI.IsTailCall;
4057   CallingConv::ID CallConv = CLI.CallConv;
4058   bool IsVarArg = CLI.IsVarArg;
4059 
4060   MachineFunction &MF = DAG.getMachineFunction();
4061   MachineFunction::CallSiteInfo CSInfo;
4062   bool IsThisReturn = false;
4063 
4064   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4065   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4066   bool IsSibCall = false;
4067 
4068   if (IsTailCall) {
4069     // Check if it's really possible to do a tail call.
4070     IsTailCall = isEligibleForTailCallOptimization(
4071         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4072     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4073       report_fatal_error("failed to perform tail call elimination on a call "
4074                          "site marked musttail");
4075 
4076     // A sibling call is one where we're under the usual C ABI and not planning
4077     // to change that but can still do a tail call:
4078     if (!TailCallOpt && IsTailCall)
4079       IsSibCall = true;
4080 
4081     if (IsTailCall)
4082       ++NumTailCalls;
4083   }
4084 
4085   // Analyze operands of the call, assigning locations to each operand.
4086   SmallVector<CCValAssign, 16> ArgLocs;
4087   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4088                  *DAG.getContext());
4089 
4090   if (IsVarArg) {
4091     // Handle fixed and variable vector arguments differently.
4092     // Variable vector arguments always go into memory.
4093     unsigned NumArgs = Outs.size();
4094 
4095     for (unsigned i = 0; i != NumArgs; ++i) {
4096       MVT ArgVT = Outs[i].VT;
4097       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4098       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4099                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4100       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4101       assert(!Res && "Call operand has unhandled type");
4102       (void)Res;
4103     }
4104   } else {
4105     // At this point, Outs[].VT may already be promoted to i32. To correctly
4106     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4107     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4108     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4109     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4110     // LocVT.
4111     unsigned NumArgs = Outs.size();
4112     for (unsigned i = 0; i != NumArgs; ++i) {
4113       MVT ValVT = Outs[i].VT;
4114       // Get type of the original argument.
4115       EVT ActualVT = getValueType(DAG.getDataLayout(),
4116                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4117                                   /*AllowUnknown*/ true);
4118       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4119       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4120       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4121       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4122         ValVT = MVT::i8;
4123       else if (ActualMVT == MVT::i16)
4124         ValVT = MVT::i16;
4125 
4126       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4127       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4128       assert(!Res && "Call operand has unhandled type");
4129       (void)Res;
4130     }
4131   }
4132 
4133   // Get a count of how many bytes are to be pushed on the stack.
4134   unsigned NumBytes = CCInfo.getNextStackOffset();
4135 
4136   if (IsSibCall) {
4137     // Since we're not changing the ABI to make this a tail call, the memory
4138     // operands are already available in the caller's incoming argument space.
4139     NumBytes = 0;
4140   }
4141 
4142   // FPDiff is the byte offset of the call's argument area from the callee's.
4143   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4144   // by this amount for a tail call. In a sibling call it must be 0 because the
4145   // caller will deallocate the entire stack and the callee still expects its
4146   // arguments to begin at SP+0. Completely unused for non-tail calls.
4147   int FPDiff = 0;
4148 
4149   if (IsTailCall && !IsSibCall) {
4150     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4151 
4152     // Since callee will pop argument stack as a tail call, we must keep the
4153     // popped size 16-byte aligned.
4154     NumBytes = alignTo(NumBytes, 16);
4155 
4156     // FPDiff will be negative if this tail call requires more space than we
4157     // would automatically have in our incoming argument space. Positive if we
4158     // can actually shrink the stack.
4159     FPDiff = NumReusableBytes - NumBytes;
4160 
4161     // The stack pointer must be 16-byte aligned at all times it's used for a
4162     // memory operation, which in practice means at *all* times and in
4163     // particular across call boundaries. Therefore our own arguments started at
4164     // a 16-byte aligned SP and the delta applied for the tail call should
4165     // satisfy the same constraint.
4166     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4167   }
4168 
4169   // Adjust the stack pointer for the new arguments...
4170   // These operations are automatically eliminated by the prolog/epilog pass
4171   if (!IsSibCall)
4172     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4173 
4174   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4175                                         getPointerTy(DAG.getDataLayout()));
4176 
4177   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4178   SmallSet<unsigned, 8> RegsUsed;
4179   SmallVector<SDValue, 8> MemOpChains;
4180   auto PtrVT = getPointerTy(DAG.getDataLayout());
4181 
4182   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4183     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4184     for (const auto &F : Forwards) {
4185       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4186        RegsToPass.emplace_back(F.PReg, Val);
4187     }
4188   }
4189 
4190   // Walk the register/memloc assignments, inserting copies/loads.
4191   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4192     CCValAssign &VA = ArgLocs[i];
4193     SDValue Arg = OutVals[i];
4194     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4195 
4196     // Promote the value if needed.
4197     switch (VA.getLocInfo()) {
4198     default:
4199       llvm_unreachable("Unknown loc info!");
4200     case CCValAssign::Full:
4201       break;
4202     case CCValAssign::SExt:
4203       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4204       break;
4205     case CCValAssign::ZExt:
4206       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4207       break;
4208     case CCValAssign::AExt:
4209       if (Outs[i].ArgVT == MVT::i1) {
4210         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4211         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4212         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4213       }
4214       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4215       break;
4216     case CCValAssign::AExtUpper:
4217       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4218       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4219       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4220                         DAG.getConstant(32, DL, VA.getLocVT()));
4221       break;
4222     case CCValAssign::BCvt:
4223       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4224       break;
4225     case CCValAssign::Trunc:
4226       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4227       break;
4228     case CCValAssign::FPExt:
4229       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4230       break;
4231     case CCValAssign::Indirect:
4232       assert(VA.getValVT().isScalableVector() &&
4233              "Only scalable vectors can be passed indirectly");
4234       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4235       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4236       unsigned Align = DAG.getDataLayout().getPrefTypeAlignment(Ty);
4237       int FI = MFI.CreateStackObject(
4238           VA.getValVT().getStoreSize().getKnownMinSize(), Align, false);
4239       MFI.setStackID(FI, TargetStackID::SVEVector);
4240 
4241       SDValue SpillSlot = DAG.getFrameIndex(
4242           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4243       Chain = DAG.getStore(
4244           Chain, DL, Arg, SpillSlot,
4245           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4246       Arg = SpillSlot;
4247       break;
4248     }
4249 
4250     if (VA.isRegLoc()) {
4251       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4252           Outs[0].VT == MVT::i64) {
4253         assert(VA.getLocVT() == MVT::i64 &&
4254                "unexpected calling convention register assignment");
4255         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4256                "unexpected use of 'returned'");
4257         IsThisReturn = true;
4258       }
4259       if (RegsUsed.count(VA.getLocReg())) {
4260         // If this register has already been used then we're trying to pack
4261         // parts of an [N x i32] into an X-register. The extension type will
4262         // take care of putting the two halves in the right place but we have to
4263         // combine them.
4264         SDValue &Bits =
4265             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4266                          [=](const std::pair<unsigned, SDValue> &Elt) {
4267                            return Elt.first == VA.getLocReg();
4268                          })
4269                 ->second;
4270         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4271         // Call site info is used for function's parameter entry value
4272         // tracking. For now we track only simple cases when parameter
4273         // is transferred through whole register.
4274         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4275                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4276                                       return ArgReg.Reg == VA.getLocReg();
4277                                     }),
4278                      CSInfo.end());
4279       } else {
4280         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4281         RegsUsed.insert(VA.getLocReg());
4282         const TargetOptions &Options = DAG.getTarget().Options;
4283         if (Options.EmitCallSiteInfo)
4284           CSInfo.emplace_back(VA.getLocReg(), i);
4285       }
4286     } else {
4287       assert(VA.isMemLoc());
4288 
4289       SDValue DstAddr;
4290       MachinePointerInfo DstInfo;
4291 
4292       // FIXME: This works on big-endian for composite byvals, which are the
4293       // common case. It should also work for fundamental types too.
4294       uint32_t BEAlign = 0;
4295       unsigned OpSize;
4296       if (VA.getLocInfo() == CCValAssign::Indirect)
4297         OpSize = VA.getLocVT().getSizeInBits();
4298       else
4299         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4300                                  : VA.getValVT().getSizeInBits();
4301       OpSize = (OpSize + 7) / 8;
4302       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4303           !Flags.isInConsecutiveRegs()) {
4304         if (OpSize < 8)
4305           BEAlign = 8 - OpSize;
4306       }
4307       unsigned LocMemOffset = VA.getLocMemOffset();
4308       int32_t Offset = LocMemOffset + BEAlign;
4309       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4310       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4311 
4312       if (IsTailCall) {
4313         Offset = Offset + FPDiff;
4314         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4315 
4316         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4317         DstInfo =
4318             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4319 
4320         // Make sure any stack arguments overlapping with where we're storing
4321         // are loaded before this eventual operation. Otherwise they'll be
4322         // clobbered.
4323         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4324       } else {
4325         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4326 
4327         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4328         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4329                                                LocMemOffset);
4330       }
4331 
4332       if (Outs[i].Flags.isByVal()) {
4333         SDValue SizeNode =
4334             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4335         SDValue Cpy = DAG.getMemcpy(
4336             Chain, DL, DstAddr, Arg, SizeNode,
4337             Outs[i].Flags.getNonZeroByValAlign(),
4338             /*isVol = */ false, /*AlwaysInline = */ false,
4339             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4340 
4341         MemOpChains.push_back(Cpy);
4342       } else {
4343         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4344         // promoted to a legal register type i32, we should truncate Arg back to
4345         // i1/i8/i16.
4346         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4347             VA.getValVT() == MVT::i16)
4348           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4349 
4350         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4351         MemOpChains.push_back(Store);
4352       }
4353     }
4354   }
4355 
4356   if (!MemOpChains.empty())
4357     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4358 
4359   // Build a sequence of copy-to-reg nodes chained together with token chain
4360   // and flag operands which copy the outgoing args into the appropriate regs.
4361   SDValue InFlag;
4362   for (auto &RegToPass : RegsToPass) {
4363     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4364                              RegToPass.second, InFlag);
4365     InFlag = Chain.getValue(1);
4366   }
4367 
4368   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4369   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4370   // node so that legalize doesn't hack it.
4371   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4372     auto GV = G->getGlobal();
4373     unsigned OpFlags =
4374         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4375     if (OpFlags & AArch64II::MO_GOT) {
4376       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4377       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4378     } else {
4379       const GlobalValue *GV = G->getGlobal();
4380       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4381     }
4382   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4383     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4384         Subtarget->isTargetMachO()) {
4385       const char *Sym = S->getSymbol();
4386       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4387       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4388     } else {
4389       const char *Sym = S->getSymbol();
4390       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4391     }
4392   }
4393 
4394   // We don't usually want to end the call-sequence here because we would tidy
4395   // the frame up *after* the call, however in the ABI-changing tail-call case
4396   // we've carefully laid out the parameters so that when sp is reset they'll be
4397   // in the correct location.
4398   if (IsTailCall && !IsSibCall) {
4399     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4400                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4401     InFlag = Chain.getValue(1);
4402   }
4403 
4404   std::vector<SDValue> Ops;
4405   Ops.push_back(Chain);
4406   Ops.push_back(Callee);
4407 
4408   if (IsTailCall) {
4409     // Each tail call may have to adjust the stack by a different amount, so
4410     // this information must travel along with the operation for eventual
4411     // consumption by emitEpilogue.
4412     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4413   }
4414 
4415   // Add argument registers to the end of the list so that they are known live
4416   // into the call.
4417   for (auto &RegToPass : RegsToPass)
4418     Ops.push_back(DAG.getRegister(RegToPass.first,
4419                                   RegToPass.second.getValueType()));
4420 
4421   // Check callee args/returns for SVE registers and set calling convention
4422   // accordingly.
4423   if (CallConv == CallingConv::C) {
4424     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4425       return Out.VT.isScalableVector();
4426     });
4427     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4428       return In.VT.isScalableVector();
4429     });
4430 
4431     if (CalleeInSVE || CalleeOutSVE)
4432       CallConv = CallingConv::AArch64_SVE_VectorCall;
4433   }
4434 
4435   // Add a register mask operand representing the call-preserved registers.
4436   const uint32_t *Mask;
4437   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4438   if (IsThisReturn) {
4439     // For 'this' returns, use the X0-preserving mask if applicable
4440     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4441     if (!Mask) {
4442       IsThisReturn = false;
4443       Mask = TRI->getCallPreservedMask(MF, CallConv);
4444     }
4445   } else
4446     Mask = TRI->getCallPreservedMask(MF, CallConv);
4447 
4448   if (Subtarget->hasCustomCallingConv())
4449     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4450 
4451   if (TRI->isAnyArgRegReserved(MF))
4452     TRI->emitReservedArgRegCallError(MF);
4453 
4454   assert(Mask && "Missing call preserved mask for calling convention");
4455   Ops.push_back(DAG.getRegisterMask(Mask));
4456 
4457   if (InFlag.getNode())
4458     Ops.push_back(InFlag);
4459 
4460   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4461 
4462   // If we're doing a tall call, use a TC_RETURN here rather than an
4463   // actual call instruction.
4464   if (IsTailCall) {
4465     MF.getFrameInfo().setHasTailCall();
4466     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4467     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4468     return Ret;
4469   }
4470 
4471   // Returns a chain and a flag for retval copy to use.
4472   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4473   InFlag = Chain.getValue(1);
4474   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4475 
4476   uint64_t CalleePopBytes =
4477       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4478 
4479   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4480                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4481                              InFlag, DL);
4482   if (!Ins.empty())
4483     InFlag = Chain.getValue(1);
4484 
4485   // Handle result values, copying them out of physregs into vregs that we
4486   // return.
4487   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4488                          InVals, IsThisReturn,
4489                          IsThisReturn ? OutVals[0] : SDValue());
4490 }
4491 
4492 bool AArch64TargetLowering::CanLowerReturn(
4493     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4494     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4495   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4496                           ? RetCC_AArch64_WebKit_JS
4497                           : RetCC_AArch64_AAPCS;
4498   SmallVector<CCValAssign, 16> RVLocs;
4499   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4500   return CCInfo.CheckReturn(Outs, RetCC);
4501 }
4502 
4503 SDValue
4504 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4505                                    bool isVarArg,
4506                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4507                                    const SmallVectorImpl<SDValue> &OutVals,
4508                                    const SDLoc &DL, SelectionDAG &DAG) const {
4509   auto &MF = DAG.getMachineFunction();
4510   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4511 
4512   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4513                           ? RetCC_AArch64_WebKit_JS
4514                           : RetCC_AArch64_AAPCS;
4515   SmallVector<CCValAssign, 16> RVLocs;
4516   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4517                  *DAG.getContext());
4518   CCInfo.AnalyzeReturn(Outs, RetCC);
4519 
4520   // Copy the result values into the output registers.
4521   SDValue Flag;
4522   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4523   SmallSet<unsigned, 4> RegsUsed;
4524   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4525        ++i, ++realRVLocIdx) {
4526     CCValAssign &VA = RVLocs[i];
4527     assert(VA.isRegLoc() && "Can only return in registers!");
4528     SDValue Arg = OutVals[realRVLocIdx];
4529 
4530     switch (VA.getLocInfo()) {
4531     default:
4532       llvm_unreachable("Unknown loc info!");
4533     case CCValAssign::Full:
4534       if (Outs[i].ArgVT == MVT::i1) {
4535         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4536         // value. This is strictly redundant on Darwin (which uses "zeroext
4537         // i1"), but will be optimised out before ISel.
4538         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4539         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4540       }
4541       break;
4542     case CCValAssign::BCvt:
4543       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4544       break;
4545     case CCValAssign::AExt:
4546     case CCValAssign::ZExt:
4547       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4548       break;
4549     case CCValAssign::AExtUpper:
4550       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4551       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4552       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4553                         DAG.getConstant(32, DL, VA.getLocVT()));
4554       break;
4555     }
4556 
4557     if (RegsUsed.count(VA.getLocReg())) {
4558       SDValue &Bits =
4559           std::find_if(RetVals.begin(), RetVals.end(),
4560                        [=](const std::pair<unsigned, SDValue> &Elt) {
4561                          return Elt.first == VA.getLocReg();
4562                        })
4563               ->second;
4564       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4565     } else {
4566       RetVals.emplace_back(VA.getLocReg(), Arg);
4567       RegsUsed.insert(VA.getLocReg());
4568     }
4569   }
4570 
4571   SmallVector<SDValue, 4> RetOps(1, Chain);
4572   for (auto &RetVal : RetVals) {
4573     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4574     Flag = Chain.getValue(1);
4575     RetOps.push_back(
4576         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4577   }
4578 
4579   // Windows AArch64 ABIs require that for returning structs by value we copy
4580   // the sret argument into X0 for the return.
4581   // We saved the argument into a virtual register in the entry block,
4582   // so now we copy the value out and into X0.
4583   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4584     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4585                                      getPointerTy(MF.getDataLayout()));
4586 
4587     unsigned RetValReg = AArch64::X0;
4588     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4589     Flag = Chain.getValue(1);
4590 
4591     RetOps.push_back(
4592       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4593   }
4594 
4595   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4596   const MCPhysReg *I =
4597       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4598   if (I) {
4599     for (; *I; ++I) {
4600       if (AArch64::GPR64RegClass.contains(*I))
4601         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4602       else if (AArch64::FPR64RegClass.contains(*I))
4603         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4604       else
4605         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4606     }
4607   }
4608 
4609   RetOps[0] = Chain; // Update chain.
4610 
4611   // Add the flag if we have it.
4612   if (Flag.getNode())
4613     RetOps.push_back(Flag);
4614 
4615   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4616 }
4617 
4618 //===----------------------------------------------------------------------===//
4619 //  Other Lowering Code
4620 //===----------------------------------------------------------------------===//
4621 
4622 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4623                                              SelectionDAG &DAG,
4624                                              unsigned Flag) const {
4625   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4626                                     N->getOffset(), Flag);
4627 }
4628 
4629 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4630                                              SelectionDAG &DAG,
4631                                              unsigned Flag) const {
4632   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4633 }
4634 
4635 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4636                                              SelectionDAG &DAG,
4637                                              unsigned Flag) const {
4638   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4639                                    N->getOffset(), Flag);
4640 }
4641 
4642 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4643                                              SelectionDAG &DAG,
4644                                              unsigned Flag) const {
4645   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4646 }
4647 
4648 // (loadGOT sym)
4649 template <class NodeTy>
4650 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4651                                       unsigned Flags) const {
4652   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4653   SDLoc DL(N);
4654   EVT Ty = getPointerTy(DAG.getDataLayout());
4655   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4656   // FIXME: Once remat is capable of dealing with instructions with register
4657   // operands, expand this into two nodes instead of using a wrapper node.
4658   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4659 }
4660 
4661 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4662 template <class NodeTy>
4663 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4664                                             unsigned Flags) const {
4665   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4666   SDLoc DL(N);
4667   EVT Ty = getPointerTy(DAG.getDataLayout());
4668   const unsigned char MO_NC = AArch64II::MO_NC;
4669   return DAG.getNode(
4670       AArch64ISD::WrapperLarge, DL, Ty,
4671       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4672       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4673       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4674       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4675 }
4676 
4677 // (addlow (adrp %hi(sym)) %lo(sym))
4678 template <class NodeTy>
4679 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4680                                        unsigned Flags) const {
4681   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4682   SDLoc DL(N);
4683   EVT Ty = getPointerTy(DAG.getDataLayout());
4684   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4685   SDValue Lo = getTargetNode(N, Ty, DAG,
4686                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4687   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4688   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4689 }
4690 
4691 // (adr sym)
4692 template <class NodeTy>
4693 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4694                                            unsigned Flags) const {
4695   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4696   SDLoc DL(N);
4697   EVT Ty = getPointerTy(DAG.getDataLayout());
4698   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4699   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4700 }
4701 
4702 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4703                                                   SelectionDAG &DAG) const {
4704   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4705   const GlobalValue *GV = GN->getGlobal();
4706   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4707 
4708   if (OpFlags != AArch64II::MO_NO_FLAG)
4709     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4710            "unexpected offset in global node");
4711 
4712   // This also catches the large code model case for Darwin, and tiny code
4713   // model with got relocations.
4714   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4715     return getGOT(GN, DAG, OpFlags);
4716   }
4717 
4718   SDValue Result;
4719   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4720     Result = getAddrLarge(GN, DAG, OpFlags);
4721   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4722     Result = getAddrTiny(GN, DAG, OpFlags);
4723   } else {
4724     Result = getAddr(GN, DAG, OpFlags);
4725   }
4726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4727   SDLoc DL(GN);
4728   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4729     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4730                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4731   return Result;
4732 }
4733 
4734 /// Convert a TLS address reference into the correct sequence of loads
4735 /// and calls to compute the variable's address (for Darwin, currently) and
4736 /// return an SDValue containing the final node.
4737 
4738 /// Darwin only has one TLS scheme which must be capable of dealing with the
4739 /// fully general situation, in the worst case. This means:
4740 ///     + "extern __thread" declaration.
4741 ///     + Defined in a possibly unknown dynamic library.
4742 ///
4743 /// The general system is that each __thread variable has a [3 x i64] descriptor
4744 /// which contains information used by the runtime to calculate the address. The
4745 /// only part of this the compiler needs to know about is the first xword, which
4746 /// contains a function pointer that must be called with the address of the
4747 /// entire descriptor in "x0".
4748 ///
4749 /// Since this descriptor may be in a different unit, in general even the
4750 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4751 /// is:
4752 ///     adrp x0, _var@TLVPPAGE
4753 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4754 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4755 ///                                      ; the function pointer
4756 ///     blr x1                           ; Uses descriptor address in x0
4757 ///     ; Address of _var is now in x0.
4758 ///
4759 /// If the address of _var's descriptor *is* known to the linker, then it can
4760 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4761 /// a slight efficiency gain.
4762 SDValue
4763 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4764                                                    SelectionDAG &DAG) const {
4765   assert(Subtarget->isTargetDarwin() &&
4766          "This function expects a Darwin target");
4767 
4768   SDLoc DL(Op);
4769   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4770   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4771   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4772 
4773   SDValue TLVPAddr =
4774       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4775   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4776 
4777   // The first entry in the descriptor is a function pointer that we must call
4778   // to obtain the address of the variable.
4779   SDValue Chain = DAG.getEntryNode();
4780   SDValue FuncTLVGet = DAG.getLoad(
4781       PtrMemVT, DL, Chain, DescAddr,
4782       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4783       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4784       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4785   Chain = FuncTLVGet.getValue(1);
4786 
4787   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4788   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4789 
4790   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4791   MFI.setAdjustsStack(true);
4792 
4793   // TLS calls preserve all registers except those that absolutely must be
4794   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4795   // silly).
4796   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4797   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4798   if (Subtarget->hasCustomCallingConv())
4799     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4800 
4801   // Finally, we can make the call. This is just a degenerate version of a
4802   // normal AArch64 call node: x0 takes the address of the descriptor, and
4803   // returns the address of the variable in this thread.
4804   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4805   Chain =
4806       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4807                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4808                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4809   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4810 }
4811 
4812 /// Convert a thread-local variable reference into a sequence of instructions to
4813 /// compute the variable's address for the local exec TLS model of ELF targets.
4814 /// The sequence depends on the maximum TLS area size.
4815 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4816                                                     SDValue ThreadBase,
4817                                                     const SDLoc &DL,
4818                                                     SelectionDAG &DAG) const {
4819   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4820   SDValue TPOff, Addr;
4821 
4822   switch (DAG.getTarget().Options.TLSSize) {
4823   default:
4824     llvm_unreachable("Unexpected TLS size");
4825 
4826   case 12: {
4827     // mrs   x0, TPIDR_EL0
4828     // add   x0, x0, :tprel_lo12:a
4829     SDValue Var = DAG.getTargetGlobalAddress(
4830         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4831     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4832                                       Var,
4833                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4834                    0);
4835   }
4836 
4837   case 24: {
4838     // mrs   x0, TPIDR_EL0
4839     // add   x0, x0, :tprel_hi12:a
4840     // add   x0, x0, :tprel_lo12_nc:a
4841     SDValue HiVar = DAG.getTargetGlobalAddress(
4842         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4843     SDValue LoVar = DAG.getTargetGlobalAddress(
4844         GV, DL, PtrVT, 0,
4845         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4846     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4847                                       HiVar,
4848                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4849                    0);
4850     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4851                                       LoVar,
4852                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4853                    0);
4854   }
4855 
4856   case 32: {
4857     // mrs   x1, TPIDR_EL0
4858     // movz  x0, #:tprel_g1:a
4859     // movk  x0, #:tprel_g0_nc:a
4860     // add   x0, x1, x0
4861     SDValue HiVar = DAG.getTargetGlobalAddress(
4862         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4863     SDValue LoVar = DAG.getTargetGlobalAddress(
4864         GV, DL, PtrVT, 0,
4865         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4866     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4867                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4868                     0);
4869     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4870                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4871                     0);
4872     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4873   }
4874 
4875   case 48: {
4876     // mrs   x1, TPIDR_EL0
4877     // movz  x0, #:tprel_g2:a
4878     // movk  x0, #:tprel_g1_nc:a
4879     // movk  x0, #:tprel_g0_nc:a
4880     // add   x0, x1, x0
4881     SDValue HiVar = DAG.getTargetGlobalAddress(
4882         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4883     SDValue MiVar = DAG.getTargetGlobalAddress(
4884         GV, DL, PtrVT, 0,
4885         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4886     SDValue LoVar = DAG.getTargetGlobalAddress(
4887         GV, DL, PtrVT, 0,
4888         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4889     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4890                                        DAG.getTargetConstant(32, DL, MVT::i32)),
4891                     0);
4892     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4893                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4894                     0);
4895     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4896                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4897                     0);
4898     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4899   }
4900   }
4901 }
4902 
4903 /// When accessing thread-local variables under either the general-dynamic or
4904 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4905 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4906 /// is a function pointer to carry out the resolution.
4907 ///
4908 /// The sequence is:
4909 ///    adrp  x0, :tlsdesc:var
4910 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4911 ///    add   x0, x0, #:tlsdesc_lo12:var
4912 ///    .tlsdesccall var
4913 ///    blr   x1
4914 ///    (TPIDR_EL0 offset now in x0)
4915 ///
4916 ///  The above sequence must be produced unscheduled, to enable the linker to
4917 ///  optimize/relax this sequence.
4918 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4919 ///  above sequence, and expanded really late in the compilation flow, to ensure
4920 ///  the sequence is produced as per above.
4921 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4922                                                       const SDLoc &DL,
4923                                                       SelectionDAG &DAG) const {
4924   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4925 
4926   SDValue Chain = DAG.getEntryNode();
4927   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4928 
4929   Chain =
4930       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4931   SDValue Glue = Chain.getValue(1);
4932 
4933   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4934 }
4935 
4936 SDValue
4937 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4938                                                 SelectionDAG &DAG) const {
4939   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4940 
4941   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4942 
4943   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4944 
4945   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4946     if (Model == TLSModel::LocalDynamic)
4947       Model = TLSModel::GeneralDynamic;
4948   }
4949 
4950   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4951       Model != TLSModel::LocalExec)
4952     report_fatal_error("ELF TLS only supported in small memory model or "
4953                        "in local exec TLS model");
4954   // Different choices can be made for the maximum size of the TLS area for a
4955   // module. For the small address model, the default TLS size is 16MiB and the
4956   // maximum TLS size is 4GiB.
4957   // FIXME: add tiny and large code model support for TLS access models other
4958   // than local exec. We currently generate the same code as small for tiny,
4959   // which may be larger than needed.
4960 
4961   SDValue TPOff;
4962   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4963   SDLoc DL(Op);
4964   const GlobalValue *GV = GA->getGlobal();
4965 
4966   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4967 
4968   if (Model == TLSModel::LocalExec) {
4969     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4970   } else if (Model == TLSModel::InitialExec) {
4971     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4972     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4973   } else if (Model == TLSModel::LocalDynamic) {
4974     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4975     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4976     // the beginning of the module's TLS region, followed by a DTPREL offset
4977     // calculation.
4978 
4979     // These accesses will need deduplicating if there's more than one.
4980     AArch64FunctionInfo *MFI =
4981         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4982     MFI->incNumLocalDynamicTLSAccesses();
4983 
4984     // The call needs a relocation too for linker relaxation. It doesn't make
4985     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4986     // the address.
4987     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4988                                                   AArch64II::MO_TLS);
4989 
4990     // Now we can calculate the offset from TPIDR_EL0 to this module's
4991     // thread-local area.
4992     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4993 
4994     // Now use :dtprel_whatever: operations to calculate this variable's offset
4995     // in its thread-storage area.
4996     SDValue HiVar = DAG.getTargetGlobalAddress(
4997         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4998     SDValue LoVar = DAG.getTargetGlobalAddress(
4999         GV, DL, MVT::i64, 0,
5000         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5001 
5002     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5003                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5004                     0);
5005     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5006                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5007                     0);
5008   } else if (Model == TLSModel::GeneralDynamic) {
5009     // The call needs a relocation too for linker relaxation. It doesn't make
5010     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5011     // the address.
5012     SDValue SymAddr =
5013         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5014 
5015     // Finally we can make a call to calculate the offset from tpidr_el0.
5016     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5017   } else
5018     llvm_unreachable("Unsupported ELF TLS access model");
5019 
5020   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5021 }
5022 
5023 SDValue
5024 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5025                                                     SelectionDAG &DAG) const {
5026   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5027 
5028   SDValue Chain = DAG.getEntryNode();
5029   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5030   SDLoc DL(Op);
5031 
5032   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5033 
5034   // Load the ThreadLocalStoragePointer from the TEB
5035   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5036   SDValue TLSArray =
5037       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5038   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5039   Chain = TLSArray.getValue(1);
5040 
5041   // Load the TLS index from the C runtime;
5042   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5043   // This also does the same as LOADgot, but using a generic i32 load,
5044   // while LOADgot only loads i64.
5045   SDValue TLSIndexHi =
5046       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5047   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5048       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5049   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5050   SDValue TLSIndex =
5051       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5052   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5053   Chain = TLSIndex.getValue(1);
5054 
5055   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5056   // offset into the TLSArray.
5057   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5058   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5059                              DAG.getConstant(3, DL, PtrVT));
5060   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5061                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5062                             MachinePointerInfo());
5063   Chain = TLS.getValue(1);
5064 
5065   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5066   const GlobalValue *GV = GA->getGlobal();
5067   SDValue TGAHi = DAG.getTargetGlobalAddress(
5068       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5069   SDValue TGALo = DAG.getTargetGlobalAddress(
5070       GV, DL, PtrVT, 0,
5071       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5072 
5073   // Add the offset from the start of the .tls section (section base).
5074   SDValue Addr =
5075       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5076                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5077               0);
5078   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5079   return Addr;
5080 }
5081 
5082 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5083                                                      SelectionDAG &DAG) const {
5084   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5085   if (DAG.getTarget().useEmulatedTLS())
5086     return LowerToTLSEmulatedModel(GA, DAG);
5087 
5088   if (Subtarget->isTargetDarwin())
5089     return LowerDarwinGlobalTLSAddress(Op, DAG);
5090   if (Subtarget->isTargetELF())
5091     return LowerELFGlobalTLSAddress(Op, DAG);
5092   if (Subtarget->isTargetWindows())
5093     return LowerWindowsGlobalTLSAddress(Op, DAG);
5094 
5095   llvm_unreachable("Unexpected platform trying to use TLS");
5096 }
5097 
5098 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5099   SDValue Chain = Op.getOperand(0);
5100   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5101   SDValue LHS = Op.getOperand(2);
5102   SDValue RHS = Op.getOperand(3);
5103   SDValue Dest = Op.getOperand(4);
5104   SDLoc dl(Op);
5105 
5106   MachineFunction &MF = DAG.getMachineFunction();
5107   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5108   // will not be produced, as they are conditional branch instructions that do
5109   // not set flags.
5110   bool ProduceNonFlagSettingCondBr =
5111       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5112 
5113   // Handle f128 first, since lowering it will result in comparing the return
5114   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5115   // is expecting to deal with.
5116   if (LHS.getValueType() == MVT::f128) {
5117     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5118 
5119     // If softenSetCCOperands returned a scalar, we need to compare the result
5120     // against zero to select between true and false values.
5121     if (!RHS.getNode()) {
5122       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5123       CC = ISD::SETNE;
5124     }
5125   }
5126 
5127   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5128   // instruction.
5129   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5130       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5131     // Only lower legal XALUO ops.
5132     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5133       return SDValue();
5134 
5135     // The actual operation with overflow check.
5136     AArch64CC::CondCode OFCC;
5137     SDValue Value, Overflow;
5138     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5139 
5140     if (CC == ISD::SETNE)
5141       OFCC = getInvertedCondCode(OFCC);
5142     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5143 
5144     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5145                        Overflow);
5146   }
5147 
5148   if (LHS.getValueType().isInteger()) {
5149     assert((LHS.getValueType() == RHS.getValueType()) &&
5150            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5151 
5152     // If the RHS of the comparison is zero, we can potentially fold this
5153     // to a specialized branch.
5154     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5155     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5156       if (CC == ISD::SETEQ) {
5157         // See if we can use a TBZ to fold in an AND as well.
5158         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5159         // out of bounds, a late MI-layer pass rewrites branches.
5160         // 403.gcc is an example that hits this case.
5161         if (LHS.getOpcode() == ISD::AND &&
5162             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5163             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5164           SDValue Test = LHS.getOperand(0);
5165           uint64_t Mask = LHS.getConstantOperandVal(1);
5166           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5167                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5168                              Dest);
5169         }
5170 
5171         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5172       } else if (CC == ISD::SETNE) {
5173         // See if we can use a TBZ to fold in an AND as well.
5174         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5175         // out of bounds, a late MI-layer pass rewrites branches.
5176         // 403.gcc is an example that hits this case.
5177         if (LHS.getOpcode() == ISD::AND &&
5178             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5179             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5180           SDValue Test = LHS.getOperand(0);
5181           uint64_t Mask = LHS.getConstantOperandVal(1);
5182           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5183                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5184                              Dest);
5185         }
5186 
5187         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5188       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5189         // Don't combine AND since emitComparison converts the AND to an ANDS
5190         // (a.k.a. TST) and the test in the test bit and branch instruction
5191         // becomes redundant.  This would also increase register pressure.
5192         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5193         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5194                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5195       }
5196     }
5197     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5198         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5199       // Don't combine AND since emitComparison converts the AND to an ANDS
5200       // (a.k.a. TST) and the test in the test bit and branch instruction
5201       // becomes redundant.  This would also increase register pressure.
5202       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5203       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5204                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5205     }
5206 
5207     SDValue CCVal;
5208     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5209     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5210                        Cmp);
5211   }
5212 
5213   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5214          LHS.getValueType() == MVT::f64);
5215 
5216   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5217   // clean.  Some of them require two branches to implement.
5218   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5219   AArch64CC::CondCode CC1, CC2;
5220   changeFPCCToAArch64CC(CC, CC1, CC2);
5221   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5222   SDValue BR1 =
5223       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5224   if (CC2 != AArch64CC::AL) {
5225     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5226     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5227                        Cmp);
5228   }
5229 
5230   return BR1;
5231 }
5232 
5233 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5234                                               SelectionDAG &DAG) const {
5235   EVT VT = Op.getValueType();
5236   SDLoc DL(Op);
5237 
5238   SDValue In1 = Op.getOperand(0);
5239   SDValue In2 = Op.getOperand(1);
5240   EVT SrcVT = In2.getValueType();
5241 
5242   if (SrcVT.bitsLT(VT))
5243     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5244   else if (SrcVT.bitsGT(VT))
5245     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5246 
5247   EVT VecVT;
5248   uint64_t EltMask;
5249   SDValue VecVal1, VecVal2;
5250 
5251   auto setVecVal = [&] (int Idx) {
5252     if (!VT.isVector()) {
5253       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5254                                           DAG.getUNDEF(VecVT), In1);
5255       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5256                                           DAG.getUNDEF(VecVT), In2);
5257     } else {
5258       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5259       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5260     }
5261   };
5262 
5263   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5264     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5265     EltMask = 0x80000000ULL;
5266     setVecVal(AArch64::ssub);
5267   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5268     VecVT = MVT::v2i64;
5269 
5270     // We want to materialize a mask with the high bit set, but the AdvSIMD
5271     // immediate moves cannot materialize that in a single instruction for
5272     // 64-bit elements. Instead, materialize zero and then negate it.
5273     EltMask = 0;
5274 
5275     setVecVal(AArch64::dsub);
5276   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5277     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5278     EltMask = 0x8000ULL;
5279     setVecVal(AArch64::hsub);
5280   } else {
5281     llvm_unreachable("Invalid type for copysign!");
5282   }
5283 
5284   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5285 
5286   // If we couldn't materialize the mask above, then the mask vector will be
5287   // the zero vector, and we need to negate it here.
5288   if (VT == MVT::f64 || VT == MVT::v2f64) {
5289     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5290     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5291     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5292   }
5293 
5294   SDValue Sel =
5295       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5296 
5297   if (VT == MVT::f16)
5298     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5299   if (VT == MVT::f32)
5300     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5301   else if (VT == MVT::f64)
5302     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5303   else
5304     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5305 }
5306 
5307 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5308   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5309           Attribute::NoImplicitFloat))
5310     return SDValue();
5311 
5312   if (!Subtarget->hasNEON())
5313     return SDValue();
5314 
5315   // While there is no integer popcount instruction, it can
5316   // be more efficiently lowered to the following sequence that uses
5317   // AdvSIMD registers/instructions as long as the copies to/from
5318   // the AdvSIMD registers are cheap.
5319   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5320   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5321   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5322   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5323   SDValue Val = Op.getOperand(0);
5324   SDLoc DL(Op);
5325   EVT VT = Op.getValueType();
5326 
5327   if (VT == MVT::i32 || VT == MVT::i64) {
5328     if (VT == MVT::i32)
5329       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5330     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5331 
5332     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5333     SDValue UaddLV = DAG.getNode(
5334         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5335         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5336 
5337     if (VT == MVT::i64)
5338       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5339     return UaddLV;
5340   }
5341 
5342   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5343           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5344          "Unexpected type for custom ctpop lowering");
5345 
5346   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5347   Val = DAG.getBitcast(VT8Bit, Val);
5348   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5349 
5350   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5351   unsigned EltSize = 8;
5352   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5353   while (EltSize != VT.getScalarSizeInBits()) {
5354     EltSize *= 2;
5355     NumElts /= 2;
5356     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5357     Val = DAG.getNode(
5358         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5359         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5360   }
5361 
5362   return Val;
5363 }
5364 
5365 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5366 
5367   if (Op.getValueType().isVector())
5368     return LowerVSETCC(Op, DAG);
5369 
5370   bool IsStrict = Op->isStrictFPOpcode();
5371   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5372   unsigned OpNo = IsStrict ? 1 : 0;
5373   SDValue Chain;
5374   if (IsStrict)
5375     Chain = Op.getOperand(0);
5376   SDValue LHS = Op.getOperand(OpNo + 0);
5377   SDValue RHS = Op.getOperand(OpNo + 1);
5378   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5379   SDLoc dl(Op);
5380 
5381   // We chose ZeroOrOneBooleanContents, so use zero and one.
5382   EVT VT = Op.getValueType();
5383   SDValue TVal = DAG.getConstant(1, dl, VT);
5384   SDValue FVal = DAG.getConstant(0, dl, VT);
5385 
5386   // Handle f128 first, since one possible outcome is a normal integer
5387   // comparison which gets picked up by the next if statement.
5388   if (LHS.getValueType() == MVT::f128) {
5389     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5390                         IsSignaling);
5391 
5392     // If softenSetCCOperands returned a scalar, use it.
5393     if (!RHS.getNode()) {
5394       assert(LHS.getValueType() == Op.getValueType() &&
5395              "Unexpected setcc expansion!");
5396       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5397     }
5398   }
5399 
5400   if (LHS.getValueType().isInteger()) {
5401     SDValue CCVal;
5402     SDValue Cmp = getAArch64Cmp(
5403         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5404 
5405     // Note that we inverted the condition above, so we reverse the order of
5406     // the true and false operands here.  This will allow the setcc to be
5407     // matched to a single CSINC instruction.
5408     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5409     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5410   }
5411 
5412   // Now we know we're dealing with FP values.
5413   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5414          LHS.getValueType() == MVT::f64);
5415 
5416   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5417   // and do the comparison.
5418   SDValue Cmp;
5419   if (IsStrict)
5420     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5421   else
5422     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5423 
5424   AArch64CC::CondCode CC1, CC2;
5425   changeFPCCToAArch64CC(CC, CC1, CC2);
5426   SDValue Res;
5427   if (CC2 == AArch64CC::AL) {
5428     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5429                           CC2);
5430     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5431 
5432     // Note that we inverted the condition above, so we reverse the order of
5433     // the true and false operands here.  This will allow the setcc to be
5434     // matched to a single CSINC instruction.
5435     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5436   } else {
5437     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5438     // totally clean.  Some of them require two CSELs to implement.  As is in
5439     // this case, we emit the first CSEL and then emit a second using the output
5440     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5441 
5442     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5443     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5444     SDValue CS1 =
5445         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5446 
5447     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5448     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5449   }
5450   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5451 }
5452 
5453 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5454                                               SDValue RHS, SDValue TVal,
5455                                               SDValue FVal, const SDLoc &dl,
5456                                               SelectionDAG &DAG) const {
5457   // Handle f128 first, because it will result in a comparison of some RTLIB
5458   // call result against zero.
5459   if (LHS.getValueType() == MVT::f128) {
5460     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5461 
5462     // If softenSetCCOperands returned a scalar, we need to compare the result
5463     // against zero to select between true and false values.
5464     if (!RHS.getNode()) {
5465       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5466       CC = ISD::SETNE;
5467     }
5468   }
5469 
5470   // Also handle f16, for which we need to do a f32 comparison.
5471   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5472     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5473     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5474   }
5475 
5476   // Next, handle integers.
5477   if (LHS.getValueType().isInteger()) {
5478     assert((LHS.getValueType() == RHS.getValueType()) &&
5479            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5480 
5481     unsigned Opcode = AArch64ISD::CSEL;
5482 
5483     // If both the TVal and the FVal are constants, see if we can swap them in
5484     // order to for a CSINV or CSINC out of them.
5485     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5486     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5487 
5488     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5489       std::swap(TVal, FVal);
5490       std::swap(CTVal, CFVal);
5491       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5492     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5493       std::swap(TVal, FVal);
5494       std::swap(CTVal, CFVal);
5495       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5496     } else if (TVal.getOpcode() == ISD::XOR) {
5497       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5498       // with a CSINV rather than a CSEL.
5499       if (isAllOnesConstant(TVal.getOperand(1))) {
5500         std::swap(TVal, FVal);
5501         std::swap(CTVal, CFVal);
5502         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5503       }
5504     } else if (TVal.getOpcode() == ISD::SUB) {
5505       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5506       // that we can match with a CSNEG rather than a CSEL.
5507       if (isNullConstant(TVal.getOperand(0))) {
5508         std::swap(TVal, FVal);
5509         std::swap(CTVal, CFVal);
5510         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5511       }
5512     } else if (CTVal && CFVal) {
5513       const int64_t TrueVal = CTVal->getSExtValue();
5514       const int64_t FalseVal = CFVal->getSExtValue();
5515       bool Swap = false;
5516 
5517       // If both TVal and FVal are constants, see if FVal is the
5518       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5519       // instead of a CSEL in that case.
5520       if (TrueVal == ~FalseVal) {
5521         Opcode = AArch64ISD::CSINV;
5522       } else if (TrueVal == -FalseVal) {
5523         Opcode = AArch64ISD::CSNEG;
5524       } else if (TVal.getValueType() == MVT::i32) {
5525         // If our operands are only 32-bit wide, make sure we use 32-bit
5526         // arithmetic for the check whether we can use CSINC. This ensures that
5527         // the addition in the check will wrap around properly in case there is
5528         // an overflow (which would not be the case if we do the check with
5529         // 64-bit arithmetic).
5530         const uint32_t TrueVal32 = CTVal->getZExtValue();
5531         const uint32_t FalseVal32 = CFVal->getZExtValue();
5532 
5533         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5534           Opcode = AArch64ISD::CSINC;
5535 
5536           if (TrueVal32 > FalseVal32) {
5537             Swap = true;
5538           }
5539         }
5540         // 64-bit check whether we can use CSINC.
5541       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5542         Opcode = AArch64ISD::CSINC;
5543 
5544         if (TrueVal > FalseVal) {
5545           Swap = true;
5546         }
5547       }
5548 
5549       // Swap TVal and FVal if necessary.
5550       if (Swap) {
5551         std::swap(TVal, FVal);
5552         std::swap(CTVal, CFVal);
5553         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5554       }
5555 
5556       if (Opcode != AArch64ISD::CSEL) {
5557         // Drop FVal since we can get its value by simply inverting/negating
5558         // TVal.
5559         FVal = TVal;
5560       }
5561     }
5562 
5563     // Avoid materializing a constant when possible by reusing a known value in
5564     // a register.  However, don't perform this optimization if the known value
5565     // is one, zero or negative one in the case of a CSEL.  We can always
5566     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5567     // FVal, respectively.
5568     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5569     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5570         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5571       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5572       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5573       // "a != C ? x : a" to avoid materializing C.
5574       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5575         TVal = LHS;
5576       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5577         FVal = LHS;
5578     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5579       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5580       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5581       // avoid materializing C.
5582       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5583       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5584         Opcode = AArch64ISD::CSINV;
5585         TVal = LHS;
5586         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5587       }
5588     }
5589 
5590     SDValue CCVal;
5591     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5592     EVT VT = TVal.getValueType();
5593     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5594   }
5595 
5596   // Now we know we're dealing with FP values.
5597   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5598          LHS.getValueType() == MVT::f64);
5599   assert(LHS.getValueType() == RHS.getValueType());
5600   EVT VT = TVal.getValueType();
5601   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5602 
5603   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5604   // clean.  Some of them require two CSELs to implement.
5605   AArch64CC::CondCode CC1, CC2;
5606   changeFPCCToAArch64CC(CC, CC1, CC2);
5607 
5608   if (DAG.getTarget().Options.UnsafeFPMath) {
5609     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5610     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5611     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5612     if (RHSVal && RHSVal->isZero()) {
5613       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5614       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5615 
5616       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5617           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5618         TVal = LHS;
5619       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5620                CFVal && CFVal->isZero() &&
5621                FVal.getValueType() == LHS.getValueType())
5622         FVal = LHS;
5623     }
5624   }
5625 
5626   // Emit first, and possibly only, CSEL.
5627   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5628   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5629 
5630   // If we need a second CSEL, emit it, using the output of the first as the
5631   // RHS.  We're effectively OR'ing the two CC's together.
5632   if (CC2 != AArch64CC::AL) {
5633     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5634     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5635   }
5636 
5637   // Otherwise, return the output of the first CSEL.
5638   return CS1;
5639 }
5640 
5641 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5642                                               SelectionDAG &DAG) const {
5643   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5644   SDValue LHS = Op.getOperand(0);
5645   SDValue RHS = Op.getOperand(1);
5646   SDValue TVal = Op.getOperand(2);
5647   SDValue FVal = Op.getOperand(3);
5648   SDLoc DL(Op);
5649   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5650 }
5651 
5652 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5653                                            SelectionDAG &DAG) const {
5654   SDValue CCVal = Op->getOperand(0);
5655   SDValue TVal = Op->getOperand(1);
5656   SDValue FVal = Op->getOperand(2);
5657   SDLoc DL(Op);
5658 
5659   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5660   // instruction.
5661   if (ISD::isOverflowIntrOpRes(CCVal)) {
5662     // Only lower legal XALUO ops.
5663     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5664       return SDValue();
5665 
5666     AArch64CC::CondCode OFCC;
5667     SDValue Value, Overflow;
5668     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5669     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5670 
5671     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5672                        CCVal, Overflow);
5673   }
5674 
5675   // Lower it the same way as we would lower a SELECT_CC node.
5676   ISD::CondCode CC;
5677   SDValue LHS, RHS;
5678   if (CCVal.getOpcode() == ISD::SETCC) {
5679     LHS = CCVal.getOperand(0);
5680     RHS = CCVal.getOperand(1);
5681     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5682   } else {
5683     LHS = CCVal;
5684     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5685     CC = ISD::SETNE;
5686   }
5687   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5688 }
5689 
5690 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5691                                               SelectionDAG &DAG) const {
5692   // Jump table entries as PC relative offsets. No additional tweaking
5693   // is necessary here. Just get the address of the jump table.
5694   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5695 
5696   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5697       !Subtarget->isTargetMachO()) {
5698     return getAddrLarge(JT, DAG);
5699   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5700     return getAddrTiny(JT, DAG);
5701   }
5702   return getAddr(JT, DAG);
5703 }
5704 
5705 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5706                                           SelectionDAG &DAG) const {
5707   // Jump table entries as PC relative offsets. No additional tweaking
5708   // is necessary here. Just get the address of the jump table.
5709   SDLoc DL(Op);
5710   SDValue JT = Op.getOperand(1);
5711   SDValue Entry = Op.getOperand(2);
5712   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5713 
5714   SDNode *Dest =
5715       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5716                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5717   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5718                      SDValue(Dest, 0));
5719 }
5720 
5721 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5722                                                  SelectionDAG &DAG) const {
5723   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5724 
5725   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5726     // Use the GOT for the large code model on iOS.
5727     if (Subtarget->isTargetMachO()) {
5728       return getGOT(CP, DAG);
5729     }
5730     return getAddrLarge(CP, DAG);
5731   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5732     return getAddrTiny(CP, DAG);
5733   } else {
5734     return getAddr(CP, DAG);
5735   }
5736 }
5737 
5738 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5739                                                SelectionDAG &DAG) const {
5740   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5741   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5742       !Subtarget->isTargetMachO()) {
5743     return getAddrLarge(BA, DAG);
5744   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5745     return getAddrTiny(BA, DAG);
5746   }
5747   return getAddr(BA, DAG);
5748 }
5749 
5750 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5751                                                  SelectionDAG &DAG) const {
5752   AArch64FunctionInfo *FuncInfo =
5753       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5754 
5755   SDLoc DL(Op);
5756   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5757                                  getPointerTy(DAG.getDataLayout()));
5758   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5759   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5760   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5761                       MachinePointerInfo(SV));
5762 }
5763 
5764 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5765                                                   SelectionDAG &DAG) const {
5766   AArch64FunctionInfo *FuncInfo =
5767       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5768 
5769   SDLoc DL(Op);
5770   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5771                                      ? FuncInfo->getVarArgsGPRIndex()
5772                                      : FuncInfo->getVarArgsStackIndex(),
5773                                  getPointerTy(DAG.getDataLayout()));
5774   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5775   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5776                       MachinePointerInfo(SV));
5777 }
5778 
5779 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5780                                                 SelectionDAG &DAG) const {
5781   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5782   // Standard, section B.3.
5783   MachineFunction &MF = DAG.getMachineFunction();
5784   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5785   auto PtrVT = getPointerTy(DAG.getDataLayout());
5786   SDLoc DL(Op);
5787 
5788   SDValue Chain = Op.getOperand(0);
5789   SDValue VAList = Op.getOperand(1);
5790   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5791   SmallVector<SDValue, 4> MemOps;
5792 
5793   // void *__stack at offset 0
5794   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5795   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5796                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5797 
5798   // void *__gr_top at offset 8
5799   int GPRSize = FuncInfo->getVarArgsGPRSize();
5800   if (GPRSize > 0) {
5801     SDValue GRTop, GRTopAddr;
5802 
5803     GRTopAddr =
5804         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5805 
5806     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5807     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5808                         DAG.getConstant(GPRSize, DL, PtrVT));
5809 
5810     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5811                                   MachinePointerInfo(SV, 8),
5812                                   /* Alignment = */ 8));
5813   }
5814 
5815   // void *__vr_top at offset 16
5816   int FPRSize = FuncInfo->getVarArgsFPRSize();
5817   if (FPRSize > 0) {
5818     SDValue VRTop, VRTopAddr;
5819     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5820                             DAG.getConstant(16, DL, PtrVT));
5821 
5822     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5823     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5824                         DAG.getConstant(FPRSize, DL, PtrVT));
5825 
5826     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5827                                   MachinePointerInfo(SV, 16),
5828                                   /* Alignment = */ 8));
5829   }
5830 
5831   // int __gr_offs at offset 24
5832   SDValue GROffsAddr =
5833       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5834   MemOps.push_back(DAG.getStore(
5835       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5836       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5837 
5838   // int __vr_offs at offset 28
5839   SDValue VROffsAddr =
5840       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5841   MemOps.push_back(DAG.getStore(
5842       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5843       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5844 
5845   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5846 }
5847 
5848 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5849                                             SelectionDAG &DAG) const {
5850   MachineFunction &MF = DAG.getMachineFunction();
5851 
5852   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5853     return LowerWin64_VASTART(Op, DAG);
5854   else if (Subtarget->isTargetDarwin())
5855     return LowerDarwin_VASTART(Op, DAG);
5856   else
5857     return LowerAAPCS_VASTART(Op, DAG);
5858 }
5859 
5860 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5861                                            SelectionDAG &DAG) const {
5862   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5863   // pointer.
5864   SDLoc DL(Op);
5865   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5866   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5867                          Subtarget->isTargetWindows()) ? PtrSize : 32;
5868   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5869   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5870 
5871   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5872                        DAG.getConstant(VaListSize, DL, MVT::i32),
5873                        Align(PtrSize), false, false, false,
5874                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
5875 }
5876 
5877 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5878   assert(Subtarget->isTargetDarwin() &&
5879          "automatic va_arg instruction only works on Darwin");
5880 
5881   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5882   EVT VT = Op.getValueType();
5883   SDLoc DL(Op);
5884   SDValue Chain = Op.getOperand(0);
5885   SDValue Addr = Op.getOperand(1);
5886   unsigned Align = Op.getConstantOperandVal(3);
5887   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5888   auto PtrVT = getPointerTy(DAG.getDataLayout());
5889   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5890   SDValue VAList =
5891       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5892   Chain = VAList.getValue(1);
5893   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5894 
5895   if (Align > MinSlotSize) {
5896     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5897     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5898                          DAG.getConstant(Align - 1, DL, PtrVT));
5899     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5900                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5901   }
5902 
5903   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5904   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5905 
5906   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5907   // up to 64 bits.  At the very least, we have to increase the striding of the
5908   // vaargs list to match this, and for FP values we need to introduce
5909   // FP_ROUND nodes as well.
5910   if (VT.isInteger() && !VT.isVector())
5911     ArgSize = std::max(ArgSize, MinSlotSize);
5912   bool NeedFPTrunc = false;
5913   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5914     ArgSize = 8;
5915     NeedFPTrunc = true;
5916   }
5917 
5918   // Increment the pointer, VAList, to the next vaarg
5919   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5920                                DAG.getConstant(ArgSize, DL, PtrVT));
5921   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5922 
5923   // Store the incremented VAList to the legalized pointer
5924   SDValue APStore =
5925       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5926 
5927   // Load the actual argument out of the pointer VAList
5928   if (NeedFPTrunc) {
5929     // Load the value as an f64.
5930     SDValue WideFP =
5931         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5932     // Round the value down to an f32.
5933     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5934                                    DAG.getIntPtrConstant(1, DL));
5935     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5936     // Merge the rounded value with the chain output of the load.
5937     return DAG.getMergeValues(Ops, DL);
5938   }
5939 
5940   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5941 }
5942 
5943 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5944                                               SelectionDAG &DAG) const {
5945   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5946   MFI.setFrameAddressIsTaken(true);
5947 
5948   EVT VT = Op.getValueType();
5949   SDLoc DL(Op);
5950   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5951   SDValue FrameAddr =
5952       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5953   while (Depth--)
5954     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5955                             MachinePointerInfo());
5956 
5957   if (Subtarget->isTargetILP32())
5958     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5959                             DAG.getValueType(VT));
5960 
5961   return FrameAddr;
5962 }
5963 
5964 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5965                                               SelectionDAG &DAG) const {
5966   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5967 
5968   EVT VT = getPointerTy(DAG.getDataLayout());
5969   SDLoc DL(Op);
5970   int FI = MFI.CreateFixedObject(4, 0, false);
5971   return DAG.getFrameIndex(FI, VT);
5972 }
5973 
5974 #define GET_REGISTER_MATCHER
5975 #include "AArch64GenAsmMatcher.inc"
5976 
5977 // FIXME? Maybe this could be a TableGen attribute on some registers and
5978 // this table could be generated automatically from RegInfo.
5979 Register AArch64TargetLowering::
5980 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5981   Register Reg = MatchRegisterName(RegName);
5982   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5983     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5984     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5985     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5986       Reg = 0;
5987   }
5988   if (Reg)
5989     return Reg;
5990   report_fatal_error(Twine("Invalid register name \""
5991                               + StringRef(RegName)  + "\"."));
5992 }
5993 
5994 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5995                                                      SelectionDAG &DAG) const {
5996   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5997 
5998   EVT VT = Op.getValueType();
5999   SDLoc DL(Op);
6000 
6001   SDValue FrameAddr =
6002       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6003   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6004 
6005   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6006 }
6007 
6008 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6009                                                SelectionDAG &DAG) const {
6010   MachineFunction &MF = DAG.getMachineFunction();
6011   MachineFrameInfo &MFI = MF.getFrameInfo();
6012   MFI.setReturnAddressIsTaken(true);
6013 
6014   EVT VT = Op.getValueType();
6015   SDLoc DL(Op);
6016   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6017   if (Depth) {
6018     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6019     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6020     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6021                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6022                        MachinePointerInfo());
6023   }
6024 
6025   // Return LR, which contains the return address. Mark it an implicit live-in.
6026   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6027   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6028 }
6029 
6030 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6031 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6032 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6033                                                     SelectionDAG &DAG) const {
6034   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6035   EVT VT = Op.getValueType();
6036   unsigned VTBits = VT.getSizeInBits();
6037   SDLoc dl(Op);
6038   SDValue ShOpLo = Op.getOperand(0);
6039   SDValue ShOpHi = Op.getOperand(1);
6040   SDValue ShAmt = Op.getOperand(2);
6041   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6042 
6043   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6044 
6045   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6046                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6047   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6048 
6049   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6050   // is "undef". We wanted 0, so CSEL it directly.
6051   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6052                                ISD::SETEQ, dl, DAG);
6053   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6054   HiBitsForLo =
6055       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6056                   HiBitsForLo, CCVal, Cmp);
6057 
6058   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6059                                    DAG.getConstant(VTBits, dl, MVT::i64));
6060 
6061   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6062   SDValue LoForNormalShift =
6063       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6064 
6065   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6066                        dl, DAG);
6067   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6068   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6069   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6070                            LoForNormalShift, CCVal, Cmp);
6071 
6072   // AArch64 shifts larger than the register width are wrapped rather than
6073   // clamped, so we can't just emit "hi >> x".
6074   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6075   SDValue HiForBigShift =
6076       Opc == ISD::SRA
6077           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6078                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6079           : DAG.getConstant(0, dl, VT);
6080   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6081                            HiForNormalShift, CCVal, Cmp);
6082 
6083   SDValue Ops[2] = { Lo, Hi };
6084   return DAG.getMergeValues(Ops, dl);
6085 }
6086 
6087 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6088 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6089 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6090                                                    SelectionDAG &DAG) const {
6091   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6092   EVT VT = Op.getValueType();
6093   unsigned VTBits = VT.getSizeInBits();
6094   SDLoc dl(Op);
6095   SDValue ShOpLo = Op.getOperand(0);
6096   SDValue ShOpHi = Op.getOperand(1);
6097   SDValue ShAmt = Op.getOperand(2);
6098 
6099   assert(Op.getOpcode() == ISD::SHL_PARTS);
6100   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6101                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6102   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6103 
6104   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6105   // is "undef". We wanted 0, so CSEL it directly.
6106   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6107                                ISD::SETEQ, dl, DAG);
6108   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6109   LoBitsForHi =
6110       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6111                   LoBitsForHi, CCVal, Cmp);
6112 
6113   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6114                                    DAG.getConstant(VTBits, dl, MVT::i64));
6115   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6116   SDValue HiForNormalShift =
6117       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6118 
6119   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6120 
6121   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6122                        dl, DAG);
6123   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6124   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6125                            HiForNormalShift, CCVal, Cmp);
6126 
6127   // AArch64 shifts of larger than register sizes are wrapped rather than
6128   // clamped, so we can't just emit "lo << a" if a is too big.
6129   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6130   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6131   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6132                            LoForNormalShift, CCVal, Cmp);
6133 
6134   SDValue Ops[2] = { Lo, Hi };
6135   return DAG.getMergeValues(Ops, dl);
6136 }
6137 
6138 bool AArch64TargetLowering::isOffsetFoldingLegal(
6139     const GlobalAddressSDNode *GA) const {
6140   // Offsets are folded in the DAG combine rather than here so that we can
6141   // intelligently choose an offset based on the uses.
6142   return false;
6143 }
6144 
6145 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6146                                          bool OptForSize) const {
6147   bool IsLegal = false;
6148   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6149   // 16-bit case when target has full fp16 support.
6150   // FIXME: We should be able to handle f128 as well with a clever lowering.
6151   const APInt ImmInt = Imm.bitcastToAPInt();
6152   if (VT == MVT::f64)
6153     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6154   else if (VT == MVT::f32)
6155     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6156   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6157     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6158   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6159   //       generate that fmov.
6160 
6161   // If we can not materialize in immediate field for fmov, check if the
6162   // value can be encoded as the immediate operand of a logical instruction.
6163   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6164   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6165     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6166     // however the mov+fmov sequence is always better because of the reduced
6167     // cache pressure. The timings are still the same if you consider
6168     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6169     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6170     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6171     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6172 			      Insn);
6173     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6174     IsLegal = Insn.size() <= Limit;
6175   }
6176 
6177   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6178                     << " imm value: "; Imm.dump(););
6179   return IsLegal;
6180 }
6181 
6182 //===----------------------------------------------------------------------===//
6183 //                          AArch64 Optimization Hooks
6184 //===----------------------------------------------------------------------===//
6185 
6186 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6187                            SDValue Operand, SelectionDAG &DAG,
6188                            int &ExtraSteps) {
6189   EVT VT = Operand.getValueType();
6190   if (ST->hasNEON() &&
6191       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6192        VT == MVT::f32 || VT == MVT::v1f32 ||
6193        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6194     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6195       // For the reciprocal estimates, convergence is quadratic, so the number
6196       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6197       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6198       // the result for float (23 mantissa bits) is 2 and for double (52
6199       // mantissa bits) is 3.
6200       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6201 
6202     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6203   }
6204 
6205   return SDValue();
6206 }
6207 
6208 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6209                                                SelectionDAG &DAG, int Enabled,
6210                                                int &ExtraSteps,
6211                                                bool &UseOneConst,
6212                                                bool Reciprocal) const {
6213   if (Enabled == ReciprocalEstimate::Enabled ||
6214       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6215     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6216                                        DAG, ExtraSteps)) {
6217       SDLoc DL(Operand);
6218       EVT VT = Operand.getValueType();
6219 
6220       SDNodeFlags Flags;
6221       Flags.setAllowReassociation(true);
6222 
6223       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6224       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6225       for (int i = ExtraSteps; i > 0; --i) {
6226         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6227                                    Flags);
6228         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6229         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6230       }
6231       if (!Reciprocal) {
6232         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6233                                       VT);
6234         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6235         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6236 
6237         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6238         // Correct the result if the operand is 0.0.
6239         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6240                                VT, Eq, Operand, Estimate);
6241       }
6242 
6243       ExtraSteps = 0;
6244       return Estimate;
6245     }
6246 
6247   return SDValue();
6248 }
6249 
6250 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6251                                                 SelectionDAG &DAG, int Enabled,
6252                                                 int &ExtraSteps) const {
6253   if (Enabled == ReciprocalEstimate::Enabled)
6254     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6255                                        DAG, ExtraSteps)) {
6256       SDLoc DL(Operand);
6257       EVT VT = Operand.getValueType();
6258 
6259       SDNodeFlags Flags;
6260       Flags.setAllowReassociation(true);
6261 
6262       // Newton reciprocal iteration: E * (2 - X * E)
6263       // AArch64 reciprocal iteration instruction: (2 - M * N)
6264       for (int i = ExtraSteps; i > 0; --i) {
6265         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6266                                    Estimate, Flags);
6267         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6268       }
6269 
6270       ExtraSteps = 0;
6271       return Estimate;
6272     }
6273 
6274   return SDValue();
6275 }
6276 
6277 //===----------------------------------------------------------------------===//
6278 //                          AArch64 Inline Assembly Support
6279 //===----------------------------------------------------------------------===//
6280 
6281 // Table of Constraints
6282 // TODO: This is the current set of constraints supported by ARM for the
6283 // compiler, not all of them may make sense.
6284 //
6285 // r - A general register
6286 // w - An FP/SIMD register of some size in the range v0-v31
6287 // x - An FP/SIMD register of some size in the range v0-v15
6288 // I - Constant that can be used with an ADD instruction
6289 // J - Constant that can be used with a SUB instruction
6290 // K - Constant that can be used with a 32-bit logical instruction
6291 // L - Constant that can be used with a 64-bit logical instruction
6292 // M - Constant that can be used as a 32-bit MOV immediate
6293 // N - Constant that can be used as a 64-bit MOV immediate
6294 // Q - A memory reference with base register and no offset
6295 // S - A symbolic address
6296 // Y - Floating point constant zero
6297 // Z - Integer constant zero
6298 //
6299 //   Note that general register operands will be output using their 64-bit x
6300 // register name, whatever the size of the variable, unless the asm operand
6301 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6302 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6303 // %q modifier.
6304 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6305   // At this point, we have to lower this constraint to something else, so we
6306   // lower it to an "r" or "w". However, by doing this we will force the result
6307   // to be in register, while the X constraint is much more permissive.
6308   //
6309   // Although we are correct (we are free to emit anything, without
6310   // constraints), we might break use cases that would expect us to be more
6311   // efficient and emit something else.
6312   if (!Subtarget->hasFPARMv8())
6313     return "r";
6314 
6315   if (ConstraintVT.isFloatingPoint())
6316     return "w";
6317 
6318   if (ConstraintVT.isVector() &&
6319      (ConstraintVT.getSizeInBits() == 64 ||
6320       ConstraintVT.getSizeInBits() == 128))
6321     return "w";
6322 
6323   return "r";
6324 }
6325 
6326 enum PredicateConstraint {
6327   Upl,
6328   Upa,
6329   Invalid
6330 };
6331 
6332 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6333   PredicateConstraint P = PredicateConstraint::Invalid;
6334   if (Constraint == "Upa")
6335     P = PredicateConstraint::Upa;
6336   if (Constraint == "Upl")
6337     P = PredicateConstraint::Upl;
6338   return P;
6339 }
6340 
6341 /// getConstraintType - Given a constraint letter, return the type of
6342 /// constraint it is for this target.
6343 AArch64TargetLowering::ConstraintType
6344 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6345   if (Constraint.size() == 1) {
6346     switch (Constraint[0]) {
6347     default:
6348       break;
6349     case 'x':
6350     case 'w':
6351     case 'y':
6352       return C_RegisterClass;
6353     // An address with a single base register. Due to the way we
6354     // currently handle addresses it is the same as 'r'.
6355     case 'Q':
6356       return C_Memory;
6357     case 'I':
6358     case 'J':
6359     case 'K':
6360     case 'L':
6361     case 'M':
6362     case 'N':
6363     case 'Y':
6364     case 'Z':
6365       return C_Immediate;
6366     case 'z':
6367     case 'S': // A symbolic address
6368       return C_Other;
6369     }
6370   } else if (parsePredicateConstraint(Constraint) !=
6371              PredicateConstraint::Invalid)
6372       return C_RegisterClass;
6373   return TargetLowering::getConstraintType(Constraint);
6374 }
6375 
6376 /// Examine constraint type and operand type and determine a weight value.
6377 /// This object must already have been set up with the operand type
6378 /// and the current alternative constraint selected.
6379 TargetLowering::ConstraintWeight
6380 AArch64TargetLowering::getSingleConstraintMatchWeight(
6381     AsmOperandInfo &info, const char *constraint) const {
6382   ConstraintWeight weight = CW_Invalid;
6383   Value *CallOperandVal = info.CallOperandVal;
6384   // If we don't have a value, we can't do a match,
6385   // but allow it at the lowest weight.
6386   if (!CallOperandVal)
6387     return CW_Default;
6388   Type *type = CallOperandVal->getType();
6389   // Look at the constraint type.
6390   switch (*constraint) {
6391   default:
6392     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6393     break;
6394   case 'x':
6395   case 'w':
6396   case 'y':
6397     if (type->isFloatingPointTy() || type->isVectorTy())
6398       weight = CW_Register;
6399     break;
6400   case 'z':
6401     weight = CW_Constant;
6402     break;
6403   case 'U':
6404     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6405       weight = CW_Register;
6406     break;
6407   }
6408   return weight;
6409 }
6410 
6411 std::pair<unsigned, const TargetRegisterClass *>
6412 AArch64TargetLowering::getRegForInlineAsmConstraint(
6413     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6414   if (Constraint.size() == 1) {
6415     switch (Constraint[0]) {
6416     case 'r':
6417       if (VT.getSizeInBits() == 64)
6418         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6419       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6420     case 'w':
6421       if (!Subtarget->hasFPARMv8())
6422         break;
6423       if (VT.isScalableVector())
6424         return std::make_pair(0U, &AArch64::ZPRRegClass);
6425       if (VT.getSizeInBits() == 16)
6426         return std::make_pair(0U, &AArch64::FPR16RegClass);
6427       if (VT.getSizeInBits() == 32)
6428         return std::make_pair(0U, &AArch64::FPR32RegClass);
6429       if (VT.getSizeInBits() == 64)
6430         return std::make_pair(0U, &AArch64::FPR64RegClass);
6431       if (VT.getSizeInBits() == 128)
6432         return std::make_pair(0U, &AArch64::FPR128RegClass);
6433       break;
6434     // The instructions that this constraint is designed for can
6435     // only take 128-bit registers so just use that regclass.
6436     case 'x':
6437       if (!Subtarget->hasFPARMv8())
6438         break;
6439       if (VT.isScalableVector())
6440         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6441       if (VT.getSizeInBits() == 128)
6442         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6443       break;
6444     case 'y':
6445       if (!Subtarget->hasFPARMv8())
6446         break;
6447       if (VT.isScalableVector())
6448         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6449       break;
6450     }
6451   } else {
6452     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6453     if (PC != PredicateConstraint::Invalid) {
6454       assert(VT.isScalableVector());
6455       bool restricted = (PC == PredicateConstraint::Upl);
6456       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6457                           : std::make_pair(0U, &AArch64::PPRRegClass);
6458     }
6459   }
6460   if (StringRef("{cc}").equals_lower(Constraint))
6461     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6462 
6463   // Use the default implementation in TargetLowering to convert the register
6464   // constraint into a member of a register class.
6465   std::pair<unsigned, const TargetRegisterClass *> Res;
6466   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6467 
6468   // Not found as a standard register?
6469   if (!Res.second) {
6470     unsigned Size = Constraint.size();
6471     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6472         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6473       int RegNo;
6474       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6475       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6476         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6477         // By default we'll emit v0-v31 for this unless there's a modifier where
6478         // we'll emit the correct register as well.
6479         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6480           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6481           Res.second = &AArch64::FPR64RegClass;
6482         } else {
6483           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6484           Res.second = &AArch64::FPR128RegClass;
6485         }
6486       }
6487     }
6488   }
6489 
6490   if (Res.second && !Subtarget->hasFPARMv8() &&
6491       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6492       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6493     return std::make_pair(0U, nullptr);
6494 
6495   return Res;
6496 }
6497 
6498 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6499 /// vector.  If it is invalid, don't add anything to Ops.
6500 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6501     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6502     SelectionDAG &DAG) const {
6503   SDValue Result;
6504 
6505   // Currently only support length 1 constraints.
6506   if (Constraint.length() != 1)
6507     return;
6508 
6509   char ConstraintLetter = Constraint[0];
6510   switch (ConstraintLetter) {
6511   default:
6512     break;
6513 
6514   // This set of constraints deal with valid constants for various instructions.
6515   // Validate and return a target constant for them if we can.
6516   case 'z': {
6517     // 'z' maps to xzr or wzr so it needs an input of 0.
6518     if (!isNullConstant(Op))
6519       return;
6520 
6521     if (Op.getValueType() == MVT::i64)
6522       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6523     else
6524       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6525     break;
6526   }
6527   case 'S': {
6528     // An absolute symbolic address or label reference.
6529     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6530       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6531                                           GA->getValueType(0));
6532     } else if (const BlockAddressSDNode *BA =
6533                    dyn_cast<BlockAddressSDNode>(Op)) {
6534       Result =
6535           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6536     } else if (const ExternalSymbolSDNode *ES =
6537                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6538       Result =
6539           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6540     } else
6541       return;
6542     break;
6543   }
6544 
6545   case 'I':
6546   case 'J':
6547   case 'K':
6548   case 'L':
6549   case 'M':
6550   case 'N':
6551     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6552     if (!C)
6553       return;
6554 
6555     // Grab the value and do some validation.
6556     uint64_t CVal = C->getZExtValue();
6557     switch (ConstraintLetter) {
6558     // The I constraint applies only to simple ADD or SUB immediate operands:
6559     // i.e. 0 to 4095 with optional shift by 12
6560     // The J constraint applies only to ADD or SUB immediates that would be
6561     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6562     // instruction [or vice versa], in other words -1 to -4095 with optional
6563     // left shift by 12.
6564     case 'I':
6565       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6566         break;
6567       return;
6568     case 'J': {
6569       uint64_t NVal = -C->getSExtValue();
6570       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6571         CVal = C->getSExtValue();
6572         break;
6573       }
6574       return;
6575     }
6576     // The K and L constraints apply *only* to logical immediates, including
6577     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6578     // been removed and MOV should be used). So these constraints have to
6579     // distinguish between bit patterns that are valid 32-bit or 64-bit
6580     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6581     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6582     // versa.
6583     case 'K':
6584       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6585         break;
6586       return;
6587     case 'L':
6588       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6589         break;
6590       return;
6591     // The M and N constraints are a superset of K and L respectively, for use
6592     // with the MOV (immediate) alias. As well as the logical immediates they
6593     // also match 32 or 64-bit immediates that can be loaded either using a
6594     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6595     // (M) or 64-bit 0x1234000000000000 (N) etc.
6596     // As a note some of this code is liberally stolen from the asm parser.
6597     case 'M': {
6598       if (!isUInt<32>(CVal))
6599         return;
6600       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6601         break;
6602       if ((CVal & 0xFFFF) == CVal)
6603         break;
6604       if ((CVal & 0xFFFF0000ULL) == CVal)
6605         break;
6606       uint64_t NCVal = ~(uint32_t)CVal;
6607       if ((NCVal & 0xFFFFULL) == NCVal)
6608         break;
6609       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6610         break;
6611       return;
6612     }
6613     case 'N': {
6614       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6615         break;
6616       if ((CVal & 0xFFFFULL) == CVal)
6617         break;
6618       if ((CVal & 0xFFFF0000ULL) == CVal)
6619         break;
6620       if ((CVal & 0xFFFF00000000ULL) == CVal)
6621         break;
6622       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6623         break;
6624       uint64_t NCVal = ~CVal;
6625       if ((NCVal & 0xFFFFULL) == NCVal)
6626         break;
6627       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6628         break;
6629       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6630         break;
6631       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6632         break;
6633       return;
6634     }
6635     default:
6636       return;
6637     }
6638 
6639     // All assembler immediates are 64-bit integers.
6640     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6641     break;
6642   }
6643 
6644   if (Result.getNode()) {
6645     Ops.push_back(Result);
6646     return;
6647   }
6648 
6649   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6650 }
6651 
6652 //===----------------------------------------------------------------------===//
6653 //                     AArch64 Advanced SIMD Support
6654 //===----------------------------------------------------------------------===//
6655 
6656 /// WidenVector - Given a value in the V64 register class, produce the
6657 /// equivalent value in the V128 register class.
6658 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6659   EVT VT = V64Reg.getValueType();
6660   unsigned NarrowSize = VT.getVectorNumElements();
6661   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6662   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6663   SDLoc DL(V64Reg);
6664 
6665   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6666                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6667 }
6668 
6669 /// getExtFactor - Determine the adjustment factor for the position when
6670 /// generating an "extract from vector registers" instruction.
6671 static unsigned getExtFactor(SDValue &V) {
6672   EVT EltType = V.getValueType().getVectorElementType();
6673   return EltType.getSizeInBits() / 8;
6674 }
6675 
6676 /// NarrowVector - Given a value in the V128 register class, produce the
6677 /// equivalent value in the V64 register class.
6678 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6679   EVT VT = V128Reg.getValueType();
6680   unsigned WideSize = VT.getVectorNumElements();
6681   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6682   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6683   SDLoc DL(V128Reg);
6684 
6685   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6686 }
6687 
6688 // Gather data to see if the operation can be modelled as a
6689 // shuffle in combination with VEXTs.
6690 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6691                                                   SelectionDAG &DAG) const {
6692   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6693   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6694   SDLoc dl(Op);
6695   EVT VT = Op.getValueType();
6696   unsigned NumElts = VT.getVectorNumElements();
6697 
6698   struct ShuffleSourceInfo {
6699     SDValue Vec;
6700     unsigned MinElt;
6701     unsigned MaxElt;
6702 
6703     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6704     // be compatible with the shuffle we intend to construct. As a result
6705     // ShuffleVec will be some sliding window into the original Vec.
6706     SDValue ShuffleVec;
6707 
6708     // Code should guarantee that element i in Vec starts at element "WindowBase
6709     // + i * WindowScale in ShuffleVec".
6710     int WindowBase;
6711     int WindowScale;
6712 
6713     ShuffleSourceInfo(SDValue Vec)
6714       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6715           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6716 
6717     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6718   };
6719 
6720   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6721   // node.
6722   SmallVector<ShuffleSourceInfo, 2> Sources;
6723   for (unsigned i = 0; i < NumElts; ++i) {
6724     SDValue V = Op.getOperand(i);
6725     if (V.isUndef())
6726       continue;
6727     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6728              !isa<ConstantSDNode>(V.getOperand(1))) {
6729       LLVM_DEBUG(
6730           dbgs() << "Reshuffle failed: "
6731                     "a shuffle can only come from building a vector from "
6732                     "various elements of other vectors, provided their "
6733                     "indices are constant\n");
6734       return SDValue();
6735     }
6736 
6737     // Add this element source to the list if it's not already there.
6738     SDValue SourceVec = V.getOperand(0);
6739     auto Source = find(Sources, SourceVec);
6740     if (Source == Sources.end())
6741       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6742 
6743     // Update the minimum and maximum lane number seen.
6744     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6745     Source->MinElt = std::min(Source->MinElt, EltNo);
6746     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6747   }
6748 
6749   if (Sources.size() > 2) {
6750     LLVM_DEBUG(
6751         dbgs() << "Reshuffle failed: currently only do something sane when at "
6752                   "most two source vectors are involved\n");
6753     return SDValue();
6754   }
6755 
6756   // Find out the smallest element size among result and two sources, and use
6757   // it as element size to build the shuffle_vector.
6758   EVT SmallestEltTy = VT.getVectorElementType();
6759   for (auto &Source : Sources) {
6760     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6761     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6762       SmallestEltTy = SrcEltTy;
6763     }
6764   }
6765   unsigned ResMultiplier =
6766       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6767   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6768   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6769 
6770   // If the source vector is too wide or too narrow, we may nevertheless be able
6771   // to construct a compatible shuffle either by concatenating it with UNDEF or
6772   // extracting a suitable range of elements.
6773   for (auto &Src : Sources) {
6774     EVT SrcVT = Src.ShuffleVec.getValueType();
6775 
6776     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6777       continue;
6778 
6779     // This stage of the search produces a source with the same element type as
6780     // the original, but with a total width matching the BUILD_VECTOR output.
6781     EVT EltVT = SrcVT.getVectorElementType();
6782     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6783     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6784 
6785     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6786       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6787       // We can pad out the smaller vector for free, so if it's part of a
6788       // shuffle...
6789       Src.ShuffleVec =
6790           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6791                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6792       continue;
6793     }
6794 
6795     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6796 
6797     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6798       LLVM_DEBUG(
6799           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6800       return SDValue();
6801     }
6802 
6803     if (Src.MinElt >= NumSrcElts) {
6804       // The extraction can just take the second half
6805       Src.ShuffleVec =
6806           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6807                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6808       Src.WindowBase = -NumSrcElts;
6809     } else if (Src.MaxElt < NumSrcElts) {
6810       // The extraction can just take the first half
6811       Src.ShuffleVec =
6812           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6813                       DAG.getConstant(0, dl, MVT::i64));
6814     } else {
6815       // An actual VEXT is needed
6816       SDValue VEXTSrc1 =
6817           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6818                       DAG.getConstant(0, dl, MVT::i64));
6819       SDValue VEXTSrc2 =
6820           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6821                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6822       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6823 
6824       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6825                                    VEXTSrc2,
6826                                    DAG.getConstant(Imm, dl, MVT::i32));
6827       Src.WindowBase = -Src.MinElt;
6828     }
6829   }
6830 
6831   // Another possible incompatibility occurs from the vector element types. We
6832   // can fix this by bitcasting the source vectors to the same type we intend
6833   // for the shuffle.
6834   for (auto &Src : Sources) {
6835     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6836     if (SrcEltTy == SmallestEltTy)
6837       continue;
6838     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6839     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6840     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6841     Src.WindowBase *= Src.WindowScale;
6842   }
6843 
6844   // Final sanity check before we try to actually produce a shuffle.
6845   LLVM_DEBUG(for (auto Src
6846                   : Sources)
6847                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6848 
6849   // The stars all align, our next step is to produce the mask for the shuffle.
6850   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6851   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6852   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6853     SDValue Entry = Op.getOperand(i);
6854     if (Entry.isUndef())
6855       continue;
6856 
6857     auto Src = find(Sources, Entry.getOperand(0));
6858     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6859 
6860     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6861     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6862     // segment.
6863     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6864     int BitsDefined =
6865         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6866     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6867 
6868     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6869     // starting at the appropriate offset.
6870     int *LaneMask = &Mask[i * ResMultiplier];
6871 
6872     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6873     ExtractBase += NumElts * (Src - Sources.begin());
6874     for (int j = 0; j < LanesDefined; ++j)
6875       LaneMask[j] = ExtractBase + j;
6876   }
6877 
6878   // Final check before we try to produce nonsense...
6879   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6880     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6881     return SDValue();
6882   }
6883 
6884   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6885   for (unsigned i = 0; i < Sources.size(); ++i)
6886     ShuffleOps[i] = Sources[i].ShuffleVec;
6887 
6888   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6889                                          ShuffleOps[1], Mask);
6890   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6891 
6892   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6893              dbgs() << "Reshuffle, creating node: "; V.dump(););
6894 
6895   return V;
6896 }
6897 
6898 // check if an EXT instruction can handle the shuffle mask when the
6899 // vector sources of the shuffle are the same.
6900 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6901   unsigned NumElts = VT.getVectorNumElements();
6902 
6903   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6904   if (M[0] < 0)
6905     return false;
6906 
6907   Imm = M[0];
6908 
6909   // If this is a VEXT shuffle, the immediate value is the index of the first
6910   // element.  The other shuffle indices must be the successive elements after
6911   // the first one.
6912   unsigned ExpectedElt = Imm;
6913   for (unsigned i = 1; i < NumElts; ++i) {
6914     // Increment the expected index.  If it wraps around, just follow it
6915     // back to index zero and keep going.
6916     ++ExpectedElt;
6917     if (ExpectedElt == NumElts)
6918       ExpectedElt = 0;
6919 
6920     if (M[i] < 0)
6921       continue; // ignore UNDEF indices
6922     if (ExpectedElt != static_cast<unsigned>(M[i]))
6923       return false;
6924   }
6925 
6926   return true;
6927 }
6928 
6929 // check if an EXT instruction can handle the shuffle mask when the
6930 // vector sources of the shuffle are different.
6931 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6932                       unsigned &Imm) {
6933   // Look for the first non-undef element.
6934   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6935 
6936   // Benefit form APInt to handle overflow when calculating expected element.
6937   unsigned NumElts = VT.getVectorNumElements();
6938   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6939   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6940   // The following shuffle indices must be the successive elements after the
6941   // first real element.
6942   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6943       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6944   if (FirstWrongElt != M.end())
6945     return false;
6946 
6947   // The index of an EXT is the first element if it is not UNDEF.
6948   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6949   // value of the first element.  E.g.
6950   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6951   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6952   // ExpectedElt is the last mask index plus 1.
6953   Imm = ExpectedElt.getZExtValue();
6954 
6955   // There are two difference cases requiring to reverse input vectors.
6956   // For example, for vector <4 x i32> we have the following cases,
6957   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6958   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6959   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6960   // to reverse two input vectors.
6961   if (Imm < NumElts)
6962     ReverseEXT = true;
6963   else
6964     Imm -= NumElts;
6965 
6966   return true;
6967 }
6968 
6969 /// isREVMask - Check if a vector shuffle corresponds to a REV
6970 /// instruction with the specified blocksize.  (The order of the elements
6971 /// within each block of the vector is reversed.)
6972 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6973   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6974          "Only possible block sizes for REV are: 16, 32, 64");
6975 
6976   unsigned EltSz = VT.getScalarSizeInBits();
6977   if (EltSz == 64)
6978     return false;
6979 
6980   unsigned NumElts = VT.getVectorNumElements();
6981   unsigned BlockElts = M[0] + 1;
6982   // If the first shuffle index is UNDEF, be optimistic.
6983   if (M[0] < 0)
6984     BlockElts = BlockSize / EltSz;
6985 
6986   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6987     return false;
6988 
6989   for (unsigned i = 0; i < NumElts; ++i) {
6990     if (M[i] < 0)
6991       continue; // ignore UNDEF indices
6992     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6993       return false;
6994   }
6995 
6996   return true;
6997 }
6998 
6999 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7000   unsigned NumElts = VT.getVectorNumElements();
7001   if (NumElts % 2 != 0)
7002     return false;
7003   WhichResult = (M[0] == 0 ? 0 : 1);
7004   unsigned Idx = WhichResult * NumElts / 2;
7005   for (unsigned i = 0; i != NumElts; i += 2) {
7006     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7007         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7008       return false;
7009     Idx += 1;
7010   }
7011 
7012   return true;
7013 }
7014 
7015 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7016   unsigned NumElts = VT.getVectorNumElements();
7017   WhichResult = (M[0] == 0 ? 0 : 1);
7018   for (unsigned i = 0; i != NumElts; ++i) {
7019     if (M[i] < 0)
7020       continue; // ignore UNDEF indices
7021     if ((unsigned)M[i] != 2 * i + WhichResult)
7022       return false;
7023   }
7024 
7025   return true;
7026 }
7027 
7028 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7029   unsigned NumElts = VT.getVectorNumElements();
7030   if (NumElts % 2 != 0)
7031     return false;
7032   WhichResult = (M[0] == 0 ? 0 : 1);
7033   for (unsigned i = 0; i < NumElts; i += 2) {
7034     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7035         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7036       return false;
7037   }
7038   return true;
7039 }
7040 
7041 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7042 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7043 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7044 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7045   unsigned NumElts = VT.getVectorNumElements();
7046   if (NumElts % 2 != 0)
7047     return false;
7048   WhichResult = (M[0] == 0 ? 0 : 1);
7049   unsigned Idx = WhichResult * NumElts / 2;
7050   for (unsigned i = 0; i != NumElts; i += 2) {
7051     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7052         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7053       return false;
7054     Idx += 1;
7055   }
7056 
7057   return true;
7058 }
7059 
7060 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7061 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7062 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7063 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7064   unsigned Half = VT.getVectorNumElements() / 2;
7065   WhichResult = (M[0] == 0 ? 0 : 1);
7066   for (unsigned j = 0; j != 2; ++j) {
7067     unsigned Idx = WhichResult;
7068     for (unsigned i = 0; i != Half; ++i) {
7069       int MIdx = M[i + j * Half];
7070       if (MIdx >= 0 && (unsigned)MIdx != Idx)
7071         return false;
7072       Idx += 2;
7073     }
7074   }
7075 
7076   return true;
7077 }
7078 
7079 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7080 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7081 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7082 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7083   unsigned NumElts = VT.getVectorNumElements();
7084   if (NumElts % 2 != 0)
7085     return false;
7086   WhichResult = (M[0] == 0 ? 0 : 1);
7087   for (unsigned i = 0; i < NumElts; i += 2) {
7088     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7089         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7090       return false;
7091   }
7092   return true;
7093 }
7094 
7095 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7096                       bool &DstIsLeft, int &Anomaly) {
7097   if (M.size() != static_cast<size_t>(NumInputElements))
7098     return false;
7099 
7100   int NumLHSMatch = 0, NumRHSMatch = 0;
7101   int LastLHSMismatch = -1, LastRHSMismatch = -1;
7102 
7103   for (int i = 0; i < NumInputElements; ++i) {
7104     if (M[i] == -1) {
7105       ++NumLHSMatch;
7106       ++NumRHSMatch;
7107       continue;
7108     }
7109 
7110     if (M[i] == i)
7111       ++NumLHSMatch;
7112     else
7113       LastLHSMismatch = i;
7114 
7115     if (M[i] == i + NumInputElements)
7116       ++NumRHSMatch;
7117     else
7118       LastRHSMismatch = i;
7119   }
7120 
7121   if (NumLHSMatch == NumInputElements - 1) {
7122     DstIsLeft = true;
7123     Anomaly = LastLHSMismatch;
7124     return true;
7125   } else if (NumRHSMatch == NumInputElements - 1) {
7126     DstIsLeft = false;
7127     Anomaly = LastRHSMismatch;
7128     return true;
7129   }
7130 
7131   return false;
7132 }
7133 
7134 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7135   if (VT.getSizeInBits() != 128)
7136     return false;
7137 
7138   unsigned NumElts = VT.getVectorNumElements();
7139 
7140   for (int I = 0, E = NumElts / 2; I != E; I++) {
7141     if (Mask[I] != I)
7142       return false;
7143   }
7144 
7145   int Offset = NumElts / 2;
7146   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7147     if (Mask[I] != I + SplitLHS * Offset)
7148       return false;
7149   }
7150 
7151   return true;
7152 }
7153 
7154 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7155   SDLoc DL(Op);
7156   EVT VT = Op.getValueType();
7157   SDValue V0 = Op.getOperand(0);
7158   SDValue V1 = Op.getOperand(1);
7159   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7160 
7161   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7162       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7163     return SDValue();
7164 
7165   bool SplitV0 = V0.getValueSizeInBits() == 128;
7166 
7167   if (!isConcatMask(Mask, VT, SplitV0))
7168     return SDValue();
7169 
7170   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7171   if (SplitV0) {
7172     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7173                      DAG.getConstant(0, DL, MVT::i64));
7174   }
7175   if (V1.getValueSizeInBits() == 128) {
7176     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7177                      DAG.getConstant(0, DL, MVT::i64));
7178   }
7179   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7180 }
7181 
7182 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7183 /// the specified operations to build the shuffle.
7184 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7185                                       SDValue RHS, SelectionDAG &DAG,
7186                                       const SDLoc &dl) {
7187   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7188   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7189   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7190 
7191   enum {
7192     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7193     OP_VREV,
7194     OP_VDUP0,
7195     OP_VDUP1,
7196     OP_VDUP2,
7197     OP_VDUP3,
7198     OP_VEXT1,
7199     OP_VEXT2,
7200     OP_VEXT3,
7201     OP_VUZPL, // VUZP, left result
7202     OP_VUZPR, // VUZP, right result
7203     OP_VZIPL, // VZIP, left result
7204     OP_VZIPR, // VZIP, right result
7205     OP_VTRNL, // VTRN, left result
7206     OP_VTRNR  // VTRN, right result
7207   };
7208 
7209   if (OpNum == OP_COPY) {
7210     if (LHSID == (1 * 9 + 2) * 9 + 3)
7211       return LHS;
7212     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7213     return RHS;
7214   }
7215 
7216   SDValue OpLHS, OpRHS;
7217   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7218   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7219   EVT VT = OpLHS.getValueType();
7220 
7221   switch (OpNum) {
7222   default:
7223     llvm_unreachable("Unknown shuffle opcode!");
7224   case OP_VREV:
7225     // VREV divides the vector in half and swaps within the half.
7226     if (VT.getVectorElementType() == MVT::i32 ||
7227         VT.getVectorElementType() == MVT::f32)
7228       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7229     // vrev <4 x i16> -> REV32
7230     if (VT.getVectorElementType() == MVT::i16 ||
7231         VT.getVectorElementType() == MVT::f16)
7232       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7233     // vrev <4 x i8> -> REV16
7234     assert(VT.getVectorElementType() == MVT::i8);
7235     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7236   case OP_VDUP0:
7237   case OP_VDUP1:
7238   case OP_VDUP2:
7239   case OP_VDUP3: {
7240     EVT EltTy = VT.getVectorElementType();
7241     unsigned Opcode;
7242     if (EltTy == MVT::i8)
7243       Opcode = AArch64ISD::DUPLANE8;
7244     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7245       Opcode = AArch64ISD::DUPLANE16;
7246     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7247       Opcode = AArch64ISD::DUPLANE32;
7248     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7249       Opcode = AArch64ISD::DUPLANE64;
7250     else
7251       llvm_unreachable("Invalid vector element type?");
7252 
7253     if (VT.getSizeInBits() == 64)
7254       OpLHS = WidenVector(OpLHS, DAG);
7255     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7256     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7257   }
7258   case OP_VEXT1:
7259   case OP_VEXT2:
7260   case OP_VEXT3: {
7261     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7262     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7263                        DAG.getConstant(Imm, dl, MVT::i32));
7264   }
7265   case OP_VUZPL:
7266     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7267                        OpRHS);
7268   case OP_VUZPR:
7269     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7270                        OpRHS);
7271   case OP_VZIPL:
7272     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7273                        OpRHS);
7274   case OP_VZIPR:
7275     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7276                        OpRHS);
7277   case OP_VTRNL:
7278     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7279                        OpRHS);
7280   case OP_VTRNR:
7281     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7282                        OpRHS);
7283   }
7284 }
7285 
7286 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7287                            SelectionDAG &DAG) {
7288   // Check to see if we can use the TBL instruction.
7289   SDValue V1 = Op.getOperand(0);
7290   SDValue V2 = Op.getOperand(1);
7291   SDLoc DL(Op);
7292 
7293   EVT EltVT = Op.getValueType().getVectorElementType();
7294   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7295 
7296   SmallVector<SDValue, 8> TBLMask;
7297   for (int Val : ShuffleMask) {
7298     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7299       unsigned Offset = Byte + Val * BytesPerElt;
7300       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7301     }
7302   }
7303 
7304   MVT IndexVT = MVT::v8i8;
7305   unsigned IndexLen = 8;
7306   if (Op.getValueSizeInBits() == 128) {
7307     IndexVT = MVT::v16i8;
7308     IndexLen = 16;
7309   }
7310 
7311   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7312   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7313 
7314   SDValue Shuffle;
7315   if (V2.getNode()->isUndef()) {
7316     if (IndexLen == 8)
7317       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7318     Shuffle = DAG.getNode(
7319         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7320         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7321         DAG.getBuildVector(IndexVT, DL,
7322                            makeArrayRef(TBLMask.data(), IndexLen)));
7323   } else {
7324     if (IndexLen == 8) {
7325       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7326       Shuffle = DAG.getNode(
7327           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7328           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7329           DAG.getBuildVector(IndexVT, DL,
7330                              makeArrayRef(TBLMask.data(), IndexLen)));
7331     } else {
7332       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7333       // cannot currently represent the register constraints on the input
7334       // table registers.
7335       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7336       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7337       //                   IndexLen));
7338       Shuffle = DAG.getNode(
7339           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7340           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7341           V2Cst, DAG.getBuildVector(IndexVT, DL,
7342                                     makeArrayRef(TBLMask.data(), IndexLen)));
7343     }
7344   }
7345   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7346 }
7347 
7348 static unsigned getDUPLANEOp(EVT EltType) {
7349   if (EltType == MVT::i8)
7350     return AArch64ISD::DUPLANE8;
7351   if (EltType == MVT::i16 || EltType == MVT::f16)
7352     return AArch64ISD::DUPLANE16;
7353   if (EltType == MVT::i32 || EltType == MVT::f32)
7354     return AArch64ISD::DUPLANE32;
7355   if (EltType == MVT::i64 || EltType == MVT::f64)
7356     return AArch64ISD::DUPLANE64;
7357 
7358   llvm_unreachable("Invalid vector element type?");
7359 }
7360 
7361 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7362                                                    SelectionDAG &DAG) const {
7363   SDLoc dl(Op);
7364   EVT VT = Op.getValueType();
7365 
7366   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7367 
7368   // Convert shuffles that are directly supported on NEON to target-specific
7369   // DAG nodes, instead of keeping them as shuffles and matching them again
7370   // during code selection.  This is more efficient and avoids the possibility
7371   // of inconsistencies between legalization and selection.
7372   ArrayRef<int> ShuffleMask = SVN->getMask();
7373 
7374   SDValue V1 = Op.getOperand(0);
7375   SDValue V2 = Op.getOperand(1);
7376 
7377   if (SVN->isSplat()) {
7378     int Lane = SVN->getSplatIndex();
7379     // If this is undef splat, generate it via "just" vdup, if possible.
7380     if (Lane == -1)
7381       Lane = 0;
7382 
7383     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7384       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7385                          V1.getOperand(0));
7386     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7387     // constant. If so, we can just reference the lane's definition directly.
7388     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7389         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7390       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7391 
7392     // Otherwise, duplicate from the lane of the input vector.
7393     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7394 
7395     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7396     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7397       // Match: dup (bitcast (extract_subv X, C)), LaneC
7398       if (BitCast.getOpcode() != ISD::BITCAST ||
7399           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7400         return false;
7401 
7402       // The extract index must align in the destination type. That may not
7403       // happen if the bitcast is from narrow to wide type.
7404       SDValue Extract = BitCast.getOperand(0);
7405       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7406       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7407       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7408       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7409       if (ExtIdxInBits % CastedEltBitWidth != 0)
7410         return false;
7411 
7412       // Update the lane value by offsetting with the scaled extract index.
7413       LaneC += ExtIdxInBits / CastedEltBitWidth;
7414 
7415       // Determine the casted vector type of the wide vector input.
7416       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7417       // Examples:
7418       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7419       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7420       unsigned SrcVecNumElts =
7421           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7422       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7423                                 SrcVecNumElts);
7424       return true;
7425     };
7426     MVT CastVT;
7427     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7428       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7429     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7430       // The lane is incremented by the index of the extract.
7431       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7432       Lane += V1.getConstantOperandVal(1);
7433       V1 = V1.getOperand(0);
7434     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7435       // The lane is decremented if we are splatting from the 2nd operand.
7436       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7437       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7438       Lane -= Idx * VT.getVectorNumElements() / 2;
7439       V1 = WidenVector(V1.getOperand(Idx), DAG);
7440     } else if (VT.getSizeInBits() == 64) {
7441       // Widen the operand to 128-bit register with undef.
7442       V1 = WidenVector(V1, DAG);
7443     }
7444     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7445   }
7446 
7447   if (isREVMask(ShuffleMask, VT, 64))
7448     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7449   if (isREVMask(ShuffleMask, VT, 32))
7450     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7451   if (isREVMask(ShuffleMask, VT, 16))
7452     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7453 
7454   bool ReverseEXT = false;
7455   unsigned Imm;
7456   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7457     if (ReverseEXT)
7458       std::swap(V1, V2);
7459     Imm *= getExtFactor(V1);
7460     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7461                        DAG.getConstant(Imm, dl, MVT::i32));
7462   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7463     Imm *= getExtFactor(V1);
7464     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7465                        DAG.getConstant(Imm, dl, MVT::i32));
7466   }
7467 
7468   unsigned WhichResult;
7469   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7470     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7471     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7472   }
7473   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7474     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7475     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7476   }
7477   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7478     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7479     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7480   }
7481 
7482   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7483     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7484     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7485   }
7486   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7487     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7488     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7489   }
7490   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7491     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7492     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7493   }
7494 
7495   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7496     return Concat;
7497 
7498   bool DstIsLeft;
7499   int Anomaly;
7500   int NumInputElements = V1.getValueType().getVectorNumElements();
7501   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7502     SDValue DstVec = DstIsLeft ? V1 : V2;
7503     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7504 
7505     SDValue SrcVec = V1;
7506     int SrcLane = ShuffleMask[Anomaly];
7507     if (SrcLane >= NumInputElements) {
7508       SrcVec = V2;
7509       SrcLane -= VT.getVectorNumElements();
7510     }
7511     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7512 
7513     EVT ScalarVT = VT.getVectorElementType();
7514 
7515     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7516       ScalarVT = MVT::i32;
7517 
7518     return DAG.getNode(
7519         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7520         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7521         DstLaneV);
7522   }
7523 
7524   // If the shuffle is not directly supported and it has 4 elements, use
7525   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7526   unsigned NumElts = VT.getVectorNumElements();
7527   if (NumElts == 4) {
7528     unsigned PFIndexes[4];
7529     for (unsigned i = 0; i != 4; ++i) {
7530       if (ShuffleMask[i] < 0)
7531         PFIndexes[i] = 8;
7532       else
7533         PFIndexes[i] = ShuffleMask[i];
7534     }
7535 
7536     // Compute the index in the perfect shuffle table.
7537     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7538                             PFIndexes[2] * 9 + PFIndexes[3];
7539     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7540     unsigned Cost = (PFEntry >> 30);
7541 
7542     if (Cost <= 4)
7543       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7544   }
7545 
7546   return GenerateTBL(Op, ShuffleMask, DAG);
7547 }
7548 
7549 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7550                                                  SelectionDAG &DAG) const {
7551   SDLoc dl(Op);
7552   EVT VT = Op.getValueType();
7553   EVT ElemVT = VT.getScalarType();
7554 
7555   SDValue SplatVal = Op.getOperand(0);
7556 
7557   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7558   // FPRs don't have this restriction.
7559   switch (ElemVT.getSimpleVT().SimpleTy) {
7560   case MVT::i1: {
7561     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
7562     // lowering code.
7563     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
7564       if (ConstVal->isOne())
7565         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
7566       // TODO: Add special case for constant false
7567     }
7568     // The general case of i1.  There isn't any natural way to do this,
7569     // so we use some trickery with whilelo.
7570     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7571     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7572                            DAG.getValueType(MVT::i1));
7573     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7574                                        MVT::i64);
7575     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7576                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7577   }
7578   case MVT::i8:
7579   case MVT::i16:
7580   case MVT::i32:
7581     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7582     break;
7583   case MVT::i64:
7584     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7585     break;
7586   case MVT::f16:
7587   case MVT::f32:
7588   case MVT::f64:
7589     // Fine as is
7590     break;
7591   default:
7592     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7593   }
7594 
7595   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7596 }
7597 
7598 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
7599                                              SelectionDAG &DAG) const {
7600   SDLoc DL(Op);
7601 
7602   EVT VT = Op.getValueType();
7603   if (!isTypeLegal(VT) || !VT.isScalableVector())
7604     return SDValue();
7605 
7606   // Current lowering only supports the SVE-ACLE types.
7607   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
7608     return SDValue();
7609 
7610   // The DUPQ operation is indepedent of element type so normalise to i64s.
7611   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
7612   SDValue Idx128 = Op.getOperand(2);
7613 
7614   // DUPQ can be used when idx is in range.
7615   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
7616   if (CIdx && (CIdx->getZExtValue() <= 3)) {
7617     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
7618     SDNode *DUPQ =
7619         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
7620     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
7621   }
7622 
7623   // The ACLE says this must produce the same result as:
7624   //   svtbl(data, svadd_x(svptrue_b64(),
7625   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
7626   //                       index * 2))
7627   SDValue One = DAG.getConstant(1, DL, MVT::i64);
7628   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
7629 
7630   // create the vector 0,1,0,1,...
7631   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
7632   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
7633                            DL, MVT::nxv2i64, Zero, One);
7634   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
7635 
7636   // create the vector idx64,idx64+1,idx64,idx64+1,...
7637   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
7638   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
7639   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
7640 
7641   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
7642   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
7643   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
7644 }
7645 
7646 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7647                                APInt &UndefBits) {
7648   EVT VT = BVN->getValueType(0);
7649   APInt SplatBits, SplatUndef;
7650   unsigned SplatBitSize;
7651   bool HasAnyUndefs;
7652   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7653     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7654 
7655     for (unsigned i = 0; i < NumSplats; ++i) {
7656       CnstBits <<= SplatBitSize;
7657       UndefBits <<= SplatBitSize;
7658       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7659       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7660     }
7661 
7662     return true;
7663   }
7664 
7665   return false;
7666 }
7667 
7668 // Try 64-bit splatted SIMD immediate.
7669 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7670                                  const APInt &Bits) {
7671   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7672     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7673     EVT VT = Op.getValueType();
7674     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7675 
7676     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7677       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7678 
7679       SDLoc dl(Op);
7680       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7681                                 DAG.getConstant(Value, dl, MVT::i32));
7682       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7683     }
7684   }
7685 
7686   return SDValue();
7687 }
7688 
7689 // Try 32-bit splatted SIMD immediate.
7690 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7691                                   const APInt &Bits,
7692                                   const SDValue *LHS = nullptr) {
7693   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7694     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7695     EVT VT = Op.getValueType();
7696     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7697     bool isAdvSIMDModImm = false;
7698     uint64_t Shift;
7699 
7700     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7701       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7702       Shift = 0;
7703     }
7704     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7705       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7706       Shift = 8;
7707     }
7708     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7709       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7710       Shift = 16;
7711     }
7712     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7713       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7714       Shift = 24;
7715     }
7716 
7717     if (isAdvSIMDModImm) {
7718       SDLoc dl(Op);
7719       SDValue Mov;
7720 
7721       if (LHS)
7722         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7723                           DAG.getConstant(Value, dl, MVT::i32),
7724                           DAG.getConstant(Shift, dl, MVT::i32));
7725       else
7726         Mov = DAG.getNode(NewOp, dl, MovTy,
7727                           DAG.getConstant(Value, dl, MVT::i32),
7728                           DAG.getConstant(Shift, dl, MVT::i32));
7729 
7730       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7731     }
7732   }
7733 
7734   return SDValue();
7735 }
7736 
7737 // Try 16-bit splatted SIMD immediate.
7738 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7739                                   const APInt &Bits,
7740                                   const SDValue *LHS = nullptr) {
7741   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7742     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7743     EVT VT = Op.getValueType();
7744     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7745     bool isAdvSIMDModImm = false;
7746     uint64_t Shift;
7747 
7748     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7749       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7750       Shift = 0;
7751     }
7752     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7753       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7754       Shift = 8;
7755     }
7756 
7757     if (isAdvSIMDModImm) {
7758       SDLoc dl(Op);
7759       SDValue Mov;
7760 
7761       if (LHS)
7762         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7763                           DAG.getConstant(Value, dl, MVT::i32),
7764                           DAG.getConstant(Shift, dl, MVT::i32));
7765       else
7766         Mov = DAG.getNode(NewOp, dl, MovTy,
7767                           DAG.getConstant(Value, dl, MVT::i32),
7768                           DAG.getConstant(Shift, dl, MVT::i32));
7769 
7770       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7771     }
7772   }
7773 
7774   return SDValue();
7775 }
7776 
7777 // Try 32-bit splatted SIMD immediate with shifted ones.
7778 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7779                                     SelectionDAG &DAG, const APInt &Bits) {
7780   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7781     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7782     EVT VT = Op.getValueType();
7783     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7784     bool isAdvSIMDModImm = false;
7785     uint64_t Shift;
7786 
7787     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7788       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7789       Shift = 264;
7790     }
7791     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7792       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7793       Shift = 272;
7794     }
7795 
7796     if (isAdvSIMDModImm) {
7797       SDLoc dl(Op);
7798       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7799                                 DAG.getConstant(Value, dl, MVT::i32),
7800                                 DAG.getConstant(Shift, dl, MVT::i32));
7801       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7802     }
7803   }
7804 
7805   return SDValue();
7806 }
7807 
7808 // Try 8-bit splatted SIMD immediate.
7809 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7810                                  const APInt &Bits) {
7811   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7812     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7813     EVT VT = Op.getValueType();
7814     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7815 
7816     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7817       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7818 
7819       SDLoc dl(Op);
7820       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7821                                 DAG.getConstant(Value, dl, MVT::i32));
7822       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7823     }
7824   }
7825 
7826   return SDValue();
7827 }
7828 
7829 // Try FP splatted SIMD immediate.
7830 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7831                                   const APInt &Bits) {
7832   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7833     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7834     EVT VT = Op.getValueType();
7835     bool isWide = (VT.getSizeInBits() == 128);
7836     MVT MovTy;
7837     bool isAdvSIMDModImm = false;
7838 
7839     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7840       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7841       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7842     }
7843     else if (isWide &&
7844              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7845       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7846       MovTy = MVT::v2f64;
7847     }
7848 
7849     if (isAdvSIMDModImm) {
7850       SDLoc dl(Op);
7851       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7852                                 DAG.getConstant(Value, dl, MVT::i32));
7853       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7854     }
7855   }
7856 
7857   return SDValue();
7858 }
7859 
7860 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7861 // consists of only the same constant int value, returned in reference arg
7862 // ConstVal
7863 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7864                                      uint64_t &ConstVal) {
7865   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7866   if (!Bvec)
7867     return false;
7868   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7869   if (!FirstElt)
7870     return false;
7871   EVT VT = Bvec->getValueType(0);
7872   unsigned NumElts = VT.getVectorNumElements();
7873   for (unsigned i = 1; i < NumElts; ++i)
7874     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7875       return false;
7876   ConstVal = FirstElt->getZExtValue();
7877   return true;
7878 }
7879 
7880 static unsigned getIntrinsicID(const SDNode *N) {
7881   unsigned Opcode = N->getOpcode();
7882   switch (Opcode) {
7883   default:
7884     return Intrinsic::not_intrinsic;
7885   case ISD::INTRINSIC_WO_CHAIN: {
7886     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7887     if (IID < Intrinsic::num_intrinsics)
7888       return IID;
7889     return Intrinsic::not_intrinsic;
7890   }
7891   }
7892 }
7893 
7894 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7895 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7896 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7897 // Also, logical shift right -> sri, with the same structure.
7898 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7899   EVT VT = N->getValueType(0);
7900 
7901   if (!VT.isVector())
7902     return SDValue();
7903 
7904   SDLoc DL(N);
7905 
7906   // Is the first op an AND?
7907   const SDValue And = N->getOperand(0);
7908   if (And.getOpcode() != ISD::AND)
7909     return SDValue();
7910 
7911   // Is the second op an shl or lshr?
7912   SDValue Shift = N->getOperand(1);
7913   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7914   // or AArch64ISD::VLSHR vector, #shift
7915   unsigned ShiftOpc = Shift.getOpcode();
7916   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7917     return SDValue();
7918   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7919 
7920   // Is the shift amount constant?
7921   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7922   if (!C2node)
7923     return SDValue();
7924 
7925   // Is the and mask vector all constant?
7926   uint64_t C1;
7927   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7928     return SDValue();
7929 
7930   // Is C1 == ~C2, taking into account how much one can shift elements of a
7931   // particular size?
7932   uint64_t C2 = C2node->getZExtValue();
7933   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7934   if (C2 > ElemSizeInBits)
7935     return SDValue();
7936   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7937   if ((C1 & ElemMask) != (~C2 & ElemMask))
7938     return SDValue();
7939 
7940   SDValue X = And.getOperand(0);
7941   SDValue Y = Shift.getOperand(0);
7942 
7943   unsigned Intrin =
7944       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7945   SDValue ResultSLI =
7946       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7947                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7948                   Shift.getOperand(1));
7949 
7950   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7951   LLVM_DEBUG(N->dump(&DAG));
7952   LLVM_DEBUG(dbgs() << "into: \n");
7953   LLVM_DEBUG(ResultSLI->dump(&DAG));
7954 
7955   ++NumShiftInserts;
7956   return ResultSLI;
7957 }
7958 
7959 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7960                                              SelectionDAG &DAG) const {
7961   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7962   if (EnableAArch64SlrGeneration) {
7963     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7964       return Res;
7965   }
7966 
7967   EVT VT = Op.getValueType();
7968 
7969   SDValue LHS = Op.getOperand(0);
7970   BuildVectorSDNode *BVN =
7971       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7972   if (!BVN) {
7973     // OR commutes, so try swapping the operands.
7974     LHS = Op.getOperand(1);
7975     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7976   }
7977   if (!BVN)
7978     return Op;
7979 
7980   APInt DefBits(VT.getSizeInBits(), 0);
7981   APInt UndefBits(VT.getSizeInBits(), 0);
7982   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7983     SDValue NewOp;
7984 
7985     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7986                                     DefBits, &LHS)) ||
7987         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7988                                     DefBits, &LHS)))
7989       return NewOp;
7990 
7991     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7992                                     UndefBits, &LHS)) ||
7993         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7994                                     UndefBits, &LHS)))
7995       return NewOp;
7996   }
7997 
7998   // We can always fall back to a non-immediate OR.
7999   return Op;
8000 }
8001 
8002 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8003 // be truncated to fit element width.
8004 static SDValue NormalizeBuildVector(SDValue Op,
8005                                     SelectionDAG &DAG) {
8006   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8007   SDLoc dl(Op);
8008   EVT VT = Op.getValueType();
8009   EVT EltTy= VT.getVectorElementType();
8010 
8011   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8012     return Op;
8013 
8014   SmallVector<SDValue, 16> Ops;
8015   for (SDValue Lane : Op->ops()) {
8016     // For integer vectors, type legalization would have promoted the
8017     // operands already. Otherwise, if Op is a floating-point splat
8018     // (with operands cast to integers), then the only possibilities
8019     // are constants and UNDEFs.
8020     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8021       APInt LowBits(EltTy.getSizeInBits(),
8022                     CstLane->getZExtValue());
8023       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8024     } else if (Lane.getNode()->isUndef()) {
8025       Lane = DAG.getUNDEF(MVT::i32);
8026     } else {
8027       assert(Lane.getValueType() == MVT::i32 &&
8028              "Unexpected BUILD_VECTOR operand type");
8029     }
8030     Ops.push_back(Lane);
8031   }
8032   return DAG.getBuildVector(VT, dl, Ops);
8033 }
8034 
8035 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8036   EVT VT = Op.getValueType();
8037 
8038   APInt DefBits(VT.getSizeInBits(), 0);
8039   APInt UndefBits(VT.getSizeInBits(), 0);
8040   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8041   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8042     SDValue NewOp;
8043     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8044         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8045         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8046         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8047         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8048         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8049       return NewOp;
8050 
8051     DefBits = ~DefBits;
8052     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8053         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8054         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8055       return NewOp;
8056 
8057     DefBits = UndefBits;
8058     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8059         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8060         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8061         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8062         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8063         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8064       return NewOp;
8065 
8066     DefBits = ~UndefBits;
8067     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8068         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8069         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8070       return NewOp;
8071   }
8072 
8073   return SDValue();
8074 }
8075 
8076 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8077                                                  SelectionDAG &DAG) const {
8078   EVT VT = Op.getValueType();
8079 
8080   // Try to build a simple constant vector.
8081   Op = NormalizeBuildVector(Op, DAG);
8082   if (VT.isInteger()) {
8083     // Certain vector constants, used to express things like logical NOT and
8084     // arithmetic NEG, are passed through unmodified.  This allows special
8085     // patterns for these operations to match, which will lower these constants
8086     // to whatever is proven necessary.
8087     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8088     if (BVN->isConstant())
8089       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8090         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8091         APInt Val(BitSize,
8092                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8093         if (Val.isNullValue() || Val.isAllOnesValue())
8094           return Op;
8095       }
8096   }
8097 
8098   if (SDValue V = ConstantBuildVector(Op, DAG))
8099     return V;
8100 
8101   // Scan through the operands to find some interesting properties we can
8102   // exploit:
8103   //   1) If only one value is used, we can use a DUP, or
8104   //   2) if only the low element is not undef, we can just insert that, or
8105   //   3) if only one constant value is used (w/ some non-constant lanes),
8106   //      we can splat the constant value into the whole vector then fill
8107   //      in the non-constant lanes.
8108   //   4) FIXME: If different constant values are used, but we can intelligently
8109   //             select the values we'll be overwriting for the non-constant
8110   //             lanes such that we can directly materialize the vector
8111   //             some other way (MOVI, e.g.), we can be sneaky.
8112   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8113   SDLoc dl(Op);
8114   unsigned NumElts = VT.getVectorNumElements();
8115   bool isOnlyLowElement = true;
8116   bool usesOnlyOneValue = true;
8117   bool usesOnlyOneConstantValue = true;
8118   bool isConstant = true;
8119   bool AllLanesExtractElt = true;
8120   unsigned NumConstantLanes = 0;
8121   SDValue Value;
8122   SDValue ConstantValue;
8123   for (unsigned i = 0; i < NumElts; ++i) {
8124     SDValue V = Op.getOperand(i);
8125     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8126       AllLanesExtractElt = false;
8127     if (V.isUndef())
8128       continue;
8129     if (i > 0)
8130       isOnlyLowElement = false;
8131     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8132       isConstant = false;
8133 
8134     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8135       ++NumConstantLanes;
8136       if (!ConstantValue.getNode())
8137         ConstantValue = V;
8138       else if (ConstantValue != V)
8139         usesOnlyOneConstantValue = false;
8140     }
8141 
8142     if (!Value.getNode())
8143       Value = V;
8144     else if (V != Value)
8145       usesOnlyOneValue = false;
8146   }
8147 
8148   if (!Value.getNode()) {
8149     LLVM_DEBUG(
8150         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8151     return DAG.getUNDEF(VT);
8152   }
8153 
8154   // Convert BUILD_VECTOR where all elements but the lowest are undef into
8155   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8156   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8157   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8158     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8159                          "SCALAR_TO_VECTOR node\n");
8160     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8161   }
8162 
8163   if (AllLanesExtractElt) {
8164     SDNode *Vector = nullptr;
8165     bool Even = false;
8166     bool Odd = false;
8167     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8168     // the Odd pattern <1,3,5,...>.
8169     for (unsigned i = 0; i < NumElts; ++i) {
8170       SDValue V = Op.getOperand(i);
8171       const SDNode *N = V.getNode();
8172       if (!isa<ConstantSDNode>(N->getOperand(1)))
8173         break;
8174       SDValue N0 = N->getOperand(0);
8175 
8176       // All elements are extracted from the same vector.
8177       if (!Vector) {
8178         Vector = N0.getNode();
8179         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8180         // BUILD_VECTOR.
8181         if (VT.getVectorElementType() !=
8182             N0.getValueType().getVectorElementType())
8183           break;
8184       } else if (Vector != N0.getNode()) {
8185         Odd = false;
8186         Even = false;
8187         break;
8188       }
8189 
8190       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8191       // indices <1,3,5,...>.
8192       uint64_t Val = N->getConstantOperandVal(1);
8193       if (Val == 2 * i) {
8194         Even = true;
8195         continue;
8196       }
8197       if (Val - 1 == 2 * i) {
8198         Odd = true;
8199         continue;
8200       }
8201 
8202       // Something does not match: abort.
8203       Odd = false;
8204       Even = false;
8205       break;
8206     }
8207     if (Even || Odd) {
8208       SDValue LHS =
8209           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8210                       DAG.getConstant(0, dl, MVT::i64));
8211       SDValue RHS =
8212           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8213                       DAG.getConstant(NumElts, dl, MVT::i64));
8214 
8215       if (Even && !Odd)
8216         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8217                            RHS);
8218       if (Odd && !Even)
8219         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8220                            RHS);
8221     }
8222   }
8223 
8224   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8225   // i32 and try again.
8226   if (usesOnlyOneValue) {
8227     if (!isConstant) {
8228       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8229           Value.getValueType() != VT) {
8230         LLVM_DEBUG(
8231             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8232         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8233       }
8234 
8235       // This is actually a DUPLANExx operation, which keeps everything vectory.
8236 
8237       SDValue Lane = Value.getOperand(1);
8238       Value = Value.getOperand(0);
8239       if (Value.getValueSizeInBits() == 64) {
8240         LLVM_DEBUG(
8241             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8242                       "widening it\n");
8243         Value = WidenVector(Value, DAG);
8244       }
8245 
8246       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8247       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8248     }
8249 
8250     if (VT.getVectorElementType().isFloatingPoint()) {
8251       SmallVector<SDValue, 8> Ops;
8252       EVT EltTy = VT.getVectorElementType();
8253       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
8254               "Unsupported floating-point vector type");
8255       LLVM_DEBUG(
8256           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8257                     "BITCASTS, and try again\n");
8258       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8259       for (unsigned i = 0; i < NumElts; ++i)
8260         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8261       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8262       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8263       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8264                  Val.dump(););
8265       Val = LowerBUILD_VECTOR(Val, DAG);
8266       if (Val.getNode())
8267         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8268     }
8269   }
8270 
8271   // If there was only one constant value used and for more than one lane,
8272   // start by splatting that value, then replace the non-constant lanes. This
8273   // is better than the default, which will perform a separate initialization
8274   // for each lane.
8275   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8276     // Firstly, try to materialize the splat constant.
8277     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8278             Val = ConstantBuildVector(Vec, DAG);
8279     if (!Val) {
8280       // Otherwise, materialize the constant and splat it.
8281       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8282       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8283     }
8284 
8285     // Now insert the non-constant lanes.
8286     for (unsigned i = 0; i < NumElts; ++i) {
8287       SDValue V = Op.getOperand(i);
8288       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8289       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8290         // Note that type legalization likely mucked about with the VT of the
8291         // source operand, so we may have to convert it here before inserting.
8292         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8293     }
8294     return Val;
8295   }
8296 
8297   // This will generate a load from the constant pool.
8298   if (isConstant) {
8299     LLVM_DEBUG(
8300         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8301                   "expansion\n");
8302     return SDValue();
8303   }
8304 
8305   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8306   if (NumElts >= 4) {
8307     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8308       return shuffle;
8309   }
8310 
8311   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8312   // know the default expansion would otherwise fall back on something even
8313   // worse. For a vector with one or two non-undef values, that's
8314   // scalar_to_vector for the elements followed by a shuffle (provided the
8315   // shuffle is valid for the target) and materialization element by element
8316   // on the stack followed by a load for everything else.
8317   if (!isConstant && !usesOnlyOneValue) {
8318     LLVM_DEBUG(
8319         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8320                   "of INSERT_VECTOR_ELT\n");
8321 
8322     SDValue Vec = DAG.getUNDEF(VT);
8323     SDValue Op0 = Op.getOperand(0);
8324     unsigned i = 0;
8325 
8326     // Use SCALAR_TO_VECTOR for lane zero to
8327     // a) Avoid a RMW dependency on the full vector register, and
8328     // b) Allow the register coalescer to fold away the copy if the
8329     //    value is already in an S or D register, and we're forced to emit an
8330     //    INSERT_SUBREG that we can't fold anywhere.
8331     //
8332     // We also allow types like i8 and i16 which are illegal scalar but legal
8333     // vector element types. After type-legalization the inserted value is
8334     // extended (i32) and it is safe to cast them to the vector type by ignoring
8335     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8336     if (!Op0.isUndef()) {
8337       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8338       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8339       ++i;
8340     }
8341     LLVM_DEBUG(if (i < NumElts) dbgs()
8342                    << "Creating nodes for the other vector elements:\n";);
8343     for (; i < NumElts; ++i) {
8344       SDValue V = Op.getOperand(i);
8345       if (V.isUndef())
8346         continue;
8347       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8348       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8349     }
8350     return Vec;
8351   }
8352 
8353   LLVM_DEBUG(
8354       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8355                 "better alternative\n");
8356   return SDValue();
8357 }
8358 
8359 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8360                                                       SelectionDAG &DAG) const {
8361   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8362 
8363   // Check for non-constant or out of range lane.
8364   EVT VT = Op.getOperand(0).getValueType();
8365   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8366   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8367     return SDValue();
8368 
8369 
8370   // Insertion/extraction are legal for V128 types.
8371   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8372       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8373       VT == MVT::v8f16)
8374     return Op;
8375 
8376   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8377       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8378     return SDValue();
8379 
8380   // For V64 types, we perform insertion by expanding the value
8381   // to a V128 type and perform the insertion on that.
8382   SDLoc DL(Op);
8383   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8384   EVT WideTy = WideVec.getValueType();
8385 
8386   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8387                              Op.getOperand(1), Op.getOperand(2));
8388   // Re-narrow the resultant vector.
8389   return NarrowVector(Node, DAG);
8390 }
8391 
8392 SDValue
8393 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8394                                                SelectionDAG &DAG) const {
8395   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8396 
8397   // Check for non-constant or out of range lane.
8398   EVT VT = Op.getOperand(0).getValueType();
8399   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8400   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8401     return SDValue();
8402 
8403 
8404   // Insertion/extraction are legal for V128 types.
8405   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8406       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8407       VT == MVT::v8f16)
8408     return Op;
8409 
8410   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8411       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8412     return SDValue();
8413 
8414   // For V64 types, we perform extraction by expanding the value
8415   // to a V128 type and perform the extraction on that.
8416   SDLoc DL(Op);
8417   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8418   EVT WideTy = WideVec.getValueType();
8419 
8420   EVT ExtrTy = WideTy.getVectorElementType();
8421   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8422     ExtrTy = MVT::i32;
8423 
8424   // For extractions, we just return the result directly.
8425   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8426                      Op.getOperand(1));
8427 }
8428 
8429 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8430                                                       SelectionDAG &DAG) const {
8431   EVT VT = Op.getOperand(0).getValueType();
8432   SDLoc dl(Op);
8433   // Just in case...
8434   if (!VT.isVector())
8435     return SDValue();
8436 
8437   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8438   if (!Cst)
8439     return SDValue();
8440   unsigned Val = Cst->getZExtValue();
8441 
8442   unsigned Size = Op.getValueSizeInBits();
8443 
8444   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8445   if (Val == 0)
8446     return Op;
8447 
8448   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8449   // that directly.
8450   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8451     return Op;
8452 
8453   return SDValue();
8454 }
8455 
8456 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8457   if (VT.getVectorNumElements() == 4 &&
8458       (VT.is128BitVector() || VT.is64BitVector())) {
8459     unsigned PFIndexes[4];
8460     for (unsigned i = 0; i != 4; ++i) {
8461       if (M[i] < 0)
8462         PFIndexes[i] = 8;
8463       else
8464         PFIndexes[i] = M[i];
8465     }
8466 
8467     // Compute the index in the perfect shuffle table.
8468     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8469                             PFIndexes[2] * 9 + PFIndexes[3];
8470     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8471     unsigned Cost = (PFEntry >> 30);
8472 
8473     if (Cost <= 4)
8474       return true;
8475   }
8476 
8477   bool DummyBool;
8478   int DummyInt;
8479   unsigned DummyUnsigned;
8480 
8481   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8482           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8483           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8484           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8485           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8486           isZIPMask(M, VT, DummyUnsigned) ||
8487           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8488           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8489           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8490           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8491           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8492 }
8493 
8494 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8495 /// operand of a vector shift operation, where all the elements of the
8496 /// build_vector must have the same constant integer value.
8497 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8498   // Ignore bit_converts.
8499   while (Op.getOpcode() == ISD::BITCAST)
8500     Op = Op.getOperand(0);
8501   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8502   APInt SplatBits, SplatUndef;
8503   unsigned SplatBitSize;
8504   bool HasAnyUndefs;
8505   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8506                                     HasAnyUndefs, ElementBits) ||
8507       SplatBitSize > ElementBits)
8508     return false;
8509   Cnt = SplatBits.getSExtValue();
8510   return true;
8511 }
8512 
8513 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8514 /// operand of a vector shift left operation.  That value must be in the range:
8515 ///   0 <= Value < ElementBits for a left shift; or
8516 ///   0 <= Value <= ElementBits for a long left shift.
8517 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8518   assert(VT.isVector() && "vector shift count is not a vector type");
8519   int64_t ElementBits = VT.getScalarSizeInBits();
8520   if (!getVShiftImm(Op, ElementBits, Cnt))
8521     return false;
8522   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8523 }
8524 
8525 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8526 /// operand of a vector shift right operation. The value must be in the range:
8527 ///   1 <= Value <= ElementBits for a right shift; or
8528 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8529   assert(VT.isVector() && "vector shift count is not a vector type");
8530   int64_t ElementBits = VT.getScalarSizeInBits();
8531   if (!getVShiftImm(Op, ElementBits, Cnt))
8532     return false;
8533   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8534 }
8535 
8536 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8537                                                       SelectionDAG &DAG) const {
8538   EVT VT = Op.getValueType();
8539   SDLoc DL(Op);
8540   int64_t Cnt;
8541 
8542   if (!Op.getOperand(1).getValueType().isVector())
8543     return Op;
8544   unsigned EltSize = VT.getScalarSizeInBits();
8545 
8546   switch (Op.getOpcode()) {
8547   default:
8548     llvm_unreachable("unexpected shift opcode");
8549 
8550   case ISD::SHL:
8551     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8552       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8553                          DAG.getConstant(Cnt, DL, MVT::i32));
8554     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8555                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8556                                        MVT::i32),
8557                        Op.getOperand(0), Op.getOperand(1));
8558   case ISD::SRA:
8559   case ISD::SRL:
8560     // Right shift immediate
8561     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8562       unsigned Opc =
8563           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8564       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8565                          DAG.getConstant(Cnt, DL, MVT::i32));
8566     }
8567 
8568     // Right shift register.  Note, there is not a shift right register
8569     // instruction, but the shift left register instruction takes a signed
8570     // value, where negative numbers specify a right shift.
8571     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8572                                                 : Intrinsic::aarch64_neon_ushl;
8573     // negate the shift amount
8574     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8575     SDValue NegShiftLeft =
8576         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8577                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8578                     NegShift);
8579     return NegShiftLeft;
8580   }
8581 
8582   return SDValue();
8583 }
8584 
8585 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8586                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8587                                     const SDLoc &dl, SelectionDAG &DAG) {
8588   EVT SrcVT = LHS.getValueType();
8589   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8590          "function only supposed to emit natural comparisons");
8591 
8592   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8593   APInt CnstBits(VT.getSizeInBits(), 0);
8594   APInt UndefBits(VT.getSizeInBits(), 0);
8595   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8596   bool IsZero = IsCnst && (CnstBits == 0);
8597 
8598   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8599     switch (CC) {
8600     default:
8601       return SDValue();
8602     case AArch64CC::NE: {
8603       SDValue Fcmeq;
8604       if (IsZero)
8605         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8606       else
8607         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8608       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8609     }
8610     case AArch64CC::EQ:
8611       if (IsZero)
8612         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8613       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8614     case AArch64CC::GE:
8615       if (IsZero)
8616         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8617       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8618     case AArch64CC::GT:
8619       if (IsZero)
8620         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8621       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8622     case AArch64CC::LS:
8623       if (IsZero)
8624         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8625       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8626     case AArch64CC::LT:
8627       if (!NoNans)
8628         return SDValue();
8629       // If we ignore NaNs then we can use to the MI implementation.
8630       LLVM_FALLTHROUGH;
8631     case AArch64CC::MI:
8632       if (IsZero)
8633         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8634       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8635     }
8636   }
8637 
8638   switch (CC) {
8639   default:
8640     return SDValue();
8641   case AArch64CC::NE: {
8642     SDValue Cmeq;
8643     if (IsZero)
8644       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8645     else
8646       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8647     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8648   }
8649   case AArch64CC::EQ:
8650     if (IsZero)
8651       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8652     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8653   case AArch64CC::GE:
8654     if (IsZero)
8655       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8656     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8657   case AArch64CC::GT:
8658     if (IsZero)
8659       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8660     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8661   case AArch64CC::LE:
8662     if (IsZero)
8663       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8664     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8665   case AArch64CC::LS:
8666     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8667   case AArch64CC::LO:
8668     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8669   case AArch64CC::LT:
8670     if (IsZero)
8671       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8672     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8673   case AArch64CC::HI:
8674     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8675   case AArch64CC::HS:
8676     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8677   }
8678 }
8679 
8680 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8681                                            SelectionDAG &DAG) const {
8682   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8683   SDValue LHS = Op.getOperand(0);
8684   SDValue RHS = Op.getOperand(1);
8685   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8686   SDLoc dl(Op);
8687 
8688   if (LHS.getValueType().getVectorElementType().isInteger()) {
8689     assert(LHS.getValueType() == RHS.getValueType());
8690     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8691     SDValue Cmp =
8692         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8693     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8694   }
8695 
8696   const bool FullFP16 =
8697     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8698 
8699   // Make v4f16 (only) fcmp operations utilise vector instructions
8700   // v8f16 support will be a litle more complicated
8701   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8702     if (LHS.getValueType().getVectorNumElements() == 4) {
8703       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8704       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8705       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8706       DAG.ReplaceAllUsesWith(Op, NewSetcc);
8707       CmpVT = MVT::v4i32;
8708     } else
8709       return SDValue();
8710   }
8711 
8712   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8713           LHS.getValueType().getVectorElementType() != MVT::f128);
8714 
8715   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8716   // clean.  Some of them require two branches to implement.
8717   AArch64CC::CondCode CC1, CC2;
8718   bool ShouldInvert;
8719   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8720 
8721   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8722   SDValue Cmp =
8723       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8724   if (!Cmp.getNode())
8725     return SDValue();
8726 
8727   if (CC2 != AArch64CC::AL) {
8728     SDValue Cmp2 =
8729         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8730     if (!Cmp2.getNode())
8731       return SDValue();
8732 
8733     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8734   }
8735 
8736   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8737 
8738   if (ShouldInvert)
8739     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8740 
8741   return Cmp;
8742 }
8743 
8744 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8745                                   SelectionDAG &DAG) {
8746   SDValue VecOp = ScalarOp.getOperand(0);
8747   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8748   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8749                      DAG.getConstant(0, DL, MVT::i64));
8750 }
8751 
8752 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8753                                               SelectionDAG &DAG) const {
8754   SDLoc dl(Op);
8755   switch (Op.getOpcode()) {
8756   case ISD::VECREDUCE_ADD:
8757     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8758   case ISD::VECREDUCE_SMAX:
8759     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8760   case ISD::VECREDUCE_SMIN:
8761     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8762   case ISD::VECREDUCE_UMAX:
8763     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8764   case ISD::VECREDUCE_UMIN:
8765     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8766   case ISD::VECREDUCE_FMAX: {
8767     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8768     return DAG.getNode(
8769         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8770         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8771         Op.getOperand(0));
8772   }
8773   case ISD::VECREDUCE_FMIN: {
8774     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8775     return DAG.getNode(
8776         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8777         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8778         Op.getOperand(0));
8779   }
8780   default:
8781     llvm_unreachable("Unhandled reduction");
8782   }
8783 }
8784 
8785 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8786                                                     SelectionDAG &DAG) const {
8787   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8788   if (!Subtarget.hasLSE())
8789     return SDValue();
8790 
8791   // LSE has an atomic load-add instruction, but not a load-sub.
8792   SDLoc dl(Op);
8793   MVT VT = Op.getSimpleValueType();
8794   SDValue RHS = Op.getOperand(2);
8795   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8796   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8797   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8798                        Op.getOperand(0), Op.getOperand(1), RHS,
8799                        AN->getMemOperand());
8800 }
8801 
8802 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8803                                                     SelectionDAG &DAG) const {
8804   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8805   if (!Subtarget.hasLSE())
8806     return SDValue();
8807 
8808   // LSE has an atomic load-clear instruction, but not a load-and.
8809   SDLoc dl(Op);
8810   MVT VT = Op.getSimpleValueType();
8811   SDValue RHS = Op.getOperand(2);
8812   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8813   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8814   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8815                        Op.getOperand(0), Op.getOperand(1), RHS,
8816                        AN->getMemOperand());
8817 }
8818 
8819 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8820     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8821   SDLoc dl(Op);
8822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8823   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8824 
8825   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8826   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8827   if (Subtarget->hasCustomCallingConv())
8828     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8829 
8830   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8831                      DAG.getConstant(4, dl, MVT::i64));
8832   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8833   Chain =
8834       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8835                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8836                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8837   // To match the actual intent better, we should read the output from X15 here
8838   // again (instead of potentially spilling it to the stack), but rereading Size
8839   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8840   // here.
8841 
8842   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8843                      DAG.getConstant(4, dl, MVT::i64));
8844   return Chain;
8845 }
8846 
8847 SDValue
8848 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8849                                                SelectionDAG &DAG) const {
8850   assert(Subtarget->isTargetWindows() &&
8851          "Only Windows alloca probing supported");
8852   SDLoc dl(Op);
8853   // Get the inputs.
8854   SDNode *Node = Op.getNode();
8855   SDValue Chain = Op.getOperand(0);
8856   SDValue Size = Op.getOperand(1);
8857   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8858   EVT VT = Node->getValueType(0);
8859 
8860   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8861           "no-stack-arg-probe")) {
8862     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8863     Chain = SP.getValue(1);
8864     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8865     if (Align)
8866       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8867                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8868     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8869     SDValue Ops[2] = {SP, Chain};
8870     return DAG.getMergeValues(Ops, dl);
8871   }
8872 
8873   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8874 
8875   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8876 
8877   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8878   Chain = SP.getValue(1);
8879   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8880   if (Align)
8881     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8882                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8883   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8884 
8885   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8886                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8887 
8888   SDValue Ops[2] = {SP, Chain};
8889   return DAG.getMergeValues(Ops, dl);
8890 }
8891 
8892 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
8893                                            SelectionDAG &DAG) const {
8894   EVT VT = Op.getValueType();
8895   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
8896 
8897   SDLoc DL(Op);
8898   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
8899   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
8900                             DL, VT);
8901 }
8902 
8903 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8904 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8905 /// specified in the intrinsic calls.
8906 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8907                                                const CallInst &I,
8908                                                MachineFunction &MF,
8909                                                unsigned Intrinsic) const {
8910   auto &DL = I.getModule()->getDataLayout();
8911   switch (Intrinsic) {
8912   case Intrinsic::aarch64_neon_ld2:
8913   case Intrinsic::aarch64_neon_ld3:
8914   case Intrinsic::aarch64_neon_ld4:
8915   case Intrinsic::aarch64_neon_ld1x2:
8916   case Intrinsic::aarch64_neon_ld1x3:
8917   case Intrinsic::aarch64_neon_ld1x4:
8918   case Intrinsic::aarch64_neon_ld2lane:
8919   case Intrinsic::aarch64_neon_ld3lane:
8920   case Intrinsic::aarch64_neon_ld4lane:
8921   case Intrinsic::aarch64_neon_ld2r:
8922   case Intrinsic::aarch64_neon_ld3r:
8923   case Intrinsic::aarch64_neon_ld4r: {
8924     Info.opc = ISD::INTRINSIC_W_CHAIN;
8925     // Conservatively set memVT to the entire set of vectors loaded.
8926     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8927     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8928     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8929     Info.offset = 0;
8930     Info.align.reset();
8931     // volatile loads with NEON intrinsics not supported
8932     Info.flags = MachineMemOperand::MOLoad;
8933     return true;
8934   }
8935   case Intrinsic::aarch64_neon_st2:
8936   case Intrinsic::aarch64_neon_st3:
8937   case Intrinsic::aarch64_neon_st4:
8938   case Intrinsic::aarch64_neon_st1x2:
8939   case Intrinsic::aarch64_neon_st1x3:
8940   case Intrinsic::aarch64_neon_st1x4:
8941   case Intrinsic::aarch64_neon_st2lane:
8942   case Intrinsic::aarch64_neon_st3lane:
8943   case Intrinsic::aarch64_neon_st4lane: {
8944     Info.opc = ISD::INTRINSIC_VOID;
8945     // Conservatively set memVT to the entire set of vectors stored.
8946     unsigned NumElts = 0;
8947     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8948       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8949       if (!ArgTy->isVectorTy())
8950         break;
8951       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8952     }
8953     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8954     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8955     Info.offset = 0;
8956     Info.align.reset();
8957     // volatile stores with NEON intrinsics not supported
8958     Info.flags = MachineMemOperand::MOStore;
8959     return true;
8960   }
8961   case Intrinsic::aarch64_ldaxr:
8962   case Intrinsic::aarch64_ldxr: {
8963     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8964     Info.opc = ISD::INTRINSIC_W_CHAIN;
8965     Info.memVT = MVT::getVT(PtrTy->getElementType());
8966     Info.ptrVal = I.getArgOperand(0);
8967     Info.offset = 0;
8968     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8969     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8970     return true;
8971   }
8972   case Intrinsic::aarch64_stlxr:
8973   case Intrinsic::aarch64_stxr: {
8974     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8975     Info.opc = ISD::INTRINSIC_W_CHAIN;
8976     Info.memVT = MVT::getVT(PtrTy->getElementType());
8977     Info.ptrVal = I.getArgOperand(1);
8978     Info.offset = 0;
8979     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8980     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8981     return true;
8982   }
8983   case Intrinsic::aarch64_ldaxp:
8984   case Intrinsic::aarch64_ldxp:
8985     Info.opc = ISD::INTRINSIC_W_CHAIN;
8986     Info.memVT = MVT::i128;
8987     Info.ptrVal = I.getArgOperand(0);
8988     Info.offset = 0;
8989     Info.align = Align(16);
8990     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8991     return true;
8992   case Intrinsic::aarch64_stlxp:
8993   case Intrinsic::aarch64_stxp:
8994     Info.opc = ISD::INTRINSIC_W_CHAIN;
8995     Info.memVT = MVT::i128;
8996     Info.ptrVal = I.getArgOperand(2);
8997     Info.offset = 0;
8998     Info.align = Align(16);
8999     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9000     return true;
9001   case Intrinsic::aarch64_sve_ld1:
9002   case Intrinsic::aarch64_sve_ldnt1: {
9003     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9004     Info.opc = ISD::INTRINSIC_W_CHAIN;
9005     Info.memVT = MVT::getVT(I.getType());
9006     Info.ptrVal = I.getArgOperand(1);
9007     Info.offset = 0;
9008     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
9009     Info.flags = MachineMemOperand::MOLoad;
9010     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9011       Info.flags |= MachineMemOperand::MONonTemporal;
9012     return true;
9013   }
9014   case Intrinsic::aarch64_sve_st1:
9015   case Intrinsic::aarch64_sve_stnt1: {
9016     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9017     Info.opc = ISD::INTRINSIC_W_CHAIN;
9018     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9019     Info.ptrVal = I.getArgOperand(2);
9020     Info.offset = 0;
9021     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
9022     Info.flags = MachineMemOperand::MOStore;
9023     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9024       Info.flags |= MachineMemOperand::MONonTemporal;
9025     return true;
9026   }
9027   default:
9028     break;
9029   }
9030 
9031   return false;
9032 }
9033 
9034 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9035                                                   ISD::LoadExtType ExtTy,
9036                                                   EVT NewVT) const {
9037   // TODO: This may be worth removing. Check regression tests for diffs.
9038   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9039     return false;
9040 
9041   // If we're reducing the load width in order to avoid having to use an extra
9042   // instruction to do extension then it's probably a good idea.
9043   if (ExtTy != ISD::NON_EXTLOAD)
9044     return true;
9045   // Don't reduce load width if it would prevent us from combining a shift into
9046   // the offset.
9047   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9048   assert(Mem);
9049   const SDValue &Base = Mem->getBasePtr();
9050   if (Base.getOpcode() == ISD::ADD &&
9051       Base.getOperand(1).getOpcode() == ISD::SHL &&
9052       Base.getOperand(1).hasOneUse() &&
9053       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9054     // The shift can be combined if it matches the size of the value being
9055     // loaded (and so reducing the width would make it not match).
9056     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9057     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9058     if (ShiftAmount == Log2_32(LoadBytes))
9059       return false;
9060   }
9061   // We have no reason to disallow reducing the load width, so allow it.
9062   return true;
9063 }
9064 
9065 // Truncations from 64-bit GPR to 32-bit GPR is free.
9066 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9067   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9068     return false;
9069   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9070   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9071   return NumBits1 > NumBits2;
9072 }
9073 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9074   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9075     return false;
9076   unsigned NumBits1 = VT1.getSizeInBits();
9077   unsigned NumBits2 = VT2.getSizeInBits();
9078   return NumBits1 > NumBits2;
9079 }
9080 
9081 /// Check if it is profitable to hoist instruction in then/else to if.
9082 /// Not profitable if I and it's user can form a FMA instruction
9083 /// because we prefer FMSUB/FMADD.
9084 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9085   if (I->getOpcode() != Instruction::FMul)
9086     return true;
9087 
9088   if (!I->hasOneUse())
9089     return true;
9090 
9091   Instruction *User = I->user_back();
9092 
9093   if (User &&
9094       !(User->getOpcode() == Instruction::FSub ||
9095         User->getOpcode() == Instruction::FAdd))
9096     return true;
9097 
9098   const TargetOptions &Options = getTargetMachine().Options;
9099   const Function *F = I->getFunction();
9100   const DataLayout &DL = F->getParent()->getDataLayout();
9101   Type *Ty = User->getOperand(0)->getType();
9102 
9103   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9104            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9105            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9106             Options.UnsafeFPMath));
9107 }
9108 
9109 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9110 // 64-bit GPR.
9111 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9112   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9113     return false;
9114   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9115   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9116   return NumBits1 == 32 && NumBits2 == 64;
9117 }
9118 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9119   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9120     return false;
9121   unsigned NumBits1 = VT1.getSizeInBits();
9122   unsigned NumBits2 = VT2.getSizeInBits();
9123   return NumBits1 == 32 && NumBits2 == 64;
9124 }
9125 
9126 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9127   EVT VT1 = Val.getValueType();
9128   if (isZExtFree(VT1, VT2)) {
9129     return true;
9130   }
9131 
9132   if (Val.getOpcode() != ISD::LOAD)
9133     return false;
9134 
9135   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9136   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9137           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9138           VT1.getSizeInBits() <= 32);
9139 }
9140 
9141 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9142   if (isa<FPExtInst>(Ext))
9143     return false;
9144 
9145   // Vector types are not free.
9146   if (Ext->getType()->isVectorTy())
9147     return false;
9148 
9149   for (const Use &U : Ext->uses()) {
9150     // The extension is free if we can fold it with a left shift in an
9151     // addressing mode or an arithmetic operation: add, sub, and cmp.
9152 
9153     // Is there a shift?
9154     const Instruction *Instr = cast<Instruction>(U.getUser());
9155 
9156     // Is this a constant shift?
9157     switch (Instr->getOpcode()) {
9158     case Instruction::Shl:
9159       if (!isa<ConstantInt>(Instr->getOperand(1)))
9160         return false;
9161       break;
9162     case Instruction::GetElementPtr: {
9163       gep_type_iterator GTI = gep_type_begin(Instr);
9164       auto &DL = Ext->getModule()->getDataLayout();
9165       std::advance(GTI, U.getOperandNo()-1);
9166       Type *IdxTy = GTI.getIndexedType();
9167       // This extension will end up with a shift because of the scaling factor.
9168       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9169       // Get the shift amount based on the scaling factor:
9170       // log2(sizeof(IdxTy)) - log2(8).
9171       uint64_t ShiftAmt =
9172         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9173       // Is the constant foldable in the shift of the addressing mode?
9174       // I.e., shift amount is between 1 and 4 inclusive.
9175       if (ShiftAmt == 0 || ShiftAmt > 4)
9176         return false;
9177       break;
9178     }
9179     case Instruction::Trunc:
9180       // Check if this is a noop.
9181       // trunc(sext ty1 to ty2) to ty1.
9182       if (Instr->getType() == Ext->getOperand(0)->getType())
9183         continue;
9184       LLVM_FALLTHROUGH;
9185     default:
9186       return false;
9187     }
9188 
9189     // At this point we can use the bfm family, so this extension is free
9190     // for that use.
9191   }
9192   return true;
9193 }
9194 
9195 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9196 /// or upper half of the vector elements.
9197 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9198   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9199     auto *FullTy = FullV->getType();
9200     auto *HalfTy = HalfV->getType();
9201     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
9202            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
9203   };
9204 
9205   auto extractHalf = [](Value *FullV, Value *HalfV) {
9206     auto *FullVT = cast<VectorType>(FullV->getType());
9207     auto *HalfVT = cast<VectorType>(HalfV->getType());
9208     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9209   };
9210 
9211   ArrayRef<int> M1, M2;
9212   Value *S1Op1, *S2Op1;
9213   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9214       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9215     return false;
9216 
9217   // Check that the operands are half as wide as the result and we extract
9218   // half of the elements of the input vectors.
9219   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9220       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9221     return false;
9222 
9223   // Check the mask extracts either the lower or upper half of vector
9224   // elements.
9225   int M1Start = -1;
9226   int M2Start = -1;
9227   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
9228   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9229       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9230       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9231     return false;
9232 
9233   return true;
9234 }
9235 
9236 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9237 /// of the vector elements.
9238 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9239   auto areExtDoubled = [](Instruction *Ext) {
9240     return Ext->getType()->getScalarSizeInBits() ==
9241            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9242   };
9243 
9244   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9245       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9246       !areExtDoubled(cast<Instruction>(Ext1)) ||
9247       !areExtDoubled(cast<Instruction>(Ext2)))
9248     return false;
9249 
9250   return true;
9251 }
9252 
9253 /// Check if sinking \p I's operands to I's basic block is profitable, because
9254 /// the operands can be folded into a target instruction, e.g.
9255 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9256 bool AArch64TargetLowering::shouldSinkOperands(
9257     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9258   if (!I->getType()->isVectorTy())
9259     return false;
9260 
9261   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9262     switch (II->getIntrinsicID()) {
9263     case Intrinsic::aarch64_neon_umull:
9264       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9265         return false;
9266       Ops.push_back(&II->getOperandUse(0));
9267       Ops.push_back(&II->getOperandUse(1));
9268       return true;
9269     default:
9270       return false;
9271     }
9272   }
9273 
9274   switch (I->getOpcode()) {
9275   case Instruction::Sub:
9276   case Instruction::Add: {
9277     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9278       return false;
9279 
9280     // If the exts' operands extract either the lower or upper elements, we
9281     // can sink them too.
9282     auto Ext1 = cast<Instruction>(I->getOperand(0));
9283     auto Ext2 = cast<Instruction>(I->getOperand(1));
9284     if (areExtractShuffleVectors(Ext1, Ext2)) {
9285       Ops.push_back(&Ext1->getOperandUse(0));
9286       Ops.push_back(&Ext2->getOperandUse(0));
9287     }
9288 
9289     Ops.push_back(&I->getOperandUse(0));
9290     Ops.push_back(&I->getOperandUse(1));
9291 
9292     return true;
9293   }
9294   default:
9295     return false;
9296   }
9297   return false;
9298 }
9299 
9300 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9301                                           unsigned &RequiredAligment) const {
9302   if (!LoadedType.isSimple() ||
9303       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9304     return false;
9305   // Cyclone supports unaligned accesses.
9306   RequiredAligment = 0;
9307   unsigned NumBits = LoadedType.getSizeInBits();
9308   return NumBits == 32 || NumBits == 64;
9309 }
9310 
9311 /// A helper function for determining the number of interleaved accesses we
9312 /// will generate when lowering accesses of the given type.
9313 unsigned
9314 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9315                                                  const DataLayout &DL) const {
9316   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9317 }
9318 
9319 MachineMemOperand::Flags
9320 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9321   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9322       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9323     return MOStridedAccess;
9324   return MachineMemOperand::MONone;
9325 }
9326 
9327 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9328     VectorType *VecTy, const DataLayout &DL) const {
9329 
9330   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9331   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9332 
9333   // Ensure the number of vector elements is greater than 1.
9334   if (VecTy->getNumElements() < 2)
9335     return false;
9336 
9337   // Ensure the element type is legal.
9338   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9339     return false;
9340 
9341   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9342   // 128 will be split into multiple interleaved accesses.
9343   return VecSize == 64 || VecSize % 128 == 0;
9344 }
9345 
9346 /// Lower an interleaved load into a ldN intrinsic.
9347 ///
9348 /// E.g. Lower an interleaved load (Factor = 2):
9349 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9350 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9351 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9352 ///
9353 ///      Into:
9354 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9355 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9356 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9357 bool AArch64TargetLowering::lowerInterleavedLoad(
9358     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9359     ArrayRef<unsigned> Indices, unsigned Factor) const {
9360   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9361          "Invalid interleave factor");
9362   assert(!Shuffles.empty() && "Empty shufflevector input");
9363   assert(Shuffles.size() == Indices.size() &&
9364          "Unmatched number of shufflevectors and indices");
9365 
9366   const DataLayout &DL = LI->getModule()->getDataLayout();
9367 
9368   VectorType *VecTy = Shuffles[0]->getType();
9369 
9370   // Skip if we do not have NEON and skip illegal vector types. We can
9371   // "legalize" wide vector types into multiple interleaved accesses as long as
9372   // the vector types are divisible by 128.
9373   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9374     return false;
9375 
9376   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9377 
9378   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9379   // load integer vectors first and then convert to pointer vectors.
9380   Type *EltTy = VecTy->getElementType();
9381   if (EltTy->isPointerTy())
9382     VecTy = VectorType::get(DL.getIntPtrType(EltTy), VecTy->getNumElements());
9383 
9384   IRBuilder<> Builder(LI);
9385 
9386   // The base address of the load.
9387   Value *BaseAddr = LI->getPointerOperand();
9388 
9389   if (NumLoads > 1) {
9390     // If we're going to generate more than one load, reset the sub-vector type
9391     // to something legal.
9392     VecTy = VectorType::get(VecTy->getElementType(),
9393                             VecTy->getNumElements() / NumLoads);
9394 
9395     // We will compute the pointer operand of each load from the original base
9396     // address using GEPs. Cast the base address to a pointer to the scalar
9397     // element type.
9398     BaseAddr = Builder.CreateBitCast(
9399         BaseAddr,
9400         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
9401   }
9402 
9403   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9404   Type *Tys[2] = {VecTy, PtrTy};
9405   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9406                                             Intrinsic::aarch64_neon_ld3,
9407                                             Intrinsic::aarch64_neon_ld4};
9408   Function *LdNFunc =
9409       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9410 
9411   // Holds sub-vectors extracted from the load intrinsic return values. The
9412   // sub-vectors are associated with the shufflevector instructions they will
9413   // replace.
9414   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9415 
9416   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9417 
9418     // If we're generating more than one load, compute the base address of
9419     // subsequent loads as an offset from the previous.
9420     if (LoadCount > 0)
9421       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
9422                                             VecTy->getNumElements() * Factor);
9423 
9424     CallInst *LdN = Builder.CreateCall(
9425         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9426 
9427     // Extract and store the sub-vectors returned by the load intrinsic.
9428     for (unsigned i = 0; i < Shuffles.size(); i++) {
9429       ShuffleVectorInst *SVI = Shuffles[i];
9430       unsigned Index = Indices[i];
9431 
9432       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9433 
9434       // Convert the integer vector to pointer vector if the element is pointer.
9435       if (EltTy->isPointerTy())
9436         SubVec = Builder.CreateIntToPtr(
9437             SubVec, VectorType::get(SVI->getType()->getElementType(),
9438                                     VecTy->getNumElements()));
9439       SubVecs[SVI].push_back(SubVec);
9440     }
9441   }
9442 
9443   // Replace uses of the shufflevector instructions with the sub-vectors
9444   // returned by the load intrinsic. If a shufflevector instruction is
9445   // associated with more than one sub-vector, those sub-vectors will be
9446   // concatenated into a single wide vector.
9447   for (ShuffleVectorInst *SVI : Shuffles) {
9448     auto &SubVec = SubVecs[SVI];
9449     auto *WideVec =
9450         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9451     SVI->replaceAllUsesWith(WideVec);
9452   }
9453 
9454   return true;
9455 }
9456 
9457 /// Lower an interleaved store into a stN intrinsic.
9458 ///
9459 /// E.g. Lower an interleaved store (Factor = 3):
9460 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9461 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9462 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9463 ///
9464 ///      Into:
9465 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9466 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9467 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9468 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9469 ///
9470 /// Note that the new shufflevectors will be removed and we'll only generate one
9471 /// st3 instruction in CodeGen.
9472 ///
9473 /// Example for a more general valid mask (Factor 3). Lower:
9474 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9475 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9476 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9477 ///
9478 ///      Into:
9479 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9480 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9481 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9482 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9483 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9484                                                   ShuffleVectorInst *SVI,
9485                                                   unsigned Factor) const {
9486   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9487          "Invalid interleave factor");
9488 
9489   VectorType *VecTy = SVI->getType();
9490   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
9491 
9492   unsigned LaneLen = VecTy->getNumElements() / Factor;
9493   Type *EltTy = VecTy->getElementType();
9494   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9495 
9496   const DataLayout &DL = SI->getModule()->getDataLayout();
9497 
9498   // Skip if we do not have NEON and skip illegal vector types. We can
9499   // "legalize" wide vector types into multiple interleaved accesses as long as
9500   // the vector types are divisible by 128.
9501   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9502     return false;
9503 
9504   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9505 
9506   Value *Op0 = SVI->getOperand(0);
9507   Value *Op1 = SVI->getOperand(1);
9508   IRBuilder<> Builder(SI);
9509 
9510   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9511   // vectors to integer vectors.
9512   if (EltTy->isPointerTy()) {
9513     Type *IntTy = DL.getIntPtrType(EltTy);
9514     unsigned NumOpElts = cast<VectorType>(Op0->getType())->getNumElements();
9515 
9516     // Convert to the corresponding integer vector.
9517     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9518     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9519     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9520 
9521     SubVecTy = VectorType::get(IntTy, LaneLen);
9522   }
9523 
9524   // The base address of the store.
9525   Value *BaseAddr = SI->getPointerOperand();
9526 
9527   if (NumStores > 1) {
9528     // If we're going to generate more than one store, reset the lane length
9529     // and sub-vector type to something legal.
9530     LaneLen /= NumStores;
9531     SubVecTy = VectorType::get(SubVecTy->getElementType(), LaneLen);
9532 
9533     // We will compute the pointer operand of each store from the original base
9534     // address using GEPs. Cast the base address to a pointer to the scalar
9535     // element type.
9536     BaseAddr = Builder.CreateBitCast(
9537         BaseAddr,
9538         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
9539   }
9540 
9541   auto Mask = SVI->getShuffleMask();
9542 
9543   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9544   Type *Tys[2] = {SubVecTy, PtrTy};
9545   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9546                                              Intrinsic::aarch64_neon_st3,
9547                                              Intrinsic::aarch64_neon_st4};
9548   Function *StNFunc =
9549       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9550 
9551   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9552 
9553     SmallVector<Value *, 5> Ops;
9554 
9555     // Split the shufflevector operands into sub vectors for the new stN call.
9556     for (unsigned i = 0; i < Factor; i++) {
9557       unsigned IdxI = StoreCount * LaneLen * Factor + i;
9558       if (Mask[IdxI] >= 0) {
9559         Ops.push_back(Builder.CreateShuffleVector(
9560             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9561       } else {
9562         unsigned StartMask = 0;
9563         for (unsigned j = 1; j < LaneLen; j++) {
9564           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9565           if (Mask[IdxJ * Factor + IdxI] >= 0) {
9566             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9567             break;
9568           }
9569         }
9570         // Note: Filling undef gaps with random elements is ok, since
9571         // those elements were being written anyway (with undefs).
9572         // In the case of all undefs we're defaulting to using elems from 0
9573         // Note: StartMask cannot be negative, it's checked in
9574         // isReInterleaveMask
9575         Ops.push_back(Builder.CreateShuffleVector(
9576             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9577       }
9578     }
9579 
9580     // If we generating more than one store, we compute the base address of
9581     // subsequent stores as an offset from the previous.
9582     if (StoreCount > 0)
9583       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
9584                                             BaseAddr, LaneLen * Factor);
9585 
9586     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9587     Builder.CreateCall(StNFunc, Ops);
9588   }
9589   return true;
9590 }
9591 
9592 
9593 EVT AArch64TargetLowering::getOptimalMemOpType(
9594     const MemOp &Op, const AttributeList &FuncAttributes) const {
9595   bool CanImplicitFloat =
9596       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9597   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9598   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9599   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9600   // taken one instruction to materialize the v2i64 zero and one store (with
9601   // restrictive addressing mode). Just do i64 stores.
9602   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9603   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
9604     if (Op.isAligned(AlignCheck))
9605       return true;
9606     bool Fast;
9607     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9608                                           &Fast) &&
9609            Fast;
9610   };
9611 
9612   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9613       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
9614     return MVT::v2i64;
9615   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
9616     return MVT::f128;
9617   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
9618     return MVT::i64;
9619   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
9620     return MVT::i32;
9621   return MVT::Other;
9622 }
9623 
9624 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9625     const MemOp &Op, const AttributeList &FuncAttributes) const {
9626   bool CanImplicitFloat =
9627       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9628   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9629   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9630   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9631   // taken one instruction to materialize the v2i64 zero and one store (with
9632   // restrictive addressing mode). Just do i64 stores.
9633   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9634   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
9635     if (Op.isAligned(AlignCheck))
9636       return true;
9637     bool Fast;
9638     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9639                                           &Fast) &&
9640            Fast;
9641   };
9642 
9643   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9644       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
9645     return LLT::vector(2, 64);
9646   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
9647     return LLT::scalar(128);
9648   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
9649     return LLT::scalar(64);
9650   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
9651     return LLT::scalar(32);
9652   return LLT();
9653 }
9654 
9655 // 12-bit optionally shifted immediates are legal for adds.
9656 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9657   if (Immed == std::numeric_limits<int64_t>::min()) {
9658     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9659                       << ": avoid UB for INT64_MIN\n");
9660     return false;
9661   }
9662   // Same encoding for add/sub, just flip the sign.
9663   Immed = std::abs(Immed);
9664   bool IsLegal = ((Immed >> 12) == 0 ||
9665                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9666   LLVM_DEBUG(dbgs() << "Is " << Immed
9667                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9668   return IsLegal;
9669 }
9670 
9671 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9672 // immediates is the same as for an add or a sub.
9673 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9674   return isLegalAddImmediate(Immed);
9675 }
9676 
9677 /// isLegalAddressingMode - Return true if the addressing mode represented
9678 /// by AM is legal for this target, for a load/store of the specified type.
9679 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9680                                                   const AddrMode &AM, Type *Ty,
9681                                                   unsigned AS, Instruction *I) const {
9682   // AArch64 has five basic addressing modes:
9683   //  reg
9684   //  reg + 9-bit signed offset
9685   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9686   //  reg1 + reg2
9687   //  reg + SIZE_IN_BYTES * reg
9688 
9689   // No global is ever allowed as a base.
9690   if (AM.BaseGV)
9691     return false;
9692 
9693   // No reg+reg+imm addressing.
9694   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9695     return false;
9696 
9697   // FIXME: Update this method to support scalable addressing modes.
9698   if (Ty->isVectorTy() && cast<VectorType>(Ty)->isScalable())
9699     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
9700 
9701   // check reg + imm case:
9702   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9703   uint64_t NumBytes = 0;
9704   if (Ty->isSized()) {
9705     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9706     NumBytes = NumBits / 8;
9707     if (!isPowerOf2_64(NumBits))
9708       NumBytes = 0;
9709   }
9710 
9711   if (!AM.Scale) {
9712     int64_t Offset = AM.BaseOffs;
9713 
9714     // 9-bit signed offset
9715     if (isInt<9>(Offset))
9716       return true;
9717 
9718     // 12-bit unsigned offset
9719     unsigned shift = Log2_64(NumBytes);
9720     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9721         // Must be a multiple of NumBytes (NumBytes is a power of 2)
9722         (Offset >> shift) << shift == Offset)
9723       return true;
9724     return false;
9725   }
9726 
9727   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9728 
9729   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9730 }
9731 
9732 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9733   // Consider splitting large offset of struct or array.
9734   return true;
9735 }
9736 
9737 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9738                                                 const AddrMode &AM, Type *Ty,
9739                                                 unsigned AS) const {
9740   // Scaling factors are not free at all.
9741   // Operands                     | Rt Latency
9742   // -------------------------------------------
9743   // Rt, [Xn, Xm]                 | 4
9744   // -------------------------------------------
9745   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9746   // Rt, [Xn, Wm, <extend> #imm]  |
9747   if (isLegalAddressingMode(DL, AM, Ty, AS))
9748     // Scale represents reg2 * scale, thus account for 1 if
9749     // it is not equal to 0 or 1.
9750     return AM.Scale != 0 && AM.Scale != 1;
9751   return -1;
9752 }
9753 
9754 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9755     const MachineFunction &MF, EVT VT) const {
9756   VT = VT.getScalarType();
9757 
9758   if (!VT.isSimple())
9759     return false;
9760 
9761   switch (VT.getSimpleVT().SimpleTy) {
9762   case MVT::f32:
9763   case MVT::f64:
9764     return true;
9765   default:
9766     break;
9767   }
9768 
9769   return false;
9770 }
9771 
9772 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9773                                                        Type *Ty) const {
9774   switch (Ty->getScalarType()->getTypeID()) {
9775   case Type::FloatTyID:
9776   case Type::DoubleTyID:
9777     return true;
9778   default:
9779     return false;
9780   }
9781 }
9782 
9783 const MCPhysReg *
9784 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9785   // LR is a callee-save register, but we must treat it as clobbered by any call
9786   // site. Hence we include LR in the scratch registers, which are in turn added
9787   // as implicit-defs for stackmaps and patchpoints.
9788   static const MCPhysReg ScratchRegs[] = {
9789     AArch64::X16, AArch64::X17, AArch64::LR, 0
9790   };
9791   return ScratchRegs;
9792 }
9793 
9794 bool
9795 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9796                                                      CombineLevel Level) const {
9797   N = N->getOperand(0).getNode();
9798   EVT VT = N->getValueType(0);
9799     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9800     // it with shift to let it be lowered to UBFX.
9801   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9802       isa<ConstantSDNode>(N->getOperand(1))) {
9803     uint64_t TruncMask = N->getConstantOperandVal(1);
9804     if (isMask_64(TruncMask) &&
9805       N->getOperand(0).getOpcode() == ISD::SRL &&
9806       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9807       return false;
9808   }
9809   return true;
9810 }
9811 
9812 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9813                                                               Type *Ty) const {
9814   assert(Ty->isIntegerTy());
9815 
9816   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9817   if (BitSize == 0)
9818     return false;
9819 
9820   int64_t Val = Imm.getSExtValue();
9821   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9822     return true;
9823 
9824   if ((int64_t)Val < 0)
9825     Val = ~Val;
9826   if (BitSize == 32)
9827     Val &= (1LL << 32) - 1;
9828 
9829   unsigned LZ = countLeadingZeros((uint64_t)Val);
9830   unsigned Shift = (63 - LZ) / 16;
9831   // MOVZ is free so return true for one or fewer MOVK.
9832   return Shift < 3;
9833 }
9834 
9835 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9836                                                     unsigned Index) const {
9837   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9838     return false;
9839 
9840   return (Index == 0 || Index == ResVT.getVectorNumElements());
9841 }
9842 
9843 /// Turn vector tests of the signbit in the form of:
9844 ///   xor (sra X, elt_size(X)-1), -1
9845 /// into:
9846 ///   cmge X, X, #0
9847 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9848                                          const AArch64Subtarget *Subtarget) {
9849   EVT VT = N->getValueType(0);
9850   if (!Subtarget->hasNEON() || !VT.isVector())
9851     return SDValue();
9852 
9853   // There must be a shift right algebraic before the xor, and the xor must be a
9854   // 'not' operation.
9855   SDValue Shift = N->getOperand(0);
9856   SDValue Ones = N->getOperand(1);
9857   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9858       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9859     return SDValue();
9860 
9861   // The shift should be smearing the sign bit across each vector element.
9862   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9863   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9864   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9865     return SDValue();
9866 
9867   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9868 }
9869 
9870 // Generate SUBS and CSEL for integer abs.
9871 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9872   EVT VT = N->getValueType(0);
9873 
9874   SDValue N0 = N->getOperand(0);
9875   SDValue N1 = N->getOperand(1);
9876   SDLoc DL(N);
9877 
9878   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9879   // and change it to SUB and CSEL.
9880   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9881       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9882       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9883     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9884       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9885         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9886                                   N0.getOperand(0));
9887         // Generate SUBS & CSEL.
9888         SDValue Cmp =
9889             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9890                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9891         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9892                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9893                            SDValue(Cmp.getNode(), 1));
9894       }
9895   return SDValue();
9896 }
9897 
9898 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9899                                  TargetLowering::DAGCombinerInfo &DCI,
9900                                  const AArch64Subtarget *Subtarget) {
9901   if (DCI.isBeforeLegalizeOps())
9902     return SDValue();
9903 
9904   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9905     return Cmp;
9906 
9907   return performIntegerAbsCombine(N, DAG);
9908 }
9909 
9910 SDValue
9911 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9912                                      SelectionDAG &DAG,
9913                                      SmallVectorImpl<SDNode *> &Created) const {
9914   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9915   if (isIntDivCheap(N->getValueType(0), Attr))
9916     return SDValue(N,0); // Lower SDIV as SDIV
9917 
9918   // fold (sdiv X, pow2)
9919   EVT VT = N->getValueType(0);
9920   if ((VT != MVT::i32 && VT != MVT::i64) ||
9921       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9922     return SDValue();
9923 
9924   SDLoc DL(N);
9925   SDValue N0 = N->getOperand(0);
9926   unsigned Lg2 = Divisor.countTrailingZeros();
9927   SDValue Zero = DAG.getConstant(0, DL, VT);
9928   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9929 
9930   // Add (N0 < 0) ? Pow2 - 1 : 0;
9931   SDValue CCVal;
9932   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9933   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9934   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9935 
9936   Created.push_back(Cmp.getNode());
9937   Created.push_back(Add.getNode());
9938   Created.push_back(CSel.getNode());
9939 
9940   // Divide by pow2.
9941   SDValue SRA =
9942       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9943 
9944   // If we're dividing by a positive value, we're done.  Otherwise, we must
9945   // negate the result.
9946   if (Divisor.isNonNegative())
9947     return SRA;
9948 
9949   Created.push_back(SRA.getNode());
9950   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9951 }
9952 
9953 static bool IsSVECntIntrinsic(SDValue S) {
9954   switch(getIntrinsicID(S.getNode())) {
9955   default:
9956     break;
9957   case Intrinsic::aarch64_sve_cntb:
9958   case Intrinsic::aarch64_sve_cnth:
9959   case Intrinsic::aarch64_sve_cntw:
9960   case Intrinsic::aarch64_sve_cntd:
9961     return true;
9962   }
9963   return false;
9964 }
9965 
9966 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9967                                  TargetLowering::DAGCombinerInfo &DCI,
9968                                  const AArch64Subtarget *Subtarget) {
9969   if (DCI.isBeforeLegalizeOps())
9970     return SDValue();
9971 
9972   // The below optimizations require a constant RHS.
9973   if (!isa<ConstantSDNode>(N->getOperand(1)))
9974     return SDValue();
9975 
9976   SDValue N0 = N->getOperand(0);
9977   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9978   const APInt &ConstValue = C->getAPIntValue();
9979 
9980   // Allow the scaling to be folded into the `cnt` instruction by preventing
9981   // the scaling to be obscured here. This makes it easier to pattern match.
9982   if (IsSVECntIntrinsic(N0) ||
9983      (N0->getOpcode() == ISD::TRUNCATE &&
9984       (IsSVECntIntrinsic(N0->getOperand(0)))))
9985        if (ConstValue.sge(1) && ConstValue.sle(16))
9986          return SDValue();
9987 
9988   // Multiplication of a power of two plus/minus one can be done more
9989   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9990   // future CPUs have a cheaper MADD instruction, this may need to be
9991   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9992   // 64-bit is 5 cycles, so this is always a win.
9993   // More aggressively, some multiplications N0 * C can be lowered to
9994   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9995   // e.g. 6=3*2=(2+1)*2.
9996   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9997   // which equals to (1+2)*16-(1+2).
9998   // TrailingZeroes is used to test if the mul can be lowered to
9999   // shift+add+shift.
10000   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10001   if (TrailingZeroes) {
10002     // Conservatively do not lower to shift+add+shift if the mul might be
10003     // folded into smul or umul.
10004     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10005                             isZeroExtended(N0.getNode(), DAG)))
10006       return SDValue();
10007     // Conservatively do not lower to shift+add+shift if the mul might be
10008     // folded into madd or msub.
10009     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10010                            N->use_begin()->getOpcode() == ISD::SUB))
10011       return SDValue();
10012   }
10013   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10014   // and shift+add+shift.
10015   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10016 
10017   unsigned ShiftAmt, AddSubOpc;
10018   // Is the shifted value the LHS operand of the add/sub?
10019   bool ShiftValUseIsN0 = true;
10020   // Do we need to negate the result?
10021   bool NegateResult = false;
10022 
10023   if (ConstValue.isNonNegative()) {
10024     // (mul x, 2^N + 1) => (add (shl x, N), x)
10025     // (mul x, 2^N - 1) => (sub (shl x, N), x)
10026     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10027     APInt SCVMinus1 = ShiftedConstValue - 1;
10028     APInt CVPlus1 = ConstValue + 1;
10029     if (SCVMinus1.isPowerOf2()) {
10030       ShiftAmt = SCVMinus1.logBase2();
10031       AddSubOpc = ISD::ADD;
10032     } else if (CVPlus1.isPowerOf2()) {
10033       ShiftAmt = CVPlus1.logBase2();
10034       AddSubOpc = ISD::SUB;
10035     } else
10036       return SDValue();
10037   } else {
10038     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10039     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10040     APInt CVNegPlus1 = -ConstValue + 1;
10041     APInt CVNegMinus1 = -ConstValue - 1;
10042     if (CVNegPlus1.isPowerOf2()) {
10043       ShiftAmt = CVNegPlus1.logBase2();
10044       AddSubOpc = ISD::SUB;
10045       ShiftValUseIsN0 = false;
10046     } else if (CVNegMinus1.isPowerOf2()) {
10047       ShiftAmt = CVNegMinus1.logBase2();
10048       AddSubOpc = ISD::ADD;
10049       NegateResult = true;
10050     } else
10051       return SDValue();
10052   }
10053 
10054   SDLoc DL(N);
10055   EVT VT = N->getValueType(0);
10056   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10057                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
10058 
10059   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10060   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10061   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10062   assert(!(NegateResult && TrailingZeroes) &&
10063          "NegateResult and TrailingZeroes cannot both be true for now.");
10064   // Negate the result.
10065   if (NegateResult)
10066     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10067   // Shift the result.
10068   if (TrailingZeroes)
10069     return DAG.getNode(ISD::SHL, DL, VT, Res,
10070                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10071   return Res;
10072 }
10073 
10074 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10075                                                          SelectionDAG &DAG) {
10076   // Take advantage of vector comparisons producing 0 or -1 in each lane to
10077   // optimize away operation when it's from a constant.
10078   //
10079   // The general transformation is:
10080   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10081   //       AND(VECTOR_CMP(x,y), constant2)
10082   //    constant2 = UNARYOP(constant)
10083 
10084   // Early exit if this isn't a vector operation, the operand of the
10085   // unary operation isn't a bitwise AND, or if the sizes of the operations
10086   // aren't the same.
10087   EVT VT = N->getValueType(0);
10088   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10089       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10090       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10091     return SDValue();
10092 
10093   // Now check that the other operand of the AND is a constant. We could
10094   // make the transformation for non-constant splats as well, but it's unclear
10095   // that would be a benefit as it would not eliminate any operations, just
10096   // perform one more step in scalar code before moving to the vector unit.
10097   if (BuildVectorSDNode *BV =
10098           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10099     // Bail out if the vector isn't a constant.
10100     if (!BV->isConstant())
10101       return SDValue();
10102 
10103     // Everything checks out. Build up the new and improved node.
10104     SDLoc DL(N);
10105     EVT IntVT = BV->getValueType(0);
10106     // Create a new constant of the appropriate type for the transformed
10107     // DAG.
10108     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10109     // The AND node needs bitcasts to/from an integer vector type around it.
10110     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10111     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10112                                  N->getOperand(0)->getOperand(0), MaskConst);
10113     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10114     return Res;
10115   }
10116 
10117   return SDValue();
10118 }
10119 
10120 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10121                                      const AArch64Subtarget *Subtarget) {
10122   // First try to optimize away the conversion when it's conditionally from
10123   // a constant. Vectors only.
10124   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10125     return Res;
10126 
10127   EVT VT = N->getValueType(0);
10128   if (VT != MVT::f32 && VT != MVT::f64)
10129     return SDValue();
10130 
10131   // Only optimize when the source and destination types have the same width.
10132   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10133     return SDValue();
10134 
10135   // If the result of an integer load is only used by an integer-to-float
10136   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10137   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10138   SDValue N0 = N->getOperand(0);
10139   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10140       // Do not change the width of a volatile load.
10141       !cast<LoadSDNode>(N0)->isVolatile()) {
10142     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10143     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10144                                LN0->getPointerInfo(), LN0->getAlignment(),
10145                                LN0->getMemOperand()->getFlags());
10146 
10147     // Make sure successors of the original load stay after it by updating them
10148     // to use the new Chain.
10149     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10150 
10151     unsigned Opcode =
10152         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10153     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10154   }
10155 
10156   return SDValue();
10157 }
10158 
10159 /// Fold a floating-point multiply by power of two into floating-point to
10160 /// fixed-point conversion.
10161 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10162                                      TargetLowering::DAGCombinerInfo &DCI,
10163                                      const AArch64Subtarget *Subtarget) {
10164   if (!Subtarget->hasNEON())
10165     return SDValue();
10166 
10167   if (!N->getValueType(0).isSimple())
10168     return SDValue();
10169 
10170   SDValue Op = N->getOperand(0);
10171   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10172       Op.getOpcode() != ISD::FMUL)
10173     return SDValue();
10174 
10175   SDValue ConstVec = Op->getOperand(1);
10176   if (!isa<BuildVectorSDNode>(ConstVec))
10177     return SDValue();
10178 
10179   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10180   uint32_t FloatBits = FloatTy.getSizeInBits();
10181   if (FloatBits != 32 && FloatBits != 64)
10182     return SDValue();
10183 
10184   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10185   uint32_t IntBits = IntTy.getSizeInBits();
10186   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10187     return SDValue();
10188 
10189   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10190   if (IntBits > FloatBits)
10191     return SDValue();
10192 
10193   BitVector UndefElements;
10194   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10195   int32_t Bits = IntBits == 64 ? 64 : 32;
10196   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10197   if (C == -1 || C == 0 || C > Bits)
10198     return SDValue();
10199 
10200   MVT ResTy;
10201   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10202   switch (NumLanes) {
10203   default:
10204     return SDValue();
10205   case 2:
10206     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10207     break;
10208   case 4:
10209     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10210     break;
10211   }
10212 
10213   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10214     return SDValue();
10215 
10216   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10217          "Illegal vector type after legalization");
10218 
10219   SDLoc DL(N);
10220   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10221   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10222                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10223   SDValue FixConv =
10224       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10225                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10226                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10227   // We can handle smaller integers by generating an extra trunc.
10228   if (IntBits < FloatBits)
10229     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10230 
10231   return FixConv;
10232 }
10233 
10234 /// Fold a floating-point divide by power of two into fixed-point to
10235 /// floating-point conversion.
10236 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10237                                   TargetLowering::DAGCombinerInfo &DCI,
10238                                   const AArch64Subtarget *Subtarget) {
10239   if (!Subtarget->hasNEON())
10240     return SDValue();
10241 
10242   SDValue Op = N->getOperand(0);
10243   unsigned Opc = Op->getOpcode();
10244   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10245       !Op.getOperand(0).getValueType().isSimple() ||
10246       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10247     return SDValue();
10248 
10249   SDValue ConstVec = N->getOperand(1);
10250   if (!isa<BuildVectorSDNode>(ConstVec))
10251     return SDValue();
10252 
10253   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10254   int32_t IntBits = IntTy.getSizeInBits();
10255   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10256     return SDValue();
10257 
10258   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10259   int32_t FloatBits = FloatTy.getSizeInBits();
10260   if (FloatBits != 32 && FloatBits != 64)
10261     return SDValue();
10262 
10263   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10264   if (IntBits > FloatBits)
10265     return SDValue();
10266 
10267   BitVector UndefElements;
10268   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10269   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10270   if (C == -1 || C == 0 || C > FloatBits)
10271     return SDValue();
10272 
10273   MVT ResTy;
10274   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10275   switch (NumLanes) {
10276   default:
10277     return SDValue();
10278   case 2:
10279     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10280     break;
10281   case 4:
10282     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10283     break;
10284   }
10285 
10286   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10287     return SDValue();
10288 
10289   SDLoc DL(N);
10290   SDValue ConvInput = Op.getOperand(0);
10291   bool IsSigned = Opc == ISD::SINT_TO_FP;
10292   if (IntBits < FloatBits)
10293     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10294                             ResTy, ConvInput);
10295 
10296   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10297                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10298   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10299                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10300                      DAG.getConstant(C, DL, MVT::i32));
10301 }
10302 
10303 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10304 /// searches for and classifies those shifts.
10305 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10306                          bool &FromHi) {
10307   if (N.getOpcode() == ISD::SHL)
10308     FromHi = false;
10309   else if (N.getOpcode() == ISD::SRL)
10310     FromHi = true;
10311   else
10312     return false;
10313 
10314   if (!isa<ConstantSDNode>(N.getOperand(1)))
10315     return false;
10316 
10317   ShiftAmount = N->getConstantOperandVal(1);
10318   Src = N->getOperand(0);
10319   return true;
10320 }
10321 
10322 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10323 /// registers viewed as a high/low pair. This function looks for the pattern:
10324 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10325 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10326 /// aren't independent.
10327 static SDValue tryCombineToEXTR(SDNode *N,
10328                                 TargetLowering::DAGCombinerInfo &DCI) {
10329   SelectionDAG &DAG = DCI.DAG;
10330   SDLoc DL(N);
10331   EVT VT = N->getValueType(0);
10332 
10333   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10334 
10335   if (VT != MVT::i32 && VT != MVT::i64)
10336     return SDValue();
10337 
10338   SDValue LHS;
10339   uint32_t ShiftLHS = 0;
10340   bool LHSFromHi = false;
10341   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10342     return SDValue();
10343 
10344   SDValue RHS;
10345   uint32_t ShiftRHS = 0;
10346   bool RHSFromHi = false;
10347   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10348     return SDValue();
10349 
10350   // If they're both trying to come from the high part of the register, they're
10351   // not really an EXTR.
10352   if (LHSFromHi == RHSFromHi)
10353     return SDValue();
10354 
10355   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10356     return SDValue();
10357 
10358   if (LHSFromHi) {
10359     std::swap(LHS, RHS);
10360     std::swap(ShiftLHS, ShiftRHS);
10361   }
10362 
10363   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10364                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10365 }
10366 
10367 static SDValue tryCombineToBSL(SDNode *N,
10368                                 TargetLowering::DAGCombinerInfo &DCI) {
10369   EVT VT = N->getValueType(0);
10370   SelectionDAG &DAG = DCI.DAG;
10371   SDLoc DL(N);
10372 
10373   if (!VT.isVector())
10374     return SDValue();
10375 
10376   SDValue N0 = N->getOperand(0);
10377   if (N0.getOpcode() != ISD::AND)
10378     return SDValue();
10379 
10380   SDValue N1 = N->getOperand(1);
10381   if (N1.getOpcode() != ISD::AND)
10382     return SDValue();
10383 
10384   // We only have to look for constant vectors here since the general, variable
10385   // case can be handled in TableGen.
10386   unsigned Bits = VT.getScalarSizeInBits();
10387   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10388   for (int i = 1; i >= 0; --i)
10389     for (int j = 1; j >= 0; --j) {
10390       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10391       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10392       if (!BVN0 || !BVN1)
10393         continue;
10394 
10395       bool FoundMatch = true;
10396       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10397         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10398         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10399         if (!CN0 || !CN1 ||
10400             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10401           FoundMatch = false;
10402           break;
10403         }
10404       }
10405 
10406       if (FoundMatch)
10407         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
10408                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10409     }
10410 
10411   return SDValue();
10412 }
10413 
10414 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10415                                 const AArch64Subtarget *Subtarget) {
10416   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10417   SelectionDAG &DAG = DCI.DAG;
10418   EVT VT = N->getValueType(0);
10419 
10420   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10421     return SDValue();
10422 
10423   if (SDValue Res = tryCombineToEXTR(N, DCI))
10424     return Res;
10425 
10426   if (SDValue Res = tryCombineToBSL(N, DCI))
10427     return Res;
10428 
10429   return SDValue();
10430 }
10431 
10432 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10433   if (!MemVT.getVectorElementType().isSimple())
10434     return false;
10435 
10436   uint64_t MaskForTy = 0ull;
10437   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10438   case MVT::i8:
10439     MaskForTy = 0xffull;
10440     break;
10441   case MVT::i16:
10442     MaskForTy = 0xffffull;
10443     break;
10444   case MVT::i32:
10445     MaskForTy = 0xffffffffull;
10446     break;
10447   default:
10448     return false;
10449     break;
10450   }
10451 
10452   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10453     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10454       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10455 
10456   return false;
10457 }
10458 
10459 static SDValue performSVEAndCombine(SDNode *N,
10460                                     TargetLowering::DAGCombinerInfo &DCI) {
10461   if (DCI.isBeforeLegalizeOps())
10462     return SDValue();
10463 
10464   SDValue Src = N->getOperand(0);
10465   SDValue Mask = N->getOperand(1);
10466 
10467   if (!Src.hasOneUse())
10468     return SDValue();
10469 
10470   EVT MemVT;
10471 
10472   // SVE load instructions perform an implicit zero-extend, which makes them
10473   // perfect candidates for combining.
10474   switch (Src->getOpcode()) {
10475   case AArch64ISD::LDNF1:
10476   case AArch64ISD::LDFF1:
10477     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
10478     break;
10479   case AArch64ISD::GLD1:
10480   case AArch64ISD::GLD1_SCALED:
10481   case AArch64ISD::GLD1_SXTW:
10482   case AArch64ISD::GLD1_SXTW_SCALED:
10483   case AArch64ISD::GLD1_UXTW:
10484   case AArch64ISD::GLD1_UXTW_SCALED:
10485   case AArch64ISD::GLD1_IMM:
10486   case AArch64ISD::GLDFF1:
10487   case AArch64ISD::GLDFF1_SCALED:
10488   case AArch64ISD::GLDFF1_SXTW:
10489   case AArch64ISD::GLDFF1_SXTW_SCALED:
10490   case AArch64ISD::GLDFF1_UXTW:
10491   case AArch64ISD::GLDFF1_UXTW_SCALED:
10492   case AArch64ISD::GLDFF1_IMM:
10493   case AArch64ISD::GLDNT1:
10494     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10495     break;
10496   default:
10497     return SDValue();
10498   }
10499 
10500   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10501     return Src;
10502 
10503   return SDValue();
10504 }
10505 
10506 static SDValue performANDCombine(SDNode *N,
10507                                  TargetLowering::DAGCombinerInfo &DCI) {
10508   SelectionDAG &DAG = DCI.DAG;
10509   SDValue LHS = N->getOperand(0);
10510   EVT VT = N->getValueType(0);
10511   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10512     return SDValue();
10513 
10514   if (VT.isScalableVector())
10515     return performSVEAndCombine(N, DCI);
10516 
10517   BuildVectorSDNode *BVN =
10518       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10519   if (!BVN)
10520     return SDValue();
10521 
10522   // AND does not accept an immediate, so check if we can use a BIC immediate
10523   // instruction instead. We do this here instead of using a (and x, (mvni imm))
10524   // pattern in isel, because some immediates may be lowered to the preferred
10525   // (and x, (movi imm)) form, even though an mvni representation also exists.
10526   APInt DefBits(VT.getSizeInBits(), 0);
10527   APInt UndefBits(VT.getSizeInBits(), 0);
10528   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10529     SDValue NewOp;
10530 
10531     DefBits = ~DefBits;
10532     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10533                                     DefBits, &LHS)) ||
10534         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10535                                     DefBits, &LHS)))
10536       return NewOp;
10537 
10538     UndefBits = ~UndefBits;
10539     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10540                                     UndefBits, &LHS)) ||
10541         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10542                                     UndefBits, &LHS)))
10543       return NewOp;
10544   }
10545 
10546   return SDValue();
10547 }
10548 
10549 static SDValue performSRLCombine(SDNode *N,
10550                                  TargetLowering::DAGCombinerInfo &DCI) {
10551   SelectionDAG &DAG = DCI.DAG;
10552   EVT VT = N->getValueType(0);
10553   if (VT != MVT::i32 && VT != MVT::i64)
10554     return SDValue();
10555 
10556   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10557   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10558   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10559   SDValue N0 = N->getOperand(0);
10560   if (N0.getOpcode() == ISD::BSWAP) {
10561     SDLoc DL(N);
10562     SDValue N1 = N->getOperand(1);
10563     SDValue N00 = N0.getOperand(0);
10564     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10565       uint64_t ShiftAmt = C->getZExtValue();
10566       if (VT == MVT::i32 && ShiftAmt == 16 &&
10567           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10568         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10569       if (VT == MVT::i64 && ShiftAmt == 32 &&
10570           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10571         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10572     }
10573   }
10574   return SDValue();
10575 }
10576 
10577 static SDValue performConcatVectorsCombine(SDNode *N,
10578                                            TargetLowering::DAGCombinerInfo &DCI,
10579                                            SelectionDAG &DAG) {
10580   SDLoc dl(N);
10581   EVT VT = N->getValueType(0);
10582   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10583 
10584   // Optimize concat_vectors of truncated vectors, where the intermediate
10585   // type is illegal, to avoid said illegality,  e.g.,
10586   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10587   //                          (v2i16 (truncate (v2i64)))))
10588   // ->
10589   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10590   //                                    (v4i32 (bitcast (v2i64))),
10591   //                                    <0, 2, 4, 6>)))
10592   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10593   // on both input and result type, so we might generate worse code.
10594   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10595   if (N->getNumOperands() == 2 &&
10596       N0->getOpcode() == ISD::TRUNCATE &&
10597       N1->getOpcode() == ISD::TRUNCATE) {
10598     SDValue N00 = N0->getOperand(0);
10599     SDValue N10 = N1->getOperand(0);
10600     EVT N00VT = N00.getValueType();
10601 
10602     if (N00VT == N10.getValueType() &&
10603         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10604         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10605       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10606       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10607       for (size_t i = 0; i < Mask.size(); ++i)
10608         Mask[i] = i * 2;
10609       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10610                          DAG.getVectorShuffle(
10611                              MidVT, dl,
10612                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10613                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10614     }
10615   }
10616 
10617   // Wait 'til after everything is legalized to try this. That way we have
10618   // legal vector types and such.
10619   if (DCI.isBeforeLegalizeOps())
10620     return SDValue();
10621 
10622   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10623   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10624   // canonicalise to that.
10625   if (N0 == N1 && VT.getVectorNumElements() == 2) {
10626     assert(VT.getScalarSizeInBits() == 64);
10627     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10628                        DAG.getConstant(0, dl, MVT::i64));
10629   }
10630 
10631   // Canonicalise concat_vectors so that the right-hand vector has as few
10632   // bit-casts as possible before its real operation. The primary matching
10633   // destination for these operations will be the narrowing "2" instructions,
10634   // which depend on the operation being performed on this right-hand vector.
10635   // For example,
10636   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10637   // becomes
10638   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10639 
10640   if (N1->getOpcode() != ISD::BITCAST)
10641     return SDValue();
10642   SDValue RHS = N1->getOperand(0);
10643   MVT RHSTy = RHS.getValueType().getSimpleVT();
10644   // If the RHS is not a vector, this is not the pattern we're looking for.
10645   if (!RHSTy.isVector())
10646     return SDValue();
10647 
10648   LLVM_DEBUG(
10649       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10650 
10651   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10652                                   RHSTy.getVectorNumElements() * 2);
10653   return DAG.getNode(ISD::BITCAST, dl, VT,
10654                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10655                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10656                                  RHS));
10657 }
10658 
10659 static SDValue tryCombineFixedPointConvert(SDNode *N,
10660                                            TargetLowering::DAGCombinerInfo &DCI,
10661                                            SelectionDAG &DAG) {
10662   // Wait until after everything is legalized to try this. That way we have
10663   // legal vector types and such.
10664   if (DCI.isBeforeLegalizeOps())
10665     return SDValue();
10666   // Transform a scalar conversion of a value from a lane extract into a
10667   // lane extract of a vector conversion. E.g., from foo1 to foo2:
10668   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10669   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10670   //
10671   // The second form interacts better with instruction selection and the
10672   // register allocator to avoid cross-class register copies that aren't
10673   // coalescable due to a lane reference.
10674 
10675   // Check the operand and see if it originates from a lane extract.
10676   SDValue Op1 = N->getOperand(1);
10677   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10678     // Yep, no additional predication needed. Perform the transform.
10679     SDValue IID = N->getOperand(0);
10680     SDValue Shift = N->getOperand(2);
10681     SDValue Vec = Op1.getOperand(0);
10682     SDValue Lane = Op1.getOperand(1);
10683     EVT ResTy = N->getValueType(0);
10684     EVT VecResTy;
10685     SDLoc DL(N);
10686 
10687     // The vector width should be 128 bits by the time we get here, even
10688     // if it started as 64 bits (the extract_vector handling will have
10689     // done so).
10690     assert(Vec.getValueSizeInBits() == 128 &&
10691            "unexpected vector size on extract_vector_elt!");
10692     if (Vec.getValueType() == MVT::v4i32)
10693       VecResTy = MVT::v4f32;
10694     else if (Vec.getValueType() == MVT::v2i64)
10695       VecResTy = MVT::v2f64;
10696     else
10697       llvm_unreachable("unexpected vector type!");
10698 
10699     SDValue Convert =
10700         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10701     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10702   }
10703   return SDValue();
10704 }
10705 
10706 // AArch64 high-vector "long" operations are formed by performing the non-high
10707 // version on an extract_subvector of each operand which gets the high half:
10708 //
10709 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10710 //
10711 // However, there are cases which don't have an extract_high explicitly, but
10712 // have another operation that can be made compatible with one for free. For
10713 // example:
10714 //
10715 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
10716 //
10717 // This routine does the actual conversion of such DUPs, once outer routines
10718 // have determined that everything else is in order.
10719 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10720 // similarly here.
10721 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10722   switch (N.getOpcode()) {
10723   case AArch64ISD::DUP:
10724   case AArch64ISD::DUPLANE8:
10725   case AArch64ISD::DUPLANE16:
10726   case AArch64ISD::DUPLANE32:
10727   case AArch64ISD::DUPLANE64:
10728   case AArch64ISD::MOVI:
10729   case AArch64ISD::MOVIshift:
10730   case AArch64ISD::MOVIedit:
10731   case AArch64ISD::MOVImsl:
10732   case AArch64ISD::MVNIshift:
10733   case AArch64ISD::MVNImsl:
10734     break;
10735   default:
10736     // FMOV could be supported, but isn't very useful, as it would only occur
10737     // if you passed a bitcast' floating point immediate to an eligible long
10738     // integer op (addl, smull, ...).
10739     return SDValue();
10740   }
10741 
10742   MVT NarrowTy = N.getSimpleValueType();
10743   if (!NarrowTy.is64BitVector())
10744     return SDValue();
10745 
10746   MVT ElementTy = NarrowTy.getVectorElementType();
10747   unsigned NumElems = NarrowTy.getVectorNumElements();
10748   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10749 
10750   SDLoc dl(N);
10751   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10752                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10753                      DAG.getConstant(NumElems, dl, MVT::i64));
10754 }
10755 
10756 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10757   if (N.getOpcode() == ISD::BITCAST)
10758     N = N.getOperand(0);
10759   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10760     return false;
10761   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10762          N.getOperand(0).getValueType().getVectorNumElements() / 2;
10763 }
10764 
10765 /// Helper structure to keep track of ISD::SET_CC operands.
10766 struct GenericSetCCInfo {
10767   const SDValue *Opnd0;
10768   const SDValue *Opnd1;
10769   ISD::CondCode CC;
10770 };
10771 
10772 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10773 struct AArch64SetCCInfo {
10774   const SDValue *Cmp;
10775   AArch64CC::CondCode CC;
10776 };
10777 
10778 /// Helper structure to keep track of SetCC information.
10779 union SetCCInfo {
10780   GenericSetCCInfo Generic;
10781   AArch64SetCCInfo AArch64;
10782 };
10783 
10784 /// Helper structure to be able to read SetCC information.  If set to
10785 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10786 /// GenericSetCCInfo.
10787 struct SetCCInfoAndKind {
10788   SetCCInfo Info;
10789   bool IsAArch64;
10790 };
10791 
10792 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10793 /// an
10794 /// AArch64 lowered one.
10795 /// \p SetCCInfo is filled accordingly.
10796 /// \post SetCCInfo is meanginfull only when this function returns true.
10797 /// \return True when Op is a kind of SET_CC operation.
10798 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10799   // If this is a setcc, this is straight forward.
10800   if (Op.getOpcode() == ISD::SETCC) {
10801     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10802     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10803     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10804     SetCCInfo.IsAArch64 = false;
10805     return true;
10806   }
10807   // Otherwise, check if this is a matching csel instruction.
10808   // In other words:
10809   // - csel 1, 0, cc
10810   // - csel 0, 1, !cc
10811   if (Op.getOpcode() != AArch64ISD::CSEL)
10812     return false;
10813   // Set the information about the operands.
10814   // TODO: we want the operands of the Cmp not the csel
10815   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10816   SetCCInfo.IsAArch64 = true;
10817   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10818       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10819 
10820   // Check that the operands matches the constraints:
10821   // (1) Both operands must be constants.
10822   // (2) One must be 1 and the other must be 0.
10823   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10824   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10825 
10826   // Check (1).
10827   if (!TValue || !FValue)
10828     return false;
10829 
10830   // Check (2).
10831   if (!TValue->isOne()) {
10832     // Update the comparison when we are interested in !cc.
10833     std::swap(TValue, FValue);
10834     SetCCInfo.Info.AArch64.CC =
10835         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10836   }
10837   return TValue->isOne() && FValue->isNullValue();
10838 }
10839 
10840 // Returns true if Op is setcc or zext of setcc.
10841 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10842   if (isSetCC(Op, Info))
10843     return true;
10844   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10845     isSetCC(Op->getOperand(0), Info));
10846 }
10847 
10848 // The folding we want to perform is:
10849 // (add x, [zext] (setcc cc ...) )
10850 //   -->
10851 // (csel x, (add x, 1), !cc ...)
10852 //
10853 // The latter will get matched to a CSINC instruction.
10854 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10855   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10856   SDValue LHS = Op->getOperand(0);
10857   SDValue RHS = Op->getOperand(1);
10858   SetCCInfoAndKind InfoAndKind;
10859 
10860   // If neither operand is a SET_CC, give up.
10861   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10862     std::swap(LHS, RHS);
10863     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10864       return SDValue();
10865   }
10866 
10867   // FIXME: This could be generatized to work for FP comparisons.
10868   EVT CmpVT = InfoAndKind.IsAArch64
10869                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10870                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10871   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10872     return SDValue();
10873 
10874   SDValue CCVal;
10875   SDValue Cmp;
10876   SDLoc dl(Op);
10877   if (InfoAndKind.IsAArch64) {
10878     CCVal = DAG.getConstant(
10879         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10880         MVT::i32);
10881     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10882   } else
10883     Cmp = getAArch64Cmp(
10884         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10885         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10886         dl);
10887 
10888   EVT VT = Op->getValueType(0);
10889   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10890   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10891 }
10892 
10893 // The basic add/sub long vector instructions have variants with "2" on the end
10894 // which act on the high-half of their inputs. They are normally matched by
10895 // patterns like:
10896 //
10897 // (add (zeroext (extract_high LHS)),
10898 //      (zeroext (extract_high RHS)))
10899 // -> uaddl2 vD, vN, vM
10900 //
10901 // However, if one of the extracts is something like a duplicate, this
10902 // instruction can still be used profitably. This function puts the DAG into a
10903 // more appropriate form for those patterns to trigger.
10904 static SDValue performAddSubLongCombine(SDNode *N,
10905                                         TargetLowering::DAGCombinerInfo &DCI,
10906                                         SelectionDAG &DAG) {
10907   if (DCI.isBeforeLegalizeOps())
10908     return SDValue();
10909 
10910   MVT VT = N->getSimpleValueType(0);
10911   if (!VT.is128BitVector()) {
10912     if (N->getOpcode() == ISD::ADD)
10913       return performSetccAddFolding(N, DAG);
10914     return SDValue();
10915   }
10916 
10917   // Make sure both branches are extended in the same way.
10918   SDValue LHS = N->getOperand(0);
10919   SDValue RHS = N->getOperand(1);
10920   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10921        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10922       LHS.getOpcode() != RHS.getOpcode())
10923     return SDValue();
10924 
10925   unsigned ExtType = LHS.getOpcode();
10926 
10927   // It's not worth doing if at least one of the inputs isn't already an
10928   // extract, but we don't know which it'll be so we have to try both.
10929   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10930     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10931     if (!RHS.getNode())
10932       return SDValue();
10933 
10934     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10935   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10936     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10937     if (!LHS.getNode())
10938       return SDValue();
10939 
10940     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10941   }
10942 
10943   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10944 }
10945 
10946 // Massage DAGs which we can use the high-half "long" operations on into
10947 // something isel will recognize better. E.g.
10948 //
10949 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10950 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10951 //                     (extract_high (v2i64 (dup128 scalar)))))
10952 //
10953 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10954                                        TargetLowering::DAGCombinerInfo &DCI,
10955                                        SelectionDAG &DAG) {
10956   if (DCI.isBeforeLegalizeOps())
10957     return SDValue();
10958 
10959   SDValue LHS = N->getOperand(1);
10960   SDValue RHS = N->getOperand(2);
10961   assert(LHS.getValueType().is64BitVector() &&
10962          RHS.getValueType().is64BitVector() &&
10963          "unexpected shape for long operation");
10964 
10965   // Either node could be a DUP, but it's not worth doing both of them (you'd
10966   // just as well use the non-high version) so look for a corresponding extract
10967   // operation on the other "wing".
10968   if (isEssentiallyExtractHighSubvector(LHS)) {
10969     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10970     if (!RHS.getNode())
10971       return SDValue();
10972   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10973     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10974     if (!LHS.getNode())
10975       return SDValue();
10976   }
10977 
10978   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10979                      N->getOperand(0), LHS, RHS);
10980 }
10981 
10982 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10983   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10984   unsigned ElemBits = ElemTy.getSizeInBits();
10985 
10986   int64_t ShiftAmount;
10987   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10988     APInt SplatValue, SplatUndef;
10989     unsigned SplatBitSize;
10990     bool HasAnyUndefs;
10991     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10992                               HasAnyUndefs, ElemBits) ||
10993         SplatBitSize != ElemBits)
10994       return SDValue();
10995 
10996     ShiftAmount = SplatValue.getSExtValue();
10997   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10998     ShiftAmount = CVN->getSExtValue();
10999   } else
11000     return SDValue();
11001 
11002   unsigned Opcode;
11003   bool IsRightShift;
11004   switch (IID) {
11005   default:
11006     llvm_unreachable("Unknown shift intrinsic");
11007   case Intrinsic::aarch64_neon_sqshl:
11008     Opcode = AArch64ISD::SQSHL_I;
11009     IsRightShift = false;
11010     break;
11011   case Intrinsic::aarch64_neon_uqshl:
11012     Opcode = AArch64ISD::UQSHL_I;
11013     IsRightShift = false;
11014     break;
11015   case Intrinsic::aarch64_neon_srshl:
11016     Opcode = AArch64ISD::SRSHR_I;
11017     IsRightShift = true;
11018     break;
11019   case Intrinsic::aarch64_neon_urshl:
11020     Opcode = AArch64ISD::URSHR_I;
11021     IsRightShift = true;
11022     break;
11023   case Intrinsic::aarch64_neon_sqshlu:
11024     Opcode = AArch64ISD::SQSHLU_I;
11025     IsRightShift = false;
11026     break;
11027   case Intrinsic::aarch64_neon_sshl:
11028   case Intrinsic::aarch64_neon_ushl:
11029     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11030     // left shift for positive shift amounts. Below, we only replace the current
11031     // node with VSHL, if this condition is met.
11032     Opcode = AArch64ISD::VSHL;
11033     IsRightShift = false;
11034     break;
11035   }
11036 
11037   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11038     SDLoc dl(N);
11039     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11040                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11041   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11042     SDLoc dl(N);
11043     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11044                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
11045   }
11046 
11047   return SDValue();
11048 }
11049 
11050 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11051 // the intrinsics must be legal and take an i32, this means there's almost
11052 // certainly going to be a zext in the DAG which we can eliminate.
11053 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11054   SDValue AndN = N->getOperand(2);
11055   if (AndN.getOpcode() != ISD::AND)
11056     return SDValue();
11057 
11058   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11059   if (!CMask || CMask->getZExtValue() != Mask)
11060     return SDValue();
11061 
11062   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11063                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11064 }
11065 
11066 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11067                                            SelectionDAG &DAG) {
11068   SDLoc dl(N);
11069   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11070                      DAG.getNode(Opc, dl,
11071                                  N->getOperand(1).getSimpleValueType(),
11072                                  N->getOperand(1)),
11073                      DAG.getConstant(0, dl, MVT::i64));
11074 }
11075 
11076 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11077                                     SelectionDAG &DAG) {
11078   SDLoc dl(N);
11079   LLVMContext &Ctx = *DAG.getContext();
11080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11081 
11082   EVT VT = N->getValueType(0);
11083   SDValue Pred = N->getOperand(1);
11084   SDValue Data = N->getOperand(2);
11085   EVT DataVT = Data.getValueType();
11086 
11087   if (DataVT.getVectorElementType().isScalarInteger() &&
11088       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11089     if (!TLI.isTypeLegal(DataVT))
11090       return SDValue();
11091 
11092     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11093       AArch64::NeonBitsPerVector / VT.getSizeInBits());
11094     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11095     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11096     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11097 
11098     return Result;
11099   }
11100 
11101   return SDValue();
11102 }
11103 
11104 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11105   SDLoc DL(N);
11106   SDValue Op1 = N->getOperand(1);
11107   SDValue Op2 = N->getOperand(2);
11108   EVT ScalarTy = Op1.getValueType();
11109 
11110   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11111     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11112     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11113   }
11114 
11115   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11116                      Op1, Op2);
11117 }
11118 
11119 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11120   SDLoc dl(N);
11121   SDValue Scalar = N->getOperand(3);
11122   EVT ScalarTy = Scalar.getValueType();
11123 
11124   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11125     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11126 
11127   return DAG.getNode(AArch64ISD::DUP_PRED, dl, N->getValueType(0),
11128                      N->getOperand(1), N->getOperand(2), Scalar);
11129 }
11130 
11131 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11132   SDLoc dl(N);
11133   LLVMContext &Ctx = *DAG.getContext();
11134   EVT VT = N->getValueType(0);
11135 
11136   assert(VT.isScalableVector() && "Expected a scalable vector.");
11137 
11138   // Current lowering only supports the SVE-ACLE types.
11139   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11140     return SDValue();
11141 
11142   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11143   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11144   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
11145 
11146   // Convert everything to the domain of EXT (i.e bytes).
11147   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
11148   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
11149   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
11150                             DAG.getConstant(ElemSize, dl, MVT::i32));
11151 
11152   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
11153   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
11154 }
11155 
11156 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
11157                                         bool Invert,
11158                                         TargetLowering::DAGCombinerInfo &DCI,
11159                                         SelectionDAG &DAG) {
11160   if (DCI.isBeforeLegalize())
11161     return SDValue();
11162 
11163   SDValue Comparator = N->getOperand(3);
11164   if (Comparator.getOpcode() == AArch64ISD::DUP ||
11165       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
11166     unsigned IID = getIntrinsicID(N);
11167     EVT VT = N->getValueType(0);
11168     EVT CmpVT = N->getOperand(2).getValueType();
11169     SDValue Pred = N->getOperand(1);
11170     SDValue Imm;
11171     SDLoc DL(N);
11172 
11173     switch (IID) {
11174     default:
11175       llvm_unreachable("Called with wrong intrinsic!");
11176       break;
11177 
11178     // Signed comparisons
11179     case Intrinsic::aarch64_sve_cmpeq_wide:
11180     case Intrinsic::aarch64_sve_cmpne_wide:
11181     case Intrinsic::aarch64_sve_cmpge_wide:
11182     case Intrinsic::aarch64_sve_cmpgt_wide:
11183     case Intrinsic::aarch64_sve_cmplt_wide:
11184     case Intrinsic::aarch64_sve_cmple_wide: {
11185       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11186         int64_t ImmVal = CN->getSExtValue();
11187         if (ImmVal >= -16 && ImmVal <= 15)
11188           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11189         else
11190           return SDValue();
11191       }
11192       break;
11193     }
11194     // Unsigned comparisons
11195     case Intrinsic::aarch64_sve_cmphs_wide:
11196     case Intrinsic::aarch64_sve_cmphi_wide:
11197     case Intrinsic::aarch64_sve_cmplo_wide:
11198     case Intrinsic::aarch64_sve_cmpls_wide:  {
11199       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11200         uint64_t ImmVal = CN->getZExtValue();
11201         if (ImmVal <= 127)
11202           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11203         else
11204           return SDValue();
11205       }
11206       break;
11207     }
11208     }
11209 
11210     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11211     SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
11212     SDValue Op0, Op1;
11213     if (Invert) {
11214       Op0 = Splat;
11215       Op1 = N->getOperand(2);
11216     } else {
11217       Op0 = N->getOperand(2);
11218       Op1 = Splat;
11219     }
11220     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11221                        ID, Pred, Op0, Op1);
11222   }
11223 
11224   return SDValue();
11225 }
11226 
11227 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11228                         AArch64CC::CondCode Cond) {
11229   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11230 
11231   SDLoc DL(Op);
11232   assert(Op.getValueType().isScalableVector() &&
11233          TLI.isTypeLegal(Op.getValueType()) &&
11234          "Expected legal scalable vector type!");
11235 
11236   // Ensure target specific opcodes are using legal type.
11237   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11238   SDValue TVal = DAG.getConstant(1, DL, OutVT);
11239   SDValue FVal = DAG.getConstant(0, DL, OutVT);
11240 
11241   // Set condition code (CC) flags.
11242   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11243 
11244   // Convert CC to integer based on requested condition.
11245   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11246   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11247   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11248   return DAG.getZExtOrTrunc(Res, DL, VT);
11249 }
11250 
11251 static SDValue performIntrinsicCombine(SDNode *N,
11252                                        TargetLowering::DAGCombinerInfo &DCI,
11253                                        const AArch64Subtarget *Subtarget) {
11254   SelectionDAG &DAG = DCI.DAG;
11255   unsigned IID = getIntrinsicID(N);
11256   switch (IID) {
11257   default:
11258     break;
11259   case Intrinsic::aarch64_neon_vcvtfxs2fp:
11260   case Intrinsic::aarch64_neon_vcvtfxu2fp:
11261     return tryCombineFixedPointConvert(N, DCI, DAG);
11262   case Intrinsic::aarch64_neon_saddv:
11263     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11264   case Intrinsic::aarch64_neon_uaddv:
11265     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11266   case Intrinsic::aarch64_neon_sminv:
11267     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11268   case Intrinsic::aarch64_neon_uminv:
11269     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11270   case Intrinsic::aarch64_neon_smaxv:
11271     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11272   case Intrinsic::aarch64_neon_umaxv:
11273     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11274   case Intrinsic::aarch64_neon_fmax:
11275     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11276                        N->getOperand(1), N->getOperand(2));
11277   case Intrinsic::aarch64_neon_fmin:
11278     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11279                        N->getOperand(1), N->getOperand(2));
11280   case Intrinsic::aarch64_neon_fmaxnm:
11281     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11282                        N->getOperand(1), N->getOperand(2));
11283   case Intrinsic::aarch64_neon_fminnm:
11284     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11285                        N->getOperand(1), N->getOperand(2));
11286   case Intrinsic::aarch64_neon_smull:
11287   case Intrinsic::aarch64_neon_umull:
11288   case Intrinsic::aarch64_neon_pmull:
11289   case Intrinsic::aarch64_neon_sqdmull:
11290     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11291   case Intrinsic::aarch64_neon_sqshl:
11292   case Intrinsic::aarch64_neon_uqshl:
11293   case Intrinsic::aarch64_neon_sqshlu:
11294   case Intrinsic::aarch64_neon_srshl:
11295   case Intrinsic::aarch64_neon_urshl:
11296   case Intrinsic::aarch64_neon_sshl:
11297   case Intrinsic::aarch64_neon_ushl:
11298     return tryCombineShiftImm(IID, N, DAG);
11299   case Intrinsic::aarch64_crc32b:
11300   case Intrinsic::aarch64_crc32cb:
11301     return tryCombineCRC32(0xff, N, DAG);
11302   case Intrinsic::aarch64_crc32h:
11303   case Intrinsic::aarch64_crc32ch:
11304     return tryCombineCRC32(0xffff, N, DAG);
11305   case Intrinsic::aarch64_sve_smaxv:
11306     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11307   case Intrinsic::aarch64_sve_umaxv:
11308     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11309   case Intrinsic::aarch64_sve_sminv:
11310     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11311   case Intrinsic::aarch64_sve_uminv:
11312     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11313   case Intrinsic::aarch64_sve_orv:
11314     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11315   case Intrinsic::aarch64_sve_eorv:
11316     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11317   case Intrinsic::aarch64_sve_andv:
11318     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11319   case Intrinsic::aarch64_sve_index:
11320     return LowerSVEIntrinsicIndex(N, DAG);
11321   case Intrinsic::aarch64_sve_dup:
11322     return LowerSVEIntrinsicDUP(N, DAG);
11323   case Intrinsic::aarch64_sve_dup_x:
11324     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
11325                        N->getOperand(1));
11326   case Intrinsic::aarch64_sve_ext:
11327     return LowerSVEIntrinsicEXT(N, DAG);
11328   case Intrinsic::aarch64_sve_sel:
11329     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
11330                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
11331   case Intrinsic::aarch64_sve_cmpeq_wide:
11332     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
11333                                     false, DCI, DAG);
11334   case Intrinsic::aarch64_sve_cmpne_wide:
11335     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
11336                                     false, DCI, DAG);
11337   case Intrinsic::aarch64_sve_cmpge_wide:
11338     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11339                                     false, DCI, DAG);
11340   case Intrinsic::aarch64_sve_cmpgt_wide:
11341     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11342                                     false, DCI, DAG);
11343   case Intrinsic::aarch64_sve_cmplt_wide:
11344     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11345                                     true, DCI, DAG);
11346   case Intrinsic::aarch64_sve_cmple_wide:
11347     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11348                                     true, DCI, DAG);
11349   case Intrinsic::aarch64_sve_cmphs_wide:
11350     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11351                                     false, DCI, DAG);
11352   case Intrinsic::aarch64_sve_cmphi_wide:
11353     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11354                                     false, DCI, DAG);
11355   case Intrinsic::aarch64_sve_cmplo_wide:
11356     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11357                                     DCI, DAG);
11358   case Intrinsic::aarch64_sve_cmpls_wide:
11359     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11360                                     DCI, DAG);
11361   case Intrinsic::aarch64_sve_ptest_any:
11362     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11363                     AArch64CC::ANY_ACTIVE);
11364   case Intrinsic::aarch64_sve_ptest_first:
11365     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11366                     AArch64CC::FIRST_ACTIVE);
11367   case Intrinsic::aarch64_sve_ptest_last:
11368     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11369                     AArch64CC::LAST_ACTIVE);
11370   }
11371   return SDValue();
11372 }
11373 
11374 static SDValue performExtendCombine(SDNode *N,
11375                                     TargetLowering::DAGCombinerInfo &DCI,
11376                                     SelectionDAG &DAG) {
11377   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11378   // we can convert that DUP into another extract_high (of a bigger DUP), which
11379   // helps the backend to decide that an sabdl2 would be useful, saving a real
11380   // extract_high operation.
11381   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11382       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11383     SDNode *ABDNode = N->getOperand(0).getNode();
11384     unsigned IID = getIntrinsicID(ABDNode);
11385     if (IID == Intrinsic::aarch64_neon_sabd ||
11386         IID == Intrinsic::aarch64_neon_uabd) {
11387       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11388       if (!NewABD.getNode())
11389         return SDValue();
11390 
11391       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11392                          NewABD);
11393     }
11394   }
11395 
11396   // This is effectively a custom type legalization for AArch64.
11397   //
11398   // Type legalization will split an extend of a small, legal, type to a larger
11399   // illegal type by first splitting the destination type, often creating
11400   // illegal source types, which then get legalized in isel-confusing ways,
11401   // leading to really terrible codegen. E.g.,
11402   //   %result = v8i32 sext v8i8 %value
11403   // becomes
11404   //   %losrc = extract_subreg %value, ...
11405   //   %hisrc = extract_subreg %value, ...
11406   //   %lo = v4i32 sext v4i8 %losrc
11407   //   %hi = v4i32 sext v4i8 %hisrc
11408   // Things go rapidly downhill from there.
11409   //
11410   // For AArch64, the [sz]ext vector instructions can only go up one element
11411   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11412   // take two instructions.
11413   //
11414   // This implies that the most efficient way to do the extend from v8i8
11415   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11416   // the normal splitting to happen for the v8i16->v8i32.
11417 
11418   // This is pre-legalization to catch some cases where the default
11419   // type legalization will create ill-tempered code.
11420   if (!DCI.isBeforeLegalizeOps())
11421     return SDValue();
11422 
11423   // We're only interested in cleaning things up for non-legal vector types
11424   // here. If both the source and destination are legal, things will just
11425   // work naturally without any fiddling.
11426   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11427   EVT ResVT = N->getValueType(0);
11428   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11429     return SDValue();
11430   // If the vector type isn't a simple VT, it's beyond the scope of what
11431   // we're  worried about here. Let legalization do its thing and hope for
11432   // the best.
11433   SDValue Src = N->getOperand(0);
11434   EVT SrcVT = Src->getValueType(0);
11435   if (!ResVT.isSimple() || !SrcVT.isSimple())
11436     return SDValue();
11437 
11438   // If the source VT is a 64-bit vector, we can play games and get the
11439   // better results we want.
11440   if (SrcVT.getSizeInBits() != 64)
11441     return SDValue();
11442 
11443   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11444   unsigned ElementCount = SrcVT.getVectorNumElements();
11445   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11446   SDLoc DL(N);
11447   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11448 
11449   // Now split the rest of the operation into two halves, each with a 64
11450   // bit source.
11451   EVT LoVT, HiVT;
11452   SDValue Lo, Hi;
11453   unsigned NumElements = ResVT.getVectorNumElements();
11454   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11455   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11456                                  ResVT.getVectorElementType(), NumElements / 2);
11457 
11458   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11459                                LoVT.getVectorNumElements());
11460   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11461                    DAG.getConstant(0, DL, MVT::i64));
11462   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11463                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11464   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11465   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11466 
11467   // Now combine the parts back together so we still have a single result
11468   // like the combiner expects.
11469   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11470 }
11471 
11472 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11473                                SDValue SplatVal, unsigned NumVecElts) {
11474   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11475   unsigned OrigAlignment = St.getAlignment();
11476   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11477 
11478   // Create scalar stores. This is at least as good as the code sequence for a
11479   // split unaligned store which is a dup.s, ext.b, and two stores.
11480   // Most of the time the three stores should be replaced by store pair
11481   // instructions (stp).
11482   SDLoc DL(&St);
11483   SDValue BasePtr = St.getBasePtr();
11484   uint64_t BaseOffset = 0;
11485 
11486   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11487   SDValue NewST1 =
11488       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11489                    OrigAlignment, St.getMemOperand()->getFlags());
11490 
11491   // As this in ISel, we will not merge this add which may degrade results.
11492   if (BasePtr->getOpcode() == ISD::ADD &&
11493       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11494     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11495     BasePtr = BasePtr->getOperand(0);
11496   }
11497 
11498   unsigned Offset = EltOffset;
11499   while (--NumVecElts) {
11500     unsigned Alignment = MinAlign(OrigAlignment, Offset);
11501     SDValue OffsetPtr =
11502         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11503                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11504     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11505                           PtrInfo.getWithOffset(Offset), Alignment,
11506                           St.getMemOperand()->getFlags());
11507     Offset += EltOffset;
11508   }
11509   return NewST1;
11510 }
11511 
11512 // Returns an SVE type that ContentTy can be trivially sign or zero extended
11513 // into.
11514 static MVT getSVEContainerType(EVT ContentTy) {
11515   assert(ContentTy.isSimple() && "No SVE containers for extended types");
11516 
11517   switch (ContentTy.getSimpleVT().SimpleTy) {
11518   default:
11519     llvm_unreachable("No known SVE container for this MVT type");
11520   case MVT::nxv2i8:
11521   case MVT::nxv2i16:
11522   case MVT::nxv2i32:
11523   case MVT::nxv2i64:
11524   case MVT::nxv2f32:
11525   case MVT::nxv2f64:
11526     return MVT::nxv2i64;
11527   case MVT::nxv4i8:
11528   case MVT::nxv4i16:
11529   case MVT::nxv4i32:
11530   case MVT::nxv4f32:
11531     return MVT::nxv4i32;
11532   case MVT::nxv8i8:
11533   case MVT::nxv8i16:
11534   case MVT::nxv8f16:
11535     return MVT::nxv8i16;
11536   case MVT::nxv16i8:
11537     return MVT::nxv16i8;
11538   }
11539 }
11540 
11541 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG) {
11542   SDLoc DL(N);
11543   EVT VT = N->getValueType(0);
11544   EVT PtrTy = N->getOperand(3).getValueType();
11545 
11546   EVT LoadVT = VT;
11547   if (VT.isFloatingPoint())
11548     LoadVT = VT.changeTypeToInteger();
11549 
11550   auto *MINode = cast<MemIntrinsicSDNode>(N);
11551   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11552   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11553                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11554                                 MINode->getOperand(2), PassThru,
11555                                 MINode->getMemoryVT(), MINode->getMemOperand(),
11556                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11557 
11558    if (VT.isFloatingPoint()) {
11559      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11560      return DAG.getMergeValues(Ops, DL);
11561    }
11562 
11563   return L;
11564 }
11565 
11566 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
11567   SDLoc DL(N);
11568 
11569   SDValue Data = N->getOperand(2);
11570   EVT DataVT = Data.getValueType();
11571   EVT PtrTy = N->getOperand(4).getValueType();
11572 
11573   if (DataVT.isFloatingPoint())
11574     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11575 
11576   auto *MINode = cast<MemIntrinsicSDNode>(N);
11577   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11578                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11579                             MINode->getMemoryVT(), MINode->getMemOperand(),
11580                             ISD::UNINDEXED, false, false);
11581 }
11582 
11583 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
11584   SDLoc DL(N);
11585   EVT VT = N->getValueType(0);
11586 
11587   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
11588     return SDValue();
11589 
11590   EVT ContainerVT = VT;
11591   if (ContainerVT.isInteger())
11592     ContainerVT = getSVEContainerType(ContainerVT);
11593 
11594   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
11595   SDValue Ops[] = { N->getOperand(0), // Chain
11596                     N->getOperand(2), // Pg
11597                     N->getOperand(3), // Base
11598                     DAG.getValueType(VT) };
11599 
11600   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
11601   SDValue LoadChain = SDValue(Load.getNode(), 1);
11602 
11603   if (ContainerVT.isInteger() && (VT != ContainerVT))
11604     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
11605 
11606   return DAG.getMergeValues({ Load, LoadChain }, DL);
11607 }
11608 
11609 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
11610 /// load store optimizer pass will merge them to store pair stores.  This should
11611 /// be better than a movi to create the vector zero followed by a vector store
11612 /// if the zero constant is not re-used, since one instructions and one register
11613 /// live range will be removed.
11614 ///
11615 /// For example, the final generated code should be:
11616 ///
11617 ///   stp xzr, xzr, [x0]
11618 ///
11619 /// instead of:
11620 ///
11621 ///   movi v0.2d, #0
11622 ///   str q0, [x0]
11623 ///
11624 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11625   SDValue StVal = St.getValue();
11626   EVT VT = StVal.getValueType();
11627 
11628   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11629   // 2, 3 or 4 i32 elements.
11630   int NumVecElts = VT.getVectorNumElements();
11631   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11632          VT.getVectorElementType().getSizeInBits() == 64) ||
11633         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11634          VT.getVectorElementType().getSizeInBits() == 32)))
11635     return SDValue();
11636 
11637   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11638     return SDValue();
11639 
11640   // If the zero constant has more than one use then the vector store could be
11641   // better since the constant mov will be amortized and stp q instructions
11642   // should be able to be formed.
11643   if (!StVal.hasOneUse())
11644     return SDValue();
11645 
11646   // If the store is truncating then it's going down to i16 or smaller, which
11647   // means it can be implemented in a single store anyway.
11648   if (St.isTruncatingStore())
11649     return SDValue();
11650 
11651   // If the immediate offset of the address operand is too large for the stp
11652   // instruction, then bail out.
11653   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11654     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11655     if (Offset < -512 || Offset > 504)
11656       return SDValue();
11657   }
11658 
11659   for (int I = 0; I < NumVecElts; ++I) {
11660     SDValue EltVal = StVal.getOperand(I);
11661     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11662       return SDValue();
11663   }
11664 
11665   // Use a CopyFromReg WZR/XZR here to prevent
11666   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11667   SDLoc DL(&St);
11668   unsigned ZeroReg;
11669   EVT ZeroVT;
11670   if (VT.getVectorElementType().getSizeInBits() == 32) {
11671     ZeroReg = AArch64::WZR;
11672     ZeroVT = MVT::i32;
11673   } else {
11674     ZeroReg = AArch64::XZR;
11675     ZeroVT = MVT::i64;
11676   }
11677   SDValue SplatVal =
11678       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11679   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11680 }
11681 
11682 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11683 /// value. The load store optimizer pass will merge them to store pair stores.
11684 /// This has better performance than a splat of the scalar followed by a split
11685 /// vector store. Even if the stores are not merged it is four stores vs a dup,
11686 /// followed by an ext.b and two stores.
11687 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11688   SDValue StVal = St.getValue();
11689   EVT VT = StVal.getValueType();
11690 
11691   // Don't replace floating point stores, they possibly won't be transformed to
11692   // stp because of the store pair suppress pass.
11693   if (VT.isFloatingPoint())
11694     return SDValue();
11695 
11696   // We can express a splat as store pair(s) for 2 or 4 elements.
11697   unsigned NumVecElts = VT.getVectorNumElements();
11698   if (NumVecElts != 4 && NumVecElts != 2)
11699     return SDValue();
11700 
11701   // If the store is truncating then it's going down to i16 or smaller, which
11702   // means it can be implemented in a single store anyway.
11703   if (St.isTruncatingStore())
11704     return SDValue();
11705 
11706   // Check that this is a splat.
11707   // Make sure that each of the relevant vector element locations are inserted
11708   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11709   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11710   SDValue SplatVal;
11711   for (unsigned I = 0; I < NumVecElts; ++I) {
11712     // Check for insert vector elements.
11713     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11714       return SDValue();
11715 
11716     // Check that same value is inserted at each vector element.
11717     if (I == 0)
11718       SplatVal = StVal.getOperand(1);
11719     else if (StVal.getOperand(1) != SplatVal)
11720       return SDValue();
11721 
11722     // Check insert element index.
11723     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11724     if (!CIndex)
11725       return SDValue();
11726     uint64_t IndexVal = CIndex->getZExtValue();
11727     if (IndexVal >= NumVecElts)
11728       return SDValue();
11729     IndexNotInserted.reset(IndexVal);
11730 
11731     StVal = StVal.getOperand(0);
11732   }
11733   // Check that all vector element locations were inserted to.
11734   if (IndexNotInserted.any())
11735       return SDValue();
11736 
11737   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11738 }
11739 
11740 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11741                            SelectionDAG &DAG,
11742                            const AArch64Subtarget *Subtarget) {
11743 
11744   StoreSDNode *S = cast<StoreSDNode>(N);
11745   if (S->isVolatile() || S->isIndexed())
11746     return SDValue();
11747 
11748   SDValue StVal = S->getValue();
11749   EVT VT = StVal.getValueType();
11750   if (!VT.isVector())
11751     return SDValue();
11752 
11753   // If we get a splat of zeros, convert this vector store to a store of
11754   // scalars. They will be merged into store pairs of xzr thereby removing one
11755   // instruction and one register.
11756   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11757     return ReplacedZeroSplat;
11758 
11759   // FIXME: The logic for deciding if an unaligned store should be split should
11760   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11761   // a call to that function here.
11762 
11763   if (!Subtarget->isMisaligned128StoreSlow())
11764     return SDValue();
11765 
11766   // Don't split at -Oz.
11767   if (DAG.getMachineFunction().getFunction().hasMinSize())
11768     return SDValue();
11769 
11770   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11771   // those up regresses performance on micro-benchmarks and olden/bh.
11772   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11773     return SDValue();
11774 
11775   // Split unaligned 16B stores. They are terrible for performance.
11776   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11777   // extensions can use this to mark that it does not want splitting to happen
11778   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11779   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11780   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11781       S->getAlignment() <= 2)
11782     return SDValue();
11783 
11784   // If we get a splat of a scalar convert this vector store to a store of
11785   // scalars. They will be merged into store pairs thereby removing two
11786   // instructions.
11787   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11788     return ReplacedSplat;
11789 
11790   SDLoc DL(S);
11791 
11792   // Split VT into two.
11793   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11794   unsigned NumElts = HalfVT.getVectorNumElements();
11795   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11796                                    DAG.getConstant(0, DL, MVT::i64));
11797   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11798                                    DAG.getConstant(NumElts, DL, MVT::i64));
11799   SDValue BasePtr = S->getBasePtr();
11800   SDValue NewST1 =
11801       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11802                    S->getAlignment(), S->getMemOperand()->getFlags());
11803   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11804                                   DAG.getConstant(8, DL, MVT::i64));
11805   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11806                       S->getPointerInfo(), S->getAlignment(),
11807                       S->getMemOperand()->getFlags());
11808 }
11809 
11810 /// Target-specific DAG combine function for post-increment LD1 (lane) and
11811 /// post-increment LD1R.
11812 static SDValue performPostLD1Combine(SDNode *N,
11813                                      TargetLowering::DAGCombinerInfo &DCI,
11814                                      bool IsLaneOp) {
11815   if (DCI.isBeforeLegalizeOps())
11816     return SDValue();
11817 
11818   SelectionDAG &DAG = DCI.DAG;
11819   EVT VT = N->getValueType(0);
11820 
11821   unsigned LoadIdx = IsLaneOp ? 1 : 0;
11822   SDNode *LD = N->getOperand(LoadIdx).getNode();
11823   // If it is not LOAD, can not do such combine.
11824   if (LD->getOpcode() != ISD::LOAD)
11825     return SDValue();
11826 
11827   // The vector lane must be a constant in the LD1LANE opcode.
11828   SDValue Lane;
11829   if (IsLaneOp) {
11830     Lane = N->getOperand(2);
11831     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11832     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11833       return SDValue();
11834   }
11835 
11836   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11837   EVT MemVT = LoadSDN->getMemoryVT();
11838   // Check if memory operand is the same type as the vector element.
11839   if (MemVT != VT.getVectorElementType())
11840     return SDValue();
11841 
11842   // Check if there are other uses. If so, do not combine as it will introduce
11843   // an extra load.
11844   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11845        ++UI) {
11846     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11847       continue;
11848     if (*UI != N)
11849       return SDValue();
11850   }
11851 
11852   SDValue Addr = LD->getOperand(1);
11853   SDValue Vector = N->getOperand(0);
11854   // Search for a use of the address operand that is an increment.
11855   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11856        Addr.getNode()->use_end(); UI != UE; ++UI) {
11857     SDNode *User = *UI;
11858     if (User->getOpcode() != ISD::ADD
11859         || UI.getUse().getResNo() != Addr.getResNo())
11860       continue;
11861 
11862     // If the increment is a constant, it must match the memory ref size.
11863     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11864     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11865       uint32_t IncVal = CInc->getZExtValue();
11866       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11867       if (IncVal != NumBytes)
11868         continue;
11869       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11870     }
11871 
11872     // To avoid cycle construction make sure that neither the load nor the add
11873     // are predecessors to each other or the Vector.
11874     SmallPtrSet<const SDNode *, 32> Visited;
11875     SmallVector<const SDNode *, 16> Worklist;
11876     Visited.insert(Addr.getNode());
11877     Worklist.push_back(User);
11878     Worklist.push_back(LD);
11879     Worklist.push_back(Vector.getNode());
11880     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11881         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11882       continue;
11883 
11884     SmallVector<SDValue, 8> Ops;
11885     Ops.push_back(LD->getOperand(0));  // Chain
11886     if (IsLaneOp) {
11887       Ops.push_back(Vector);           // The vector to be inserted
11888       Ops.push_back(Lane);             // The lane to be inserted in the vector
11889     }
11890     Ops.push_back(Addr);
11891     Ops.push_back(Inc);
11892 
11893     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11894     SDVTList SDTys = DAG.getVTList(Tys);
11895     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11896     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11897                                            MemVT,
11898                                            LoadSDN->getMemOperand());
11899 
11900     // Update the uses.
11901     SDValue NewResults[] = {
11902         SDValue(LD, 0),            // The result of load
11903         SDValue(UpdN.getNode(), 2) // Chain
11904     };
11905     DCI.CombineTo(LD, NewResults);
11906     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
11907     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
11908 
11909     break;
11910   }
11911   return SDValue();
11912 }
11913 
11914 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11915 /// address translation.
11916 static bool performTBISimplification(SDValue Addr,
11917                                      TargetLowering::DAGCombinerInfo &DCI,
11918                                      SelectionDAG &DAG) {
11919   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11920   KnownBits Known;
11921   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11922                                         !DCI.isBeforeLegalizeOps());
11923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11924   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11925     DCI.CommitTargetLoweringOpt(TLO);
11926     return true;
11927   }
11928   return false;
11929 }
11930 
11931 static SDValue performSTORECombine(SDNode *N,
11932                                    TargetLowering::DAGCombinerInfo &DCI,
11933                                    SelectionDAG &DAG,
11934                                    const AArch64Subtarget *Subtarget) {
11935   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11936     return Split;
11937 
11938   if (Subtarget->supportsAddressTopByteIgnored() &&
11939       performTBISimplification(N->getOperand(2), DCI, DAG))
11940     return SDValue(N, 0);
11941 
11942   return SDValue();
11943 }
11944 
11945 
11946 /// Target-specific DAG combine function for NEON load/store intrinsics
11947 /// to merge base address updates.
11948 static SDValue performNEONPostLDSTCombine(SDNode *N,
11949                                           TargetLowering::DAGCombinerInfo &DCI,
11950                                           SelectionDAG &DAG) {
11951   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11952     return SDValue();
11953 
11954   unsigned AddrOpIdx = N->getNumOperands() - 1;
11955   SDValue Addr = N->getOperand(AddrOpIdx);
11956 
11957   // Search for a use of the address operand that is an increment.
11958   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11959        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11960     SDNode *User = *UI;
11961     if (User->getOpcode() != ISD::ADD ||
11962         UI.getUse().getResNo() != Addr.getResNo())
11963       continue;
11964 
11965     // Check that the add is independent of the load/store.  Otherwise, folding
11966     // it would create a cycle.
11967     SmallPtrSet<const SDNode *, 32> Visited;
11968     SmallVector<const SDNode *, 16> Worklist;
11969     Visited.insert(Addr.getNode());
11970     Worklist.push_back(N);
11971     Worklist.push_back(User);
11972     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11973         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11974       continue;
11975 
11976     // Find the new opcode for the updating load/store.
11977     bool IsStore = false;
11978     bool IsLaneOp = false;
11979     bool IsDupOp = false;
11980     unsigned NewOpc = 0;
11981     unsigned NumVecs = 0;
11982     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11983     switch (IntNo) {
11984     default: llvm_unreachable("unexpected intrinsic for Neon base update");
11985     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11986       NumVecs = 2; break;
11987     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11988       NumVecs = 3; break;
11989     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11990       NumVecs = 4; break;
11991     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11992       NumVecs = 2; IsStore = true; break;
11993     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11994       NumVecs = 3; IsStore = true; break;
11995     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11996       NumVecs = 4; IsStore = true; break;
11997     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
11998       NumVecs = 2; break;
11999     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
12000       NumVecs = 3; break;
12001     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
12002       NumVecs = 4; break;
12003     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
12004       NumVecs = 2; IsStore = true; break;
12005     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
12006       NumVecs = 3; IsStore = true; break;
12007     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
12008       NumVecs = 4; IsStore = true; break;
12009     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
12010       NumVecs = 2; IsDupOp = true; break;
12011     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
12012       NumVecs = 3; IsDupOp = true; break;
12013     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
12014       NumVecs = 4; IsDupOp = true; break;
12015     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
12016       NumVecs = 2; IsLaneOp = true; break;
12017     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
12018       NumVecs = 3; IsLaneOp = true; break;
12019     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
12020       NumVecs = 4; IsLaneOp = true; break;
12021     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
12022       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
12023     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
12024       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
12025     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
12026       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
12027     }
12028 
12029     EVT VecTy;
12030     if (IsStore)
12031       VecTy = N->getOperand(2).getValueType();
12032     else
12033       VecTy = N->getValueType(0);
12034 
12035     // If the increment is a constant, it must match the memory ref size.
12036     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12037     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12038       uint32_t IncVal = CInc->getZExtValue();
12039       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12040       if (IsLaneOp || IsDupOp)
12041         NumBytes /= VecTy.getVectorNumElements();
12042       if (IncVal != NumBytes)
12043         continue;
12044       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12045     }
12046     SmallVector<SDValue, 8> Ops;
12047     Ops.push_back(N->getOperand(0)); // Incoming chain
12048     // Load lane and store have vector list as input.
12049     if (IsLaneOp || IsStore)
12050       for (unsigned i = 2; i < AddrOpIdx; ++i)
12051         Ops.push_back(N->getOperand(i));
12052     Ops.push_back(Addr); // Base register
12053     Ops.push_back(Inc);
12054 
12055     // Return Types.
12056     EVT Tys[6];
12057     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
12058     unsigned n;
12059     for (n = 0; n < NumResultVecs; ++n)
12060       Tys[n] = VecTy;
12061     Tys[n++] = MVT::i64;  // Type of write back register
12062     Tys[n] = MVT::Other;  // Type of the chain
12063     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
12064 
12065     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
12066     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
12067                                            MemInt->getMemoryVT(),
12068                                            MemInt->getMemOperand());
12069 
12070     // Update the uses.
12071     std::vector<SDValue> NewResults;
12072     for (unsigned i = 0; i < NumResultVecs; ++i) {
12073       NewResults.push_back(SDValue(UpdN.getNode(), i));
12074     }
12075     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
12076     DCI.CombineTo(N, NewResults);
12077     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12078 
12079     break;
12080   }
12081   return SDValue();
12082 }
12083 
12084 // Checks to see if the value is the prescribed width and returns information
12085 // about its extension mode.
12086 static
12087 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
12088   ExtType = ISD::NON_EXTLOAD;
12089   switch(V.getNode()->getOpcode()) {
12090   default:
12091     return false;
12092   case ISD::LOAD: {
12093     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
12094     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
12095        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
12096       ExtType = LoadNode->getExtensionType();
12097       return true;
12098     }
12099     return false;
12100   }
12101   case ISD::AssertSext: {
12102     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12103     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12104        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12105       ExtType = ISD::SEXTLOAD;
12106       return true;
12107     }
12108     return false;
12109   }
12110   case ISD::AssertZext: {
12111     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12112     if ((TypeNode->getVT() == MVT::i8 && width == 8)
12113        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12114       ExtType = ISD::ZEXTLOAD;
12115       return true;
12116     }
12117     return false;
12118   }
12119   case ISD::Constant:
12120   case ISD::TargetConstant: {
12121     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
12122            1LL << (width - 1);
12123   }
12124   }
12125 
12126   return true;
12127 }
12128 
12129 // This function does a whole lot of voodoo to determine if the tests are
12130 // equivalent without and with a mask. Essentially what happens is that given a
12131 // DAG resembling:
12132 //
12133 //  +-------------+ +-------------+ +-------------+ +-------------+
12134 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
12135 //  +-------------+ +-------------+ +-------------+ +-------------+
12136 //           |           |           |               |
12137 //           V           V           |    +----------+
12138 //          +-------------+  +----+  |    |
12139 //          |     ADD     |  |0xff|  |    |
12140 //          +-------------+  +----+  |    |
12141 //                  |           |    |    |
12142 //                  V           V    |    |
12143 //                 +-------------+   |    |
12144 //                 |     AND     |   |    |
12145 //                 +-------------+   |    |
12146 //                      |            |    |
12147 //                      +-----+      |    |
12148 //                            |      |    |
12149 //                            V      V    V
12150 //                           +-------------+
12151 //                           |     CMP     |
12152 //                           +-------------+
12153 //
12154 // The AND node may be safely removed for some combinations of inputs. In
12155 // particular we need to take into account the extension type of the Input,
12156 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
12157 // width of the input (this can work for any width inputs, the above graph is
12158 // specific to 8 bits.
12159 //
12160 // The specific equations were worked out by generating output tables for each
12161 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
12162 // problem was simplified by working with 4 bit inputs, which means we only
12163 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
12164 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
12165 // patterns present in both extensions (0,7). For every distinct set of
12166 // AddConstant and CompConstants bit patterns we can consider the masked and
12167 // unmasked versions to be equivalent if the result of this function is true for
12168 // all 16 distinct bit patterns of for the current extension type of Input (w0).
12169 //
12170 //   sub      w8, w0, w1
12171 //   and      w10, w8, #0x0f
12172 //   cmp      w8, w2
12173 //   cset     w9, AArch64CC
12174 //   cmp      w10, w2
12175 //   cset     w11, AArch64CC
12176 //   cmp      w9, w11
12177 //   cset     w0, eq
12178 //   ret
12179 //
12180 // Since the above function shows when the outputs are equivalent it defines
12181 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
12182 // would be expensive to run during compiles. The equations below were written
12183 // in a test harness that confirmed they gave equivalent outputs to the above
12184 // for all inputs function, so they can be used determine if the removal is
12185 // legal instead.
12186 //
12187 // isEquivalentMaskless() is the code for testing if the AND can be removed
12188 // factored out of the DAG recognition as the DAG can take several forms.
12189 
12190 static bool isEquivalentMaskless(unsigned CC, unsigned width,
12191                                  ISD::LoadExtType ExtType, int AddConstant,
12192                                  int CompConstant) {
12193   // By being careful about our equations and only writing the in term
12194   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
12195   // make them generally applicable to all bit widths.
12196   int MaxUInt = (1 << width);
12197 
12198   // For the purposes of these comparisons sign extending the type is
12199   // equivalent to zero extending the add and displacing it by half the integer
12200   // width. Provided we are careful and make sure our equations are valid over
12201   // the whole range we can just adjust the input and avoid writing equations
12202   // for sign extended inputs.
12203   if (ExtType == ISD::SEXTLOAD)
12204     AddConstant -= (1 << (width-1));
12205 
12206   switch(CC) {
12207   case AArch64CC::LE:
12208   case AArch64CC::GT:
12209     if ((AddConstant == 0) ||
12210         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
12211         (AddConstant >= 0 && CompConstant < 0) ||
12212         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
12213       return true;
12214     break;
12215   case AArch64CC::LT:
12216   case AArch64CC::GE:
12217     if ((AddConstant == 0) ||
12218         (AddConstant >= 0 && CompConstant <= 0) ||
12219         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
12220       return true;
12221     break;
12222   case AArch64CC::HI:
12223   case AArch64CC::LS:
12224     if ((AddConstant >= 0 && CompConstant < 0) ||
12225        (AddConstant <= 0 && CompConstant >= -1 &&
12226         CompConstant < AddConstant + MaxUInt))
12227       return true;
12228    break;
12229   case AArch64CC::PL:
12230   case AArch64CC::MI:
12231     if ((AddConstant == 0) ||
12232         (AddConstant > 0 && CompConstant <= 0) ||
12233         (AddConstant < 0 && CompConstant <= AddConstant))
12234       return true;
12235     break;
12236   case AArch64CC::LO:
12237   case AArch64CC::HS:
12238     if ((AddConstant >= 0 && CompConstant <= 0) ||
12239         (AddConstant <= 0 && CompConstant >= 0 &&
12240          CompConstant <= AddConstant + MaxUInt))
12241       return true;
12242     break;
12243   case AArch64CC::EQ:
12244   case AArch64CC::NE:
12245     if ((AddConstant > 0 && CompConstant < 0) ||
12246         (AddConstant < 0 && CompConstant >= 0 &&
12247          CompConstant < AddConstant + MaxUInt) ||
12248         (AddConstant >= 0 && CompConstant >= 0 &&
12249          CompConstant >= AddConstant) ||
12250         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
12251       return true;
12252     break;
12253   case AArch64CC::VS:
12254   case AArch64CC::VC:
12255   case AArch64CC::AL:
12256   case AArch64CC::NV:
12257     return true;
12258   case AArch64CC::Invalid:
12259     break;
12260   }
12261 
12262   return false;
12263 }
12264 
12265 static
12266 SDValue performCONDCombine(SDNode *N,
12267                            TargetLowering::DAGCombinerInfo &DCI,
12268                            SelectionDAG &DAG, unsigned CCIndex,
12269                            unsigned CmpIndex) {
12270   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
12271   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
12272   unsigned CondOpcode = SubsNode->getOpcode();
12273 
12274   if (CondOpcode != AArch64ISD::SUBS)
12275     return SDValue();
12276 
12277   // There is a SUBS feeding this condition. Is it fed by a mask we can
12278   // use?
12279 
12280   SDNode *AndNode = SubsNode->getOperand(0).getNode();
12281   unsigned MaskBits = 0;
12282 
12283   if (AndNode->getOpcode() != ISD::AND)
12284     return SDValue();
12285 
12286   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
12287     uint32_t CNV = CN->getZExtValue();
12288     if (CNV == 255)
12289       MaskBits = 8;
12290     else if (CNV == 65535)
12291       MaskBits = 16;
12292   }
12293 
12294   if (!MaskBits)
12295     return SDValue();
12296 
12297   SDValue AddValue = AndNode->getOperand(0);
12298 
12299   if (AddValue.getOpcode() != ISD::ADD)
12300     return SDValue();
12301 
12302   // The basic dag structure is correct, grab the inputs and validate them.
12303 
12304   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
12305   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
12306   SDValue SubsInputValue = SubsNode->getOperand(1);
12307 
12308   // The mask is present and the provenance of all the values is a smaller type,
12309   // lets see if the mask is superfluous.
12310 
12311   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
12312       !isa<ConstantSDNode>(SubsInputValue.getNode()))
12313     return SDValue();
12314 
12315   ISD::LoadExtType ExtType;
12316 
12317   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
12318       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
12319       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
12320     return SDValue();
12321 
12322   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
12323                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
12324                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
12325     return SDValue();
12326 
12327   // The AND is not necessary, remove it.
12328 
12329   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
12330                                SubsNode->getValueType(1));
12331   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
12332 
12333   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
12334   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
12335 
12336   return SDValue(N, 0);
12337 }
12338 
12339 // Optimize compare with zero and branch.
12340 static SDValue performBRCONDCombine(SDNode *N,
12341                                     TargetLowering::DAGCombinerInfo &DCI,
12342                                     SelectionDAG &DAG) {
12343   MachineFunction &MF = DAG.getMachineFunction();
12344   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
12345   // will not be produced, as they are conditional branch instructions that do
12346   // not set flags.
12347   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
12348     return SDValue();
12349 
12350   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
12351     N = NV.getNode();
12352   SDValue Chain = N->getOperand(0);
12353   SDValue Dest = N->getOperand(1);
12354   SDValue CCVal = N->getOperand(2);
12355   SDValue Cmp = N->getOperand(3);
12356 
12357   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
12358   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
12359   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
12360     return SDValue();
12361 
12362   unsigned CmpOpc = Cmp.getOpcode();
12363   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
12364     return SDValue();
12365 
12366   // Only attempt folding if there is only one use of the flag and no use of the
12367   // value.
12368   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
12369     return SDValue();
12370 
12371   SDValue LHS = Cmp.getOperand(0);
12372   SDValue RHS = Cmp.getOperand(1);
12373 
12374   assert(LHS.getValueType() == RHS.getValueType() &&
12375          "Expected the value type to be the same for both operands!");
12376   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
12377     return SDValue();
12378 
12379   if (isNullConstant(LHS))
12380     std::swap(LHS, RHS);
12381 
12382   if (!isNullConstant(RHS))
12383     return SDValue();
12384 
12385   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
12386       LHS.getOpcode() == ISD::SRL)
12387     return SDValue();
12388 
12389   // Fold the compare into the branch instruction.
12390   SDValue BR;
12391   if (CC == AArch64CC::EQ)
12392     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12393   else
12394     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12395 
12396   // Do not add new nodes to DAG combiner worklist.
12397   DCI.CombineTo(N, BR, false);
12398 
12399   return SDValue();
12400 }
12401 
12402 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
12403 // as well as whether the test should be inverted.  This code is required to
12404 // catch these cases (as opposed to standard dag combines) because
12405 // AArch64ISD::TBZ is matched during legalization.
12406 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12407                                  SelectionDAG &DAG) {
12408 
12409   if (!Op->hasOneUse())
12410     return Op;
12411 
12412   // We don't handle undef/constant-fold cases below, as they should have
12413   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12414   // etc.)
12415 
12416   // (tbz (trunc x), b) -> (tbz x, b)
12417   // This case is just here to enable more of the below cases to be caught.
12418   if (Op->getOpcode() == ISD::TRUNCATE &&
12419       Bit < Op->getValueType(0).getSizeInBits()) {
12420     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12421   }
12422 
12423   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12424   if (Op->getOpcode() == ISD::ANY_EXTEND &&
12425       Bit < Op->getOperand(0).getValueSizeInBits()) {
12426     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12427   }
12428 
12429   if (Op->getNumOperands() != 2)
12430     return Op;
12431 
12432   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12433   if (!C)
12434     return Op;
12435 
12436   switch (Op->getOpcode()) {
12437   default:
12438     return Op;
12439 
12440   // (tbz (and x, m), b) -> (tbz x, b)
12441   case ISD::AND:
12442     if ((C->getZExtValue() >> Bit) & 1)
12443       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12444     return Op;
12445 
12446   // (tbz (shl x, c), b) -> (tbz x, b-c)
12447   case ISD::SHL:
12448     if (C->getZExtValue() <= Bit &&
12449         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12450       Bit = Bit - C->getZExtValue();
12451       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12452     }
12453     return Op;
12454 
12455   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12456   case ISD::SRA:
12457     Bit = Bit + C->getZExtValue();
12458     if (Bit >= Op->getValueType(0).getSizeInBits())
12459       Bit = Op->getValueType(0).getSizeInBits() - 1;
12460     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12461 
12462   // (tbz (srl x, c), b) -> (tbz x, b+c)
12463   case ISD::SRL:
12464     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12465       Bit = Bit + C->getZExtValue();
12466       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12467     }
12468     return Op;
12469 
12470   // (tbz (xor x, -1), b) -> (tbnz x, b)
12471   case ISD::XOR:
12472     if ((C->getZExtValue() >> Bit) & 1)
12473       Invert = !Invert;
12474     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12475   }
12476 }
12477 
12478 // Optimize test single bit zero/non-zero and branch.
12479 static SDValue performTBZCombine(SDNode *N,
12480                                  TargetLowering::DAGCombinerInfo &DCI,
12481                                  SelectionDAG &DAG) {
12482   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12483   bool Invert = false;
12484   SDValue TestSrc = N->getOperand(1);
12485   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12486 
12487   if (TestSrc == NewTestSrc)
12488     return SDValue();
12489 
12490   unsigned NewOpc = N->getOpcode();
12491   if (Invert) {
12492     if (NewOpc == AArch64ISD::TBZ)
12493       NewOpc = AArch64ISD::TBNZ;
12494     else {
12495       assert(NewOpc == AArch64ISD::TBNZ);
12496       NewOpc = AArch64ISD::TBZ;
12497     }
12498   }
12499 
12500   SDLoc DL(N);
12501   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12502                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12503 }
12504 
12505 // vselect (v1i1 setcc) ->
12506 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
12507 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12508 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12509 // such VSELECT.
12510 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12511   SDValue N0 = N->getOperand(0);
12512   EVT CCVT = N0.getValueType();
12513 
12514   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12515       CCVT.getVectorElementType() != MVT::i1)
12516     return SDValue();
12517 
12518   EVT ResVT = N->getValueType(0);
12519   EVT CmpVT = N0.getOperand(0).getValueType();
12520   // Only combine when the result type is of the same size as the compared
12521   // operands.
12522   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12523     return SDValue();
12524 
12525   SDValue IfTrue = N->getOperand(1);
12526   SDValue IfFalse = N->getOperand(2);
12527   SDValue SetCC =
12528       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12529                    N0.getOperand(0), N0.getOperand(1),
12530                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
12531   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12532                      IfTrue, IfFalse);
12533 }
12534 
12535 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12536 /// the compare-mask instructions rather than going via NZCV, even if LHS and
12537 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
12538 /// with a vector one followed by a DUP shuffle on the result.
12539 static SDValue performSelectCombine(SDNode *N,
12540                                     TargetLowering::DAGCombinerInfo &DCI) {
12541   SelectionDAG &DAG = DCI.DAG;
12542   SDValue N0 = N->getOperand(0);
12543   EVT ResVT = N->getValueType(0);
12544 
12545   if (N0.getOpcode() != ISD::SETCC)
12546     return SDValue();
12547 
12548   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12549   // scalar SetCCResultType. We also don't expect vectors, because we assume
12550   // that selects fed by vector SETCCs are canonicalized to VSELECT.
12551   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12552          "Scalar-SETCC feeding SELECT has unexpected result type!");
12553 
12554   // If NumMaskElts == 0, the comparison is larger than select result. The
12555   // largest real NEON comparison is 64-bits per lane, which means the result is
12556   // at most 32-bits and an illegal vector. Just bail out for now.
12557   EVT SrcVT = N0.getOperand(0).getValueType();
12558 
12559   // Don't try to do this optimization when the setcc itself has i1 operands.
12560   // There are no legal vectors of i1, so this would be pointless.
12561   if (SrcVT == MVT::i1)
12562     return SDValue();
12563 
12564   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12565   if (!ResVT.isVector() || NumMaskElts == 0)
12566     return SDValue();
12567 
12568   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12569   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12570 
12571   // Also bail out if the vector CCVT isn't the same size as ResVT.
12572   // This can happen if the SETCC operand size doesn't divide the ResVT size
12573   // (e.g., f64 vs v3f32).
12574   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12575     return SDValue();
12576 
12577   // Make sure we didn't create illegal types, if we're not supposed to.
12578   assert(DCI.isBeforeLegalize() ||
12579          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12580 
12581   // First perform a vector comparison, where lane 0 is the one we're interested
12582   // in.
12583   SDLoc DL(N0);
12584   SDValue LHS =
12585       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12586   SDValue RHS =
12587       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12588   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12589 
12590   // Now duplicate the comparison mask we want across all other lanes.
12591   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12592   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12593   Mask = DAG.getNode(ISD::BITCAST, DL,
12594                      ResVT.changeVectorElementTypeToInteger(), Mask);
12595 
12596   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12597 }
12598 
12599 /// Get rid of unnecessary NVCASTs (that don't change the type).
12600 static SDValue performNVCASTCombine(SDNode *N) {
12601   if (N->getValueType(0) == N->getOperand(0).getValueType())
12602     return N->getOperand(0);
12603 
12604   return SDValue();
12605 }
12606 
12607 // If all users of the globaladdr are of the form (globaladdr + constant), find
12608 // the smallest constant, fold it into the globaladdr's offset and rewrite the
12609 // globaladdr as (globaladdr + constant) - constant.
12610 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12611                                            const AArch64Subtarget *Subtarget,
12612                                            const TargetMachine &TM) {
12613   auto *GN = cast<GlobalAddressSDNode>(N);
12614   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12615       AArch64II::MO_NO_FLAG)
12616     return SDValue();
12617 
12618   uint64_t MinOffset = -1ull;
12619   for (SDNode *N : GN->uses()) {
12620     if (N->getOpcode() != ISD::ADD)
12621       return SDValue();
12622     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12623     if (!C)
12624       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12625     if (!C)
12626       return SDValue();
12627     MinOffset = std::min(MinOffset, C->getZExtValue());
12628   }
12629   uint64_t Offset = MinOffset + GN->getOffset();
12630 
12631   // Require that the new offset is larger than the existing one. Otherwise, we
12632   // can end up oscillating between two possible DAGs, for example,
12633   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12634   if (Offset <= uint64_t(GN->getOffset()))
12635     return SDValue();
12636 
12637   // Check whether folding this offset is legal. It must not go out of bounds of
12638   // the referenced object to avoid violating the code model, and must be
12639   // smaller than 2^21 because this is the largest offset expressible in all
12640   // object formats.
12641   //
12642   // This check also prevents us from folding negative offsets, which will end
12643   // up being treated in the same way as large positive ones. They could also
12644   // cause code model violations, and aren't really common enough to matter.
12645   if (Offset >= (1 << 21))
12646     return SDValue();
12647 
12648   const GlobalValue *GV = GN->getGlobal();
12649   Type *T = GV->getValueType();
12650   if (!T->isSized() ||
12651       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12652     return SDValue();
12653 
12654   SDLoc DL(GN);
12655   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12656   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12657                      DAG.getConstant(MinOffset, DL, MVT::i64));
12658 }
12659 
12660 // Turns the vector of indices into a vector of byte offstes by scaling Offset
12661 // by (BitWidth / 8).
12662 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
12663                                           SDLoc DL, unsigned BitWidth) {
12664   assert(Offset.getValueType().isScalableVector() &&
12665          "This method is only for scalable vectors of offsets");
12666 
12667   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
12668   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
12669 
12670   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
12671 }
12672 
12673 /// Check if the value of \p OffsetInBytes can be used as an immediate for
12674 /// the gather load/prefetch and scatter store instructions with vector base and
12675 /// immediate offset addressing mode:
12676 ///
12677 ///      [<Zn>.[S|D]{, #<imm>}]
12678 ///
12679 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
12680 
12681 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
12682                                                   unsigned ScalarSizeInBytes) {
12683   // The immediate is not a multiple of the scalar size.
12684   if (OffsetInBytes % ScalarSizeInBytes)
12685     return false;
12686 
12687   // The immediate is out of range.
12688   if (OffsetInBytes / ScalarSizeInBytes > 31)
12689     return false;
12690 
12691   return true;
12692 }
12693 
12694 /// Check if the value of \p Offset represents a valid immediate for the SVE
12695 /// gather load/prefetch and scatter store instructiona with vector base and
12696 /// immediate offset addressing mode:
12697 ///
12698 ///      [<Zn>.[S|D]{, #<imm>}]
12699 ///
12700 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
12701 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
12702                                            unsigned ScalarSizeInBytes) {
12703   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12704   return OffsetConst && isValidImmForSVEVecImmAddrMode(
12705                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
12706 }
12707 
12708 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
12709                                           unsigned Opcode,
12710                                           bool OnlyPackedOffsets = true) {
12711   const SDValue Src = N->getOperand(2);
12712   const EVT SrcVT = Src->getValueType(0);
12713   assert(SrcVT.isScalableVector() &&
12714          "Scatter stores are only possible for SVE vectors");
12715 
12716   SDLoc DL(N);
12717   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12718 
12719   // Make sure that source data will fit into an SVE register
12720   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12721     return SDValue();
12722 
12723   // For FPs, ACLE only supports _packed_ single and double precision types.
12724   if (SrcElVT.isFloatingPoint())
12725     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12726       return SDValue();
12727 
12728   // Depending on the addressing mode, this is either a pointer or a vector of
12729   // pointers (that fits into one register)
12730   SDValue Base = N->getOperand(4);
12731   // Depending on the addressing mode, this is either a single offset or a
12732   // vector of offsets  (that fits into one register)
12733   SDValue Offset = N->getOperand(5);
12734 
12735   // For "scalar + vector of indices", just scale the indices. This only
12736   // applies to non-temporal scatters because there's no instruction that takes
12737   // indicies.
12738   if (Opcode == AArch64ISD::SSTNT1_INDEX) {
12739     Offset =
12740         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
12741     Opcode = AArch64ISD::SSTNT1;
12742   }
12743 
12744   // In the case of non-temporal gather loads there's only one SVE instruction
12745   // per data-size: "scalar + vector", i.e.
12746   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
12747   // Since we do have intrinsics that allow the arguments to be in a different
12748   // order, we may need to swap them to match the spec.
12749   if (Opcode == AArch64ISD::SSTNT1 && Offset.getValueType().isVector())
12750       std::swap(Base, Offset);
12751 
12752   // SST1_IMM requires that the offset is an immediate that is:
12753   //    * a multiple of #SizeInBytes,
12754   //    * in the range [0, 31 x #SizeInBytes],
12755   // where #SizeInBytes is the size in bytes of the stored items. For
12756   // immediates outside that range and non-immediate scalar offsets use SST1 or
12757   // SST1_UXTW instead.
12758   if (Opcode == AArch64ISD::SST1_IMM) {
12759     if (!isValidImmForSVEVecImmAddrMode(Offset,
12760                                         SrcVT.getScalarSizeInBits() / 8)) {
12761       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12762         Opcode = AArch64ISD::SST1_UXTW;
12763       else
12764         Opcode = AArch64ISD::SST1;
12765 
12766       std::swap(Base, Offset);
12767     }
12768   }
12769 
12770   auto &TLI = DAG.getTargetLoweringInfo();
12771   if (!TLI.isTypeLegal(Base.getValueType()))
12772     return SDValue();
12773 
12774   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12775   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12776   // nxv2i64. Legalize accordingly.
12777   if (!OnlyPackedOffsets &&
12778       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12779     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12780 
12781   if (!TLI.isTypeLegal(Offset.getValueType()))
12782     return SDValue();
12783 
12784   // Source value type that is representable in hardware
12785   EVT HwSrcVt = getSVEContainerType(SrcVT);
12786 
12787   // Keep the original type of the input data to store - this is needed to be
12788   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
12789   // FP values we want the integer equivalent, so just use HwSrcVt.
12790   SDValue InputVT = DAG.getValueType(SrcVT);
12791   if (SrcVT.isFloatingPoint())
12792     InputVT = DAG.getValueType(HwSrcVt);
12793 
12794   SDVTList VTs = DAG.getVTList(MVT::Other);
12795   SDValue SrcNew;
12796 
12797   if (Src.getValueType().isFloatingPoint())
12798     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12799   else
12800     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12801 
12802   SDValue Ops[] = {N->getOperand(0), // Chain
12803                    SrcNew,
12804                    N->getOperand(3), // Pg
12805                    Base,
12806                    Offset,
12807                    InputVT};
12808 
12809   return DAG.getNode(Opcode, DL, VTs, Ops);
12810 }
12811 
12812 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
12813                                         unsigned Opcode,
12814                                         bool OnlyPackedOffsets = true) {
12815   const EVT RetVT = N->getValueType(0);
12816   assert(RetVT.isScalableVector() &&
12817          "Gather loads are only possible for SVE vectors");
12818 
12819   SDLoc DL(N);
12820 
12821   // Make sure that the loaded data will fit into an SVE register
12822   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12823     return SDValue();
12824 
12825   // Depending on the addressing mode, this is either a pointer or a vector of
12826   // pointers (that fits into one register)
12827   SDValue Base = N->getOperand(3);
12828   // Depending on the addressing mode, this is either a single offset or a
12829   // vector of offsets  (that fits into one register)
12830   SDValue Offset = N->getOperand(4);
12831 
12832   // For "scalar + vector of indices", just scale the indices. This only
12833   // applies to non-temporal gathers because there's no instruction that takes
12834   // indicies.
12835   if (Opcode == AArch64ISD::GLDNT1_INDEX) {
12836     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
12837                                         RetVT.getScalarSizeInBits());
12838     Opcode = AArch64ISD::GLDNT1;
12839   }
12840 
12841   // In the case of non-temporal gather loads there's only one SVE instruction
12842   // per data-size: "scalar + vector", i.e.
12843   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
12844   // Since we do have intrinsics that allow the arguments to be in a different
12845   // order, we may need to swap them to match the spec.
12846   if (Opcode == AArch64ISD::GLDNT1 && Offset.getValueType().isVector())
12847       std::swap(Base, Offset);
12848 
12849   // GLD{FF}1_IMM requires that the offset is an immediate that is:
12850   //    * a multiple of #SizeInBytes,
12851   //    * in the range [0, 31 x #SizeInBytes],
12852   // where #SizeInBytes is the size in bytes of the loaded items. For
12853   // immediates outside that range and non-immediate scalar offsets use GLD1 or
12854   // GLD1_UXTW instead.
12855   if (Opcode == AArch64ISD::GLD1_IMM || Opcode == AArch64ISD::GLDFF1_IMM) {
12856     if (!isValidImmForSVEVecImmAddrMode(Offset,
12857                                         RetVT.getScalarSizeInBits() / 8)) {
12858       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12859         Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1_UXTW
12860                                                   : AArch64ISD::GLDFF1_UXTW;
12861       else
12862         Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1
12863                                                   : AArch64ISD::GLDFF1;
12864 
12865       std::swap(Base, Offset);
12866     }
12867   }
12868 
12869   auto &TLI = DAG.getTargetLoweringInfo();
12870   if (!TLI.isTypeLegal(Base.getValueType()))
12871     return SDValue();
12872 
12873   // Some gather load variants allow unpacked offsets, but only as nxv2i32
12874   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12875   // nxv2i64. Legalize accordingly.
12876   if (!OnlyPackedOffsets &&
12877       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12878     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12879 
12880   // Return value type that is representable in hardware
12881   EVT HwRetVt = getSVEContainerType(RetVT);
12882 
12883   // Keep the original output value type around - this is needed to be able to
12884   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
12885   // values we want the integer equivalent, so just use HwRetVT.
12886   SDValue OutVT = DAG.getValueType(RetVT);
12887   if (RetVT.isFloatingPoint())
12888     OutVT = DAG.getValueType(HwRetVt);
12889 
12890   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12891   SDValue Ops[] = {N->getOperand(0), // Chain
12892                    N->getOperand(2), // Pg
12893                    Base, Offset, OutVT};
12894 
12895   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12896   SDValue LoadChain = SDValue(Load.getNode(), 1);
12897 
12898   if (RetVT.isInteger() && (RetVT != HwRetVt))
12899     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12900 
12901   // If the original return value was FP, bitcast accordingly. Doing it here
12902   // means that we can avoid adding TableGen patterns for FPs.
12903   if (RetVT.isFloatingPoint())
12904     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12905 
12906   return DAG.getMergeValues({Load, LoadChain}, DL);
12907 }
12908 
12909 static SDValue
12910 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12911                               SelectionDAG &DAG) {
12912   if (DCI.isBeforeLegalizeOps())
12913     return SDValue();
12914 
12915   SDValue Src = N->getOperand(0);
12916   unsigned Opc = Src->getOpcode();
12917 
12918   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12919   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12920   unsigned NewOpc;
12921   unsigned MemVTOpNum = 4;
12922   switch (Opc) {
12923   case AArch64ISD::LDNF1:
12924     NewOpc = AArch64ISD::LDNF1S;
12925     MemVTOpNum = 3;
12926     break;
12927   case AArch64ISD::LDFF1:
12928     NewOpc = AArch64ISD::LDFF1S;
12929     MemVTOpNum = 3;
12930     break;
12931   case AArch64ISD::GLD1:
12932     NewOpc = AArch64ISD::GLD1S;
12933     break;
12934   case AArch64ISD::GLD1_SCALED:
12935     NewOpc = AArch64ISD::GLD1S_SCALED;
12936     break;
12937   case AArch64ISD::GLD1_SXTW:
12938     NewOpc = AArch64ISD::GLD1S_SXTW;
12939     break;
12940   case AArch64ISD::GLD1_SXTW_SCALED:
12941     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12942     break;
12943   case AArch64ISD::GLD1_UXTW:
12944     NewOpc = AArch64ISD::GLD1S_UXTW;
12945     break;
12946   case AArch64ISD::GLD1_UXTW_SCALED:
12947     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12948     break;
12949   case AArch64ISD::GLD1_IMM:
12950     NewOpc = AArch64ISD::GLD1S_IMM;
12951     break;
12952   case AArch64ISD::GLDFF1:
12953     NewOpc = AArch64ISD::GLDFF1S;
12954     break;
12955   case AArch64ISD::GLDFF1_SCALED:
12956     NewOpc = AArch64ISD::GLDFF1S_SCALED;
12957     break;
12958   case AArch64ISD::GLDFF1_SXTW:
12959     NewOpc = AArch64ISD::GLDFF1S_SXTW;
12960     break;
12961   case AArch64ISD::GLDFF1_SXTW_SCALED:
12962     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED;
12963     break;
12964   case AArch64ISD::GLDFF1_UXTW:
12965     NewOpc = AArch64ISD::GLDFF1S_UXTW;
12966     break;
12967   case AArch64ISD::GLDFF1_UXTW_SCALED:
12968     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED;
12969     break;
12970   case AArch64ISD::GLDFF1_IMM:
12971     NewOpc = AArch64ISD::GLDFF1S_IMM;
12972     break;
12973   case AArch64ISD::GLDNT1:
12974     NewOpc = AArch64ISD::GLDNT1S;
12975     break;
12976   default:
12977     return SDValue();
12978   }
12979 
12980   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12981   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
12982 
12983   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
12984     return SDValue();
12985 
12986   EVT DstVT = N->getValueType(0);
12987   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12988 
12989   SmallVector<SDValue, 5> Ops;
12990   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
12991     Ops.push_back(Src->getOperand(I));
12992 
12993   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12994   DCI.CombineTo(N, ExtLoad);
12995   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12996 
12997   // Return N so it doesn't get rechecked
12998   return SDValue(N, 0);
12999 }
13000 
13001 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
13002 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
13003 /// != nxv2i32) do not need legalization.
13004 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
13005   const unsigned OffsetPos = 4;
13006   SDValue Offset = N->getOperand(OffsetPos);
13007 
13008   // Not an unpacked vector, bail out.
13009   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
13010     return SDValue();
13011 
13012   // Extend the unpacked offset vector to 64-bit lanes.
13013   SDLoc DL(N);
13014   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
13015   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13016   // Replace the offset operand with the 64-bit one.
13017   Ops[OffsetPos] = Offset;
13018 
13019   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13020 }
13021 
13022 /// Combines a node carrying the intrinsic `aarch64_sve_prf<T>_gather` into a
13023 /// node that uses `aarch64_sve_prf<T>_gather_scaled_uxtw` when the scalar
13024 /// offset passed to `aarch64_sve_prf<T>_gather` is not a valid immediate for
13025 /// the sve gather prefetch instruction with vector plus immediate addressing
13026 /// mode.
13027 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
13028                                                unsigned NewIID,
13029                                                unsigned ScalarSizeInBytes) {
13030   const unsigned ImmPos = 4, OffsetPos = 3;
13031   // No need to combine the node if the immediate is valid...
13032   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
13033     return SDValue();
13034 
13035   // ...otherwise swap the offset base with the offset...
13036   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13037   std::swap(Ops[ImmPos], Ops[OffsetPos]);
13038   // ...and remap the intrinsic `aarch64_sve_prf_gather<T>` to
13039   // `aarch64_sve_prf_gather<T>_scaled_uxtw`.
13040   SDLoc DL(N);
13041   Ops[1] = DAG.getConstant(NewIID, DL, MVT::i64);
13042 
13043   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13044 }
13045 
13046 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
13047                                                  DAGCombinerInfo &DCI) const {
13048   SelectionDAG &DAG = DCI.DAG;
13049   switch (N->getOpcode()) {
13050   default:
13051     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
13052     break;
13053   case ISD::ADD:
13054   case ISD::SUB:
13055     return performAddSubLongCombine(N, DCI, DAG);
13056   case ISD::XOR:
13057     return performXorCombine(N, DAG, DCI, Subtarget);
13058   case ISD::MUL:
13059     return performMulCombine(N, DAG, DCI, Subtarget);
13060   case ISD::SINT_TO_FP:
13061   case ISD::UINT_TO_FP:
13062     return performIntToFpCombine(N, DAG, Subtarget);
13063   case ISD::FP_TO_SINT:
13064   case ISD::FP_TO_UINT:
13065     return performFpToIntCombine(N, DAG, DCI, Subtarget);
13066   case ISD::FDIV:
13067     return performFDivCombine(N, DAG, DCI, Subtarget);
13068   case ISD::OR:
13069     return performORCombine(N, DCI, Subtarget);
13070   case ISD::AND:
13071     return performANDCombine(N, DCI);
13072   case ISD::SRL:
13073     return performSRLCombine(N, DCI);
13074   case ISD::INTRINSIC_WO_CHAIN:
13075     return performIntrinsicCombine(N, DCI, Subtarget);
13076   case ISD::ANY_EXTEND:
13077   case ISD::ZERO_EXTEND:
13078   case ISD::SIGN_EXTEND:
13079     return performExtendCombine(N, DCI, DAG);
13080   case ISD::SIGN_EXTEND_INREG:
13081     return performSignExtendInRegCombine(N, DCI, DAG);
13082   case ISD::CONCAT_VECTORS:
13083     return performConcatVectorsCombine(N, DCI, DAG);
13084   case ISD::SELECT:
13085     return performSelectCombine(N, DCI);
13086   case ISD::VSELECT:
13087     return performVSelectCombine(N, DCI.DAG);
13088   case ISD::LOAD:
13089     if (performTBISimplification(N->getOperand(1), DCI, DAG))
13090       return SDValue(N, 0);
13091     break;
13092   case ISD::STORE:
13093     return performSTORECombine(N, DCI, DAG, Subtarget);
13094   case AArch64ISD::BRCOND:
13095     return performBRCONDCombine(N, DCI, DAG);
13096   case AArch64ISD::TBNZ:
13097   case AArch64ISD::TBZ:
13098     return performTBZCombine(N, DCI, DAG);
13099   case AArch64ISD::CSEL:
13100     return performCONDCombine(N, DCI, DAG, 2, 3);
13101   case AArch64ISD::DUP:
13102     return performPostLD1Combine(N, DCI, false);
13103   case AArch64ISD::NVCAST:
13104     return performNVCASTCombine(N);
13105   case ISD::INSERT_VECTOR_ELT:
13106     return performPostLD1Combine(N, DCI, true);
13107   case ISD::INTRINSIC_VOID:
13108   case ISD::INTRINSIC_W_CHAIN:
13109     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13110     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
13111       return combineSVEPrefetchVecBaseImmOff(
13112           N, DAG, Intrinsic::aarch64_sve_prfb_gather_uxtw_index,
13113           1 /*=ScalarSizeInBytes*/);
13114     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
13115       return combineSVEPrefetchVecBaseImmOff(
13116           N, DAG, Intrinsic::aarch64_sve_prfh_gather_uxtw_index,
13117           2 /*=ScalarSizeInBytes*/);
13118     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
13119       return combineSVEPrefetchVecBaseImmOff(
13120           N, DAG, Intrinsic::aarch64_sve_prfw_gather_uxtw_index,
13121           4 /*=ScalarSizeInBytes*/);
13122     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
13123       return combineSVEPrefetchVecBaseImmOff(
13124           N, DAG, Intrinsic::aarch64_sve_prfd_gather_uxtw_index,
13125           8 /*=ScalarSizeInBytes*/);
13126     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
13127     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
13128     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
13129     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
13130     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
13131     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
13132     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
13133     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
13134       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
13135     case Intrinsic::aarch64_neon_ld2:
13136     case Intrinsic::aarch64_neon_ld3:
13137     case Intrinsic::aarch64_neon_ld4:
13138     case Intrinsic::aarch64_neon_ld1x2:
13139     case Intrinsic::aarch64_neon_ld1x3:
13140     case Intrinsic::aarch64_neon_ld1x4:
13141     case Intrinsic::aarch64_neon_ld2lane:
13142     case Intrinsic::aarch64_neon_ld3lane:
13143     case Intrinsic::aarch64_neon_ld4lane:
13144     case Intrinsic::aarch64_neon_ld2r:
13145     case Intrinsic::aarch64_neon_ld3r:
13146     case Intrinsic::aarch64_neon_ld4r:
13147     case Intrinsic::aarch64_neon_st2:
13148     case Intrinsic::aarch64_neon_st3:
13149     case Intrinsic::aarch64_neon_st4:
13150     case Intrinsic::aarch64_neon_st1x2:
13151     case Intrinsic::aarch64_neon_st1x3:
13152     case Intrinsic::aarch64_neon_st1x4:
13153     case Intrinsic::aarch64_neon_st2lane:
13154     case Intrinsic::aarch64_neon_st3lane:
13155     case Intrinsic::aarch64_neon_st4lane:
13156       return performNEONPostLDSTCombine(N, DCI, DAG);
13157     case Intrinsic::aarch64_sve_ld1:
13158     case Intrinsic::aarch64_sve_ldnt1:
13159       return performLD1Combine(N, DAG);
13160     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
13161       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13162     case Intrinsic::aarch64_sve_ldnt1_gather:
13163       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13164     case Intrinsic::aarch64_sve_ldnt1_gather_index:
13165       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_INDEX);
13166     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
13167       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1);
13168     case Intrinsic::aarch64_sve_ldnf1:
13169       return performLDNF1Combine(N, DAG, AArch64ISD::LDNF1);
13170     case Intrinsic::aarch64_sve_ldff1:
13171       return performLDNF1Combine(N, DAG, AArch64ISD::LDFF1);
13172     case Intrinsic::aarch64_sve_st1:
13173     case Intrinsic::aarch64_sve_stnt1:
13174       return performST1Combine(N, DAG);
13175     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
13176       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13177     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
13178       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13179     case Intrinsic::aarch64_sve_stnt1_scatter:
13180       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1);
13181     case Intrinsic::aarch64_sve_stnt1_scatter_index:
13182       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX);
13183     case Intrinsic::aarch64_sve_ld1_gather:
13184       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1);
13185     case Intrinsic::aarch64_sve_ld1_gather_index:
13186       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SCALED);
13187     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
13188       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW,
13189                                       /*OnlyPackedOffsets=*/false);
13190     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
13191       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW,
13192                                       /*OnlyPackedOffsets=*/false);
13193     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
13194       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
13195                                       /*OnlyPackedOffsets=*/false);
13196     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
13197       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
13198                                       /*OnlyPackedOffsets=*/false);
13199     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
13200       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM);
13201     case Intrinsic::aarch64_sve_ldff1_gather:
13202       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1);
13203     case Intrinsic::aarch64_sve_ldff1_gather_index:
13204       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SCALED);
13205     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
13206       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW,
13207                                       /*OnlyPackedOffsets=*/false);
13208     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
13209       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW,
13210                                       /*OnlyPackedOffsets=*/false);
13211     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
13212       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW_SCALED,
13213                                       /*OnlyPackedOffsets=*/false);
13214     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
13215       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW_SCALED,
13216                                       /*OnlyPackedOffsets=*/false);
13217     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
13218       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_IMM);
13219     case Intrinsic::aarch64_sve_st1_scatter:
13220       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1);
13221     case Intrinsic::aarch64_sve_st1_scatter_index:
13222       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED);
13223     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
13224       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW,
13225                                         /*OnlyPackedOffsets=*/false);
13226     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
13227       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW,
13228                                         /*OnlyPackedOffsets=*/false);
13229     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
13230       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
13231                                         /*OnlyPackedOffsets=*/false);
13232     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
13233       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
13234                                         /*OnlyPackedOffsets=*/false);
13235     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
13236       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM);
13237     default:
13238       break;
13239     }
13240     break;
13241   case ISD::GlobalAddress:
13242     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
13243   }
13244   return SDValue();
13245 }
13246 
13247 // Check if the return value is used as only a return value, as otherwise
13248 // we can't perform a tail-call. In particular, we need to check for
13249 // target ISD nodes that are returns and any other "odd" constructs
13250 // that the generic analysis code won't necessarily catch.
13251 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
13252                                                SDValue &Chain) const {
13253   if (N->getNumValues() != 1)
13254     return false;
13255   if (!N->hasNUsesOfValue(1, 0))
13256     return false;
13257 
13258   SDValue TCChain = Chain;
13259   SDNode *Copy = *N->use_begin();
13260   if (Copy->getOpcode() == ISD::CopyToReg) {
13261     // If the copy has a glue operand, we conservatively assume it isn't safe to
13262     // perform a tail call.
13263     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
13264         MVT::Glue)
13265       return false;
13266     TCChain = Copy->getOperand(0);
13267   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
13268     return false;
13269 
13270   bool HasRet = false;
13271   for (SDNode *Node : Copy->uses()) {
13272     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
13273       return false;
13274     HasRet = true;
13275   }
13276 
13277   if (!HasRet)
13278     return false;
13279 
13280   Chain = TCChain;
13281   return true;
13282 }
13283 
13284 // Return whether the an instruction can potentially be optimized to a tail
13285 // call. This will cause the optimizers to attempt to move, or duplicate,
13286 // return instructions to help enable tail call optimizations for this
13287 // instruction.
13288 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
13289   return CI->isTailCall();
13290 }
13291 
13292 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
13293                                                    SDValue &Offset,
13294                                                    ISD::MemIndexedMode &AM,
13295                                                    bool &IsInc,
13296                                                    SelectionDAG &DAG) const {
13297   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
13298     return false;
13299 
13300   Base = Op->getOperand(0);
13301   // All of the indexed addressing mode instructions take a signed
13302   // 9 bit immediate offset.
13303   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
13304     int64_t RHSC = RHS->getSExtValue();
13305     if (Op->getOpcode() == ISD::SUB)
13306       RHSC = -(uint64_t)RHSC;
13307     if (!isInt<9>(RHSC))
13308       return false;
13309     IsInc = (Op->getOpcode() == ISD::ADD);
13310     Offset = Op->getOperand(1);
13311     return true;
13312   }
13313   return false;
13314 }
13315 
13316 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13317                                                       SDValue &Offset,
13318                                                       ISD::MemIndexedMode &AM,
13319                                                       SelectionDAG &DAG) const {
13320   EVT VT;
13321   SDValue Ptr;
13322   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13323     VT = LD->getMemoryVT();
13324     Ptr = LD->getBasePtr();
13325   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13326     VT = ST->getMemoryVT();
13327     Ptr = ST->getBasePtr();
13328   } else
13329     return false;
13330 
13331   bool IsInc;
13332   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
13333     return false;
13334   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
13335   return true;
13336 }
13337 
13338 bool AArch64TargetLowering::getPostIndexedAddressParts(
13339     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
13340     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
13341   EVT VT;
13342   SDValue Ptr;
13343   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13344     VT = LD->getMemoryVT();
13345     Ptr = LD->getBasePtr();
13346   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13347     VT = ST->getMemoryVT();
13348     Ptr = ST->getBasePtr();
13349   } else
13350     return false;
13351 
13352   bool IsInc;
13353   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
13354     return false;
13355   // Post-indexing updates the base, so it's not a valid transform
13356   // if that's not the same as the load's pointer.
13357   if (Ptr != Base)
13358     return false;
13359   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
13360   return true;
13361 }
13362 
13363 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
13364                                   SelectionDAG &DAG) {
13365   SDLoc DL(N);
13366   SDValue Op = N->getOperand(0);
13367 
13368   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
13369     return;
13370 
13371   Op = SDValue(
13372       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
13373                          DAG.getUNDEF(MVT::i32), Op,
13374                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
13375       0);
13376   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
13377   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
13378 }
13379 
13380 static void ReplaceReductionResults(SDNode *N,
13381                                     SmallVectorImpl<SDValue> &Results,
13382                                     SelectionDAG &DAG, unsigned InterOp,
13383                                     unsigned AcrossOp) {
13384   EVT LoVT, HiVT;
13385   SDValue Lo, Hi;
13386   SDLoc dl(N);
13387   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
13388   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
13389   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
13390   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
13391   Results.push_back(SplitVal);
13392 }
13393 
13394 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
13395   SDLoc DL(N);
13396   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
13397   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
13398                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
13399                                        DAG.getConstant(64, DL, MVT::i64)));
13400   return std::make_pair(Lo, Hi);
13401 }
13402 
13403 // Create an even/odd pair of X registers holding integer value V.
13404 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
13405   SDLoc dl(V.getNode());
13406   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
13407   SDValue VHi = DAG.getAnyExtOrTrunc(
13408       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
13409       dl, MVT::i64);
13410   if (DAG.getDataLayout().isBigEndian())
13411     std::swap (VLo, VHi);
13412   SDValue RegClass =
13413       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
13414   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
13415   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
13416   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
13417   return SDValue(
13418       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
13419 }
13420 
13421 static void ReplaceCMP_SWAP_128Results(SDNode *N,
13422                                        SmallVectorImpl<SDValue> &Results,
13423                                        SelectionDAG &DAG,
13424                                        const AArch64Subtarget *Subtarget) {
13425   assert(N->getValueType(0) == MVT::i128 &&
13426          "AtomicCmpSwap on types less than 128 should be legal");
13427 
13428   if (Subtarget->hasLSE()) {
13429     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
13430     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
13431     SDValue Ops[] = {
13432         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
13433         createGPRPairNode(DAG, N->getOperand(3)), // Store value
13434         N->getOperand(1), // Ptr
13435         N->getOperand(0), // Chain in
13436     };
13437 
13438     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13439 
13440     unsigned Opcode;
13441     switch (MemOp->getOrdering()) {
13442     case AtomicOrdering::Monotonic:
13443       Opcode = AArch64::CASPX;
13444       break;
13445     case AtomicOrdering::Acquire:
13446       Opcode = AArch64::CASPAX;
13447       break;
13448     case AtomicOrdering::Release:
13449       Opcode = AArch64::CASPLX;
13450       break;
13451     case AtomicOrdering::AcquireRelease:
13452     case AtomicOrdering::SequentiallyConsistent:
13453       Opcode = AArch64::CASPALX;
13454       break;
13455     default:
13456       llvm_unreachable("Unexpected ordering!");
13457     }
13458 
13459     MachineSDNode *CmpSwap = DAG.getMachineNode(
13460         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
13461     DAG.setNodeMemRefs(CmpSwap, {MemOp});
13462 
13463     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
13464     if (DAG.getDataLayout().isBigEndian())
13465       std::swap(SubReg1, SubReg2);
13466     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
13467                                             SDValue(CmpSwap, 0));
13468     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
13469                                             SDValue(CmpSwap, 0));
13470     Results.push_back(
13471         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
13472     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
13473     return;
13474   }
13475 
13476   auto Desired = splitInt128(N->getOperand(2), DAG);
13477   auto New = splitInt128(N->getOperand(3), DAG);
13478   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
13479                    New.first,        New.second,    N->getOperand(0)};
13480   SDNode *CmpSwap = DAG.getMachineNode(
13481       AArch64::CMP_SWAP_128, SDLoc(N),
13482       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
13483 
13484   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13485   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
13486 
13487   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13488                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
13489   Results.push_back(SDValue(CmpSwap, 3));
13490 }
13491 
13492 void AArch64TargetLowering::ReplaceNodeResults(
13493     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
13494   switch (N->getOpcode()) {
13495   default:
13496     llvm_unreachable("Don't know how to custom expand this");
13497   case ISD::BITCAST:
13498     ReplaceBITCASTResults(N, Results, DAG);
13499     return;
13500   case ISD::VECREDUCE_ADD:
13501   case ISD::VECREDUCE_SMAX:
13502   case ISD::VECREDUCE_SMIN:
13503   case ISD::VECREDUCE_UMAX:
13504   case ISD::VECREDUCE_UMIN:
13505     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
13506     return;
13507 
13508   case AArch64ISD::SADDV:
13509     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
13510     return;
13511   case AArch64ISD::UADDV:
13512     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
13513     return;
13514   case AArch64ISD::SMINV:
13515     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
13516     return;
13517   case AArch64ISD::UMINV:
13518     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
13519     return;
13520   case AArch64ISD::SMAXV:
13521     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
13522     return;
13523   case AArch64ISD::UMAXV:
13524     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
13525     return;
13526   case ISD::FP_TO_UINT:
13527   case ISD::FP_TO_SINT:
13528     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
13529     // Let normal code take care of it by not adding anything to Results.
13530     return;
13531   case ISD::ATOMIC_CMP_SWAP:
13532     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
13533     return;
13534   case ISD::LOAD: {
13535     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
13536            "unexpected load's value type");
13537     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
13538     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
13539       // Non-volatile loads are optimized later in AArch64's load/store
13540       // optimizer.
13541       return;
13542     }
13543 
13544     SDValue Result = DAG.getMemIntrinsicNode(
13545         AArch64ISD::LDP, SDLoc(N),
13546         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
13547         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
13548         LoadNode->getMemOperand());
13549 
13550     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13551                                Result.getValue(0), Result.getValue(1));
13552     Results.append({Pair, Result.getValue(2) /* Chain */});
13553     return;
13554   }
13555   case ISD::INTRINSIC_WO_CHAIN: {
13556     EVT VT = N->getValueType(0);
13557     assert((VT == MVT::i8 || VT == MVT::i16) &&
13558            "custom lowering for unexpected type");
13559 
13560     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
13561     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13562     switch (IntID) {
13563     default:
13564       return;
13565     case Intrinsic::aarch64_sve_clasta_n: {
13566       SDLoc DL(N);
13567       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13568       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
13569                            N->getOperand(1), Op2, N->getOperand(3));
13570       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13571       return;
13572     }
13573     case Intrinsic::aarch64_sve_clastb_n: {
13574       SDLoc DL(N);
13575       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13576       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
13577                            N->getOperand(1), Op2, N->getOperand(3));
13578       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13579       return;
13580     }
13581     case Intrinsic::aarch64_sve_lasta: {
13582       SDLoc DL(N);
13583       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
13584                            N->getOperand(1), N->getOperand(2));
13585       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13586       return;
13587     }
13588     case Intrinsic::aarch64_sve_lastb: {
13589       SDLoc DL(N);
13590       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
13591                            N->getOperand(1), N->getOperand(2));
13592       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13593       return;
13594     }
13595     }
13596   }
13597   }
13598 }
13599 
13600 bool AArch64TargetLowering::useLoadStackGuardNode() const {
13601   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
13602     return TargetLowering::useLoadStackGuardNode();
13603   return true;
13604 }
13605 
13606 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
13607   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13608   // reciprocal if there are three or more FDIVs.
13609   return 3;
13610 }
13611 
13612 TargetLoweringBase::LegalizeTypeAction
13613 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
13614   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
13615   // v4i16, v2i32 instead of to promote.
13616   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
13617       VT == MVT::v1f32)
13618     return TypeWidenVector;
13619 
13620   return TargetLoweringBase::getPreferredVectorAction(VT);
13621 }
13622 
13623 // Loads and stores less than 128-bits are already atomic; ones above that
13624 // are doomed anyway, so defer to the default libcall and blame the OS when
13625 // things go wrong.
13626 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13627   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13628   return Size == 128;
13629 }
13630 
13631 // Loads and stores less than 128-bits are already atomic; ones above that
13632 // are doomed anyway, so defer to the default libcall and blame the OS when
13633 // things go wrong.
13634 TargetLowering::AtomicExpansionKind
13635 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13636   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13637   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
13638 }
13639 
13640 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
13641 TargetLowering::AtomicExpansionKind
13642 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13643   if (AI->isFloatingPointOperation())
13644     return AtomicExpansionKind::CmpXChg;
13645 
13646   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13647   if (Size > 128) return AtomicExpansionKind::None;
13648   // Nand not supported in LSE.
13649   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13650   // Leave 128 bits to LLSC.
13651   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13652 }
13653 
13654 TargetLowering::AtomicExpansionKind
13655 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13656     AtomicCmpXchgInst *AI) const {
13657   // If subtarget has LSE, leave cmpxchg intact for codegen.
13658   if (Subtarget->hasLSE())
13659     return AtomicExpansionKind::None;
13660   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13661   // implement cmpxchg without spilling. If the address being exchanged is also
13662   // on the stack and close enough to the spill slot, this can lead to a
13663   // situation where the monitor always gets cleared and the atomic operation
13664   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13665   if (getTargetMachine().getOptLevel() == 0)
13666     return AtomicExpansionKind::None;
13667   return AtomicExpansionKind::LLSC;
13668 }
13669 
13670 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13671                                              AtomicOrdering Ord) const {
13672   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13673   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13674   bool IsAcquire = isAcquireOrStronger(Ord);
13675 
13676   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13677   // intrinsic must return {i64, i64} and we have to recombine them into a
13678   // single i128 here.
13679   if (ValTy->getPrimitiveSizeInBits() == 128) {
13680     Intrinsic::ID Int =
13681         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13682     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13683 
13684     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13685     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13686 
13687     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13688     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13689     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13690     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13691     return Builder.CreateOr(
13692         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13693   }
13694 
13695   Type *Tys[] = { Addr->getType() };
13696   Intrinsic::ID Int =
13697       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13698   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13699 
13700   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13701 
13702   const DataLayout &DL = M->getDataLayout();
13703   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13704   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13705 
13706   return Builder.CreateBitCast(Trunc, EltTy);
13707 }
13708 
13709 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13710     IRBuilder<> &Builder) const {
13711   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13712   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13713 }
13714 
13715 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13716                                                    Value *Val, Value *Addr,
13717                                                    AtomicOrdering Ord) const {
13718   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13719   bool IsRelease = isReleaseOrStronger(Ord);
13720 
13721   // Since the intrinsics must have legal type, the i128 intrinsics take two
13722   // parameters: "i64, i64". We must marshal Val into the appropriate form
13723   // before the call.
13724   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13725     Intrinsic::ID Int =
13726         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13727     Function *Stxr = Intrinsic::getDeclaration(M, Int);
13728     Type *Int64Ty = Type::getInt64Ty(M->getContext());
13729 
13730     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13731     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13732     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13733     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13734   }
13735 
13736   Intrinsic::ID Int =
13737       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13738   Type *Tys[] = { Addr->getType() };
13739   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13740 
13741   const DataLayout &DL = M->getDataLayout();
13742   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13743   Val = Builder.CreateBitCast(Val, IntValTy);
13744 
13745   return Builder.CreateCall(Stxr,
13746                             {Builder.CreateZExtOrBitCast(
13747                                  Val, Stxr->getFunctionType()->getParamType(0)),
13748                              Addr});
13749 }
13750 
13751 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13752     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13753   return Ty->isArrayTy();
13754 }
13755 
13756 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13757                                                             EVT) const {
13758   return false;
13759 }
13760 
13761 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13762   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13763   Function *ThreadPointerFunc =
13764       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13765   return IRB.CreatePointerCast(
13766       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13767                              Offset),
13768       IRB.getInt8PtrTy()->getPointerTo(0));
13769 }
13770 
13771 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13772   // Android provides a fixed TLS slot for the stack cookie. See the definition
13773   // of TLS_SLOT_STACK_GUARD in
13774   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13775   if (Subtarget->isTargetAndroid())
13776     return UseTlsOffset(IRB, 0x28);
13777 
13778   // Fuchsia is similar.
13779   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13780   if (Subtarget->isTargetFuchsia())
13781     return UseTlsOffset(IRB, -0x10);
13782 
13783   return TargetLowering::getIRStackGuard(IRB);
13784 }
13785 
13786 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13787   // MSVC CRT provides functionalities for stack protection.
13788   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13789     // MSVC CRT has a global variable holding security cookie.
13790     M.getOrInsertGlobal("__security_cookie",
13791                         Type::getInt8PtrTy(M.getContext()));
13792 
13793     // MSVC CRT has a function to validate security cookie.
13794     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13795         "__security_check_cookie", Type::getVoidTy(M.getContext()),
13796         Type::getInt8PtrTy(M.getContext()));
13797     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13798       F->setCallingConv(CallingConv::Win64);
13799       F->addAttribute(1, Attribute::AttrKind::InReg);
13800     }
13801     return;
13802   }
13803   TargetLowering::insertSSPDeclarations(M);
13804 }
13805 
13806 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13807   // MSVC CRT has a global variable holding security cookie.
13808   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13809     return M.getGlobalVariable("__security_cookie");
13810   return TargetLowering::getSDagStackGuard(M);
13811 }
13812 
13813 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13814   // MSVC CRT has a function to validate security cookie.
13815   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13816     return M.getFunction("__security_check_cookie");
13817   return TargetLowering::getSSPStackGuardCheck(M);
13818 }
13819 
13820 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13821   // Android provides a fixed TLS slot for the SafeStack pointer. See the
13822   // definition of TLS_SLOT_SAFESTACK in
13823   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13824   if (Subtarget->isTargetAndroid())
13825     return UseTlsOffset(IRB, 0x48);
13826 
13827   // Fuchsia is similar.
13828   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13829   if (Subtarget->isTargetFuchsia())
13830     return UseTlsOffset(IRB, -0x8);
13831 
13832   return TargetLowering::getSafeStackPointerLocation(IRB);
13833 }
13834 
13835 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13836     const Instruction &AndI) const {
13837   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13838   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
13839   // may be beneficial to sink in other cases, but we would have to check that
13840   // the cmp would not get folded into the br to form a cbz for these to be
13841   // beneficial.
13842   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13843   if (!Mask)
13844     return false;
13845   return Mask->getValue().isPowerOf2();
13846 }
13847 
13848 bool AArch64TargetLowering::
13849     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13850         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13851         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13852         SelectionDAG &DAG) const {
13853   // Does baseline recommend not to perform the fold by default?
13854   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13855           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13856     return false;
13857   // Else, if this is a vector shift, prefer 'shl'.
13858   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13859 }
13860 
13861 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13862                                               SDNode *N) const {
13863   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13864       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13865     return false;
13866   return true;
13867 }
13868 
13869 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13870   // Update IsSplitCSR in AArch64unctionInfo.
13871   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13872   AFI->setIsSplitCSR(true);
13873 }
13874 
13875 void AArch64TargetLowering::insertCopiesSplitCSR(
13876     MachineBasicBlock *Entry,
13877     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13878   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13879   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13880   if (!IStart)
13881     return;
13882 
13883   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13884   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13885   MachineBasicBlock::iterator MBBI = Entry->begin();
13886   for (const MCPhysReg *I = IStart; *I; ++I) {
13887     const TargetRegisterClass *RC = nullptr;
13888     if (AArch64::GPR64RegClass.contains(*I))
13889       RC = &AArch64::GPR64RegClass;
13890     else if (AArch64::FPR64RegClass.contains(*I))
13891       RC = &AArch64::FPR64RegClass;
13892     else
13893       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13894 
13895     Register NewVR = MRI->createVirtualRegister(RC);
13896     // Create copy from CSR to a virtual register.
13897     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13898     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13899     // nounwind. If we want to generalize this later, we may need to emit
13900     // CFI pseudo-instructions.
13901     assert(Entry->getParent()->getFunction().hasFnAttribute(
13902                Attribute::NoUnwind) &&
13903            "Function should be nounwind in insertCopiesSplitCSR!");
13904     Entry->addLiveIn(*I);
13905     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13906         .addReg(*I);
13907 
13908     // Insert the copy-back instructions right before the terminator.
13909     for (auto *Exit : Exits)
13910       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13911               TII->get(TargetOpcode::COPY), *I)
13912           .addReg(NewVR);
13913   }
13914 }
13915 
13916 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13917   // Integer division on AArch64 is expensive. However, when aggressively
13918   // optimizing for code size, we prefer to use a div instruction, as it is
13919   // usually smaller than the alternative sequence.
13920   // The exception to this is vector division. Since AArch64 doesn't have vector
13921   // integer division, leaving the division as-is is a loss even in terms of
13922   // size, because it will have to be scalarized, while the alternative code
13923   // sequence can be performed in vector form.
13924   bool OptSize =
13925       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13926   return OptSize && !VT.isVector();
13927 }
13928 
13929 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13930   // We want inc-of-add for scalars and sub-of-not for vectors.
13931   return VT.isScalarInteger();
13932 }
13933 
13934 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13935   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13936 }
13937 
13938 unsigned
13939 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13940   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13941     return getPointerTy(DL).getSizeInBits();
13942 
13943   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13944 }
13945 
13946 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13947   MF.getFrameInfo().computeMaxCallFrameSize(MF);
13948   TargetLoweringBase::finalizeLowering(MF);
13949 }
13950 
13951 // Unlike X86, we let frame lowering assign offsets to all catch objects.
13952 bool AArch64TargetLowering::needsFixedCatchObjects() const {
13953   return false;
13954 }
13955 
13956 bool AArch64TargetLowering::shouldLocalize(
13957     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
13958   if (MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE) {
13959     // On Darwin, TLS global vars get selected into function calls, which
13960     // we don't want localized, as they can get moved into the middle of a
13961     // another call sequence.
13962     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
13963     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
13964       return false;
13965   }
13966   return TargetLoweringBase::shouldLocalize(MI, TTI);
13967 }
13968