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 
203   // Compute derived properties from the register classes
204   computeRegisterProperties(Subtarget->getRegisterInfo());
205 
206   // Provide all sorts of operation actions
207   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
209   setOperationAction(ISD::SETCC, MVT::i32, Custom);
210   setOperationAction(ISD::SETCC, MVT::i64, Custom);
211   setOperationAction(ISD::SETCC, MVT::f16, Custom);
212   setOperationAction(ISD::SETCC, MVT::f32, Custom);
213   setOperationAction(ISD::SETCC, MVT::f64, Custom);
214   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
215   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
216   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
217   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
218   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
219   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
220   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
221   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
222   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
224   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
225   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
226   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
227   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
228   setOperationAction(ISD::SELECT, MVT::i32, Custom);
229   setOperationAction(ISD::SELECT, MVT::i64, Custom);
230   setOperationAction(ISD::SELECT, MVT::f16, Custom);
231   setOperationAction(ISD::SELECT, MVT::f32, Custom);
232   setOperationAction(ISD::SELECT, MVT::f64, Custom);
233   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
234   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
235   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
236   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
237   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
238   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
239   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
240 
241   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
242   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
243   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
244 
245   setOperationAction(ISD::FREM, MVT::f32, Expand);
246   setOperationAction(ISD::FREM, MVT::f64, Expand);
247   setOperationAction(ISD::FREM, MVT::f80, Expand);
248 
249   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
250 
251   // Custom lowering hooks are needed for XOR
252   // to fold it into CSINC/CSINV.
253   setOperationAction(ISD::XOR, MVT::i32, Custom);
254   setOperationAction(ISD::XOR, MVT::i64, Custom);
255 
256   // Virtually no operation on f128 is legal, but LLVM can't expand them when
257   // there's a valid register class, so we need custom operations in most cases.
258   setOperationAction(ISD::FABS, MVT::f128, Expand);
259   setOperationAction(ISD::FADD, MVT::f128, Custom);
260   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
261   setOperationAction(ISD::FCOS, MVT::f128, Expand);
262   setOperationAction(ISD::FDIV, MVT::f128, Custom);
263   setOperationAction(ISD::FMA, MVT::f128, Expand);
264   setOperationAction(ISD::FMUL, MVT::f128, Custom);
265   setOperationAction(ISD::FNEG, MVT::f128, Expand);
266   setOperationAction(ISD::FPOW, MVT::f128, Expand);
267   setOperationAction(ISD::FREM, MVT::f128, Expand);
268   setOperationAction(ISD::FRINT, MVT::f128, Expand);
269   setOperationAction(ISD::FSIN, MVT::f128, Expand);
270   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
271   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
272   setOperationAction(ISD::FSUB, MVT::f128, Custom);
273   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
274   setOperationAction(ISD::SETCC, MVT::f128, Custom);
275   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
276   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
277   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
278   setOperationAction(ISD::SELECT, MVT::f128, Custom);
279   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
280   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
281 
282   // Lowering for many of the conversions is actually specified by the non-f128
283   // type. The LowerXXX function will be trivial when f128 isn't involved.
284   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
285   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
286   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
287   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
288   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
289   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
290   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
291   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
292   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
293   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
294   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
295   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
296   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
297   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
298   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
299   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
300   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
301   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
302   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
303   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
304   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
305   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
306   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
307   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
308   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
309   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
310   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
311   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
312 
313   // Variable arguments.
314   setOperationAction(ISD::VASTART, MVT::Other, Custom);
315   setOperationAction(ISD::VAARG, MVT::Other, Custom);
316   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
317   setOperationAction(ISD::VAEND, MVT::Other, Expand);
318 
319   // Variable-sized objects.
320   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
321   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
322 
323   if (Subtarget->isTargetWindows())
324     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
325   else
326     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
327 
328   // Constant pool entries
329   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
330 
331   // BlockAddress
332   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
333 
334   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
335   setOperationAction(ISD::ADDC, MVT::i32, Custom);
336   setOperationAction(ISD::ADDE, MVT::i32, Custom);
337   setOperationAction(ISD::SUBC, MVT::i32, Custom);
338   setOperationAction(ISD::SUBE, MVT::i32, Custom);
339   setOperationAction(ISD::ADDC, MVT::i64, Custom);
340   setOperationAction(ISD::ADDE, MVT::i64, Custom);
341   setOperationAction(ISD::SUBC, MVT::i64, Custom);
342   setOperationAction(ISD::SUBE, MVT::i64, Custom);
343 
344   // AArch64 lacks both left-rotate and popcount instructions.
345   setOperationAction(ISD::ROTL, MVT::i32, Expand);
346   setOperationAction(ISD::ROTL, MVT::i64, Expand);
347   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
348     setOperationAction(ISD::ROTL, VT, Expand);
349     setOperationAction(ISD::ROTR, VT, Expand);
350   }
351 
352   // AArch64 doesn't have {U|S}MUL_LOHI.
353   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
354   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
355 
356   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
357   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
358 
359   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
360   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
361   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
362     setOperationAction(ISD::SDIVREM, VT, Expand);
363     setOperationAction(ISD::UDIVREM, VT, Expand);
364   }
365   setOperationAction(ISD::SREM, MVT::i32, Expand);
366   setOperationAction(ISD::SREM, MVT::i64, Expand);
367   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
368   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
369   setOperationAction(ISD::UREM, MVT::i32, Expand);
370   setOperationAction(ISD::UREM, MVT::i64, Expand);
371 
372   // Custom lower Add/Sub/Mul with overflow.
373   setOperationAction(ISD::SADDO, MVT::i32, Custom);
374   setOperationAction(ISD::SADDO, MVT::i64, Custom);
375   setOperationAction(ISD::UADDO, MVT::i32, Custom);
376   setOperationAction(ISD::UADDO, MVT::i64, Custom);
377   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
378   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
379   setOperationAction(ISD::USUBO, MVT::i32, Custom);
380   setOperationAction(ISD::USUBO, MVT::i64, Custom);
381   setOperationAction(ISD::SMULO, MVT::i32, Custom);
382   setOperationAction(ISD::SMULO, MVT::i64, Custom);
383   setOperationAction(ISD::UMULO, MVT::i32, Custom);
384   setOperationAction(ISD::UMULO, MVT::i64, Custom);
385 
386   setOperationAction(ISD::FSIN, MVT::f32, Expand);
387   setOperationAction(ISD::FSIN, MVT::f64, Expand);
388   setOperationAction(ISD::FCOS, MVT::f32, Expand);
389   setOperationAction(ISD::FCOS, MVT::f64, Expand);
390   setOperationAction(ISD::FPOW, MVT::f32, Expand);
391   setOperationAction(ISD::FPOW, MVT::f64, Expand);
392   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
393   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
394   if (Subtarget->hasFullFP16())
395     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
396   else
397     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
398 
399   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
400   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
401   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
402   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
403   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
404   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
405   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
406   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
407   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
408   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
409   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
410   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
411   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
412   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
413   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
414   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
415   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
416   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
417   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
418   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
419   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
420   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
421   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
422   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
423   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
424   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
425   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
426   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
427   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
428   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
429   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
430   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
431   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
432 
433   if (!Subtarget->hasFullFP16()) {
434     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
435     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
436     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
437     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
438     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
439     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
440     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
441     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
442     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
443     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
444     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
445     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
446     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
447     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
448     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
449     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
450     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
451     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
452     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
453     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
454     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
455     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
456 
457     // promote v4f16 to v4f32 when that is known to be safe.
458     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
459     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
460     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
461     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
462     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
463     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
464     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
465     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
466 
467     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
468     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
469     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
470     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
471     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
472     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
473     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
474     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
475     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
476     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
477     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
478     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
479     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
480     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
481     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
482 
483     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
484     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
485     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
486     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
487     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
488     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
489     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
490     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
491     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
492     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
493     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
494     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
495     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
496     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
497     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
498     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
499     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
500     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
501     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
502     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
503   }
504 
505   // AArch64 has implementations of a lot of rounding-like FP operations.
506   for (MVT Ty : {MVT::f32, MVT::f64}) {
507     setOperationAction(ISD::FFLOOR, Ty, Legal);
508     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
509     setOperationAction(ISD::FCEIL, Ty, Legal);
510     setOperationAction(ISD::FRINT, Ty, Legal);
511     setOperationAction(ISD::FTRUNC, Ty, Legal);
512     setOperationAction(ISD::FROUND, Ty, Legal);
513     setOperationAction(ISD::FMINNUM, Ty, Legal);
514     setOperationAction(ISD::FMAXNUM, Ty, Legal);
515     setOperationAction(ISD::FMINIMUM, Ty, Legal);
516     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
517     setOperationAction(ISD::LROUND, Ty, Legal);
518     setOperationAction(ISD::LLROUND, Ty, Legal);
519     setOperationAction(ISD::LRINT, Ty, Legal);
520     setOperationAction(ISD::LLRINT, Ty, Legal);
521   }
522 
523   if (Subtarget->hasFullFP16()) {
524     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
525     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
526     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
527     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
528     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
529     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
530     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
531     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
532     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
533     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
534   }
535 
536   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
537 
538   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
539 
540   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
541   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
542   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
544   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
545 
546   // 128-bit loads and stores can be done without expanding
547   setOperationAction(ISD::LOAD, MVT::i128, Custom);
548   setOperationAction(ISD::STORE, MVT::i128, Custom);
549 
550   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
551   // custom lowering, as there are no un-paired non-temporal stores and
552   // legalization will break up 256 bit inputs.
553   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
554   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
555   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
556   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
557   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
558   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
559   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
560 
561   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
562   // This requires the Performance Monitors extension.
563   if (Subtarget->hasPerfMon())
564     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
565 
566   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
567       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
568     // Issue __sincos_stret if available.
569     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
570     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
571   } else {
572     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
573     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
574   }
575 
576   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
577     // MSVCRT doesn't have powi; fall back to pow
578     setLibcallName(RTLIB::POWI_F32, nullptr);
579     setLibcallName(RTLIB::POWI_F64, nullptr);
580   }
581 
582   // Make floating-point constants legal for the large code model, so they don't
583   // become loads from the constant pool.
584   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
585     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
586     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
587   }
588 
589   // AArch64 does not have floating-point extending loads, i1 sign-extending
590   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
591   for (MVT VT : MVT::fp_valuetypes()) {
592     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
593     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
594     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
595     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
596   }
597   for (MVT VT : MVT::integer_valuetypes())
598     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
599 
600   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
601   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
602   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
603   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
604   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
605   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
606   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
607 
608   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
609   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
610 
611   // Indexed loads and stores are supported.
612   for (unsigned im = (unsigned)ISD::PRE_INC;
613        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
614     setIndexedLoadAction(im, MVT::i8, Legal);
615     setIndexedLoadAction(im, MVT::i16, Legal);
616     setIndexedLoadAction(im, MVT::i32, Legal);
617     setIndexedLoadAction(im, MVT::i64, Legal);
618     setIndexedLoadAction(im, MVT::f64, Legal);
619     setIndexedLoadAction(im, MVT::f32, Legal);
620     setIndexedLoadAction(im, MVT::f16, Legal);
621     setIndexedStoreAction(im, MVT::i8, Legal);
622     setIndexedStoreAction(im, MVT::i16, Legal);
623     setIndexedStoreAction(im, MVT::i32, Legal);
624     setIndexedStoreAction(im, MVT::i64, Legal);
625     setIndexedStoreAction(im, MVT::f64, Legal);
626     setIndexedStoreAction(im, MVT::f32, Legal);
627     setIndexedStoreAction(im, MVT::f16, Legal);
628   }
629 
630   // Trap.
631   setOperationAction(ISD::TRAP, MVT::Other, Legal);
632   if (Subtarget->isTargetWindows())
633     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634 
635   // We combine OR nodes for bitfield operations.
636   setTargetDAGCombine(ISD::OR);
637   // Try to create BICs for vector ANDs.
638   setTargetDAGCombine(ISD::AND);
639 
640   // Vector add and sub nodes may conceal a high-half opportunity.
641   // Also, try to fold ADD into CSINC/CSINV..
642   setTargetDAGCombine(ISD::ADD);
643   setTargetDAGCombine(ISD::SUB);
644   setTargetDAGCombine(ISD::SRL);
645   setTargetDAGCombine(ISD::XOR);
646   setTargetDAGCombine(ISD::SINT_TO_FP);
647   setTargetDAGCombine(ISD::UINT_TO_FP);
648 
649   setTargetDAGCombine(ISD::FP_TO_SINT);
650   setTargetDAGCombine(ISD::FP_TO_UINT);
651   setTargetDAGCombine(ISD::FDIV);
652 
653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
654 
655   setTargetDAGCombine(ISD::ANY_EXTEND);
656   setTargetDAGCombine(ISD::ZERO_EXTEND);
657   setTargetDAGCombine(ISD::SIGN_EXTEND);
658   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
659   setTargetDAGCombine(ISD::CONCAT_VECTORS);
660   setTargetDAGCombine(ISD::STORE);
661   if (Subtarget->supportsAddressTopByteIgnored())
662     setTargetDAGCombine(ISD::LOAD);
663 
664   setTargetDAGCombine(ISD::MUL);
665 
666   setTargetDAGCombine(ISD::SELECT);
667   setTargetDAGCombine(ISD::VSELECT);
668 
669   setTargetDAGCombine(ISD::INTRINSIC_VOID);
670   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
671   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
672 
673   setTargetDAGCombine(ISD::GlobalAddress);
674 
675   // In case of strict alignment, avoid an excessive number of byte wide stores.
676   MaxStoresPerMemsetOptSize = 8;
677   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
678                        ? MaxStoresPerMemsetOptSize : 32;
679 
680   MaxGluedStoresPerMemcpy = 4;
681   MaxStoresPerMemcpyOptSize = 4;
682   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
683                        ? MaxStoresPerMemcpyOptSize : 16;
684 
685   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
686 
687   MaxLoadsPerMemcmpOptSize = 4;
688   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
689                       ? MaxLoadsPerMemcmpOptSize : 8;
690 
691   setStackPointerRegisterToSaveRestore(AArch64::SP);
692 
693   setSchedulingPreference(Sched::Hybrid);
694 
695   EnableExtLdPromotion = true;
696 
697   // Set required alignment.
698   setMinFunctionAlignment(Align(4));
699   // Set preferred alignments.
700   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
701   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
702 
703   // Only change the limit for entries in a jump table if specified by
704   // the sub target, but not at the command line.
705   unsigned MaxJT = STI.getMaximumJumpTableSize();
706   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
707     setMaximumJumpTableSize(MaxJT);
708 
709   setHasExtractBitsInsn(true);
710 
711   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
712 
713   if (Subtarget->hasNEON()) {
714     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
715     // silliness like this:
716     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
717     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
718     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
720     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
721     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
722     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
723     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
724     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
725     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
726     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
727     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
728     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
729     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
730     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
731     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
732     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
733     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
734     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
735     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
736     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
737     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
738     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
739     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
740     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
741 
742     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
743     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
744     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
745     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
746     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
747 
748     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
749 
750     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
751     // elements smaller than i32, so promote the input to i32 first.
752     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
753     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
754     // i8 vector elements also need promotion to i32 for v8i8
755     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
756     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
757     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
758     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
759     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
760     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
761     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
762     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
763     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
764     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
765     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
766 
767     if (Subtarget->hasFullFP16()) {
768       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
769       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
770       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
771       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
772     } else {
773       // when AArch64 doesn't have fullfp16 support, promote the input
774       // to i32 first.
775       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
776       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
777       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
778       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
779     }
780 
781     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
782     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
783 
784     // AArch64 doesn't have MUL.2d:
785     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
786     // Custom handling for some quad-vector types to detect MULL.
787     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
788     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
789     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
790 
791     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
792                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
793       // Vector reductions
794       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
795       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
796       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
797       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
798       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
799 
800       // Saturates
801       setOperationAction(ISD::SADDSAT, VT, Legal);
802       setOperationAction(ISD::UADDSAT, VT, Legal);
803       setOperationAction(ISD::SSUBSAT, VT, Legal);
804       setOperationAction(ISD::USUBSAT, VT, Legal);
805     }
806     for (MVT VT : { MVT::v4f16, MVT::v2f32,
807                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
808       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
809       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
810     }
811 
812     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
813     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
814     // Likewise, narrowing and extending vector loads/stores aren't handled
815     // directly.
816     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
817       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
818 
819       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
820         setOperationAction(ISD::MULHS, VT, Legal);
821         setOperationAction(ISD::MULHU, VT, Legal);
822       } else {
823         setOperationAction(ISD::MULHS, VT, Expand);
824         setOperationAction(ISD::MULHU, VT, Expand);
825       }
826       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
827       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
828 
829       setOperationAction(ISD::BSWAP, VT, Expand);
830       setOperationAction(ISD::CTTZ, VT, Expand);
831 
832       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
833         setTruncStoreAction(VT, InnerVT, Expand);
834         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
835         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
836         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
837       }
838     }
839 
840     // AArch64 has implementations of a lot of rounding-like FP operations.
841     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
842       setOperationAction(ISD::FFLOOR, Ty, Legal);
843       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
844       setOperationAction(ISD::FCEIL, Ty, Legal);
845       setOperationAction(ISD::FRINT, Ty, Legal);
846       setOperationAction(ISD::FTRUNC, Ty, Legal);
847       setOperationAction(ISD::FROUND, Ty, Legal);
848     }
849 
850     if (Subtarget->hasFullFP16()) {
851       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
852         setOperationAction(ISD::FFLOOR, Ty, Legal);
853         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
854         setOperationAction(ISD::FCEIL, Ty, Legal);
855         setOperationAction(ISD::FRINT, Ty, Legal);
856         setOperationAction(ISD::FTRUNC, Ty, Legal);
857         setOperationAction(ISD::FROUND, Ty, Legal);
858       }
859     }
860 
861     if (Subtarget->hasSVE())
862       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
863 
864     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
865   }
866 
867   if (Subtarget->hasSVE()) {
868     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
869     // splat of 0 or undef) once vector selects supported in SVE codegen. See
870     // D68877 for more details.
871     for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
872       if (isTypeLegal(VT))
873         setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
874     }
875     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
876     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
877   }
878 
879   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
880 }
881 
882 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
883   assert(VT.isVector() && "VT should be a vector type");
884 
885   if (VT.isFloatingPoint()) {
886     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
887     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
888     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
889   }
890 
891   // Mark vector float intrinsics as expand.
892   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
893     setOperationAction(ISD::FSIN, VT, Expand);
894     setOperationAction(ISD::FCOS, VT, Expand);
895     setOperationAction(ISD::FPOW, VT, Expand);
896     setOperationAction(ISD::FLOG, VT, Expand);
897     setOperationAction(ISD::FLOG2, VT, Expand);
898     setOperationAction(ISD::FLOG10, VT, Expand);
899     setOperationAction(ISD::FEXP, VT, Expand);
900     setOperationAction(ISD::FEXP2, VT, Expand);
901 
902     // But we do support custom-lowering for FCOPYSIGN.
903     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
904   }
905 
906   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
907   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
908   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
911   setOperationAction(ISD::SRA, VT, Custom);
912   setOperationAction(ISD::SRL, VT, Custom);
913   setOperationAction(ISD::SHL, VT, Custom);
914   setOperationAction(ISD::OR, VT, Custom);
915   setOperationAction(ISD::SETCC, VT, Custom);
916   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
917 
918   setOperationAction(ISD::SELECT, VT, Expand);
919   setOperationAction(ISD::SELECT_CC, VT, Expand);
920   setOperationAction(ISD::VSELECT, VT, Expand);
921   for (MVT InnerVT : MVT::all_valuetypes())
922     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
923 
924   // CNT supports only B element sizes, then use UADDLP to widen.
925   if (VT != MVT::v8i8 && VT != MVT::v16i8)
926     setOperationAction(ISD::CTPOP, VT, Custom);
927 
928   setOperationAction(ISD::UDIV, VT, Expand);
929   setOperationAction(ISD::SDIV, VT, Expand);
930   setOperationAction(ISD::UREM, VT, Expand);
931   setOperationAction(ISD::SREM, VT, Expand);
932   setOperationAction(ISD::FREM, VT, Expand);
933 
934   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
935   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
936 
937   if (!VT.isFloatingPoint())
938     setOperationAction(ISD::ABS, VT, Legal);
939 
940   // [SU][MIN|MAX] are available for all NEON types apart from i64.
941   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
942     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
943       setOperationAction(Opcode, VT, Legal);
944 
945   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
946   if (VT.isFloatingPoint() &&
947       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
948     for (unsigned Opcode :
949          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
950       setOperationAction(Opcode, VT, Legal);
951 
952   if (Subtarget->isLittleEndian()) {
953     for (unsigned im = (unsigned)ISD::PRE_INC;
954          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
955       setIndexedLoadAction(im, VT, Legal);
956       setIndexedStoreAction(im, VT, Legal);
957     }
958   }
959 }
960 
961 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
962   addRegisterClass(VT, &AArch64::FPR64RegClass);
963   addTypeForNEON(VT, MVT::v2i32);
964 }
965 
966 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
967   addRegisterClass(VT, &AArch64::FPR128RegClass);
968   addTypeForNEON(VT, MVT::v4i32);
969 }
970 
971 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
972                                               EVT VT) const {
973   if (!VT.isVector())
974     return MVT::i32;
975   return VT.changeVectorElementTypeToInteger();
976 }
977 
978 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
979                                const APInt &Demanded,
980                                TargetLowering::TargetLoweringOpt &TLO,
981                                unsigned NewOpc) {
982   uint64_t OldImm = Imm, NewImm, Enc;
983   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
984 
985   // Return if the immediate is already all zeros, all ones, a bimm32 or a
986   // bimm64.
987   if (Imm == 0 || Imm == Mask ||
988       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
989     return false;
990 
991   unsigned EltSize = Size;
992   uint64_t DemandedBits = Demanded.getZExtValue();
993 
994   // Clear bits that are not demanded.
995   Imm &= DemandedBits;
996 
997   while (true) {
998     // The goal here is to set the non-demanded bits in a way that minimizes
999     // the number of switching between 0 and 1. In order to achieve this goal,
1000     // we set the non-demanded bits to the value of the preceding demanded bits.
1001     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1002     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1003     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1004     // The final result is 0b11000011.
1005     uint64_t NonDemandedBits = ~DemandedBits;
1006     uint64_t InvertedImm = ~Imm & DemandedBits;
1007     uint64_t RotatedImm =
1008         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1009         NonDemandedBits;
1010     uint64_t Sum = RotatedImm + NonDemandedBits;
1011     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1012     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1013     NewImm = (Imm | Ones) & Mask;
1014 
1015     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1016     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1017     // we halve the element size and continue the search.
1018     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1019       break;
1020 
1021     // We cannot shrink the element size any further if it is 2-bits.
1022     if (EltSize == 2)
1023       return false;
1024 
1025     EltSize /= 2;
1026     Mask >>= EltSize;
1027     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1028 
1029     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1030     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1031       return false;
1032 
1033     // Merge the upper and lower halves of Imm and DemandedBits.
1034     Imm |= Hi;
1035     DemandedBits |= DemandedBitsHi;
1036   }
1037 
1038   ++NumOptimizedImms;
1039 
1040   // Replicate the element across the register width.
1041   while (EltSize < Size) {
1042     NewImm |= NewImm << EltSize;
1043     EltSize *= 2;
1044   }
1045 
1046   (void)OldImm;
1047   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1048          "demanded bits should never be altered");
1049   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1050 
1051   // Create the new constant immediate node.
1052   EVT VT = Op.getValueType();
1053   SDLoc DL(Op);
1054   SDValue New;
1055 
1056   // If the new constant immediate is all-zeros or all-ones, let the target
1057   // independent DAG combine optimize this node.
1058   if (NewImm == 0 || NewImm == OrigMask) {
1059     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1060                           TLO.DAG.getConstant(NewImm, DL, VT));
1061   // Otherwise, create a machine node so that target independent DAG combine
1062   // doesn't undo this optimization.
1063   } else {
1064     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1065     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1066     New = SDValue(
1067         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1068   }
1069 
1070   return TLO.CombineTo(Op, New);
1071 }
1072 
1073 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1074     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1075   // Delay this optimization to as late as possible.
1076   if (!TLO.LegalOps)
1077     return false;
1078 
1079   if (!EnableOptimizeLogicalImm)
1080     return false;
1081 
1082   EVT VT = Op.getValueType();
1083   if (VT.isVector())
1084     return false;
1085 
1086   unsigned Size = VT.getSizeInBits();
1087   assert((Size == 32 || Size == 64) &&
1088          "i32 or i64 is expected after legalization.");
1089 
1090   // Exit early if we demand all bits.
1091   if (Demanded.countPopulation() == Size)
1092     return false;
1093 
1094   unsigned NewOpc;
1095   switch (Op.getOpcode()) {
1096   default:
1097     return false;
1098   case ISD::AND:
1099     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1100     break;
1101   case ISD::OR:
1102     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1103     break;
1104   case ISD::XOR:
1105     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1106     break;
1107   }
1108   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1109   if (!C)
1110     return false;
1111   uint64_t Imm = C->getZExtValue();
1112   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1113 }
1114 
1115 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1116 /// Mask are known to be either zero or one and return them Known.
1117 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1118     const SDValue Op, KnownBits &Known,
1119     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1120   switch (Op.getOpcode()) {
1121   default:
1122     break;
1123   case AArch64ISD::CSEL: {
1124     KnownBits Known2;
1125     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1126     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1127     Known.Zero &= Known2.Zero;
1128     Known.One &= Known2.One;
1129     break;
1130   }
1131   case AArch64ISD::LOADgot:
1132   case AArch64ISD::ADDlow: {
1133     if (!Subtarget->isTargetILP32())
1134       break;
1135     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1136     Known.Zero = APInt::getHighBitsSet(64, 32);
1137     break;
1138   }
1139   case ISD::INTRINSIC_W_CHAIN: {
1140     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1141     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1142     switch (IntID) {
1143     default: return;
1144     case Intrinsic::aarch64_ldaxr:
1145     case Intrinsic::aarch64_ldxr: {
1146       unsigned BitWidth = Known.getBitWidth();
1147       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1148       unsigned MemBits = VT.getScalarSizeInBits();
1149       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1150       return;
1151     }
1152     }
1153     break;
1154   }
1155   case ISD::INTRINSIC_WO_CHAIN:
1156   case ISD::INTRINSIC_VOID: {
1157     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1158     switch (IntNo) {
1159     default:
1160       break;
1161     case Intrinsic::aarch64_neon_umaxv:
1162     case Intrinsic::aarch64_neon_uminv: {
1163       // Figure out the datatype of the vector operand. The UMINV instruction
1164       // will zero extend the result, so we can mark as known zero all the
1165       // bits larger than the element datatype. 32-bit or larget doesn't need
1166       // this as those are legal types and will be handled by isel directly.
1167       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1168       unsigned BitWidth = Known.getBitWidth();
1169       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1170         assert(BitWidth >= 8 && "Unexpected width!");
1171         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1172         Known.Zero |= Mask;
1173       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1174         assert(BitWidth >= 16 && "Unexpected width!");
1175         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1176         Known.Zero |= Mask;
1177       }
1178       break;
1179     } break;
1180     }
1181   }
1182   }
1183 }
1184 
1185 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1186                                                   EVT) const {
1187   return MVT::i64;
1188 }
1189 
1190 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1191     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1192     bool *Fast) const {
1193   if (Subtarget->requiresStrictAlign())
1194     return false;
1195 
1196   if (Fast) {
1197     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1198     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1199             // See comments in performSTORECombine() for more details about
1200             // these conditions.
1201 
1202             // Code that uses clang vector extensions can mark that it
1203             // wants unaligned accesses to be treated as fast by
1204             // underspecifying alignment to be 1 or 2.
1205             Align <= 2 ||
1206 
1207             // Disregard v2i64. Memcpy lowering produces those and splitting
1208             // them regresses performance on micro-benchmarks and olden/bh.
1209             VT == MVT::v2i64;
1210   }
1211   return true;
1212 }
1213 
1214 // Same as above but handling LLTs instead.
1215 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1216     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1217     bool *Fast) const {
1218   if (Subtarget->requiresStrictAlign())
1219     return false;
1220 
1221   if (Fast) {
1222     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1223     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1224             Ty.getSizeInBytes() != 16 ||
1225             // See comments in performSTORECombine() for more details about
1226             // these conditions.
1227 
1228             // Code that uses clang vector extensions can mark that it
1229             // wants unaligned accesses to be treated as fast by
1230             // underspecifying alignment to be 1 or 2.
1231             Align <= 2 ||
1232 
1233             // Disregard v2i64. Memcpy lowering produces those and splitting
1234             // them regresses performance on micro-benchmarks and olden/bh.
1235             Ty == LLT::vector(2, 64);
1236   }
1237   return true;
1238 }
1239 
1240 FastISel *
1241 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1242                                       const TargetLibraryInfo *libInfo) const {
1243   return AArch64::createFastISel(funcInfo, libInfo);
1244 }
1245 
1246 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1247   switch ((AArch64ISD::NodeType)Opcode) {
1248   case AArch64ISD::FIRST_NUMBER:      break;
1249   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1250   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1251   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1252   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1253   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1254   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1255   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1256   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1257   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1258   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1259   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1260   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1261   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1262   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1263   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1264   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1265   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1266   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1267   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1268   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1269   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1270   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1271   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1272   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1273   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1274   case AArch64ISD::STRICT_FCMP:       return "AArch64ISD::STRICT_FCMP";
1275   case AArch64ISD::STRICT_FCMPE:      return "AArch64ISD::STRICT_FCMPE";
1276   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1277   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1278   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1279   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1280   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1281   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1282   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1283   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1284   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1285   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1286   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1287   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1288   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1289   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1290   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1291   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1292   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1293   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1294   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1295   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1296   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1297   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1298   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1299   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1300   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1301   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1302   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1303   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1304   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1305   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1306   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1307   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1308   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1309   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1310   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1311   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1312   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1313   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1314   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1315   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1316   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1317   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1318   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1319   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1320   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1321   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1322   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1323   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1324   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1325   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1326   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1327   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1328   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1329   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1330   case AArch64ISD::SMAXV_PRED:        return "AArch64ISD::SMAXV_PRED";
1331   case AArch64ISD::UMAXV_PRED:        return "AArch64ISD::UMAXV_PRED";
1332   case AArch64ISD::SMINV_PRED:        return "AArch64ISD::SMINV_PRED";
1333   case AArch64ISD::UMINV_PRED:        return "AArch64ISD::UMINV_PRED";
1334   case AArch64ISD::ORV_PRED:          return "AArch64ISD::ORV_PRED";
1335   case AArch64ISD::EORV_PRED:         return "AArch64ISD::EORV_PRED";
1336   case AArch64ISD::ANDV_PRED:         return "AArch64ISD::ANDV_PRED";
1337   case AArch64ISD::CLASTA_N:          return "AArch64ISD::CLASTA_N";
1338   case AArch64ISD::CLASTB_N:          return "AArch64ISD::CLASTB_N";
1339   case AArch64ISD::LASTA:             return "AArch64ISD::LASTA";
1340   case AArch64ISD::LASTB:             return "AArch64ISD::LASTB";
1341   case AArch64ISD::REV:               return "AArch64ISD::REV";
1342   case AArch64ISD::TBL:               return "AArch64ISD::TBL";
1343   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1344   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1345   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1346   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1347   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1348   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1349   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1350   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1351   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1352   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1353   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1354   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1355   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1356   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1357   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1358   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1359   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1360   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1361   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1362   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1363   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1364   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1365   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1366   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1367   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1368   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1369   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1370   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1371   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1372   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1373   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1374   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1375   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1376   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1377   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1378   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1379   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1380   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1381   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1382   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1383   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1384   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1385   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1386   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1387   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1388   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1389   case AArch64ISD::STG:               return "AArch64ISD::STG";
1390   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1391   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1392   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1393   case AArch64ISD::SUNPKHI:           return "AArch64ISD::SUNPKHI";
1394   case AArch64ISD::SUNPKLO:           return "AArch64ISD::SUNPKLO";
1395   case AArch64ISD::UUNPKHI:           return "AArch64ISD::UUNPKHI";
1396   case AArch64ISD::UUNPKLO:           return "AArch64ISD::UUNPKLO";
1397   case AArch64ISD::INSR:              return "AArch64ISD::INSR";
1398   case AArch64ISD::PTEST:             return "AArch64ISD::PTEST";
1399   case AArch64ISD::PTRUE:             return "AArch64ISD::PTRUE";
1400   case AArch64ISD::LDNF1:             return "AArch64ISD::LDNF1";
1401   case AArch64ISD::LDNF1S:            return "AArch64ISD::LDNF1S";
1402   case AArch64ISD::LDFF1:             return "AArch64ISD::LDFF1";
1403   case AArch64ISD::LDFF1S:            return "AArch64ISD::LDFF1S";
1404   case AArch64ISD::GLD1:              return "AArch64ISD::GLD1";
1405   case AArch64ISD::GLD1_SCALED:       return "AArch64ISD::GLD1_SCALED";
1406   case AArch64ISD::GLD1_SXTW:         return "AArch64ISD::GLD1_SXTW";
1407   case AArch64ISD::GLD1_UXTW:         return "AArch64ISD::GLD1_UXTW";
1408   case AArch64ISD::GLD1_SXTW_SCALED:  return "AArch64ISD::GLD1_SXTW_SCALED";
1409   case AArch64ISD::GLD1_UXTW_SCALED:  return "AArch64ISD::GLD1_UXTW_SCALED";
1410   case AArch64ISD::GLD1_IMM:          return "AArch64ISD::GLD1_IMM";
1411   case AArch64ISD::GLD1S:             return "AArch64ISD::GLD1S";
1412   case AArch64ISD::GLD1S_SCALED:      return "AArch64ISD::GLD1S_SCALED";
1413   case AArch64ISD::GLD1S_SXTW:        return "AArch64ISD::GLD1S_SXTW";
1414   case AArch64ISD::GLD1S_UXTW:        return "AArch64ISD::GLD1S_UXTW";
1415   case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1416   case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1417   case AArch64ISD::GLD1S_IMM:         return "AArch64ISD::GLD1S_IMM";
1418   case AArch64ISD::SST1:              return "AArch64ISD::SST1";
1419   case AArch64ISD::SST1_SCALED:       return "AArch64ISD::SST1_SCALED";
1420   case AArch64ISD::SST1_SXTW:         return "AArch64ISD::SST1_SXTW";
1421   case AArch64ISD::SST1_UXTW:         return "AArch64ISD::SST1_UXTW";
1422   case AArch64ISD::SST1_SXTW_SCALED:  return "AArch64ISD::SST1_SXTW_SCALED";
1423   case AArch64ISD::SST1_UXTW_SCALED:  return "AArch64ISD::SST1_UXTW_SCALED";
1424   case AArch64ISD::SST1_IMM:          return "AArch64ISD::SST1_IMM";
1425   case AArch64ISD::LDP:               return "AArch64ISD::LDP";
1426   case AArch64ISD::STP:               return "AArch64ISD::STP";
1427   case AArch64ISD::STNP:              return "AArch64ISD::STNP";
1428   }
1429   return nullptr;
1430 }
1431 
1432 MachineBasicBlock *
1433 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1434                                     MachineBasicBlock *MBB) const {
1435   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1436   // phi node:
1437 
1438   // OrigBB:
1439   //     [... previous instrs leading to comparison ...]
1440   //     b.ne TrueBB
1441   //     b EndBB
1442   // TrueBB:
1443   //     ; Fallthrough
1444   // EndBB:
1445   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1446 
1447   MachineFunction *MF = MBB->getParent();
1448   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1449   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1450   DebugLoc DL = MI.getDebugLoc();
1451   MachineFunction::iterator It = ++MBB->getIterator();
1452 
1453   Register DestReg = MI.getOperand(0).getReg();
1454   Register IfTrueReg = MI.getOperand(1).getReg();
1455   Register IfFalseReg = MI.getOperand(2).getReg();
1456   unsigned CondCode = MI.getOperand(3).getImm();
1457   bool NZCVKilled = MI.getOperand(4).isKill();
1458 
1459   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1460   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1461   MF->insert(It, TrueBB);
1462   MF->insert(It, EndBB);
1463 
1464   // Transfer rest of current basic-block to EndBB
1465   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1466                 MBB->end());
1467   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1468 
1469   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1470   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1471   MBB->addSuccessor(TrueBB);
1472   MBB->addSuccessor(EndBB);
1473 
1474   // TrueBB falls through to the end.
1475   TrueBB->addSuccessor(EndBB);
1476 
1477   if (!NZCVKilled) {
1478     TrueBB->addLiveIn(AArch64::NZCV);
1479     EndBB->addLiveIn(AArch64::NZCV);
1480   }
1481 
1482   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1483       .addReg(IfTrueReg)
1484       .addMBB(TrueBB)
1485       .addReg(IfFalseReg)
1486       .addMBB(MBB);
1487 
1488   MI.eraseFromParent();
1489   return EndBB;
1490 }
1491 
1492 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1493        MachineInstr &MI, MachineBasicBlock *BB) const {
1494   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1495              BB->getParent()->getFunction().getPersonalityFn())) &&
1496          "SEH does not use catchret!");
1497   return BB;
1498 }
1499 
1500 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1501      MachineInstr &MI, MachineBasicBlock *BB) const {
1502   MI.eraseFromParent();
1503   return BB;
1504 }
1505 
1506 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1507     MachineInstr &MI, MachineBasicBlock *BB) const {
1508   switch (MI.getOpcode()) {
1509   default:
1510 #ifndef NDEBUG
1511     MI.dump();
1512 #endif
1513     llvm_unreachable("Unexpected instruction for custom inserter!");
1514 
1515   case AArch64::F128CSEL:
1516     return EmitF128CSEL(MI, BB);
1517 
1518   case TargetOpcode::STACKMAP:
1519   case TargetOpcode::PATCHPOINT:
1520     return emitPatchPoint(MI, BB);
1521 
1522   case AArch64::CATCHRET:
1523     return EmitLoweredCatchRet(MI, BB);
1524   case AArch64::CATCHPAD:
1525     return EmitLoweredCatchPad(MI, BB);
1526   }
1527 }
1528 
1529 //===----------------------------------------------------------------------===//
1530 // AArch64 Lowering private implementation.
1531 //===----------------------------------------------------------------------===//
1532 
1533 //===----------------------------------------------------------------------===//
1534 // Lowering Code
1535 //===----------------------------------------------------------------------===//
1536 
1537 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1538 /// CC
1539 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1540   switch (CC) {
1541   default:
1542     llvm_unreachable("Unknown condition code!");
1543   case ISD::SETNE:
1544     return AArch64CC::NE;
1545   case ISD::SETEQ:
1546     return AArch64CC::EQ;
1547   case ISD::SETGT:
1548     return AArch64CC::GT;
1549   case ISD::SETGE:
1550     return AArch64CC::GE;
1551   case ISD::SETLT:
1552     return AArch64CC::LT;
1553   case ISD::SETLE:
1554     return AArch64CC::LE;
1555   case ISD::SETUGT:
1556     return AArch64CC::HI;
1557   case ISD::SETUGE:
1558     return AArch64CC::HS;
1559   case ISD::SETULT:
1560     return AArch64CC::LO;
1561   case ISD::SETULE:
1562     return AArch64CC::LS;
1563   }
1564 }
1565 
1566 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1567 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1568                                   AArch64CC::CondCode &CondCode,
1569                                   AArch64CC::CondCode &CondCode2) {
1570   CondCode2 = AArch64CC::AL;
1571   switch (CC) {
1572   default:
1573     llvm_unreachable("Unknown FP condition!");
1574   case ISD::SETEQ:
1575   case ISD::SETOEQ:
1576     CondCode = AArch64CC::EQ;
1577     break;
1578   case ISD::SETGT:
1579   case ISD::SETOGT:
1580     CondCode = AArch64CC::GT;
1581     break;
1582   case ISD::SETGE:
1583   case ISD::SETOGE:
1584     CondCode = AArch64CC::GE;
1585     break;
1586   case ISD::SETOLT:
1587     CondCode = AArch64CC::MI;
1588     break;
1589   case ISD::SETOLE:
1590     CondCode = AArch64CC::LS;
1591     break;
1592   case ISD::SETONE:
1593     CondCode = AArch64CC::MI;
1594     CondCode2 = AArch64CC::GT;
1595     break;
1596   case ISD::SETO:
1597     CondCode = AArch64CC::VC;
1598     break;
1599   case ISD::SETUO:
1600     CondCode = AArch64CC::VS;
1601     break;
1602   case ISD::SETUEQ:
1603     CondCode = AArch64CC::EQ;
1604     CondCode2 = AArch64CC::VS;
1605     break;
1606   case ISD::SETUGT:
1607     CondCode = AArch64CC::HI;
1608     break;
1609   case ISD::SETUGE:
1610     CondCode = AArch64CC::PL;
1611     break;
1612   case ISD::SETLT:
1613   case ISD::SETULT:
1614     CondCode = AArch64CC::LT;
1615     break;
1616   case ISD::SETLE:
1617   case ISD::SETULE:
1618     CondCode = AArch64CC::LE;
1619     break;
1620   case ISD::SETNE:
1621   case ISD::SETUNE:
1622     CondCode = AArch64CC::NE;
1623     break;
1624   }
1625 }
1626 
1627 /// Convert a DAG fp condition code to an AArch64 CC.
1628 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1629 /// should be AND'ed instead of OR'ed.
1630 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1631                                      AArch64CC::CondCode &CondCode,
1632                                      AArch64CC::CondCode &CondCode2) {
1633   CondCode2 = AArch64CC::AL;
1634   switch (CC) {
1635   default:
1636     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1637     assert(CondCode2 == AArch64CC::AL);
1638     break;
1639   case ISD::SETONE:
1640     // (a one b)
1641     // == ((a olt b) || (a ogt b))
1642     // == ((a ord b) && (a une b))
1643     CondCode = AArch64CC::VC;
1644     CondCode2 = AArch64CC::NE;
1645     break;
1646   case ISD::SETUEQ:
1647     // (a ueq b)
1648     // == ((a uno b) || (a oeq b))
1649     // == ((a ule b) && (a uge b))
1650     CondCode = AArch64CC::PL;
1651     CondCode2 = AArch64CC::LE;
1652     break;
1653   }
1654 }
1655 
1656 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1657 /// CC usable with the vector instructions. Fewer operations are available
1658 /// without a real NZCV register, so we have to use less efficient combinations
1659 /// to get the same effect.
1660 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1661                                         AArch64CC::CondCode &CondCode,
1662                                         AArch64CC::CondCode &CondCode2,
1663                                         bool &Invert) {
1664   Invert = false;
1665   switch (CC) {
1666   default:
1667     // Mostly the scalar mappings work fine.
1668     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1669     break;
1670   case ISD::SETUO:
1671     Invert = true;
1672     LLVM_FALLTHROUGH;
1673   case ISD::SETO:
1674     CondCode = AArch64CC::MI;
1675     CondCode2 = AArch64CC::GE;
1676     break;
1677   case ISD::SETUEQ:
1678   case ISD::SETULT:
1679   case ISD::SETULE:
1680   case ISD::SETUGT:
1681   case ISD::SETUGE:
1682     // All of the compare-mask comparisons are ordered, but we can switch
1683     // between the two by a double inversion. E.g. ULE == !OGT.
1684     Invert = true;
1685     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1686                           CondCode, CondCode2);
1687     break;
1688   }
1689 }
1690 
1691 static bool isLegalArithImmed(uint64_t C) {
1692   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1693   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1694   LLVM_DEBUG(dbgs() << "Is imm " << C
1695                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1696   return IsLegal;
1697 }
1698 
1699 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1700 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1701 // can be set differently by this operation. It comes down to whether
1702 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1703 // everything is fine. If not then the optimization is wrong. Thus general
1704 // comparisons are only valid if op2 != 0.
1705 //
1706 // So, finally, the only LLVM-native comparisons that don't mention C and V
1707 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1708 // the absence of information about op2.
1709 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1710   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1711          (CC == ISD::SETEQ || CC == ISD::SETNE);
1712 }
1713 
1714 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1715                                       SelectionDAG &DAG, SDValue Chain,
1716                                       bool IsSignaling) {
1717   EVT VT = LHS.getValueType();
1718   assert(VT != MVT::f128);
1719   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1720   unsigned Opcode =
1721       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1722   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1723 }
1724 
1725 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1726                               const SDLoc &dl, SelectionDAG &DAG) {
1727   EVT VT = LHS.getValueType();
1728   const bool FullFP16 =
1729     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1730 
1731   if (VT.isFloatingPoint()) {
1732     assert(VT != MVT::f128);
1733     if (VT == MVT::f16 && !FullFP16) {
1734       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1735       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1736       VT = MVT::f32;
1737     }
1738     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1739   }
1740 
1741   // The CMP instruction is just an alias for SUBS, and representing it as
1742   // SUBS means that it's possible to get CSE with subtract operations.
1743   // A later phase can perform the optimization of setting the destination
1744   // register to WZR/XZR if it ends up being unused.
1745   unsigned Opcode = AArch64ISD::SUBS;
1746 
1747   if (isCMN(RHS, CC)) {
1748     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1749     Opcode = AArch64ISD::ADDS;
1750     RHS = RHS.getOperand(1);
1751   } else if (isCMN(LHS, CC)) {
1752     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1753     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1754     Opcode = AArch64ISD::ADDS;
1755     LHS = LHS.getOperand(1);
1756   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1757              !isUnsignedIntSetCC(CC)) {
1758     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1759     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1760     // of the signed comparisons.
1761     Opcode = AArch64ISD::ANDS;
1762     RHS = LHS.getOperand(1);
1763     LHS = LHS.getOperand(0);
1764   }
1765 
1766   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1767       .getValue(1);
1768 }
1769 
1770 /// \defgroup AArch64CCMP CMP;CCMP matching
1771 ///
1772 /// These functions deal with the formation of CMP;CCMP;... sequences.
1773 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1774 /// a comparison. They set the NZCV flags to a predefined value if their
1775 /// predicate is false. This allows to express arbitrary conjunctions, for
1776 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1777 /// expressed as:
1778 ///   cmp A
1779 ///   ccmp B, inv(CB), CA
1780 ///   check for CB flags
1781 ///
1782 /// This naturally lets us implement chains of AND operations with SETCC
1783 /// operands. And we can even implement some other situations by transforming
1784 /// them:
1785 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1786 ///     negating the flags used in a CCMP/FCCMP operations.
1787 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1788 ///     by negating the flags we test for afterwards. i.e.
1789 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1790 ///   - Note that we can only ever negate all previously processed results.
1791 ///     What we can not implement by flipping the flags to test is a negation
1792 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1793 ///     far, so the 2nd sub-tree we emit would also affect the first).
1794 /// With those tools we can implement some OR operations:
1795 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1796 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1797 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1798 ///     elimination rules from earlier to implement the whole thing as a
1799 ///     CCMP/FCCMP chain.
1800 ///
1801 /// As complete example:
1802 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1803 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1804 /// can be reassociated to:
1805 ///     or (and (setCC (cmp C)) setCD (cmp D))
1806 //         (or (setCA (cmp A)) (setCB (cmp B)))
1807 /// can be transformed to:
1808 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1809 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1810 /// which can be implemented as:
1811 ///   cmp C
1812 ///   ccmp D, inv(CD), CC
1813 ///   ccmp A, CA, inv(CD)
1814 ///   ccmp B, CB, inv(CA)
1815 ///   check for CB flags
1816 ///
1817 /// A counterexample is "or (and A B) (and C D)" which translates to
1818 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1819 /// can only implement 1 of the inner (not) operations, but not both!
1820 /// @{
1821 
1822 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1823 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1824                                          ISD::CondCode CC, SDValue CCOp,
1825                                          AArch64CC::CondCode Predicate,
1826                                          AArch64CC::CondCode OutCC,
1827                                          const SDLoc &DL, SelectionDAG &DAG) {
1828   unsigned Opcode = 0;
1829   const bool FullFP16 =
1830     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1831 
1832   if (LHS.getValueType().isFloatingPoint()) {
1833     assert(LHS.getValueType() != MVT::f128);
1834     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1835       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1836       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1837     }
1838     Opcode = AArch64ISD::FCCMP;
1839   } else if (RHS.getOpcode() == ISD::SUB) {
1840     SDValue SubOp0 = RHS.getOperand(0);
1841     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1842       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1843       Opcode = AArch64ISD::CCMN;
1844       RHS = RHS.getOperand(1);
1845     }
1846   }
1847   if (Opcode == 0)
1848     Opcode = AArch64ISD::CCMP;
1849 
1850   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1851   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1852   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1853   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1854   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1855 }
1856 
1857 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1858 /// expressed as a conjunction. See \ref AArch64CCMP.
1859 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1860 ///                     changing the conditions on the SETCC tests.
1861 ///                     (this means we can call emitConjunctionRec() with
1862 ///                      Negate==true on this sub-tree)
1863 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1864 ///                     cannot do the negation naturally. We are required to
1865 ///                     emit the subtree first in this case.
1866 /// \param WillNegate   Is true if are called when the result of this
1867 ///                     subexpression must be negated. This happens when the
1868 ///                     outer expression is an OR. We can use this fact to know
1869 ///                     that we have a double negation (or (or ...) ...) that
1870 ///                     can be implemented for free.
1871 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1872                                bool &MustBeFirst, bool WillNegate,
1873                                unsigned Depth = 0) {
1874   if (!Val.hasOneUse())
1875     return false;
1876   unsigned Opcode = Val->getOpcode();
1877   if (Opcode == ISD::SETCC) {
1878     if (Val->getOperand(0).getValueType() == MVT::f128)
1879       return false;
1880     CanNegate = true;
1881     MustBeFirst = false;
1882     return true;
1883   }
1884   // Protect against exponential runtime and stack overflow.
1885   if (Depth > 6)
1886     return false;
1887   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1888     bool IsOR = Opcode == ISD::OR;
1889     SDValue O0 = Val->getOperand(0);
1890     SDValue O1 = Val->getOperand(1);
1891     bool CanNegateL;
1892     bool MustBeFirstL;
1893     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1894       return false;
1895     bool CanNegateR;
1896     bool MustBeFirstR;
1897     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1898       return false;
1899 
1900     if (MustBeFirstL && MustBeFirstR)
1901       return false;
1902 
1903     if (IsOR) {
1904       // For an OR expression we need to be able to naturally negate at least
1905       // one side or we cannot do the transformation at all.
1906       if (!CanNegateL && !CanNegateR)
1907         return false;
1908       // If we the result of the OR will be negated and we can naturally negate
1909       // the leafs, then this sub-tree as a whole negates naturally.
1910       CanNegate = WillNegate && CanNegateL && CanNegateR;
1911       // If we cannot naturally negate the whole sub-tree, then this must be
1912       // emitted first.
1913       MustBeFirst = !CanNegate;
1914     } else {
1915       assert(Opcode == ISD::AND && "Must be OR or AND");
1916       // We cannot naturally negate an AND operation.
1917       CanNegate = false;
1918       MustBeFirst = MustBeFirstL || MustBeFirstR;
1919     }
1920     return true;
1921   }
1922   return false;
1923 }
1924 
1925 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1926 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1927 /// Tries to transform the given i1 producing node @p Val to a series compare
1928 /// and conditional compare operations. @returns an NZCV flags producing node
1929 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1930 /// transformation was not possible.
1931 /// \p Negate is true if we want this sub-tree being negated just by changing
1932 /// SETCC conditions.
1933 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1934     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1935     AArch64CC::CondCode Predicate) {
1936   // We're at a tree leaf, produce a conditional comparison operation.
1937   unsigned Opcode = Val->getOpcode();
1938   if (Opcode == ISD::SETCC) {
1939     SDValue LHS = Val->getOperand(0);
1940     SDValue RHS = Val->getOperand(1);
1941     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1942     bool isInteger = LHS.getValueType().isInteger();
1943     if (Negate)
1944       CC = getSetCCInverse(CC, LHS.getValueType());
1945     SDLoc DL(Val);
1946     // Determine OutCC and handle FP special case.
1947     if (isInteger) {
1948       OutCC = changeIntCCToAArch64CC(CC);
1949     } else {
1950       assert(LHS.getValueType().isFloatingPoint());
1951       AArch64CC::CondCode ExtraCC;
1952       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1953       // Some floating point conditions can't be tested with a single condition
1954       // code. Construct an additional comparison in this case.
1955       if (ExtraCC != AArch64CC::AL) {
1956         SDValue ExtraCmp;
1957         if (!CCOp.getNode())
1958           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1959         else
1960           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1961                                                ExtraCC, DL, DAG);
1962         CCOp = ExtraCmp;
1963         Predicate = ExtraCC;
1964       }
1965     }
1966 
1967     // Produce a normal comparison if we are first in the chain
1968     if (!CCOp)
1969       return emitComparison(LHS, RHS, CC, DL, DAG);
1970     // Otherwise produce a ccmp.
1971     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1972                                      DAG);
1973   }
1974   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1975 
1976   bool IsOR = Opcode == ISD::OR;
1977 
1978   SDValue LHS = Val->getOperand(0);
1979   bool CanNegateL;
1980   bool MustBeFirstL;
1981   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1982   assert(ValidL && "Valid conjunction/disjunction tree");
1983   (void)ValidL;
1984 
1985   SDValue RHS = Val->getOperand(1);
1986   bool CanNegateR;
1987   bool MustBeFirstR;
1988   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1989   assert(ValidR && "Valid conjunction/disjunction tree");
1990   (void)ValidR;
1991 
1992   // Swap sub-tree that must come first to the right side.
1993   if (MustBeFirstL) {
1994     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1995     std::swap(LHS, RHS);
1996     std::swap(CanNegateL, CanNegateR);
1997     std::swap(MustBeFirstL, MustBeFirstR);
1998   }
1999 
2000   bool NegateR;
2001   bool NegateAfterR;
2002   bool NegateL;
2003   bool NegateAfterAll;
2004   if (Opcode == ISD::OR) {
2005     // Swap the sub-tree that we can negate naturally to the left.
2006     if (!CanNegateL) {
2007       assert(CanNegateR && "at least one side must be negatable");
2008       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2009       assert(!Negate);
2010       std::swap(LHS, RHS);
2011       NegateR = false;
2012       NegateAfterR = true;
2013     } else {
2014       // Negate the left sub-tree if possible, otherwise negate the result.
2015       NegateR = CanNegateR;
2016       NegateAfterR = !CanNegateR;
2017     }
2018     NegateL = true;
2019     NegateAfterAll = !Negate;
2020   } else {
2021     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2022     assert(!Negate && "Valid conjunction/disjunction tree");
2023 
2024     NegateL = false;
2025     NegateR = false;
2026     NegateAfterR = false;
2027     NegateAfterAll = false;
2028   }
2029 
2030   // Emit sub-trees.
2031   AArch64CC::CondCode RHSCC;
2032   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2033   if (NegateAfterR)
2034     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2035   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2036   if (NegateAfterAll)
2037     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2038   return CmpL;
2039 }
2040 
2041 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2042 /// In some cases this is even possible with OR operations in the expression.
2043 /// See \ref AArch64CCMP.
2044 /// \see emitConjunctionRec().
2045 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2046                                AArch64CC::CondCode &OutCC) {
2047   bool DummyCanNegate;
2048   bool DummyMustBeFirst;
2049   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2050     return SDValue();
2051 
2052   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2053 }
2054 
2055 /// @}
2056 
2057 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2058 /// extension operations.
2059 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2060   auto isSupportedExtend = [&](SDValue V) {
2061     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2062       return true;
2063 
2064     if (V.getOpcode() == ISD::AND)
2065       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2066         uint64_t Mask = MaskCst->getZExtValue();
2067         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2068       }
2069 
2070     return false;
2071   };
2072 
2073   if (!Op.hasOneUse())
2074     return 0;
2075 
2076   if (isSupportedExtend(Op))
2077     return 1;
2078 
2079   unsigned Opc = Op.getOpcode();
2080   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2081     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2082       uint64_t Shift = ShiftCst->getZExtValue();
2083       if (isSupportedExtend(Op.getOperand(0)))
2084         return (Shift <= 4) ? 2 : 1;
2085       EVT VT = Op.getValueType();
2086       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2087         return 1;
2088     }
2089 
2090   return 0;
2091 }
2092 
2093 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2094                              SDValue &AArch64cc, SelectionDAG &DAG,
2095                              const SDLoc &dl) {
2096   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2097     EVT VT = RHS.getValueType();
2098     uint64_t C = RHSC->getZExtValue();
2099     if (!isLegalArithImmed(C)) {
2100       // Constant does not fit, try adjusting it by one?
2101       switch (CC) {
2102       default:
2103         break;
2104       case ISD::SETLT:
2105       case ISD::SETGE:
2106         if ((VT == MVT::i32 && C != 0x80000000 &&
2107              isLegalArithImmed((uint32_t)(C - 1))) ||
2108             (VT == MVT::i64 && C != 0x80000000ULL &&
2109              isLegalArithImmed(C - 1ULL))) {
2110           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2111           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2112           RHS = DAG.getConstant(C, dl, VT);
2113         }
2114         break;
2115       case ISD::SETULT:
2116       case ISD::SETUGE:
2117         if ((VT == MVT::i32 && C != 0 &&
2118              isLegalArithImmed((uint32_t)(C - 1))) ||
2119             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2120           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2121           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2122           RHS = DAG.getConstant(C, dl, VT);
2123         }
2124         break;
2125       case ISD::SETLE:
2126       case ISD::SETGT:
2127         if ((VT == MVT::i32 && C != INT32_MAX &&
2128              isLegalArithImmed((uint32_t)(C + 1))) ||
2129             (VT == MVT::i64 && C != INT64_MAX &&
2130              isLegalArithImmed(C + 1ULL))) {
2131           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2132           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2133           RHS = DAG.getConstant(C, dl, VT);
2134         }
2135         break;
2136       case ISD::SETULE:
2137       case ISD::SETUGT:
2138         if ((VT == MVT::i32 && C != UINT32_MAX &&
2139              isLegalArithImmed((uint32_t)(C + 1))) ||
2140             (VT == MVT::i64 && C != UINT64_MAX &&
2141              isLegalArithImmed(C + 1ULL))) {
2142           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2143           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2144           RHS = DAG.getConstant(C, dl, VT);
2145         }
2146         break;
2147       }
2148     }
2149   }
2150 
2151   // Comparisons are canonicalized so that the RHS operand is simpler than the
2152   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2153   // can fold some shift+extend operations on the RHS operand, so swap the
2154   // operands if that can be done.
2155   //
2156   // For example:
2157   //    lsl     w13, w11, #1
2158   //    cmp     w13, w12
2159   // can be turned into:
2160   //    cmp     w12, w11, lsl #1
2161   if (!isa<ConstantSDNode>(RHS) ||
2162       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2163     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2164 
2165     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2166       std::swap(LHS, RHS);
2167       CC = ISD::getSetCCSwappedOperands(CC);
2168     }
2169   }
2170 
2171   SDValue Cmp;
2172   AArch64CC::CondCode AArch64CC;
2173   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2174     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2175 
2176     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2177     // For the i8 operand, the largest immediate is 255, so this can be easily
2178     // encoded in the compare instruction. For the i16 operand, however, the
2179     // largest immediate cannot be encoded in the compare.
2180     // Therefore, use a sign extending load and cmn to avoid materializing the
2181     // -1 constant. For example,
2182     // movz w1, #65535
2183     // ldrh w0, [x0, #0]
2184     // cmp w0, w1
2185     // >
2186     // ldrsh w0, [x0, #0]
2187     // cmn w0, #1
2188     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2189     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2190     // ensure both the LHS and RHS are truly zero extended and to make sure the
2191     // transformation is profitable.
2192     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2193         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2194         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2195         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2196       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2197       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2198         SDValue SExt =
2199             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2200                         DAG.getValueType(MVT::i16));
2201         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2202                                                    RHS.getValueType()),
2203                              CC, dl, DAG);
2204         AArch64CC = changeIntCCToAArch64CC(CC);
2205       }
2206     }
2207 
2208     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2209       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2210         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2211           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2212       }
2213     }
2214   }
2215 
2216   if (!Cmp) {
2217     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2218     AArch64CC = changeIntCCToAArch64CC(CC);
2219   }
2220   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2221   return Cmp;
2222 }
2223 
2224 static std::pair<SDValue, SDValue>
2225 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2226   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2227          "Unsupported value type");
2228   SDValue Value, Overflow;
2229   SDLoc DL(Op);
2230   SDValue LHS = Op.getOperand(0);
2231   SDValue RHS = Op.getOperand(1);
2232   unsigned Opc = 0;
2233   switch (Op.getOpcode()) {
2234   default:
2235     llvm_unreachable("Unknown overflow instruction!");
2236   case ISD::SADDO:
2237     Opc = AArch64ISD::ADDS;
2238     CC = AArch64CC::VS;
2239     break;
2240   case ISD::UADDO:
2241     Opc = AArch64ISD::ADDS;
2242     CC = AArch64CC::HS;
2243     break;
2244   case ISD::SSUBO:
2245     Opc = AArch64ISD::SUBS;
2246     CC = AArch64CC::VS;
2247     break;
2248   case ISD::USUBO:
2249     Opc = AArch64ISD::SUBS;
2250     CC = AArch64CC::LO;
2251     break;
2252   // Multiply needs a little bit extra work.
2253   case ISD::SMULO:
2254   case ISD::UMULO: {
2255     CC = AArch64CC::NE;
2256     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2257     if (Op.getValueType() == MVT::i32) {
2258       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2259       // For a 32 bit multiply with overflow check we want the instruction
2260       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2261       // need to generate the following pattern:
2262       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2263       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2264       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2265       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2266       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2267                                 DAG.getConstant(0, DL, MVT::i64));
2268       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2269       // operation. We need to clear out the upper 32 bits, because we used a
2270       // widening multiply that wrote all 64 bits. In the end this should be a
2271       // noop.
2272       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2273       if (IsSigned) {
2274         // The signed overflow check requires more than just a simple check for
2275         // any bit set in the upper 32 bits of the result. These bits could be
2276         // just the sign bits of a negative number. To perform the overflow
2277         // check we have to arithmetic shift right the 32nd bit of the result by
2278         // 31 bits. Then we compare the result to the upper 32 bits.
2279         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2280                                         DAG.getConstant(32, DL, MVT::i64));
2281         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2282         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2283                                         DAG.getConstant(31, DL, MVT::i64));
2284         // It is important that LowerBits is last, otherwise the arithmetic
2285         // shift will not be folded into the compare (SUBS).
2286         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2287         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2288                        .getValue(1);
2289       } else {
2290         // The overflow check for unsigned multiply is easy. We only need to
2291         // check if any of the upper 32 bits are set. This can be done with a
2292         // CMP (shifted register). For that we need to generate the following
2293         // pattern:
2294         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2295         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2296                                         DAG.getConstant(32, DL, MVT::i64));
2297         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2298         Overflow =
2299             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2300                         DAG.getConstant(0, DL, MVT::i64),
2301                         UpperBits).getValue(1);
2302       }
2303       break;
2304     }
2305     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2306     // For the 64 bit multiply
2307     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2308     if (IsSigned) {
2309       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2310       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2311                                       DAG.getConstant(63, DL, MVT::i64));
2312       // It is important that LowerBits is last, otherwise the arithmetic
2313       // shift will not be folded into the compare (SUBS).
2314       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2315       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2316                      .getValue(1);
2317     } else {
2318       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2319       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2320       Overflow =
2321           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2322                       DAG.getConstant(0, DL, MVT::i64),
2323                       UpperBits).getValue(1);
2324     }
2325     break;
2326   }
2327   } // switch (...)
2328 
2329   if (Opc) {
2330     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2331 
2332     // Emit the AArch64 operation with overflow check.
2333     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2334     Overflow = Value.getValue(1);
2335   }
2336   return std::make_pair(Value, Overflow);
2337 }
2338 
2339 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2340                                              RTLIB::Libcall Call) const {
2341   bool IsStrict = Op->isStrictFPOpcode();
2342   unsigned Offset = IsStrict ? 1 : 0;
2343   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2344   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2345   MakeLibCallOptions CallOptions;
2346   SDValue Result;
2347   SDLoc dl(Op);
2348   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2349                                         CallOptions, dl, Chain);
2350   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2351 }
2352 
2353 // Returns true if the given Op is the overflow flag result of an overflow
2354 // intrinsic operation.
2355 static bool isOverflowIntrOpRes(SDValue Op) {
2356   unsigned Opc = Op.getOpcode();
2357   return (Op.getResNo() == 1 &&
2358           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2359            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2360 }
2361 
2362 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2363   SDValue Sel = Op.getOperand(0);
2364   SDValue Other = Op.getOperand(1);
2365   SDLoc dl(Sel);
2366 
2367   // If the operand is an overflow checking operation, invert the condition
2368   // code and kill the Not operation. I.e., transform:
2369   // (xor (overflow_op_bool, 1))
2370   //   -->
2371   // (csel 1, 0, invert(cc), overflow_op_bool)
2372   // ... which later gets transformed to just a cset instruction with an
2373   // inverted condition code, rather than a cset + eor sequence.
2374   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2375     // Only lower legal XALUO ops.
2376     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2377       return SDValue();
2378 
2379     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2380     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2381     AArch64CC::CondCode CC;
2382     SDValue Value, Overflow;
2383     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2384     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2385     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2386                        CCVal, Overflow);
2387   }
2388   // If neither operand is a SELECT_CC, give up.
2389   if (Sel.getOpcode() != ISD::SELECT_CC)
2390     std::swap(Sel, Other);
2391   if (Sel.getOpcode() != ISD::SELECT_CC)
2392     return Op;
2393 
2394   // The folding we want to perform is:
2395   // (xor x, (select_cc a, b, cc, 0, -1) )
2396   //   -->
2397   // (csel x, (xor x, -1), cc ...)
2398   //
2399   // The latter will get matched to a CSINV instruction.
2400 
2401   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2402   SDValue LHS = Sel.getOperand(0);
2403   SDValue RHS = Sel.getOperand(1);
2404   SDValue TVal = Sel.getOperand(2);
2405   SDValue FVal = Sel.getOperand(3);
2406 
2407   // FIXME: This could be generalized to non-integer comparisons.
2408   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2409     return Op;
2410 
2411   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2412   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2413 
2414   // The values aren't constants, this isn't the pattern we're looking for.
2415   if (!CFVal || !CTVal)
2416     return Op;
2417 
2418   // We can commute the SELECT_CC by inverting the condition.  This
2419   // might be needed to make this fit into a CSINV pattern.
2420   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2421     std::swap(TVal, FVal);
2422     std::swap(CTVal, CFVal);
2423     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2424   }
2425 
2426   // If the constants line up, perform the transform!
2427   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2428     SDValue CCVal;
2429     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2430 
2431     FVal = Other;
2432     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2433                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2434 
2435     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2436                        CCVal, Cmp);
2437   }
2438 
2439   return Op;
2440 }
2441 
2442 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2443   EVT VT = Op.getValueType();
2444 
2445   // Let legalize expand this if it isn't a legal type yet.
2446   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2447     return SDValue();
2448 
2449   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2450 
2451   unsigned Opc;
2452   bool ExtraOp = false;
2453   switch (Op.getOpcode()) {
2454   default:
2455     llvm_unreachable("Invalid code");
2456   case ISD::ADDC:
2457     Opc = AArch64ISD::ADDS;
2458     break;
2459   case ISD::SUBC:
2460     Opc = AArch64ISD::SUBS;
2461     break;
2462   case ISD::ADDE:
2463     Opc = AArch64ISD::ADCS;
2464     ExtraOp = true;
2465     break;
2466   case ISD::SUBE:
2467     Opc = AArch64ISD::SBCS;
2468     ExtraOp = true;
2469     break;
2470   }
2471 
2472   if (!ExtraOp)
2473     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2474   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2475                      Op.getOperand(2));
2476 }
2477 
2478 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2479   // Let legalize expand this if it isn't a legal type yet.
2480   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2481     return SDValue();
2482 
2483   SDLoc dl(Op);
2484   AArch64CC::CondCode CC;
2485   // The actual operation that sets the overflow or carry flag.
2486   SDValue Value, Overflow;
2487   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2488 
2489   // We use 0 and 1 as false and true values.
2490   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2491   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2492 
2493   // We use an inverted condition, because the conditional select is inverted
2494   // too. This will allow it to be selected to a single instruction:
2495   // CSINC Wd, WZR, WZR, invert(cond).
2496   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2497   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2498                          CCVal, Overflow);
2499 
2500   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2501   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2502 }
2503 
2504 // Prefetch operands are:
2505 // 1: Address to prefetch
2506 // 2: bool isWrite
2507 // 3: int locality (0 = no locality ... 3 = extreme locality)
2508 // 4: bool isDataCache
2509 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2510   SDLoc DL(Op);
2511   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2512   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2513   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2514 
2515   bool IsStream = !Locality;
2516   // When the locality number is set
2517   if (Locality) {
2518     // The front-end should have filtered out the out-of-range values
2519     assert(Locality <= 3 && "Prefetch locality out-of-range");
2520     // The locality degree is the opposite of the cache speed.
2521     // Put the number the other way around.
2522     // The encoding starts at 0 for level 1
2523     Locality = 3 - Locality;
2524   }
2525 
2526   // built the mask value encoding the expected behavior.
2527   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2528                    (!IsData << 3) |     // IsDataCache bit
2529                    (Locality << 1) |    // Cache level bits
2530                    (unsigned)IsStream;  // Stream bit
2531   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2532                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2533 }
2534 
2535 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2536                                               SelectionDAG &DAG) const {
2537   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2538 
2539   RTLIB::Libcall LC;
2540   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2541 
2542   return LowerF128Call(Op, DAG, LC);
2543 }
2544 
2545 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2546                                              SelectionDAG &DAG) const {
2547   bool IsStrict = Op->isStrictFPOpcode();
2548   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2549   if (SrcVal.getValueType() != MVT::f128) {
2550     // It's legal except when f128 is involved
2551     return Op;
2552   }
2553 
2554   RTLIB::Libcall LC;
2555   LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType());
2556 
2557   // FP_ROUND node has a second operand indicating whether it is known to be
2558   // precise. That doesn't take part in the LibCall so we can't directly use
2559   // LowerF128Call.
2560   MakeLibCallOptions CallOptions;
2561   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2562   SDValue Result;
2563   SDLoc dl(Op);
2564   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2565                                         CallOptions, dl, Chain);
2566   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2567 }
2568 
2569 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2570                                                     SelectionDAG &DAG) const {
2571   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2572   // Any additional optimization in this function should be recorded
2573   // in the cost tables.
2574   EVT InVT = Op.getOperand(0).getValueType();
2575   EVT VT = Op.getValueType();
2576   unsigned NumElts = InVT.getVectorNumElements();
2577 
2578   // f16 conversions are promoted to f32 when full fp16 is not supported.
2579   if (InVT.getVectorElementType() == MVT::f16 &&
2580       !Subtarget->hasFullFP16()) {
2581     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2582     SDLoc dl(Op);
2583     return DAG.getNode(
2584         Op.getOpcode(), dl, Op.getValueType(),
2585         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2586   }
2587 
2588   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2589     SDLoc dl(Op);
2590     SDValue Cv =
2591         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2592                     Op.getOperand(0));
2593     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2594   }
2595 
2596   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2597     SDLoc dl(Op);
2598     MVT ExtVT =
2599         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2600                          VT.getVectorNumElements());
2601     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2602     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2603   }
2604 
2605   // Type changing conversions are illegal.
2606   return Op;
2607 }
2608 
2609 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2610                                               SelectionDAG &DAG) const {
2611   bool IsStrict = Op->isStrictFPOpcode();
2612   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2613 
2614   if (SrcVal.getValueType().isVector())
2615     return LowerVectorFP_TO_INT(Op, DAG);
2616 
2617   // f16 conversions are promoted to f32 when full fp16 is not supported.
2618   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2619     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2620     SDLoc dl(Op);
2621     return DAG.getNode(
2622         Op.getOpcode(), dl, Op.getValueType(),
2623         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2624   }
2625 
2626   if (SrcVal.getValueType() != MVT::f128) {
2627     // It's legal except when f128 is involved
2628     return Op;
2629   }
2630 
2631   RTLIB::Libcall LC;
2632   if (Op.getOpcode() == ISD::FP_TO_SINT ||
2633       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2634     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2635   else
2636     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2637 
2638   return LowerF128Call(Op, DAG, LC);
2639 }
2640 
2641 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2642   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2643   // Any additional optimization in this function should be recorded
2644   // in the cost tables.
2645   EVT VT = Op.getValueType();
2646   SDLoc dl(Op);
2647   SDValue In = Op.getOperand(0);
2648   EVT InVT = In.getValueType();
2649 
2650   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2651     MVT CastVT =
2652         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2653                          InVT.getVectorNumElements());
2654     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2655     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2656   }
2657 
2658   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2659     unsigned CastOpc =
2660         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2661     EVT CastVT = VT.changeVectorElementTypeToInteger();
2662     In = DAG.getNode(CastOpc, dl, CastVT, In);
2663     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2664   }
2665 
2666   return Op;
2667 }
2668 
2669 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2670                                             SelectionDAG &DAG) const {
2671   if (Op.getValueType().isVector())
2672     return LowerVectorINT_TO_FP(Op, DAG);
2673 
2674   bool IsStrict = Op->isStrictFPOpcode();
2675   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2676 
2677   // f16 conversions are promoted to f32 when full fp16 is not supported.
2678   if (Op.getValueType() == MVT::f16 &&
2679       !Subtarget->hasFullFP16()) {
2680     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2681     SDLoc dl(Op);
2682     return DAG.getNode(
2683         ISD::FP_ROUND, dl, MVT::f16,
2684         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2685         DAG.getIntPtrConstant(0, dl));
2686   }
2687 
2688   // i128 conversions are libcalls.
2689   if (SrcVal.getValueType() == MVT::i128)
2690     return SDValue();
2691 
2692   // Other conversions are legal, unless it's to the completely software-based
2693   // fp128.
2694   if (Op.getValueType() != MVT::f128)
2695     return Op;
2696 
2697   RTLIB::Libcall LC;
2698   if (Op.getOpcode() == ISD::SINT_TO_FP ||
2699       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2700     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2701   else
2702     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2703 
2704   return LowerF128Call(Op, DAG, LC);
2705 }
2706 
2707 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2708                                             SelectionDAG &DAG) const {
2709   // For iOS, we want to call an alternative entry point: __sincos_stret,
2710   // which returns the values in two S / D registers.
2711   SDLoc dl(Op);
2712   SDValue Arg = Op.getOperand(0);
2713   EVT ArgVT = Arg.getValueType();
2714   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2715 
2716   ArgListTy Args;
2717   ArgListEntry Entry;
2718 
2719   Entry.Node = Arg;
2720   Entry.Ty = ArgTy;
2721   Entry.IsSExt = false;
2722   Entry.IsZExt = false;
2723   Args.push_back(Entry);
2724 
2725   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2726                                         : RTLIB::SINCOS_STRET_F32;
2727   const char *LibcallName = getLibcallName(LC);
2728   SDValue Callee =
2729       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2730 
2731   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2732   TargetLowering::CallLoweringInfo CLI(DAG);
2733   CLI.setDebugLoc(dl)
2734       .setChain(DAG.getEntryNode())
2735       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2736 
2737   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2738   return CallResult.first;
2739 }
2740 
2741 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2742   if (Op.getValueType() != MVT::f16)
2743     return SDValue();
2744 
2745   assert(Op.getOperand(0).getValueType() == MVT::i16);
2746   SDLoc DL(Op);
2747 
2748   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2749   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2750   return SDValue(
2751       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2752                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2753       0);
2754 }
2755 
2756 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2757   if (OrigVT.getSizeInBits() >= 64)
2758     return OrigVT;
2759 
2760   assert(OrigVT.isSimple() && "Expecting a simple value type");
2761 
2762   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2763   switch (OrigSimpleTy) {
2764   default: llvm_unreachable("Unexpected Vector Type");
2765   case MVT::v2i8:
2766   case MVT::v2i16:
2767      return MVT::v2i32;
2768   case MVT::v4i8:
2769     return  MVT::v4i16;
2770   }
2771 }
2772 
2773 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2774                                                  const EVT &OrigTy,
2775                                                  const EVT &ExtTy,
2776                                                  unsigned ExtOpcode) {
2777   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2778   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2779   // 64-bits we need to insert a new extension so that it will be 64-bits.
2780   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2781   if (OrigTy.getSizeInBits() >= 64)
2782     return N;
2783 
2784   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2785   EVT NewVT = getExtensionTo64Bits(OrigTy);
2786 
2787   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2788 }
2789 
2790 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2791                                    bool isSigned) {
2792   EVT VT = N->getValueType(0);
2793 
2794   if (N->getOpcode() != ISD::BUILD_VECTOR)
2795     return false;
2796 
2797   for (const SDValue &Elt : N->op_values()) {
2798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2799       unsigned EltSize = VT.getScalarSizeInBits();
2800       unsigned HalfSize = EltSize / 2;
2801       if (isSigned) {
2802         if (!isIntN(HalfSize, C->getSExtValue()))
2803           return false;
2804       } else {
2805         if (!isUIntN(HalfSize, C->getZExtValue()))
2806           return false;
2807       }
2808       continue;
2809     }
2810     return false;
2811   }
2812 
2813   return true;
2814 }
2815 
2816 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2817   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2818     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2819                                              N->getOperand(0)->getValueType(0),
2820                                              N->getValueType(0),
2821                                              N->getOpcode());
2822 
2823   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2824   EVT VT = N->getValueType(0);
2825   SDLoc dl(N);
2826   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2827   unsigned NumElts = VT.getVectorNumElements();
2828   MVT TruncVT = MVT::getIntegerVT(EltSize);
2829   SmallVector<SDValue, 8> Ops;
2830   for (unsigned i = 0; i != NumElts; ++i) {
2831     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2832     const APInt &CInt = C->getAPIntValue();
2833     // Element types smaller than 32 bits are not legal, so use i32 elements.
2834     // The values are implicitly truncated so sext vs. zext doesn't matter.
2835     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2836   }
2837   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2838 }
2839 
2840 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2841   return N->getOpcode() == ISD::SIGN_EXTEND ||
2842          isExtendedBUILD_VECTOR(N, DAG, true);
2843 }
2844 
2845 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2846   return N->getOpcode() == ISD::ZERO_EXTEND ||
2847          isExtendedBUILD_VECTOR(N, DAG, false);
2848 }
2849 
2850 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2851   unsigned Opcode = N->getOpcode();
2852   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2853     SDNode *N0 = N->getOperand(0).getNode();
2854     SDNode *N1 = N->getOperand(1).getNode();
2855     return N0->hasOneUse() && N1->hasOneUse() &&
2856       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2857   }
2858   return false;
2859 }
2860 
2861 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2862   unsigned Opcode = N->getOpcode();
2863   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2864     SDNode *N0 = N->getOperand(0).getNode();
2865     SDNode *N1 = N->getOperand(1).getNode();
2866     return N0->hasOneUse() && N1->hasOneUse() &&
2867       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2868   }
2869   return false;
2870 }
2871 
2872 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2873                                                 SelectionDAG &DAG) const {
2874   // The rounding mode is in bits 23:22 of the FPSCR.
2875   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2876   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2877   // so that the shift + and get folded into a bitfield extract.
2878   SDLoc dl(Op);
2879 
2880   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2881                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2882                                                 MVT::i64));
2883   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2884   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2885                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2886   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2887                               DAG.getConstant(22, dl, MVT::i32));
2888   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2889                      DAG.getConstant(3, dl, MVT::i32));
2890 }
2891 
2892 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2893   // Multiplications are only custom-lowered for 128-bit vectors so that
2894   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2895   EVT VT = Op.getValueType();
2896   assert(VT.is128BitVector() && VT.isInteger() &&
2897          "unexpected type for custom-lowering ISD::MUL");
2898   SDNode *N0 = Op.getOperand(0).getNode();
2899   SDNode *N1 = Op.getOperand(1).getNode();
2900   unsigned NewOpc = 0;
2901   bool isMLA = false;
2902   bool isN0SExt = isSignExtended(N0, DAG);
2903   bool isN1SExt = isSignExtended(N1, DAG);
2904   if (isN0SExt && isN1SExt)
2905     NewOpc = AArch64ISD::SMULL;
2906   else {
2907     bool isN0ZExt = isZeroExtended(N0, DAG);
2908     bool isN1ZExt = isZeroExtended(N1, DAG);
2909     if (isN0ZExt && isN1ZExt)
2910       NewOpc = AArch64ISD::UMULL;
2911     else if (isN1SExt || isN1ZExt) {
2912       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2913       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2914       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2915         NewOpc = AArch64ISD::SMULL;
2916         isMLA = true;
2917       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2918         NewOpc =  AArch64ISD::UMULL;
2919         isMLA = true;
2920       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2921         std::swap(N0, N1);
2922         NewOpc =  AArch64ISD::UMULL;
2923         isMLA = true;
2924       }
2925     }
2926 
2927     if (!NewOpc) {
2928       if (VT == MVT::v2i64)
2929         // Fall through to expand this.  It is not legal.
2930         return SDValue();
2931       else
2932         // Other vector multiplications are legal.
2933         return Op;
2934     }
2935   }
2936 
2937   // Legalize to a S/UMULL instruction
2938   SDLoc DL(Op);
2939   SDValue Op0;
2940   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2941   if (!isMLA) {
2942     Op0 = skipExtensionForVectorMULL(N0, DAG);
2943     assert(Op0.getValueType().is64BitVector() &&
2944            Op1.getValueType().is64BitVector() &&
2945            "unexpected types for extended operands to VMULL");
2946     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2947   }
2948   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2949   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2950   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2951   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2952   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2953   EVT Op1VT = Op1.getValueType();
2954   return DAG.getNode(N0->getOpcode(), DL, VT,
2955                      DAG.getNode(NewOpc, DL, VT,
2956                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2957                      DAG.getNode(NewOpc, DL, VT,
2958                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2959 }
2960 
2961 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2962                                                      SelectionDAG &DAG) const {
2963   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2964   SDLoc dl(Op);
2965   switch (IntNo) {
2966   default: return SDValue();    // Don't custom lower most intrinsics.
2967   case Intrinsic::thread_pointer: {
2968     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2969     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2970   }
2971   case Intrinsic::aarch64_neon_abs: {
2972     EVT Ty = Op.getValueType();
2973     if (Ty == MVT::i64) {
2974       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2975                                    Op.getOperand(1));
2976       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2977       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2978     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2979       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2980     } else {
2981       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2982     }
2983   }
2984   case Intrinsic::aarch64_neon_smax:
2985     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2986                        Op.getOperand(1), Op.getOperand(2));
2987   case Intrinsic::aarch64_neon_umax:
2988     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2989                        Op.getOperand(1), Op.getOperand(2));
2990   case Intrinsic::aarch64_neon_smin:
2991     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2992                        Op.getOperand(1), Op.getOperand(2));
2993   case Intrinsic::aarch64_neon_umin:
2994     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2995                        Op.getOperand(1), Op.getOperand(2));
2996 
2997   case Intrinsic::aarch64_sve_sunpkhi:
2998     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
2999                        Op.getOperand(1));
3000   case Intrinsic::aarch64_sve_sunpklo:
3001     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3002                        Op.getOperand(1));
3003   case Intrinsic::aarch64_sve_uunpkhi:
3004     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3005                        Op.getOperand(1));
3006   case Intrinsic::aarch64_sve_uunpklo:
3007     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3008                        Op.getOperand(1));
3009   case Intrinsic::aarch64_sve_clasta_n:
3010     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3011                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3012   case Intrinsic::aarch64_sve_clastb_n:
3013     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3014                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3015   case Intrinsic::aarch64_sve_lasta:
3016     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3017                        Op.getOperand(1), Op.getOperand(2));
3018   case Intrinsic::aarch64_sve_lastb:
3019     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3020                        Op.getOperand(1), Op.getOperand(2));
3021   case Intrinsic::aarch64_sve_rev:
3022     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3023                        Op.getOperand(1));
3024   case Intrinsic::aarch64_sve_tbl:
3025     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3026                        Op.getOperand(1), Op.getOperand(2));
3027   case Intrinsic::aarch64_sve_trn1:
3028     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3029                        Op.getOperand(1), Op.getOperand(2));
3030   case Intrinsic::aarch64_sve_trn2:
3031     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3032                        Op.getOperand(1), Op.getOperand(2));
3033   case Intrinsic::aarch64_sve_uzp1:
3034     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3035                        Op.getOperand(1), Op.getOperand(2));
3036   case Intrinsic::aarch64_sve_uzp2:
3037     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3038                        Op.getOperand(1), Op.getOperand(2));
3039   case Intrinsic::aarch64_sve_zip1:
3040     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3041                        Op.getOperand(1), Op.getOperand(2));
3042   case Intrinsic::aarch64_sve_zip2:
3043     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3044                        Op.getOperand(1), Op.getOperand(2));
3045   case Intrinsic::aarch64_sve_ptrue:
3046     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3047                        Op.getOperand(1));
3048 
3049   case Intrinsic::aarch64_sve_insr: {
3050     SDValue Scalar = Op.getOperand(2);
3051     EVT ScalarTy = Scalar.getValueType();
3052     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3053       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3054 
3055     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3056                        Op.getOperand(1), Scalar);
3057   }
3058 
3059   case Intrinsic::localaddress: {
3060     const auto &MF = DAG.getMachineFunction();
3061     const auto *RegInfo = Subtarget->getRegisterInfo();
3062     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3063     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3064                               Op.getSimpleValueType());
3065   }
3066 
3067   case Intrinsic::eh_recoverfp: {
3068     // FIXME: This needs to be implemented to correctly handle highly aligned
3069     // stack objects. For now we simply return the incoming FP. Refer D53541
3070     // for more details.
3071     SDValue FnOp = Op.getOperand(1);
3072     SDValue IncomingFPOp = Op.getOperand(2);
3073     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3074     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3075     if (!Fn)
3076       report_fatal_error(
3077           "llvm.eh.recoverfp must take a function as the first argument");
3078     return IncomingFPOp;
3079   }
3080   }
3081 }
3082 
3083 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3084   return ExtVal.getValueType().isScalableVector();
3085 }
3086 
3087 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3088 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3089                                         EVT VT, EVT MemVT,
3090                                         SelectionDAG &DAG) {
3091   assert(VT.isVector() && "VT should be a vector type");
3092   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3093 
3094   SDValue Value = ST->getValue();
3095 
3096   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3097   // the word lane which represent the v4i8 subvector.  It optimizes the store
3098   // to:
3099   //
3100   //   xtn  v0.8b, v0.8h
3101   //   str  s0, [x0]
3102 
3103   SDValue Undef = DAG.getUNDEF(MVT::i16);
3104   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3105                                         {Undef, Undef, Undef, Undef});
3106 
3107   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3108                                  Value, UndefVec);
3109   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3110 
3111   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3112   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3113                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3114 
3115   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3116                       ST->getBasePtr(), ST->getMemOperand());
3117 }
3118 
3119 // Custom lowering for any store, vector or scalar and/or default or with
3120 // a truncate operations.  Currently only custom lower truncate operation
3121 // from vector v4i16 to v4i8 or volatile stores of i128.
3122 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3123                                           SelectionDAG &DAG) const {
3124   SDLoc Dl(Op);
3125   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3126   assert (StoreNode && "Can only custom lower store nodes");
3127 
3128   SDValue Value = StoreNode->getValue();
3129 
3130   EVT VT = Value.getValueType();
3131   EVT MemVT = StoreNode->getMemoryVT();
3132 
3133   if (VT.isVector()) {
3134     unsigned AS = StoreNode->getAddressSpace();
3135     unsigned Align = StoreNode->getAlignment();
3136     if (Align < MemVT.getStoreSize() &&
3137         !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3138                                         StoreNode->getMemOperand()->getFlags(),
3139                                         nullptr)) {
3140       return scalarizeVectorStore(StoreNode, DAG);
3141     }
3142 
3143     if (StoreNode->isTruncatingStore()) {
3144       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3145     }
3146     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3147     // the custom lowering, as there are no un-paired non-temporal stores and
3148     // legalization will break up 256 bit inputs.
3149     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3150         MemVT.getVectorElementCount().Min % 2u == 0 &&
3151         ((MemVT.getScalarSizeInBits() == 8u ||
3152           MemVT.getScalarSizeInBits() == 16u ||
3153           MemVT.getScalarSizeInBits() == 32u ||
3154           MemVT.getScalarSizeInBits() == 64u))) {
3155       SDValue Lo =
3156           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3157                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3158                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3159       SDValue Hi = DAG.getNode(
3160           ISD::EXTRACT_SUBVECTOR, Dl,
3161           MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3162           StoreNode->getValue(),
3163           DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3164       SDValue Result = DAG.getMemIntrinsicNode(
3165           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3166           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3167           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3168       return Result;
3169     }
3170   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3171     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3172     SDValue Lo =
3173         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3174                     DAG.getConstant(0, Dl, MVT::i64));
3175     SDValue Hi =
3176         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3177                     DAG.getConstant(1, Dl, MVT::i64));
3178     SDValue Result = DAG.getMemIntrinsicNode(
3179         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3180         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3181         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3182     return Result;
3183   }
3184 
3185   return SDValue();
3186 }
3187 
3188 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3189                                               SelectionDAG &DAG) const {
3190   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3191   LLVM_DEBUG(Op.dump());
3192 
3193   switch (Op.getOpcode()) {
3194   default:
3195     llvm_unreachable("unimplemented operand");
3196     return SDValue();
3197   case ISD::BITCAST:
3198     return LowerBITCAST(Op, DAG);
3199   case ISD::GlobalAddress:
3200     return LowerGlobalAddress(Op, DAG);
3201   case ISD::GlobalTLSAddress:
3202     return LowerGlobalTLSAddress(Op, DAG);
3203   case ISD::SETCC:
3204   case ISD::STRICT_FSETCC:
3205   case ISD::STRICT_FSETCCS:
3206     return LowerSETCC(Op, DAG);
3207   case ISD::BR_CC:
3208     return LowerBR_CC(Op, DAG);
3209   case ISD::SELECT:
3210     return LowerSELECT(Op, DAG);
3211   case ISD::SELECT_CC:
3212     return LowerSELECT_CC(Op, DAG);
3213   case ISD::JumpTable:
3214     return LowerJumpTable(Op, DAG);
3215   case ISD::BR_JT:
3216     return LowerBR_JT(Op, DAG);
3217   case ISD::ConstantPool:
3218     return LowerConstantPool(Op, DAG);
3219   case ISD::BlockAddress:
3220     return LowerBlockAddress(Op, DAG);
3221   case ISD::VASTART:
3222     return LowerVASTART(Op, DAG);
3223   case ISD::VACOPY:
3224     return LowerVACOPY(Op, DAG);
3225   case ISD::VAARG:
3226     return LowerVAARG(Op, DAG);
3227   case ISD::ADDC:
3228   case ISD::ADDE:
3229   case ISD::SUBC:
3230   case ISD::SUBE:
3231     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3232   case ISD::SADDO:
3233   case ISD::UADDO:
3234   case ISD::SSUBO:
3235   case ISD::USUBO:
3236   case ISD::SMULO:
3237   case ISD::UMULO:
3238     return LowerXALUO(Op, DAG);
3239   case ISD::FADD:
3240     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3241   case ISD::FSUB:
3242     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3243   case ISD::FMUL:
3244     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3245   case ISD::FDIV:
3246     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3247   case ISD::FP_ROUND:
3248   case ISD::STRICT_FP_ROUND:
3249     return LowerFP_ROUND(Op, DAG);
3250   case ISD::FP_EXTEND:
3251     return LowerFP_EXTEND(Op, DAG);
3252   case ISD::FRAMEADDR:
3253     return LowerFRAMEADDR(Op, DAG);
3254   case ISD::SPONENTRY:
3255     return LowerSPONENTRY(Op, DAG);
3256   case ISD::RETURNADDR:
3257     return LowerRETURNADDR(Op, DAG);
3258   case ISD::ADDROFRETURNADDR:
3259     return LowerADDROFRETURNADDR(Op, DAG);
3260   case ISD::INSERT_VECTOR_ELT:
3261     return LowerINSERT_VECTOR_ELT(Op, DAG);
3262   case ISD::EXTRACT_VECTOR_ELT:
3263     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3264   case ISD::BUILD_VECTOR:
3265     return LowerBUILD_VECTOR(Op, DAG);
3266   case ISD::VECTOR_SHUFFLE:
3267     return LowerVECTOR_SHUFFLE(Op, DAG);
3268   case ISD::SPLAT_VECTOR:
3269     return LowerSPLAT_VECTOR(Op, DAG);
3270   case ISD::EXTRACT_SUBVECTOR:
3271     return LowerEXTRACT_SUBVECTOR(Op, DAG);
3272   case ISD::SRA:
3273   case ISD::SRL:
3274   case ISD::SHL:
3275     return LowerVectorSRA_SRL_SHL(Op, DAG);
3276   case ISD::SHL_PARTS:
3277     return LowerShiftLeftParts(Op, DAG);
3278   case ISD::SRL_PARTS:
3279   case ISD::SRA_PARTS:
3280     return LowerShiftRightParts(Op, DAG);
3281   case ISD::CTPOP:
3282     return LowerCTPOP(Op, DAG);
3283   case ISD::FCOPYSIGN:
3284     return LowerFCOPYSIGN(Op, DAG);
3285   case ISD::OR:
3286     return LowerVectorOR(Op, DAG);
3287   case ISD::XOR:
3288     return LowerXOR(Op, DAG);
3289   case ISD::PREFETCH:
3290     return LowerPREFETCH(Op, DAG);
3291   case ISD::SINT_TO_FP:
3292   case ISD::UINT_TO_FP:
3293   case ISD::STRICT_SINT_TO_FP:
3294   case ISD::STRICT_UINT_TO_FP:
3295     return LowerINT_TO_FP(Op, DAG);
3296   case ISD::FP_TO_SINT:
3297   case ISD::FP_TO_UINT:
3298   case ISD::STRICT_FP_TO_SINT:
3299   case ISD::STRICT_FP_TO_UINT:
3300     return LowerFP_TO_INT(Op, DAG);
3301   case ISD::FSINCOS:
3302     return LowerFSINCOS(Op, DAG);
3303   case ISD::FLT_ROUNDS_:
3304     return LowerFLT_ROUNDS_(Op, DAG);
3305   case ISD::MUL:
3306     return LowerMUL(Op, DAG);
3307   case ISD::INTRINSIC_WO_CHAIN:
3308     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3309   case ISD::STORE:
3310     return LowerSTORE(Op, DAG);
3311   case ISD::VECREDUCE_ADD:
3312   case ISD::VECREDUCE_SMAX:
3313   case ISD::VECREDUCE_SMIN:
3314   case ISD::VECREDUCE_UMAX:
3315   case ISD::VECREDUCE_UMIN:
3316   case ISD::VECREDUCE_FMAX:
3317   case ISD::VECREDUCE_FMIN:
3318     return LowerVECREDUCE(Op, DAG);
3319   case ISD::ATOMIC_LOAD_SUB:
3320     return LowerATOMIC_LOAD_SUB(Op, DAG);
3321   case ISD::ATOMIC_LOAD_AND:
3322     return LowerATOMIC_LOAD_AND(Op, DAG);
3323   case ISD::DYNAMIC_STACKALLOC:
3324     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3325   case ISD::VSCALE:
3326     return LowerVSCALE(Op, DAG);
3327   }
3328 }
3329 
3330 //===----------------------------------------------------------------------===//
3331 //                      Calling Convention Implementation
3332 //===----------------------------------------------------------------------===//
3333 
3334 /// Selects the correct CCAssignFn for a given CallingConvention value.
3335 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3336                                                      bool IsVarArg) const {
3337   switch (CC) {
3338   default:
3339     report_fatal_error("Unsupported calling convention.");
3340   case CallingConv::AArch64_SVE_VectorCall:
3341     // Calling SVE functions is currently not yet supported.
3342     report_fatal_error("Unsupported calling convention.");
3343   case CallingConv::WebKit_JS:
3344     return CC_AArch64_WebKit_JS;
3345   case CallingConv::GHC:
3346     return CC_AArch64_GHC;
3347   case CallingConv::C:
3348   case CallingConv::Fast:
3349   case CallingConv::PreserveMost:
3350   case CallingConv::CXX_FAST_TLS:
3351   case CallingConv::Swift:
3352     if (Subtarget->isTargetWindows() && IsVarArg)
3353       return CC_AArch64_Win64_VarArg;
3354     if (!Subtarget->isTargetDarwin())
3355       return CC_AArch64_AAPCS;
3356     if (!IsVarArg)
3357       return CC_AArch64_DarwinPCS;
3358     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3359                                       : CC_AArch64_DarwinPCS_VarArg;
3360    case CallingConv::Win64:
3361     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3362    case CallingConv::CFGuard_Check:
3363      return CC_AArch64_Win64_CFGuard_Check;
3364    case CallingConv::AArch64_VectorCall:
3365      return CC_AArch64_AAPCS;
3366   }
3367 }
3368 
3369 CCAssignFn *
3370 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3371   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3372                                       : RetCC_AArch64_AAPCS;
3373 }
3374 
3375 SDValue AArch64TargetLowering::LowerFormalArguments(
3376     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3377     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3378     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3379   MachineFunction &MF = DAG.getMachineFunction();
3380   MachineFrameInfo &MFI = MF.getFrameInfo();
3381   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3382 
3383   // Assign locations to all of the incoming arguments.
3384   SmallVector<CCValAssign, 16> ArgLocs;
3385   DenseMap<unsigned, SDValue> CopiedRegs;
3386   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3387                  *DAG.getContext());
3388 
3389   // At this point, Ins[].VT may already be promoted to i32. To correctly
3390   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3391   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3392   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3393   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3394   // LocVT.
3395   unsigned NumArgs = Ins.size();
3396   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3397   unsigned CurArgIdx = 0;
3398   for (unsigned i = 0; i != NumArgs; ++i) {
3399     MVT ValVT = Ins[i].VT;
3400     if (Ins[i].isOrigArg()) {
3401       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3402       CurArgIdx = Ins[i].getOrigArgIndex();
3403 
3404       // Get type of the original argument.
3405       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3406                                   /*AllowUnknown*/ true);
3407       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3408       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3409       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3410         ValVT = MVT::i8;
3411       else if (ActualMVT == MVT::i16)
3412         ValVT = MVT::i16;
3413     }
3414     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3415     bool Res =
3416         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3417     assert(!Res && "Call operand has unhandled type");
3418     (void)Res;
3419   }
3420   assert(ArgLocs.size() == Ins.size());
3421   SmallVector<SDValue, 16> ArgValues;
3422   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3423     CCValAssign &VA = ArgLocs[i];
3424 
3425     if (Ins[i].Flags.isByVal()) {
3426       // Byval is used for HFAs in the PCS, but the system should work in a
3427       // non-compliant manner for larger structs.
3428       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3429       int Size = Ins[i].Flags.getByValSize();
3430       unsigned NumRegs = (Size + 7) / 8;
3431 
3432       // FIXME: This works on big-endian for composite byvals, which are the common
3433       // case. It should also work for fundamental types too.
3434       unsigned FrameIdx =
3435         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3436       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3437       InVals.push_back(FrameIdxN);
3438 
3439       continue;
3440     }
3441 
3442     SDValue ArgValue;
3443     if (VA.isRegLoc()) {
3444       // Arguments stored in registers.
3445       EVT RegVT = VA.getLocVT();
3446       const TargetRegisterClass *RC;
3447 
3448       if (RegVT == MVT::i32)
3449         RC = &AArch64::GPR32RegClass;
3450       else if (RegVT == MVT::i64)
3451         RC = &AArch64::GPR64RegClass;
3452       else if (RegVT == MVT::f16)
3453         RC = &AArch64::FPR16RegClass;
3454       else if (RegVT == MVT::f32)
3455         RC = &AArch64::FPR32RegClass;
3456       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3457         RC = &AArch64::FPR64RegClass;
3458       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3459         RC = &AArch64::FPR128RegClass;
3460       else if (RegVT.isScalableVector() &&
3461                RegVT.getVectorElementType() == MVT::i1)
3462         RC = &AArch64::PPRRegClass;
3463       else if (RegVT.isScalableVector())
3464         RC = &AArch64::ZPRRegClass;
3465       else
3466         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3467 
3468       // Transform the arguments in physical registers into virtual ones.
3469       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3470       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3471 
3472       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3473       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3474       // truncate to the right size.
3475       switch (VA.getLocInfo()) {
3476       default:
3477         llvm_unreachable("Unknown loc info!");
3478       case CCValAssign::Full:
3479         break;
3480       case CCValAssign::Indirect:
3481         assert(VA.getValVT().isScalableVector() &&
3482                "Only scalable vectors can be passed indirectly");
3483         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3484       case CCValAssign::BCvt:
3485         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3486         break;
3487       case CCValAssign::AExt:
3488       case CCValAssign::SExt:
3489       case CCValAssign::ZExt:
3490         break;
3491       case CCValAssign::AExtUpper:
3492         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3493                                DAG.getConstant(32, DL, RegVT));
3494         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3495         break;
3496       }
3497     } else { // VA.isRegLoc()
3498       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3499       unsigned ArgOffset = VA.getLocMemOffset();
3500       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3501 
3502       uint32_t BEAlign = 0;
3503       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3504           !Ins[i].Flags.isInConsecutiveRegs())
3505         BEAlign = 8 - ArgSize;
3506 
3507       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3508 
3509       // Create load nodes to retrieve arguments from the stack.
3510       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3511 
3512       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3513       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3514       MVT MemVT = VA.getValVT();
3515 
3516       switch (VA.getLocInfo()) {
3517       default:
3518         break;
3519       case CCValAssign::Trunc:
3520       case CCValAssign::BCvt:
3521         MemVT = VA.getLocVT();
3522         break;
3523       case CCValAssign::Indirect:
3524         assert(VA.getValVT().isScalableVector() &&
3525                "Only scalable vectors can be passed indirectly");
3526         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3527       case CCValAssign::SExt:
3528         ExtType = ISD::SEXTLOAD;
3529         break;
3530       case CCValAssign::ZExt:
3531         ExtType = ISD::ZEXTLOAD;
3532         break;
3533       case CCValAssign::AExt:
3534         ExtType = ISD::EXTLOAD;
3535         break;
3536       }
3537 
3538       ArgValue = DAG.getExtLoad(
3539           ExtType, DL, VA.getLocVT(), Chain, FIN,
3540           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3541           MemVT);
3542 
3543     }
3544     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3545       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3546                              ArgValue, DAG.getValueType(MVT::i32));
3547     InVals.push_back(ArgValue);
3548   }
3549 
3550   // varargs
3551   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3552   if (isVarArg) {
3553     if (!Subtarget->isTargetDarwin() || IsWin64) {
3554       // The AAPCS variadic function ABI is identical to the non-variadic
3555       // one. As a result there may be more arguments in registers and we should
3556       // save them for future reference.
3557       // Win64 variadic functions also pass arguments in registers, but all float
3558       // arguments are passed in integer registers.
3559       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3560     }
3561 
3562     // This will point to the next argument passed via stack.
3563     unsigned StackOffset = CCInfo.getNextStackOffset();
3564     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3565     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3566     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3567 
3568     if (MFI.hasMustTailInVarArgFunc()) {
3569       SmallVector<MVT, 2> RegParmTypes;
3570       RegParmTypes.push_back(MVT::i64);
3571       RegParmTypes.push_back(MVT::f128);
3572       // Compute the set of forwarded registers. The rest are scratch.
3573       SmallVectorImpl<ForwardedRegister> &Forwards =
3574                                        FuncInfo->getForwardedMustTailRegParms();
3575       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3576                                                CC_AArch64_AAPCS);
3577 
3578       // Conservatively forward X8, since it might be used for aggregate return.
3579       if (!CCInfo.isAllocated(AArch64::X8)) {
3580         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3581         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3582       }
3583     }
3584   }
3585 
3586   // On Windows, InReg pointers must be returned, so record the pointer in a
3587   // virtual register at the start of the function so it can be returned in the
3588   // epilogue.
3589   if (IsWin64) {
3590     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3591       if (Ins[I].Flags.isInReg()) {
3592         assert(!FuncInfo->getSRetReturnReg());
3593 
3594         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3595         Register Reg =
3596             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3597         FuncInfo->setSRetReturnReg(Reg);
3598 
3599         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3600         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3601         break;
3602       }
3603     }
3604   }
3605 
3606   unsigned StackArgSize = CCInfo.getNextStackOffset();
3607   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3608   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3609     // This is a non-standard ABI so by fiat I say we're allowed to make full
3610     // use of the stack area to be popped, which must be aligned to 16 bytes in
3611     // any case:
3612     StackArgSize = alignTo(StackArgSize, 16);
3613 
3614     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3615     // a multiple of 16.
3616     FuncInfo->setArgumentStackToRestore(StackArgSize);
3617 
3618     // This realignment carries over to the available bytes below. Our own
3619     // callers will guarantee the space is free by giving an aligned value to
3620     // CALLSEQ_START.
3621   }
3622   // Even if we're not expected to free up the space, it's useful to know how
3623   // much is there while considering tail calls (because we can reuse it).
3624   FuncInfo->setBytesInStackArgArea(StackArgSize);
3625 
3626   if (Subtarget->hasCustomCallingConv())
3627     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3628 
3629   return Chain;
3630 }
3631 
3632 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3633                                                 SelectionDAG &DAG,
3634                                                 const SDLoc &DL,
3635                                                 SDValue &Chain) const {
3636   MachineFunction &MF = DAG.getMachineFunction();
3637   MachineFrameInfo &MFI = MF.getFrameInfo();
3638   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3639   auto PtrVT = getPointerTy(DAG.getDataLayout());
3640   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3641 
3642   SmallVector<SDValue, 8> MemOps;
3643 
3644   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3645                                           AArch64::X3, AArch64::X4, AArch64::X5,
3646                                           AArch64::X6, AArch64::X7 };
3647   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3648   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3649 
3650   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3651   int GPRIdx = 0;
3652   if (GPRSaveSize != 0) {
3653     if (IsWin64) {
3654       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3655       if (GPRSaveSize & 15)
3656         // The extra size here, if triggered, will always be 8.
3657         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3658     } else
3659       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3660 
3661     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3662 
3663     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3664       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3665       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3666       SDValue Store = DAG.getStore(
3667           Val.getValue(1), DL, Val, FIN,
3668           IsWin64
3669               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3670                                                   GPRIdx,
3671                                                   (i - FirstVariadicGPR) * 8)
3672               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3673       MemOps.push_back(Store);
3674       FIN =
3675           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3676     }
3677   }
3678   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3679   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3680 
3681   if (Subtarget->hasFPARMv8() && !IsWin64) {
3682     static const MCPhysReg FPRArgRegs[] = {
3683         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3684         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3685     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3686     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3687 
3688     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3689     int FPRIdx = 0;
3690     if (FPRSaveSize != 0) {
3691       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3692 
3693       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3694 
3695       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3696         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3697         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3698 
3699         SDValue Store = DAG.getStore(
3700             Val.getValue(1), DL, Val, FIN,
3701             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3702         MemOps.push_back(Store);
3703         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3704                           DAG.getConstant(16, DL, PtrVT));
3705       }
3706     }
3707     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3708     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3709   }
3710 
3711   if (!MemOps.empty()) {
3712     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3713   }
3714 }
3715 
3716 /// LowerCallResult - Lower the result values of a call into the
3717 /// appropriate copies out of appropriate physical registers.
3718 SDValue AArch64TargetLowering::LowerCallResult(
3719     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3720     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3721     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3722     SDValue ThisVal) const {
3723   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3724                           ? RetCC_AArch64_WebKit_JS
3725                           : RetCC_AArch64_AAPCS;
3726   // Assign locations to each value returned by this call.
3727   SmallVector<CCValAssign, 16> RVLocs;
3728   DenseMap<unsigned, SDValue> CopiedRegs;
3729   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3730                  *DAG.getContext());
3731   CCInfo.AnalyzeCallResult(Ins, RetCC);
3732 
3733   // Copy all of the result registers out of their specified physreg.
3734   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3735     CCValAssign VA = RVLocs[i];
3736 
3737     // Pass 'this' value directly from the argument to return value, to avoid
3738     // reg unit interference
3739     if (i == 0 && isThisReturn) {
3740       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3741              "unexpected return calling convention register assignment");
3742       InVals.push_back(ThisVal);
3743       continue;
3744     }
3745 
3746     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3747     // allows one use of a physreg per block.
3748     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3749     if (!Val) {
3750       Val =
3751           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3752       Chain = Val.getValue(1);
3753       InFlag = Val.getValue(2);
3754       CopiedRegs[VA.getLocReg()] = Val;
3755     }
3756 
3757     switch (VA.getLocInfo()) {
3758     default:
3759       llvm_unreachable("Unknown loc info!");
3760     case CCValAssign::Full:
3761       break;
3762     case CCValAssign::BCvt:
3763       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3764       break;
3765     case CCValAssign::AExtUpper:
3766       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3767                         DAG.getConstant(32, DL, VA.getLocVT()));
3768       LLVM_FALLTHROUGH;
3769     case CCValAssign::AExt:
3770       LLVM_FALLTHROUGH;
3771     case CCValAssign::ZExt:
3772       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3773       break;
3774     }
3775 
3776     InVals.push_back(Val);
3777   }
3778 
3779   return Chain;
3780 }
3781 
3782 /// Return true if the calling convention is one that we can guarantee TCO for.
3783 static bool canGuaranteeTCO(CallingConv::ID CC) {
3784   return CC == CallingConv::Fast;
3785 }
3786 
3787 /// Return true if we might ever do TCO for calls with this calling convention.
3788 static bool mayTailCallThisCC(CallingConv::ID CC) {
3789   switch (CC) {
3790   case CallingConv::C:
3791   case CallingConv::PreserveMost:
3792   case CallingConv::Swift:
3793     return true;
3794   default:
3795     return canGuaranteeTCO(CC);
3796   }
3797 }
3798 
3799 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3800     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3801     const SmallVectorImpl<ISD::OutputArg> &Outs,
3802     const SmallVectorImpl<SDValue> &OutVals,
3803     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3804   if (!mayTailCallThisCC(CalleeCC))
3805     return false;
3806 
3807   MachineFunction &MF = DAG.getMachineFunction();
3808   const Function &CallerF = MF.getFunction();
3809   CallingConv::ID CallerCC = CallerF.getCallingConv();
3810   bool CCMatch = CallerCC == CalleeCC;
3811 
3812   // Byval parameters hand the function a pointer directly into the stack area
3813   // we want to reuse during a tail call. Working around this *is* possible (see
3814   // X86) but less efficient and uglier in LowerCall.
3815   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3816                                     e = CallerF.arg_end();
3817        i != e; ++i) {
3818     if (i->hasByValAttr())
3819       return false;
3820 
3821     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3822     // In this case, it is necessary to save/restore X0 in the callee. Tail
3823     // call opt interferes with this. So we disable tail call opt when the
3824     // caller has an argument with "inreg" attribute.
3825 
3826     // FIXME: Check whether the callee also has an "inreg" argument.
3827     if (i->hasInRegAttr())
3828       return false;
3829   }
3830 
3831   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3832     return canGuaranteeTCO(CalleeCC) && CCMatch;
3833 
3834   // Externally-defined functions with weak linkage should not be
3835   // tail-called on AArch64 when the OS does not support dynamic
3836   // pre-emption of symbols, as the AAELF spec requires normal calls
3837   // to undefined weak functions to be replaced with a NOP or jump to the
3838   // next instruction. The behaviour of branch instructions in this
3839   // situation (as used for tail calls) is implementation-defined, so we
3840   // cannot rely on the linker replacing the tail call with a return.
3841   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3842     const GlobalValue *GV = G->getGlobal();
3843     const Triple &TT = getTargetMachine().getTargetTriple();
3844     if (GV->hasExternalWeakLinkage() &&
3845         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3846       return false;
3847   }
3848 
3849   // Now we search for cases where we can use a tail call without changing the
3850   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3851   // concept.
3852 
3853   // I want anyone implementing a new calling convention to think long and hard
3854   // about this assert.
3855   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3856          "Unexpected variadic calling convention");
3857 
3858   LLVMContext &C = *DAG.getContext();
3859   if (isVarArg && !Outs.empty()) {
3860     // At least two cases here: if caller is fastcc then we can't have any
3861     // memory arguments (we'd be expected to clean up the stack afterwards). If
3862     // caller is C then we could potentially use its argument area.
3863 
3864     // FIXME: for now we take the most conservative of these in both cases:
3865     // disallow all variadic memory operands.
3866     SmallVector<CCValAssign, 16> ArgLocs;
3867     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3868 
3869     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3870     for (const CCValAssign &ArgLoc : ArgLocs)
3871       if (!ArgLoc.isRegLoc())
3872         return false;
3873   }
3874 
3875   // Check that the call results are passed in the same way.
3876   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3877                                   CCAssignFnForCall(CalleeCC, isVarArg),
3878                                   CCAssignFnForCall(CallerCC, isVarArg)))
3879     return false;
3880   // The callee has to preserve all registers the caller needs to preserve.
3881   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3882   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3883   if (!CCMatch) {
3884     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3885     if (Subtarget->hasCustomCallingConv()) {
3886       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3887       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3888     }
3889     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3890       return false;
3891   }
3892 
3893   // Nothing more to check if the callee is taking no arguments
3894   if (Outs.empty())
3895     return true;
3896 
3897   SmallVector<CCValAssign, 16> ArgLocs;
3898   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3899 
3900   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3901 
3902   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3903 
3904   // If the stack arguments for this call do not fit into our own save area then
3905   // the call cannot be made tail.
3906   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3907     return false;
3908 
3909   const MachineRegisterInfo &MRI = MF.getRegInfo();
3910   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3911     return false;
3912 
3913   return true;
3914 }
3915 
3916 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3917                                                    SelectionDAG &DAG,
3918                                                    MachineFrameInfo &MFI,
3919                                                    int ClobberedFI) const {
3920   SmallVector<SDValue, 8> ArgChains;
3921   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3922   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3923 
3924   // Include the original chain at the beginning of the list. When this is
3925   // used by target LowerCall hooks, this helps legalize find the
3926   // CALLSEQ_BEGIN node.
3927   ArgChains.push_back(Chain);
3928 
3929   // Add a chain value for each stack argument corresponding
3930   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3931                             UE = DAG.getEntryNode().getNode()->use_end();
3932        U != UE; ++U)
3933     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3934       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3935         if (FI->getIndex() < 0) {
3936           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3937           int64_t InLastByte = InFirstByte;
3938           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3939 
3940           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3941               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3942             ArgChains.push_back(SDValue(L, 1));
3943         }
3944 
3945   // Build a tokenfactor for all the chains.
3946   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3947 }
3948 
3949 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3950                                                    bool TailCallOpt) const {
3951   return CallCC == CallingConv::Fast && TailCallOpt;
3952 }
3953 
3954 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3955 /// and add input and output parameter nodes.
3956 SDValue
3957 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3958                                  SmallVectorImpl<SDValue> &InVals) const {
3959   SelectionDAG &DAG = CLI.DAG;
3960   SDLoc &DL = CLI.DL;
3961   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3962   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3963   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3964   SDValue Chain = CLI.Chain;
3965   SDValue Callee = CLI.Callee;
3966   bool &IsTailCall = CLI.IsTailCall;
3967   CallingConv::ID CallConv = CLI.CallConv;
3968   bool IsVarArg = CLI.IsVarArg;
3969 
3970   MachineFunction &MF = DAG.getMachineFunction();
3971   MachineFunction::CallSiteInfo CSInfo;
3972   bool IsThisReturn = false;
3973 
3974   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3975   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3976   bool IsSibCall = false;
3977 
3978   if (IsTailCall) {
3979     // Check if it's really possible to do a tail call.
3980     IsTailCall = isEligibleForTailCallOptimization(
3981         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3982     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3983       report_fatal_error("failed to perform tail call elimination on a call "
3984                          "site marked musttail");
3985 
3986     // A sibling call is one where we're under the usual C ABI and not planning
3987     // to change that but can still do a tail call:
3988     if (!TailCallOpt && IsTailCall)
3989       IsSibCall = true;
3990 
3991     if (IsTailCall)
3992       ++NumTailCalls;
3993   }
3994 
3995   // Analyze operands of the call, assigning locations to each operand.
3996   SmallVector<CCValAssign, 16> ArgLocs;
3997   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3998                  *DAG.getContext());
3999 
4000   if (IsVarArg) {
4001     // Handle fixed and variable vector arguments differently.
4002     // Variable vector arguments always go into memory.
4003     unsigned NumArgs = Outs.size();
4004 
4005     for (unsigned i = 0; i != NumArgs; ++i) {
4006       MVT ArgVT = Outs[i].VT;
4007       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4008       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4009                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4010       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4011       assert(!Res && "Call operand has unhandled type");
4012       (void)Res;
4013     }
4014   } else {
4015     // At this point, Outs[].VT may already be promoted to i32. To correctly
4016     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4017     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4018     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4019     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4020     // LocVT.
4021     unsigned NumArgs = Outs.size();
4022     for (unsigned i = 0; i != NumArgs; ++i) {
4023       MVT ValVT = Outs[i].VT;
4024       // Get type of the original argument.
4025       EVT ActualVT = getValueType(DAG.getDataLayout(),
4026                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4027                                   /*AllowUnknown*/ true);
4028       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4029       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4030       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4031       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4032         ValVT = MVT::i8;
4033       else if (ActualMVT == MVT::i16)
4034         ValVT = MVT::i16;
4035 
4036       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4037       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4038       assert(!Res && "Call operand has unhandled type");
4039       (void)Res;
4040     }
4041   }
4042 
4043   // Get a count of how many bytes are to be pushed on the stack.
4044   unsigned NumBytes = CCInfo.getNextStackOffset();
4045 
4046   if (IsSibCall) {
4047     // Since we're not changing the ABI to make this a tail call, the memory
4048     // operands are already available in the caller's incoming argument space.
4049     NumBytes = 0;
4050   }
4051 
4052   // FPDiff is the byte offset of the call's argument area from the callee's.
4053   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4054   // by this amount for a tail call. In a sibling call it must be 0 because the
4055   // caller will deallocate the entire stack and the callee still expects its
4056   // arguments to begin at SP+0. Completely unused for non-tail calls.
4057   int FPDiff = 0;
4058 
4059   if (IsTailCall && !IsSibCall) {
4060     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4061 
4062     // Since callee will pop argument stack as a tail call, we must keep the
4063     // popped size 16-byte aligned.
4064     NumBytes = alignTo(NumBytes, 16);
4065 
4066     // FPDiff will be negative if this tail call requires more space than we
4067     // would automatically have in our incoming argument space. Positive if we
4068     // can actually shrink the stack.
4069     FPDiff = NumReusableBytes - NumBytes;
4070 
4071     // The stack pointer must be 16-byte aligned at all times it's used for a
4072     // memory operation, which in practice means at *all* times and in
4073     // particular across call boundaries. Therefore our own arguments started at
4074     // a 16-byte aligned SP and the delta applied for the tail call should
4075     // satisfy the same constraint.
4076     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4077   }
4078 
4079   // Adjust the stack pointer for the new arguments...
4080   // These operations are automatically eliminated by the prolog/epilog pass
4081   if (!IsSibCall)
4082     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4083 
4084   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4085                                         getPointerTy(DAG.getDataLayout()));
4086 
4087   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4088   SmallSet<unsigned, 8> RegsUsed;
4089   SmallVector<SDValue, 8> MemOpChains;
4090   auto PtrVT = getPointerTy(DAG.getDataLayout());
4091 
4092   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
4093     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4094     for (const auto &F : Forwards) {
4095       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4096        RegsToPass.emplace_back(F.PReg, Val);
4097     }
4098   }
4099 
4100   // Walk the register/memloc assignments, inserting copies/loads.
4101   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4102     CCValAssign &VA = ArgLocs[i];
4103     SDValue Arg = OutVals[i];
4104     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4105 
4106     // Promote the value if needed.
4107     switch (VA.getLocInfo()) {
4108     default:
4109       llvm_unreachable("Unknown loc info!");
4110     case CCValAssign::Full:
4111       break;
4112     case CCValAssign::SExt:
4113       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4114       break;
4115     case CCValAssign::ZExt:
4116       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4117       break;
4118     case CCValAssign::AExt:
4119       if (Outs[i].ArgVT == MVT::i1) {
4120         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4121         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4122         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4123       }
4124       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4125       break;
4126     case CCValAssign::AExtUpper:
4127       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4128       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4129       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4130                         DAG.getConstant(32, DL, VA.getLocVT()));
4131       break;
4132     case CCValAssign::BCvt:
4133       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4134       break;
4135     case CCValAssign::Trunc:
4136       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4137       break;
4138     case CCValAssign::FPExt:
4139       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4140       break;
4141     case CCValAssign::Indirect:
4142       assert(VA.getValVT().isScalableVector() &&
4143              "Only scalable vectors can be passed indirectly");
4144       llvm_unreachable("Spilling of SVE vectors not yet implemented");
4145     }
4146 
4147     if (VA.isRegLoc()) {
4148       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4149           Outs[0].VT == MVT::i64) {
4150         assert(VA.getLocVT() == MVT::i64 &&
4151                "unexpected calling convention register assignment");
4152         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4153                "unexpected use of 'returned'");
4154         IsThisReturn = true;
4155       }
4156       if (RegsUsed.count(VA.getLocReg())) {
4157         // If this register has already been used then we're trying to pack
4158         // parts of an [N x i32] into an X-register. The extension type will
4159         // take care of putting the two halves in the right place but we have to
4160         // combine them.
4161         SDValue &Bits =
4162             std::find_if(RegsToPass.begin(), RegsToPass.end(),
4163                          [=](const std::pair<unsigned, SDValue> &Elt) {
4164                            return Elt.first == VA.getLocReg();
4165                          })
4166                 ->second;
4167         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4168         // Call site info is used for function's parameter entry value
4169         // tracking. For now we track only simple cases when parameter
4170         // is transferred through whole register.
4171         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4172                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
4173                                       return ArgReg.Reg == VA.getLocReg();
4174                                     }),
4175                      CSInfo.end());
4176       } else {
4177         RegsToPass.emplace_back(VA.getLocReg(), Arg);
4178         RegsUsed.insert(VA.getLocReg());
4179         const TargetOptions &Options = DAG.getTarget().Options;
4180         if (Options.EnableDebugEntryValues)
4181           CSInfo.emplace_back(VA.getLocReg(), i);
4182       }
4183     } else {
4184       assert(VA.isMemLoc());
4185 
4186       SDValue DstAddr;
4187       MachinePointerInfo DstInfo;
4188 
4189       // FIXME: This works on big-endian for composite byvals, which are the
4190       // common case. It should also work for fundamental types too.
4191       uint32_t BEAlign = 0;
4192       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4193                                         : VA.getValVT().getSizeInBits();
4194       OpSize = (OpSize + 7) / 8;
4195       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4196           !Flags.isInConsecutiveRegs()) {
4197         if (OpSize < 8)
4198           BEAlign = 8 - OpSize;
4199       }
4200       unsigned LocMemOffset = VA.getLocMemOffset();
4201       int32_t Offset = LocMemOffset + BEAlign;
4202       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4203       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4204 
4205       if (IsTailCall) {
4206         Offset = Offset + FPDiff;
4207         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4208 
4209         DstAddr = DAG.getFrameIndex(FI, PtrVT);
4210         DstInfo =
4211             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4212 
4213         // Make sure any stack arguments overlapping with where we're storing
4214         // are loaded before this eventual operation. Otherwise they'll be
4215         // clobbered.
4216         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4217       } else {
4218         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4219 
4220         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4221         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4222                                                LocMemOffset);
4223       }
4224 
4225       if (Outs[i].Flags.isByVal()) {
4226         SDValue SizeNode =
4227             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4228         SDValue Cpy = DAG.getMemcpy(
4229             Chain, DL, DstAddr, Arg, SizeNode,
4230             Outs[i].Flags.getNonZeroByValAlign(),
4231             /*isVol = */ false, /*AlwaysInline = */ false,
4232             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4233 
4234         MemOpChains.push_back(Cpy);
4235       } else {
4236         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4237         // promoted to a legal register type i32, we should truncate Arg back to
4238         // i1/i8/i16.
4239         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4240             VA.getValVT() == MVT::i16)
4241           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4242 
4243         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4244         MemOpChains.push_back(Store);
4245       }
4246     }
4247   }
4248 
4249   if (!MemOpChains.empty())
4250     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4251 
4252   // Build a sequence of copy-to-reg nodes chained together with token chain
4253   // and flag operands which copy the outgoing args into the appropriate regs.
4254   SDValue InFlag;
4255   for (auto &RegToPass : RegsToPass) {
4256     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4257                              RegToPass.second, InFlag);
4258     InFlag = Chain.getValue(1);
4259   }
4260 
4261   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4262   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4263   // node so that legalize doesn't hack it.
4264   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4265     auto GV = G->getGlobal();
4266     unsigned OpFlags =
4267         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4268     if (OpFlags & AArch64II::MO_GOT) {
4269       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4270       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4271     } else {
4272       const GlobalValue *GV = G->getGlobal();
4273       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4274     }
4275   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4276     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4277         Subtarget->isTargetMachO()) {
4278       const char *Sym = S->getSymbol();
4279       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4280       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4281     } else {
4282       const char *Sym = S->getSymbol();
4283       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4284     }
4285   }
4286 
4287   // We don't usually want to end the call-sequence here because we would tidy
4288   // the frame up *after* the call, however in the ABI-changing tail-call case
4289   // we've carefully laid out the parameters so that when sp is reset they'll be
4290   // in the correct location.
4291   if (IsTailCall && !IsSibCall) {
4292     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4293                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4294     InFlag = Chain.getValue(1);
4295   }
4296 
4297   std::vector<SDValue> Ops;
4298   Ops.push_back(Chain);
4299   Ops.push_back(Callee);
4300 
4301   if (IsTailCall) {
4302     // Each tail call may have to adjust the stack by a different amount, so
4303     // this information must travel along with the operation for eventual
4304     // consumption by emitEpilogue.
4305     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4306   }
4307 
4308   // Add argument registers to the end of the list so that they are known live
4309   // into the call.
4310   for (auto &RegToPass : RegsToPass)
4311     Ops.push_back(DAG.getRegister(RegToPass.first,
4312                                   RegToPass.second.getValueType()));
4313 
4314   // Check callee args/returns for SVE registers and set calling convention
4315   // accordingly.
4316   if (CallConv == CallingConv::C) {
4317     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4318       return Out.VT.isScalableVector();
4319     });
4320     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4321       return In.VT.isScalableVector();
4322     });
4323 
4324     if (CalleeInSVE || CalleeOutSVE)
4325       CallConv = CallingConv::AArch64_SVE_VectorCall;
4326   }
4327 
4328   // Add a register mask operand representing the call-preserved registers.
4329   const uint32_t *Mask;
4330   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4331   if (IsThisReturn) {
4332     // For 'this' returns, use the X0-preserving mask if applicable
4333     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4334     if (!Mask) {
4335       IsThisReturn = false;
4336       Mask = TRI->getCallPreservedMask(MF, CallConv);
4337     }
4338   } else
4339     Mask = TRI->getCallPreservedMask(MF, CallConv);
4340 
4341   if (Subtarget->hasCustomCallingConv())
4342     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4343 
4344   if (TRI->isAnyArgRegReserved(MF))
4345     TRI->emitReservedArgRegCallError(MF);
4346 
4347   assert(Mask && "Missing call preserved mask for calling convention");
4348   Ops.push_back(DAG.getRegisterMask(Mask));
4349 
4350   if (InFlag.getNode())
4351     Ops.push_back(InFlag);
4352 
4353   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4354 
4355   // If we're doing a tall call, use a TC_RETURN here rather than an
4356   // actual call instruction.
4357   if (IsTailCall) {
4358     MF.getFrameInfo().setHasTailCall();
4359     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4360     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4361     return Ret;
4362   }
4363 
4364   // Returns a chain and a flag for retval copy to use.
4365   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4366   InFlag = Chain.getValue(1);
4367   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4368 
4369   uint64_t CalleePopBytes =
4370       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4371 
4372   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4373                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4374                              InFlag, DL);
4375   if (!Ins.empty())
4376     InFlag = Chain.getValue(1);
4377 
4378   // Handle result values, copying them out of physregs into vregs that we
4379   // return.
4380   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4381                          InVals, IsThisReturn,
4382                          IsThisReturn ? OutVals[0] : SDValue());
4383 }
4384 
4385 bool AArch64TargetLowering::CanLowerReturn(
4386     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4387     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4388   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4389                           ? RetCC_AArch64_WebKit_JS
4390                           : RetCC_AArch64_AAPCS;
4391   SmallVector<CCValAssign, 16> RVLocs;
4392   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4393   return CCInfo.CheckReturn(Outs, RetCC);
4394 }
4395 
4396 SDValue
4397 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4398                                    bool isVarArg,
4399                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4400                                    const SmallVectorImpl<SDValue> &OutVals,
4401                                    const SDLoc &DL, SelectionDAG &DAG) const {
4402   auto &MF = DAG.getMachineFunction();
4403   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4404 
4405   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4406                           ? RetCC_AArch64_WebKit_JS
4407                           : RetCC_AArch64_AAPCS;
4408   SmallVector<CCValAssign, 16> RVLocs;
4409   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4410                  *DAG.getContext());
4411   CCInfo.AnalyzeReturn(Outs, RetCC);
4412 
4413   // Copy the result values into the output registers.
4414   SDValue Flag;
4415   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4416   SmallSet<unsigned, 4> RegsUsed;
4417   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4418        ++i, ++realRVLocIdx) {
4419     CCValAssign &VA = RVLocs[i];
4420     assert(VA.isRegLoc() && "Can only return in registers!");
4421     SDValue Arg = OutVals[realRVLocIdx];
4422 
4423     switch (VA.getLocInfo()) {
4424     default:
4425       llvm_unreachable("Unknown loc info!");
4426     case CCValAssign::Full:
4427       if (Outs[i].ArgVT == MVT::i1) {
4428         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4429         // value. This is strictly redundant on Darwin (which uses "zeroext
4430         // i1"), but will be optimised out before ISel.
4431         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4432         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4433       }
4434       break;
4435     case CCValAssign::BCvt:
4436       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4437       break;
4438     case CCValAssign::AExt:
4439     case CCValAssign::ZExt:
4440       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4441       break;
4442     case CCValAssign::AExtUpper:
4443       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4444       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4445       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4446                         DAG.getConstant(32, DL, VA.getLocVT()));
4447       break;
4448     }
4449 
4450     if (RegsUsed.count(VA.getLocReg())) {
4451       SDValue &Bits =
4452           std::find_if(RetVals.begin(), RetVals.end(),
4453                        [=](const std::pair<unsigned, SDValue> &Elt) {
4454                          return Elt.first == VA.getLocReg();
4455                        })
4456               ->second;
4457       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4458     } else {
4459       RetVals.emplace_back(VA.getLocReg(), Arg);
4460       RegsUsed.insert(VA.getLocReg());
4461     }
4462   }
4463 
4464   SmallVector<SDValue, 4> RetOps(1, Chain);
4465   for (auto &RetVal : RetVals) {
4466     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4467     Flag = Chain.getValue(1);
4468     RetOps.push_back(
4469         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4470   }
4471 
4472   // Windows AArch64 ABIs require that for returning structs by value we copy
4473   // the sret argument into X0 for the return.
4474   // We saved the argument into a virtual register in the entry block,
4475   // so now we copy the value out and into X0.
4476   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4477     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4478                                      getPointerTy(MF.getDataLayout()));
4479 
4480     unsigned RetValReg = AArch64::X0;
4481     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4482     Flag = Chain.getValue(1);
4483 
4484     RetOps.push_back(
4485       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4486   }
4487 
4488   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4489   const MCPhysReg *I =
4490       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4491   if (I) {
4492     for (; *I; ++I) {
4493       if (AArch64::GPR64RegClass.contains(*I))
4494         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4495       else if (AArch64::FPR64RegClass.contains(*I))
4496         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4497       else
4498         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4499     }
4500   }
4501 
4502   RetOps[0] = Chain; // Update chain.
4503 
4504   // Add the flag if we have it.
4505   if (Flag.getNode())
4506     RetOps.push_back(Flag);
4507 
4508   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4509 }
4510 
4511 //===----------------------------------------------------------------------===//
4512 //  Other Lowering Code
4513 //===----------------------------------------------------------------------===//
4514 
4515 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4516                                              SelectionDAG &DAG,
4517                                              unsigned Flag) const {
4518   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4519                                     N->getOffset(), Flag);
4520 }
4521 
4522 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4523                                              SelectionDAG &DAG,
4524                                              unsigned Flag) const {
4525   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4526 }
4527 
4528 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4529                                              SelectionDAG &DAG,
4530                                              unsigned Flag) const {
4531   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4532                                    N->getOffset(), Flag);
4533 }
4534 
4535 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4536                                              SelectionDAG &DAG,
4537                                              unsigned Flag) const {
4538   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4539 }
4540 
4541 // (loadGOT sym)
4542 template <class NodeTy>
4543 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4544                                       unsigned Flags) const {
4545   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4546   SDLoc DL(N);
4547   EVT Ty = getPointerTy(DAG.getDataLayout());
4548   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4549   // FIXME: Once remat is capable of dealing with instructions with register
4550   // operands, expand this into two nodes instead of using a wrapper node.
4551   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4552 }
4553 
4554 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4555 template <class NodeTy>
4556 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4557                                             unsigned Flags) const {
4558   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4559   SDLoc DL(N);
4560   EVT Ty = getPointerTy(DAG.getDataLayout());
4561   const unsigned char MO_NC = AArch64II::MO_NC;
4562   return DAG.getNode(
4563       AArch64ISD::WrapperLarge, DL, Ty,
4564       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4565       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4566       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4567       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4568 }
4569 
4570 // (addlow (adrp %hi(sym)) %lo(sym))
4571 template <class NodeTy>
4572 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4573                                        unsigned Flags) const {
4574   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4575   SDLoc DL(N);
4576   EVT Ty = getPointerTy(DAG.getDataLayout());
4577   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4578   SDValue Lo = getTargetNode(N, Ty, DAG,
4579                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4580   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4581   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4582 }
4583 
4584 // (adr sym)
4585 template <class NodeTy>
4586 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4587                                            unsigned Flags) const {
4588   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4589   SDLoc DL(N);
4590   EVT Ty = getPointerTy(DAG.getDataLayout());
4591   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4592   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4593 }
4594 
4595 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4596                                                   SelectionDAG &DAG) const {
4597   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4598   const GlobalValue *GV = GN->getGlobal();
4599   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4600 
4601   if (OpFlags != AArch64II::MO_NO_FLAG)
4602     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4603            "unexpected offset in global node");
4604 
4605   // This also catches the large code model case for Darwin, and tiny code
4606   // model with got relocations.
4607   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4608     return getGOT(GN, DAG, OpFlags);
4609   }
4610 
4611   SDValue Result;
4612   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4613     Result = getAddrLarge(GN, DAG, OpFlags);
4614   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4615     Result = getAddrTiny(GN, DAG, OpFlags);
4616   } else {
4617     Result = getAddr(GN, DAG, OpFlags);
4618   }
4619   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4620   SDLoc DL(GN);
4621   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4622     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4623                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4624   return Result;
4625 }
4626 
4627 /// Convert a TLS address reference into the correct sequence of loads
4628 /// and calls to compute the variable's address (for Darwin, currently) and
4629 /// return an SDValue containing the final node.
4630 
4631 /// Darwin only has one TLS scheme which must be capable of dealing with the
4632 /// fully general situation, in the worst case. This means:
4633 ///     + "extern __thread" declaration.
4634 ///     + Defined in a possibly unknown dynamic library.
4635 ///
4636 /// The general system is that each __thread variable has a [3 x i64] descriptor
4637 /// which contains information used by the runtime to calculate the address. The
4638 /// only part of this the compiler needs to know about is the first xword, which
4639 /// contains a function pointer that must be called with the address of the
4640 /// entire descriptor in "x0".
4641 ///
4642 /// Since this descriptor may be in a different unit, in general even the
4643 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4644 /// is:
4645 ///     adrp x0, _var@TLVPPAGE
4646 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4647 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4648 ///                                      ; the function pointer
4649 ///     blr x1                           ; Uses descriptor address in x0
4650 ///     ; Address of _var is now in x0.
4651 ///
4652 /// If the address of _var's descriptor *is* known to the linker, then it can
4653 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4654 /// a slight efficiency gain.
4655 SDValue
4656 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4657                                                    SelectionDAG &DAG) const {
4658   assert(Subtarget->isTargetDarwin() &&
4659          "This function expects a Darwin target");
4660 
4661   SDLoc DL(Op);
4662   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4663   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4664   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4665 
4666   SDValue TLVPAddr =
4667       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4668   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4669 
4670   // The first entry in the descriptor is a function pointer that we must call
4671   // to obtain the address of the variable.
4672   SDValue Chain = DAG.getEntryNode();
4673   SDValue FuncTLVGet = DAG.getLoad(
4674       PtrMemVT, DL, Chain, DescAddr,
4675       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4676       /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4677       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4678   Chain = FuncTLVGet.getValue(1);
4679 
4680   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4681   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4682 
4683   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4684   MFI.setAdjustsStack(true);
4685 
4686   // TLS calls preserve all registers except those that absolutely must be
4687   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4688   // silly).
4689   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4690   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4691   if (Subtarget->hasCustomCallingConv())
4692     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4693 
4694   // Finally, we can make the call. This is just a degenerate version of a
4695   // normal AArch64 call node: x0 takes the address of the descriptor, and
4696   // returns the address of the variable in this thread.
4697   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4698   Chain =
4699       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4700                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4701                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4702   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4703 }
4704 
4705 /// Convert a thread-local variable reference into a sequence of instructions to
4706 /// compute the variable's address for the local exec TLS model of ELF targets.
4707 /// The sequence depends on the maximum TLS area size.
4708 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4709                                                     SDValue ThreadBase,
4710                                                     const SDLoc &DL,
4711                                                     SelectionDAG &DAG) const {
4712   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4713   SDValue TPOff, Addr;
4714 
4715   switch (DAG.getTarget().Options.TLSSize) {
4716   default:
4717     llvm_unreachable("Unexpected TLS size");
4718 
4719   case 12: {
4720     // mrs   x0, TPIDR_EL0
4721     // add   x0, x0, :tprel_lo12:a
4722     SDValue Var = DAG.getTargetGlobalAddress(
4723         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4724     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4725                                       Var,
4726                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4727                    0);
4728   }
4729 
4730   case 24: {
4731     // mrs   x0, TPIDR_EL0
4732     // add   x0, x0, :tprel_hi12:a
4733     // add   x0, x0, :tprel_lo12_nc:a
4734     SDValue HiVar = DAG.getTargetGlobalAddress(
4735         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4736     SDValue LoVar = DAG.getTargetGlobalAddress(
4737         GV, DL, PtrVT, 0,
4738         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4739     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4740                                       HiVar,
4741                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4742                    0);
4743     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4744                                       LoVar,
4745                                       DAG.getTargetConstant(0, DL, MVT::i32)),
4746                    0);
4747   }
4748 
4749   case 32: {
4750     // mrs   x1, TPIDR_EL0
4751     // movz  x0, #:tprel_g1:a
4752     // movk  x0, #:tprel_g0_nc:a
4753     // add   x0, x1, x0
4754     SDValue HiVar = DAG.getTargetGlobalAddress(
4755         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4756     SDValue LoVar = DAG.getTargetGlobalAddress(
4757         GV, DL, PtrVT, 0,
4758         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4759     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4760                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4761                     0);
4762     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4763                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4764                     0);
4765     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4766   }
4767 
4768   case 48: {
4769     // mrs   x1, TPIDR_EL0
4770     // movz  x0, #:tprel_g2:a
4771     // movk  x0, #:tprel_g1_nc:a
4772     // movk  x0, #:tprel_g0_nc:a
4773     // add   x0, x1, x0
4774     SDValue HiVar = DAG.getTargetGlobalAddress(
4775         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4776     SDValue MiVar = DAG.getTargetGlobalAddress(
4777         GV, DL, PtrVT, 0,
4778         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4779     SDValue LoVar = DAG.getTargetGlobalAddress(
4780         GV, DL, PtrVT, 0,
4781         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4782     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4783                                        DAG.getTargetConstant(32, DL, MVT::i32)),
4784                     0);
4785     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4786                                        DAG.getTargetConstant(16, DL, MVT::i32)),
4787                     0);
4788     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4789                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4790                     0);
4791     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4792   }
4793   }
4794 }
4795 
4796 /// When accessing thread-local variables under either the general-dynamic or
4797 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4798 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4799 /// is a function pointer to carry out the resolution.
4800 ///
4801 /// The sequence is:
4802 ///    adrp  x0, :tlsdesc:var
4803 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4804 ///    add   x0, x0, #:tlsdesc_lo12:var
4805 ///    .tlsdesccall var
4806 ///    blr   x1
4807 ///    (TPIDR_EL0 offset now in x0)
4808 ///
4809 ///  The above sequence must be produced unscheduled, to enable the linker to
4810 ///  optimize/relax this sequence.
4811 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4812 ///  above sequence, and expanded really late in the compilation flow, to ensure
4813 ///  the sequence is produced as per above.
4814 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4815                                                       const SDLoc &DL,
4816                                                       SelectionDAG &DAG) const {
4817   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4818 
4819   SDValue Chain = DAG.getEntryNode();
4820   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4821 
4822   Chain =
4823       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4824   SDValue Glue = Chain.getValue(1);
4825 
4826   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4827 }
4828 
4829 SDValue
4830 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4831                                                 SelectionDAG &DAG) const {
4832   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4833 
4834   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4835 
4836   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4837 
4838   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4839     if (Model == TLSModel::LocalDynamic)
4840       Model = TLSModel::GeneralDynamic;
4841   }
4842 
4843   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4844       Model != TLSModel::LocalExec)
4845     report_fatal_error("ELF TLS only supported in small memory model or "
4846                        "in local exec TLS model");
4847   // Different choices can be made for the maximum size of the TLS area for a
4848   // module. For the small address model, the default TLS size is 16MiB and the
4849   // maximum TLS size is 4GiB.
4850   // FIXME: add tiny and large code model support for TLS access models other
4851   // than local exec. We currently generate the same code as small for tiny,
4852   // which may be larger than needed.
4853 
4854   SDValue TPOff;
4855   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4856   SDLoc DL(Op);
4857   const GlobalValue *GV = GA->getGlobal();
4858 
4859   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4860 
4861   if (Model == TLSModel::LocalExec) {
4862     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4863   } else if (Model == TLSModel::InitialExec) {
4864     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4865     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4866   } else if (Model == TLSModel::LocalDynamic) {
4867     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4868     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4869     // the beginning of the module's TLS region, followed by a DTPREL offset
4870     // calculation.
4871 
4872     // These accesses will need deduplicating if there's more than one.
4873     AArch64FunctionInfo *MFI =
4874         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4875     MFI->incNumLocalDynamicTLSAccesses();
4876 
4877     // The call needs a relocation too for linker relaxation. It doesn't make
4878     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4879     // the address.
4880     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4881                                                   AArch64II::MO_TLS);
4882 
4883     // Now we can calculate the offset from TPIDR_EL0 to this module's
4884     // thread-local area.
4885     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4886 
4887     // Now use :dtprel_whatever: operations to calculate this variable's offset
4888     // in its thread-storage area.
4889     SDValue HiVar = DAG.getTargetGlobalAddress(
4890         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4891     SDValue LoVar = DAG.getTargetGlobalAddress(
4892         GV, DL, MVT::i64, 0,
4893         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4894 
4895     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4896                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4897                     0);
4898     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4899                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4900                     0);
4901   } else if (Model == TLSModel::GeneralDynamic) {
4902     // The call needs a relocation too for linker relaxation. It doesn't make
4903     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4904     // the address.
4905     SDValue SymAddr =
4906         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4907 
4908     // Finally we can make a call to calculate the offset from tpidr_el0.
4909     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4910   } else
4911     llvm_unreachable("Unsupported ELF TLS access model");
4912 
4913   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4914 }
4915 
4916 SDValue
4917 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4918                                                     SelectionDAG &DAG) const {
4919   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4920 
4921   SDValue Chain = DAG.getEntryNode();
4922   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4923   SDLoc DL(Op);
4924 
4925   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4926 
4927   // Load the ThreadLocalStoragePointer from the TEB
4928   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4929   SDValue TLSArray =
4930       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4931   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4932   Chain = TLSArray.getValue(1);
4933 
4934   // Load the TLS index from the C runtime;
4935   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4936   // This also does the same as LOADgot, but using a generic i32 load,
4937   // while LOADgot only loads i64.
4938   SDValue TLSIndexHi =
4939       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4940   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4941       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4942   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4943   SDValue TLSIndex =
4944       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4945   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4946   Chain = TLSIndex.getValue(1);
4947 
4948   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4949   // offset into the TLSArray.
4950   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4951   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4952                              DAG.getConstant(3, DL, PtrVT));
4953   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4954                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4955                             MachinePointerInfo());
4956   Chain = TLS.getValue(1);
4957 
4958   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4959   const GlobalValue *GV = GA->getGlobal();
4960   SDValue TGAHi = DAG.getTargetGlobalAddress(
4961       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4962   SDValue TGALo = DAG.getTargetGlobalAddress(
4963       GV, DL, PtrVT, 0,
4964       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4965 
4966   // Add the offset from the start of the .tls section (section base).
4967   SDValue Addr =
4968       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4969                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4970               0);
4971   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4972   return Addr;
4973 }
4974 
4975 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4976                                                      SelectionDAG &DAG) const {
4977   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4978   if (DAG.getTarget().useEmulatedTLS())
4979     return LowerToTLSEmulatedModel(GA, DAG);
4980 
4981   if (Subtarget->isTargetDarwin())
4982     return LowerDarwinGlobalTLSAddress(Op, DAG);
4983   if (Subtarget->isTargetELF())
4984     return LowerELFGlobalTLSAddress(Op, DAG);
4985   if (Subtarget->isTargetWindows())
4986     return LowerWindowsGlobalTLSAddress(Op, DAG);
4987 
4988   llvm_unreachable("Unexpected platform trying to use TLS");
4989 }
4990 
4991 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4992   SDValue Chain = Op.getOperand(0);
4993   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4994   SDValue LHS = Op.getOperand(2);
4995   SDValue RHS = Op.getOperand(3);
4996   SDValue Dest = Op.getOperand(4);
4997   SDLoc dl(Op);
4998 
4999   MachineFunction &MF = DAG.getMachineFunction();
5000   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5001   // will not be produced, as they are conditional branch instructions that do
5002   // not set flags.
5003   bool ProduceNonFlagSettingCondBr =
5004       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5005 
5006   // Handle f128 first, since lowering it will result in comparing the return
5007   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5008   // is expecting to deal with.
5009   if (LHS.getValueType() == MVT::f128) {
5010     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5011 
5012     // If softenSetCCOperands returned a scalar, we need to compare the result
5013     // against zero to select between true and false values.
5014     if (!RHS.getNode()) {
5015       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5016       CC = ISD::SETNE;
5017     }
5018   }
5019 
5020   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5021   // instruction.
5022   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5023       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5024     // Only lower legal XALUO ops.
5025     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5026       return SDValue();
5027 
5028     // The actual operation with overflow check.
5029     AArch64CC::CondCode OFCC;
5030     SDValue Value, Overflow;
5031     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5032 
5033     if (CC == ISD::SETNE)
5034       OFCC = getInvertedCondCode(OFCC);
5035     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5036 
5037     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5038                        Overflow);
5039   }
5040 
5041   if (LHS.getValueType().isInteger()) {
5042     assert((LHS.getValueType() == RHS.getValueType()) &&
5043            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5044 
5045     // If the RHS of the comparison is zero, we can potentially fold this
5046     // to a specialized branch.
5047     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5048     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5049       if (CC == ISD::SETEQ) {
5050         // See if we can use a TBZ to fold in an AND as well.
5051         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5052         // out of bounds, a late MI-layer pass rewrites branches.
5053         // 403.gcc is an example that hits this case.
5054         if (LHS.getOpcode() == ISD::AND &&
5055             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5056             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5057           SDValue Test = LHS.getOperand(0);
5058           uint64_t Mask = LHS.getConstantOperandVal(1);
5059           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5060                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5061                              Dest);
5062         }
5063 
5064         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5065       } else if (CC == ISD::SETNE) {
5066         // See if we can use a TBZ to fold in an AND as well.
5067         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5068         // out of bounds, a late MI-layer pass rewrites branches.
5069         // 403.gcc is an example that hits this case.
5070         if (LHS.getOpcode() == ISD::AND &&
5071             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5072             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5073           SDValue Test = LHS.getOperand(0);
5074           uint64_t Mask = LHS.getConstantOperandVal(1);
5075           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5076                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5077                              Dest);
5078         }
5079 
5080         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5081       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5082         // Don't combine AND since emitComparison converts the AND to an ANDS
5083         // (a.k.a. TST) and the test in the test bit and branch instruction
5084         // becomes redundant.  This would also increase register pressure.
5085         uint64_t Mask = LHS.getValueSizeInBits() - 1;
5086         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5087                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
5088       }
5089     }
5090     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5091         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5092       // Don't combine AND since emitComparison converts the AND to an ANDS
5093       // (a.k.a. TST) and the test in the test bit and branch instruction
5094       // becomes redundant.  This would also increase register pressure.
5095       uint64_t Mask = LHS.getValueSizeInBits() - 1;
5096       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5097                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
5098     }
5099 
5100     SDValue CCVal;
5101     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5102     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5103                        Cmp);
5104   }
5105 
5106   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5107          LHS.getValueType() == MVT::f64);
5108 
5109   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5110   // clean.  Some of them require two branches to implement.
5111   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5112   AArch64CC::CondCode CC1, CC2;
5113   changeFPCCToAArch64CC(CC, CC1, CC2);
5114   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5115   SDValue BR1 =
5116       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5117   if (CC2 != AArch64CC::AL) {
5118     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5119     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5120                        Cmp);
5121   }
5122 
5123   return BR1;
5124 }
5125 
5126 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5127                                               SelectionDAG &DAG) const {
5128   EVT VT = Op.getValueType();
5129   SDLoc DL(Op);
5130 
5131   SDValue In1 = Op.getOperand(0);
5132   SDValue In2 = Op.getOperand(1);
5133   EVT SrcVT = In2.getValueType();
5134 
5135   if (SrcVT.bitsLT(VT))
5136     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5137   else if (SrcVT.bitsGT(VT))
5138     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5139 
5140   EVT VecVT;
5141   uint64_t EltMask;
5142   SDValue VecVal1, VecVal2;
5143 
5144   auto setVecVal = [&] (int Idx) {
5145     if (!VT.isVector()) {
5146       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5147                                           DAG.getUNDEF(VecVT), In1);
5148       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5149                                           DAG.getUNDEF(VecVT), In2);
5150     } else {
5151       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5152       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5153     }
5154   };
5155 
5156   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5157     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5158     EltMask = 0x80000000ULL;
5159     setVecVal(AArch64::ssub);
5160   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5161     VecVT = MVT::v2i64;
5162 
5163     // We want to materialize a mask with the high bit set, but the AdvSIMD
5164     // immediate moves cannot materialize that in a single instruction for
5165     // 64-bit elements. Instead, materialize zero and then negate it.
5166     EltMask = 0;
5167 
5168     setVecVal(AArch64::dsub);
5169   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5170     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5171     EltMask = 0x8000ULL;
5172     setVecVal(AArch64::hsub);
5173   } else {
5174     llvm_unreachable("Invalid type for copysign!");
5175   }
5176 
5177   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5178 
5179   // If we couldn't materialize the mask above, then the mask vector will be
5180   // the zero vector, and we need to negate it here.
5181   if (VT == MVT::f64 || VT == MVT::v2f64) {
5182     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5183     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5184     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5185   }
5186 
5187   SDValue Sel =
5188       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5189 
5190   if (VT == MVT::f16)
5191     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5192   if (VT == MVT::f32)
5193     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5194   else if (VT == MVT::f64)
5195     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5196   else
5197     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5198 }
5199 
5200 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5201   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5202           Attribute::NoImplicitFloat))
5203     return SDValue();
5204 
5205   if (!Subtarget->hasNEON())
5206     return SDValue();
5207 
5208   // While there is no integer popcount instruction, it can
5209   // be more efficiently lowered to the following sequence that uses
5210   // AdvSIMD registers/instructions as long as the copies to/from
5211   // the AdvSIMD registers are cheap.
5212   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
5213   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
5214   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
5215   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
5216   SDValue Val = Op.getOperand(0);
5217   SDLoc DL(Op);
5218   EVT VT = Op.getValueType();
5219 
5220   if (VT == MVT::i32 || VT == MVT::i64) {
5221     if (VT == MVT::i32)
5222       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5223     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5224 
5225     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5226     SDValue UaddLV = DAG.getNode(
5227         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5228         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5229 
5230     if (VT == MVT::i64)
5231       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5232     return UaddLV;
5233   }
5234 
5235   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5236           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5237          "Unexpected type for custom ctpop lowering");
5238 
5239   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5240   Val = DAG.getBitcast(VT8Bit, Val);
5241   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5242 
5243   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5244   unsigned EltSize = 8;
5245   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5246   while (EltSize != VT.getScalarSizeInBits()) {
5247     EltSize *= 2;
5248     NumElts /= 2;
5249     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5250     Val = DAG.getNode(
5251         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5252         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5253   }
5254 
5255   return Val;
5256 }
5257 
5258 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5259 
5260   if (Op.getValueType().isVector())
5261     return LowerVSETCC(Op, DAG);
5262 
5263   bool IsStrict = Op->isStrictFPOpcode();
5264   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5265   unsigned OpNo = IsStrict ? 1 : 0;
5266   SDValue Chain;
5267   if (IsStrict)
5268     Chain = Op.getOperand(0);
5269   SDValue LHS = Op.getOperand(OpNo + 0);
5270   SDValue RHS = Op.getOperand(OpNo + 1);
5271   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5272   SDLoc dl(Op);
5273 
5274   // We chose ZeroOrOneBooleanContents, so use zero and one.
5275   EVT VT = Op.getValueType();
5276   SDValue TVal = DAG.getConstant(1, dl, VT);
5277   SDValue FVal = DAG.getConstant(0, dl, VT);
5278 
5279   // Handle f128 first, since one possible outcome is a normal integer
5280   // comparison which gets picked up by the next if statement.
5281   if (LHS.getValueType() == MVT::f128) {
5282     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5283                         IsSignaling);
5284 
5285     // If softenSetCCOperands returned a scalar, use it.
5286     if (!RHS.getNode()) {
5287       assert(LHS.getValueType() == Op.getValueType() &&
5288              "Unexpected setcc expansion!");
5289       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5290     }
5291   }
5292 
5293   if (LHS.getValueType().isInteger()) {
5294     SDValue CCVal;
5295     SDValue Cmp = getAArch64Cmp(
5296         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5297 
5298     // Note that we inverted the condition above, so we reverse the order of
5299     // the true and false operands here.  This will allow the setcc to be
5300     // matched to a single CSINC instruction.
5301     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5302     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5303   }
5304 
5305   // Now we know we're dealing with FP values.
5306   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5307          LHS.getValueType() == MVT::f64);
5308 
5309   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
5310   // and do the comparison.
5311   SDValue Cmp;
5312   if (IsStrict)
5313     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5314   else
5315     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5316 
5317   AArch64CC::CondCode CC1, CC2;
5318   changeFPCCToAArch64CC(CC, CC1, CC2);
5319   SDValue Res;
5320   if (CC2 == AArch64CC::AL) {
5321     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5322                           CC2);
5323     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5324 
5325     // Note that we inverted the condition above, so we reverse the order of
5326     // the true and false operands here.  This will allow the setcc to be
5327     // matched to a single CSINC instruction.
5328     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5329   } else {
5330     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5331     // totally clean.  Some of them require two CSELs to implement.  As is in
5332     // this case, we emit the first CSEL and then emit a second using the output
5333     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
5334 
5335     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5336     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5337     SDValue CS1 =
5338         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5339 
5340     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5341     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5342   }
5343   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5344 }
5345 
5346 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5347                                               SDValue RHS, SDValue TVal,
5348                                               SDValue FVal, const SDLoc &dl,
5349                                               SelectionDAG &DAG) const {
5350   // Handle f128 first, because it will result in a comparison of some RTLIB
5351   // call result against zero.
5352   if (LHS.getValueType() == MVT::f128) {
5353     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5354 
5355     // If softenSetCCOperands returned a scalar, we need to compare the result
5356     // against zero to select between true and false values.
5357     if (!RHS.getNode()) {
5358       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5359       CC = ISD::SETNE;
5360     }
5361   }
5362 
5363   // Also handle f16, for which we need to do a f32 comparison.
5364   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5365     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5366     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5367   }
5368 
5369   // Next, handle integers.
5370   if (LHS.getValueType().isInteger()) {
5371     assert((LHS.getValueType() == RHS.getValueType()) &&
5372            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5373 
5374     unsigned Opcode = AArch64ISD::CSEL;
5375 
5376     // If both the TVal and the FVal are constants, see if we can swap them in
5377     // order to for a CSINV or CSINC out of them.
5378     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5379     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5380 
5381     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5382       std::swap(TVal, FVal);
5383       std::swap(CTVal, CFVal);
5384       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5385     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5386       std::swap(TVal, FVal);
5387       std::swap(CTVal, CFVal);
5388       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5389     } else if (TVal.getOpcode() == ISD::XOR) {
5390       // If TVal is a NOT we want to swap TVal and FVal so that we can match
5391       // with a CSINV rather than a CSEL.
5392       if (isAllOnesConstant(TVal.getOperand(1))) {
5393         std::swap(TVal, FVal);
5394         std::swap(CTVal, CFVal);
5395         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5396       }
5397     } else if (TVal.getOpcode() == ISD::SUB) {
5398       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5399       // that we can match with a CSNEG rather than a CSEL.
5400       if (isNullConstant(TVal.getOperand(0))) {
5401         std::swap(TVal, FVal);
5402         std::swap(CTVal, CFVal);
5403         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5404       }
5405     } else if (CTVal && CFVal) {
5406       const int64_t TrueVal = CTVal->getSExtValue();
5407       const int64_t FalseVal = CFVal->getSExtValue();
5408       bool Swap = false;
5409 
5410       // If both TVal and FVal are constants, see if FVal is the
5411       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5412       // instead of a CSEL in that case.
5413       if (TrueVal == ~FalseVal) {
5414         Opcode = AArch64ISD::CSINV;
5415       } else if (TrueVal == -FalseVal) {
5416         Opcode = AArch64ISD::CSNEG;
5417       } else if (TVal.getValueType() == MVT::i32) {
5418         // If our operands are only 32-bit wide, make sure we use 32-bit
5419         // arithmetic for the check whether we can use CSINC. This ensures that
5420         // the addition in the check will wrap around properly in case there is
5421         // an overflow (which would not be the case if we do the check with
5422         // 64-bit arithmetic).
5423         const uint32_t TrueVal32 = CTVal->getZExtValue();
5424         const uint32_t FalseVal32 = CFVal->getZExtValue();
5425 
5426         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5427           Opcode = AArch64ISD::CSINC;
5428 
5429           if (TrueVal32 > FalseVal32) {
5430             Swap = true;
5431           }
5432         }
5433         // 64-bit check whether we can use CSINC.
5434       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5435         Opcode = AArch64ISD::CSINC;
5436 
5437         if (TrueVal > FalseVal) {
5438           Swap = true;
5439         }
5440       }
5441 
5442       // Swap TVal and FVal if necessary.
5443       if (Swap) {
5444         std::swap(TVal, FVal);
5445         std::swap(CTVal, CFVal);
5446         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5447       }
5448 
5449       if (Opcode != AArch64ISD::CSEL) {
5450         // Drop FVal since we can get its value by simply inverting/negating
5451         // TVal.
5452         FVal = TVal;
5453       }
5454     }
5455 
5456     // Avoid materializing a constant when possible by reusing a known value in
5457     // a register.  However, don't perform this optimization if the known value
5458     // is one, zero or negative one in the case of a CSEL.  We can always
5459     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5460     // FVal, respectively.
5461     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5462     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5463         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5464       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5465       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5466       // "a != C ? x : a" to avoid materializing C.
5467       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5468         TVal = LHS;
5469       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5470         FVal = LHS;
5471     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5472       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5473       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5474       // avoid materializing C.
5475       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5476       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5477         Opcode = AArch64ISD::CSINV;
5478         TVal = LHS;
5479         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5480       }
5481     }
5482 
5483     SDValue CCVal;
5484     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5485     EVT VT = TVal.getValueType();
5486     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5487   }
5488 
5489   // Now we know we're dealing with FP values.
5490   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5491          LHS.getValueType() == MVT::f64);
5492   assert(LHS.getValueType() == RHS.getValueType());
5493   EVT VT = TVal.getValueType();
5494   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5495 
5496   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5497   // clean.  Some of them require two CSELs to implement.
5498   AArch64CC::CondCode CC1, CC2;
5499   changeFPCCToAArch64CC(CC, CC1, CC2);
5500 
5501   if (DAG.getTarget().Options.UnsafeFPMath) {
5502     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5503     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5504     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5505     if (RHSVal && RHSVal->isZero()) {
5506       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5507       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5508 
5509       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5510           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5511         TVal = LHS;
5512       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5513                CFVal && CFVal->isZero() &&
5514                FVal.getValueType() == LHS.getValueType())
5515         FVal = LHS;
5516     }
5517   }
5518 
5519   // Emit first, and possibly only, CSEL.
5520   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5521   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5522 
5523   // If we need a second CSEL, emit it, using the output of the first as the
5524   // RHS.  We're effectively OR'ing the two CC's together.
5525   if (CC2 != AArch64CC::AL) {
5526     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5527     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5528   }
5529 
5530   // Otherwise, return the output of the first CSEL.
5531   return CS1;
5532 }
5533 
5534 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5535                                               SelectionDAG &DAG) const {
5536   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5537   SDValue LHS = Op.getOperand(0);
5538   SDValue RHS = Op.getOperand(1);
5539   SDValue TVal = Op.getOperand(2);
5540   SDValue FVal = Op.getOperand(3);
5541   SDLoc DL(Op);
5542   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5543 }
5544 
5545 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5546                                            SelectionDAG &DAG) const {
5547   SDValue CCVal = Op->getOperand(0);
5548   SDValue TVal = Op->getOperand(1);
5549   SDValue FVal = Op->getOperand(2);
5550   SDLoc DL(Op);
5551 
5552   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5553   // instruction.
5554   if (isOverflowIntrOpRes(CCVal)) {
5555     // Only lower legal XALUO ops.
5556     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5557       return SDValue();
5558 
5559     AArch64CC::CondCode OFCC;
5560     SDValue Value, Overflow;
5561     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5562     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5563 
5564     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5565                        CCVal, Overflow);
5566   }
5567 
5568   // Lower it the same way as we would lower a SELECT_CC node.
5569   ISD::CondCode CC;
5570   SDValue LHS, RHS;
5571   if (CCVal.getOpcode() == ISD::SETCC) {
5572     LHS = CCVal.getOperand(0);
5573     RHS = CCVal.getOperand(1);
5574     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5575   } else {
5576     LHS = CCVal;
5577     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5578     CC = ISD::SETNE;
5579   }
5580   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5581 }
5582 
5583 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5584                                               SelectionDAG &DAG) const {
5585   // Jump table entries as PC relative offsets. No additional tweaking
5586   // is necessary here. Just get the address of the jump table.
5587   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5588 
5589   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5590       !Subtarget->isTargetMachO()) {
5591     return getAddrLarge(JT, DAG);
5592   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5593     return getAddrTiny(JT, DAG);
5594   }
5595   return getAddr(JT, DAG);
5596 }
5597 
5598 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5599                                           SelectionDAG &DAG) const {
5600   // Jump table entries as PC relative offsets. No additional tweaking
5601   // is necessary here. Just get the address of the jump table.
5602   SDLoc DL(Op);
5603   SDValue JT = Op.getOperand(1);
5604   SDValue Entry = Op.getOperand(2);
5605   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5606 
5607   SDNode *Dest =
5608       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5609                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5610   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5611                      SDValue(Dest, 0));
5612 }
5613 
5614 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5615                                                  SelectionDAG &DAG) const {
5616   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5617 
5618   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5619     // Use the GOT for the large code model on iOS.
5620     if (Subtarget->isTargetMachO()) {
5621       return getGOT(CP, DAG);
5622     }
5623     return getAddrLarge(CP, DAG);
5624   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5625     return getAddrTiny(CP, DAG);
5626   } else {
5627     return getAddr(CP, DAG);
5628   }
5629 }
5630 
5631 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5632                                                SelectionDAG &DAG) const {
5633   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5634   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5635       !Subtarget->isTargetMachO()) {
5636     return getAddrLarge(BA, DAG);
5637   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5638     return getAddrTiny(BA, DAG);
5639   }
5640   return getAddr(BA, DAG);
5641 }
5642 
5643 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5644                                                  SelectionDAG &DAG) const {
5645   AArch64FunctionInfo *FuncInfo =
5646       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5647 
5648   SDLoc DL(Op);
5649   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5650                                  getPointerTy(DAG.getDataLayout()));
5651   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5652   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5653   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5654                       MachinePointerInfo(SV));
5655 }
5656 
5657 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5658                                                   SelectionDAG &DAG) const {
5659   AArch64FunctionInfo *FuncInfo =
5660       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5661 
5662   SDLoc DL(Op);
5663   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5664                                      ? FuncInfo->getVarArgsGPRIndex()
5665                                      : FuncInfo->getVarArgsStackIndex(),
5666                                  getPointerTy(DAG.getDataLayout()));
5667   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5668   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5669                       MachinePointerInfo(SV));
5670 }
5671 
5672 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5673                                                 SelectionDAG &DAG) const {
5674   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5675   // Standard, section B.3.
5676   MachineFunction &MF = DAG.getMachineFunction();
5677   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5678   auto PtrVT = getPointerTy(DAG.getDataLayout());
5679   SDLoc DL(Op);
5680 
5681   SDValue Chain = Op.getOperand(0);
5682   SDValue VAList = Op.getOperand(1);
5683   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5684   SmallVector<SDValue, 4> MemOps;
5685 
5686   // void *__stack at offset 0
5687   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5688   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5689                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5690 
5691   // void *__gr_top at offset 8
5692   int GPRSize = FuncInfo->getVarArgsGPRSize();
5693   if (GPRSize > 0) {
5694     SDValue GRTop, GRTopAddr;
5695 
5696     GRTopAddr =
5697         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5698 
5699     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5700     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5701                         DAG.getConstant(GPRSize, DL, PtrVT));
5702 
5703     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5704                                   MachinePointerInfo(SV, 8),
5705                                   /* Alignment = */ 8));
5706   }
5707 
5708   // void *__vr_top at offset 16
5709   int FPRSize = FuncInfo->getVarArgsFPRSize();
5710   if (FPRSize > 0) {
5711     SDValue VRTop, VRTopAddr;
5712     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5713                             DAG.getConstant(16, DL, PtrVT));
5714 
5715     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5716     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5717                         DAG.getConstant(FPRSize, DL, PtrVT));
5718 
5719     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5720                                   MachinePointerInfo(SV, 16),
5721                                   /* Alignment = */ 8));
5722   }
5723 
5724   // int __gr_offs at offset 24
5725   SDValue GROffsAddr =
5726       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5727   MemOps.push_back(DAG.getStore(
5728       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5729       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5730 
5731   // int __vr_offs at offset 28
5732   SDValue VROffsAddr =
5733       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5734   MemOps.push_back(DAG.getStore(
5735       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5736       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5737 
5738   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5739 }
5740 
5741 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5742                                             SelectionDAG &DAG) const {
5743   MachineFunction &MF = DAG.getMachineFunction();
5744 
5745   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5746     return LowerWin64_VASTART(Op, DAG);
5747   else if (Subtarget->isTargetDarwin())
5748     return LowerDarwin_VASTART(Op, DAG);
5749   else
5750     return LowerAAPCS_VASTART(Op, DAG);
5751 }
5752 
5753 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5754                                            SelectionDAG &DAG) const {
5755   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5756   // pointer.
5757   SDLoc DL(Op);
5758   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5759   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5760                          Subtarget->isTargetWindows()) ? PtrSize : 32;
5761   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5762   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5763 
5764   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5765                        DAG.getConstant(VaListSize, DL, MVT::i32),
5766                        Align(PtrSize), false, false, false,
5767                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
5768 }
5769 
5770 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5771   assert(Subtarget->isTargetDarwin() &&
5772          "automatic va_arg instruction only works on Darwin");
5773 
5774   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5775   EVT VT = Op.getValueType();
5776   SDLoc DL(Op);
5777   SDValue Chain = Op.getOperand(0);
5778   SDValue Addr = Op.getOperand(1);
5779   unsigned Align = Op.getConstantOperandVal(3);
5780   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5781   auto PtrVT = getPointerTy(DAG.getDataLayout());
5782   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5783   SDValue VAList =
5784       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5785   Chain = VAList.getValue(1);
5786   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5787 
5788   if (Align > MinSlotSize) {
5789     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5790     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5791                          DAG.getConstant(Align - 1, DL, PtrVT));
5792     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5793                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5794   }
5795 
5796   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5797   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5798 
5799   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5800   // up to 64 bits.  At the very least, we have to increase the striding of the
5801   // vaargs list to match this, and for FP values we need to introduce
5802   // FP_ROUND nodes as well.
5803   if (VT.isInteger() && !VT.isVector())
5804     ArgSize = std::max(ArgSize, MinSlotSize);
5805   bool NeedFPTrunc = false;
5806   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5807     ArgSize = 8;
5808     NeedFPTrunc = true;
5809   }
5810 
5811   // Increment the pointer, VAList, to the next vaarg
5812   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5813                                DAG.getConstant(ArgSize, DL, PtrVT));
5814   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5815 
5816   // Store the incremented VAList to the legalized pointer
5817   SDValue APStore =
5818       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5819 
5820   // Load the actual argument out of the pointer VAList
5821   if (NeedFPTrunc) {
5822     // Load the value as an f64.
5823     SDValue WideFP =
5824         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5825     // Round the value down to an f32.
5826     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5827                                    DAG.getIntPtrConstant(1, DL));
5828     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5829     // Merge the rounded value with the chain output of the load.
5830     return DAG.getMergeValues(Ops, DL);
5831   }
5832 
5833   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5834 }
5835 
5836 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5837                                               SelectionDAG &DAG) const {
5838   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5839   MFI.setFrameAddressIsTaken(true);
5840 
5841   EVT VT = Op.getValueType();
5842   SDLoc DL(Op);
5843   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5844   SDValue FrameAddr =
5845       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5846   while (Depth--)
5847     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5848                             MachinePointerInfo());
5849 
5850   if (Subtarget->isTargetILP32())
5851     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5852                             DAG.getValueType(VT));
5853 
5854   return FrameAddr;
5855 }
5856 
5857 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5858                                               SelectionDAG &DAG) const {
5859   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5860 
5861   EVT VT = getPointerTy(DAG.getDataLayout());
5862   SDLoc DL(Op);
5863   int FI = MFI.CreateFixedObject(4, 0, false);
5864   return DAG.getFrameIndex(FI, VT);
5865 }
5866 
5867 #define GET_REGISTER_MATCHER
5868 #include "AArch64GenAsmMatcher.inc"
5869 
5870 // FIXME? Maybe this could be a TableGen attribute on some registers and
5871 // this table could be generated automatically from RegInfo.
5872 Register AArch64TargetLowering::
5873 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5874   Register Reg = MatchRegisterName(RegName);
5875   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5876     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5877     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5878     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5879       Reg = 0;
5880   }
5881   if (Reg)
5882     return Reg;
5883   report_fatal_error(Twine("Invalid register name \""
5884                               + StringRef(RegName)  + "\"."));
5885 }
5886 
5887 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5888                                                      SelectionDAG &DAG) const {
5889   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5890 
5891   EVT VT = Op.getValueType();
5892   SDLoc DL(Op);
5893 
5894   SDValue FrameAddr =
5895       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5896   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5897 
5898   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5899 }
5900 
5901 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5902                                                SelectionDAG &DAG) const {
5903   MachineFunction &MF = DAG.getMachineFunction();
5904   MachineFrameInfo &MFI = MF.getFrameInfo();
5905   MFI.setReturnAddressIsTaken(true);
5906 
5907   EVT VT = Op.getValueType();
5908   SDLoc DL(Op);
5909   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5910   if (Depth) {
5911     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5912     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5913     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5914                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5915                        MachinePointerInfo());
5916   }
5917 
5918   // Return LR, which contains the return address. Mark it an implicit live-in.
5919   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5920   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5921 }
5922 
5923 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5924 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5925 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5926                                                     SelectionDAG &DAG) const {
5927   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5928   EVT VT = Op.getValueType();
5929   unsigned VTBits = VT.getSizeInBits();
5930   SDLoc dl(Op);
5931   SDValue ShOpLo = Op.getOperand(0);
5932   SDValue ShOpHi = Op.getOperand(1);
5933   SDValue ShAmt = Op.getOperand(2);
5934   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5935 
5936   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5937 
5938   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5939                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5940   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5941 
5942   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5943   // is "undef". We wanted 0, so CSEL it directly.
5944   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5945                                ISD::SETEQ, dl, DAG);
5946   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5947   HiBitsForLo =
5948       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5949                   HiBitsForLo, CCVal, Cmp);
5950 
5951   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5952                                    DAG.getConstant(VTBits, dl, MVT::i64));
5953 
5954   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5955   SDValue LoForNormalShift =
5956       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5957 
5958   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5959                        dl, DAG);
5960   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5961   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5962   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5963                            LoForNormalShift, CCVal, Cmp);
5964 
5965   // AArch64 shifts larger than the register width are wrapped rather than
5966   // clamped, so we can't just emit "hi >> x".
5967   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5968   SDValue HiForBigShift =
5969       Opc == ISD::SRA
5970           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5971                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5972           : DAG.getConstant(0, dl, VT);
5973   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5974                            HiForNormalShift, CCVal, Cmp);
5975 
5976   SDValue Ops[2] = { Lo, Hi };
5977   return DAG.getMergeValues(Ops, dl);
5978 }
5979 
5980 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5981 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5982 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5983                                                    SelectionDAG &DAG) const {
5984   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5985   EVT VT = Op.getValueType();
5986   unsigned VTBits = VT.getSizeInBits();
5987   SDLoc dl(Op);
5988   SDValue ShOpLo = Op.getOperand(0);
5989   SDValue ShOpHi = Op.getOperand(1);
5990   SDValue ShAmt = Op.getOperand(2);
5991 
5992   assert(Op.getOpcode() == ISD::SHL_PARTS);
5993   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5994                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5995   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5996 
5997   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5998   // is "undef". We wanted 0, so CSEL it directly.
5999   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6000                                ISD::SETEQ, dl, DAG);
6001   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6002   LoBitsForHi =
6003       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6004                   LoBitsForHi, CCVal, Cmp);
6005 
6006   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6007                                    DAG.getConstant(VTBits, dl, MVT::i64));
6008   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6009   SDValue HiForNormalShift =
6010       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6011 
6012   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6013 
6014   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6015                        dl, DAG);
6016   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6017   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6018                            HiForNormalShift, CCVal, Cmp);
6019 
6020   // AArch64 shifts of larger than register sizes are wrapped rather than
6021   // clamped, so we can't just emit "lo << a" if a is too big.
6022   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6023   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6024   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6025                            LoForNormalShift, CCVal, Cmp);
6026 
6027   SDValue Ops[2] = { Lo, Hi };
6028   return DAG.getMergeValues(Ops, dl);
6029 }
6030 
6031 bool AArch64TargetLowering::isOffsetFoldingLegal(
6032     const GlobalAddressSDNode *GA) const {
6033   // Offsets are folded in the DAG combine rather than here so that we can
6034   // intelligently choose an offset based on the uses.
6035   return false;
6036 }
6037 
6038 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6039                                          bool OptForSize) const {
6040   bool IsLegal = false;
6041   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6042   // 16-bit case when target has full fp16 support.
6043   // FIXME: We should be able to handle f128 as well with a clever lowering.
6044   const APInt ImmInt = Imm.bitcastToAPInt();
6045   if (VT == MVT::f64)
6046     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6047   else if (VT == MVT::f32)
6048     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6049   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6050     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6051   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6052   //       generate that fmov.
6053 
6054   // If we can not materialize in immediate field for fmov, check if the
6055   // value can be encoded as the immediate operand of a logical instruction.
6056   // The immediate value will be created with either MOVZ, MOVN, or ORR.
6057   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6058     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6059     // however the mov+fmov sequence is always better because of the reduced
6060     // cache pressure. The timings are still the same if you consider
6061     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6062     // movw+movk is fused). So we limit up to 2 instrdduction at most.
6063     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6064     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6065 			      Insn);
6066     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6067     IsLegal = Insn.size() <= Limit;
6068   }
6069 
6070   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6071                     << " imm value: "; Imm.dump(););
6072   return IsLegal;
6073 }
6074 
6075 //===----------------------------------------------------------------------===//
6076 //                          AArch64 Optimization Hooks
6077 //===----------------------------------------------------------------------===//
6078 
6079 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6080                            SDValue Operand, SelectionDAG &DAG,
6081                            int &ExtraSteps) {
6082   EVT VT = Operand.getValueType();
6083   if (ST->hasNEON() &&
6084       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6085        VT == MVT::f32 || VT == MVT::v1f32 ||
6086        VT == MVT::v2f32 || VT == MVT::v4f32)) {
6087     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6088       // For the reciprocal estimates, convergence is quadratic, so the number
6089       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
6090       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
6091       // the result for float (23 mantissa bits) is 2 and for double (52
6092       // mantissa bits) is 3.
6093       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6094 
6095     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6096   }
6097 
6098   return SDValue();
6099 }
6100 
6101 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6102                                                SelectionDAG &DAG, int Enabled,
6103                                                int &ExtraSteps,
6104                                                bool &UseOneConst,
6105                                                bool Reciprocal) const {
6106   if (Enabled == ReciprocalEstimate::Enabled ||
6107       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6108     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6109                                        DAG, ExtraSteps)) {
6110       SDLoc DL(Operand);
6111       EVT VT = Operand.getValueType();
6112 
6113       SDNodeFlags Flags;
6114       Flags.setAllowReassociation(true);
6115 
6116       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6117       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6118       for (int i = ExtraSteps; i > 0; --i) {
6119         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6120                                    Flags);
6121         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6122         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6123       }
6124       if (!Reciprocal) {
6125         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6126                                       VT);
6127         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6128         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6129 
6130         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6131         // Correct the result if the operand is 0.0.
6132         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6133                                VT, Eq, Operand, Estimate);
6134       }
6135 
6136       ExtraSteps = 0;
6137       return Estimate;
6138     }
6139 
6140   return SDValue();
6141 }
6142 
6143 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6144                                                 SelectionDAG &DAG, int Enabled,
6145                                                 int &ExtraSteps) const {
6146   if (Enabled == ReciprocalEstimate::Enabled)
6147     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6148                                        DAG, ExtraSteps)) {
6149       SDLoc DL(Operand);
6150       EVT VT = Operand.getValueType();
6151 
6152       SDNodeFlags Flags;
6153       Flags.setAllowReassociation(true);
6154 
6155       // Newton reciprocal iteration: E * (2 - X * E)
6156       // AArch64 reciprocal iteration instruction: (2 - M * N)
6157       for (int i = ExtraSteps; i > 0; --i) {
6158         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6159                                    Estimate, Flags);
6160         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6161       }
6162 
6163       ExtraSteps = 0;
6164       return Estimate;
6165     }
6166 
6167   return SDValue();
6168 }
6169 
6170 //===----------------------------------------------------------------------===//
6171 //                          AArch64 Inline Assembly Support
6172 //===----------------------------------------------------------------------===//
6173 
6174 // Table of Constraints
6175 // TODO: This is the current set of constraints supported by ARM for the
6176 // compiler, not all of them may make sense.
6177 //
6178 // r - A general register
6179 // w - An FP/SIMD register of some size in the range v0-v31
6180 // x - An FP/SIMD register of some size in the range v0-v15
6181 // I - Constant that can be used with an ADD instruction
6182 // J - Constant that can be used with a SUB instruction
6183 // K - Constant that can be used with a 32-bit logical instruction
6184 // L - Constant that can be used with a 64-bit logical instruction
6185 // M - Constant that can be used as a 32-bit MOV immediate
6186 // N - Constant that can be used as a 64-bit MOV immediate
6187 // Q - A memory reference with base register and no offset
6188 // S - A symbolic address
6189 // Y - Floating point constant zero
6190 // Z - Integer constant zero
6191 //
6192 //   Note that general register operands will be output using their 64-bit x
6193 // register name, whatever the size of the variable, unless the asm operand
6194 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6195 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6196 // %q modifier.
6197 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6198   // At this point, we have to lower this constraint to something else, so we
6199   // lower it to an "r" or "w". However, by doing this we will force the result
6200   // to be in register, while the X constraint is much more permissive.
6201   //
6202   // Although we are correct (we are free to emit anything, without
6203   // constraints), we might break use cases that would expect us to be more
6204   // efficient and emit something else.
6205   if (!Subtarget->hasFPARMv8())
6206     return "r";
6207 
6208   if (ConstraintVT.isFloatingPoint())
6209     return "w";
6210 
6211   if (ConstraintVT.isVector() &&
6212      (ConstraintVT.getSizeInBits() == 64 ||
6213       ConstraintVT.getSizeInBits() == 128))
6214     return "w";
6215 
6216   return "r";
6217 }
6218 
6219 enum PredicateConstraint {
6220   Upl,
6221   Upa,
6222   Invalid
6223 };
6224 
6225 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6226   PredicateConstraint P = PredicateConstraint::Invalid;
6227   if (Constraint == "Upa")
6228     P = PredicateConstraint::Upa;
6229   if (Constraint == "Upl")
6230     P = PredicateConstraint::Upl;
6231   return P;
6232 }
6233 
6234 /// getConstraintType - Given a constraint letter, return the type of
6235 /// constraint it is for this target.
6236 AArch64TargetLowering::ConstraintType
6237 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6238   if (Constraint.size() == 1) {
6239     switch (Constraint[0]) {
6240     default:
6241       break;
6242     case 'x':
6243     case 'w':
6244     case 'y':
6245       return C_RegisterClass;
6246     // An address with a single base register. Due to the way we
6247     // currently handle addresses it is the same as 'r'.
6248     case 'Q':
6249       return C_Memory;
6250     case 'I':
6251     case 'J':
6252     case 'K':
6253     case 'L':
6254     case 'M':
6255     case 'N':
6256     case 'Y':
6257     case 'Z':
6258       return C_Immediate;
6259     case 'z':
6260     case 'S': // A symbolic address
6261       return C_Other;
6262     }
6263   } else if (parsePredicateConstraint(Constraint) !=
6264              PredicateConstraint::Invalid)
6265       return C_RegisterClass;
6266   return TargetLowering::getConstraintType(Constraint);
6267 }
6268 
6269 /// Examine constraint type and operand type and determine a weight value.
6270 /// This object must already have been set up with the operand type
6271 /// and the current alternative constraint selected.
6272 TargetLowering::ConstraintWeight
6273 AArch64TargetLowering::getSingleConstraintMatchWeight(
6274     AsmOperandInfo &info, const char *constraint) const {
6275   ConstraintWeight weight = CW_Invalid;
6276   Value *CallOperandVal = info.CallOperandVal;
6277   // If we don't have a value, we can't do a match,
6278   // but allow it at the lowest weight.
6279   if (!CallOperandVal)
6280     return CW_Default;
6281   Type *type = CallOperandVal->getType();
6282   // Look at the constraint type.
6283   switch (*constraint) {
6284   default:
6285     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6286     break;
6287   case 'x':
6288   case 'w':
6289   case 'y':
6290     if (type->isFloatingPointTy() || type->isVectorTy())
6291       weight = CW_Register;
6292     break;
6293   case 'z':
6294     weight = CW_Constant;
6295     break;
6296   case 'U':
6297     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6298       weight = CW_Register;
6299     break;
6300   }
6301   return weight;
6302 }
6303 
6304 std::pair<unsigned, const TargetRegisterClass *>
6305 AArch64TargetLowering::getRegForInlineAsmConstraint(
6306     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6307   if (Constraint.size() == 1) {
6308     switch (Constraint[0]) {
6309     case 'r':
6310       if (VT.getSizeInBits() == 64)
6311         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6312       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6313     case 'w':
6314       if (!Subtarget->hasFPARMv8())
6315         break;
6316       if (VT.isScalableVector())
6317         return std::make_pair(0U, &AArch64::ZPRRegClass);
6318       if (VT.getSizeInBits() == 16)
6319         return std::make_pair(0U, &AArch64::FPR16RegClass);
6320       if (VT.getSizeInBits() == 32)
6321         return std::make_pair(0U, &AArch64::FPR32RegClass);
6322       if (VT.getSizeInBits() == 64)
6323         return std::make_pair(0U, &AArch64::FPR64RegClass);
6324       if (VT.getSizeInBits() == 128)
6325         return std::make_pair(0U, &AArch64::FPR128RegClass);
6326       break;
6327     // The instructions that this constraint is designed for can
6328     // only take 128-bit registers so just use that regclass.
6329     case 'x':
6330       if (!Subtarget->hasFPARMv8())
6331         break;
6332       if (VT.isScalableVector())
6333         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6334       if (VT.getSizeInBits() == 128)
6335         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6336       break;
6337     case 'y':
6338       if (!Subtarget->hasFPARMv8())
6339         break;
6340       if (VT.isScalableVector())
6341         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6342       break;
6343     }
6344   } else {
6345     PredicateConstraint PC = parsePredicateConstraint(Constraint);
6346     if (PC != PredicateConstraint::Invalid) {
6347       assert(VT.isScalableVector());
6348       bool restricted = (PC == PredicateConstraint::Upl);
6349       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6350                           : std::make_pair(0U, &AArch64::PPRRegClass);
6351     }
6352   }
6353   if (StringRef("{cc}").equals_lower(Constraint))
6354     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6355 
6356   // Use the default implementation in TargetLowering to convert the register
6357   // constraint into a member of a register class.
6358   std::pair<unsigned, const TargetRegisterClass *> Res;
6359   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6360 
6361   // Not found as a standard register?
6362   if (!Res.second) {
6363     unsigned Size = Constraint.size();
6364     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6365         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6366       int RegNo;
6367       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6368       if (!Failed && RegNo >= 0 && RegNo <= 31) {
6369         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6370         // By default we'll emit v0-v31 for this unless there's a modifier where
6371         // we'll emit the correct register as well.
6372         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6373           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6374           Res.second = &AArch64::FPR64RegClass;
6375         } else {
6376           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6377           Res.second = &AArch64::FPR128RegClass;
6378         }
6379       }
6380     }
6381   }
6382 
6383   if (Res.second && !Subtarget->hasFPARMv8() &&
6384       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6385       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6386     return std::make_pair(0U, nullptr);
6387 
6388   return Res;
6389 }
6390 
6391 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6392 /// vector.  If it is invalid, don't add anything to Ops.
6393 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6394     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6395     SelectionDAG &DAG) const {
6396   SDValue Result;
6397 
6398   // Currently only support length 1 constraints.
6399   if (Constraint.length() != 1)
6400     return;
6401 
6402   char ConstraintLetter = Constraint[0];
6403   switch (ConstraintLetter) {
6404   default:
6405     break;
6406 
6407   // This set of constraints deal with valid constants for various instructions.
6408   // Validate and return a target constant for them if we can.
6409   case 'z': {
6410     // 'z' maps to xzr or wzr so it needs an input of 0.
6411     if (!isNullConstant(Op))
6412       return;
6413 
6414     if (Op.getValueType() == MVT::i64)
6415       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6416     else
6417       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6418     break;
6419   }
6420   case 'S': {
6421     // An absolute symbolic address or label reference.
6422     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6423       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6424                                           GA->getValueType(0));
6425     } else if (const BlockAddressSDNode *BA =
6426                    dyn_cast<BlockAddressSDNode>(Op)) {
6427       Result =
6428           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6429     } else if (const ExternalSymbolSDNode *ES =
6430                    dyn_cast<ExternalSymbolSDNode>(Op)) {
6431       Result =
6432           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6433     } else
6434       return;
6435     break;
6436   }
6437 
6438   case 'I':
6439   case 'J':
6440   case 'K':
6441   case 'L':
6442   case 'M':
6443   case 'N':
6444     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6445     if (!C)
6446       return;
6447 
6448     // Grab the value and do some validation.
6449     uint64_t CVal = C->getZExtValue();
6450     switch (ConstraintLetter) {
6451     // The I constraint applies only to simple ADD or SUB immediate operands:
6452     // i.e. 0 to 4095 with optional shift by 12
6453     // The J constraint applies only to ADD or SUB immediates that would be
6454     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6455     // instruction [or vice versa], in other words -1 to -4095 with optional
6456     // left shift by 12.
6457     case 'I':
6458       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6459         break;
6460       return;
6461     case 'J': {
6462       uint64_t NVal = -C->getSExtValue();
6463       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6464         CVal = C->getSExtValue();
6465         break;
6466       }
6467       return;
6468     }
6469     // The K and L constraints apply *only* to logical immediates, including
6470     // what used to be the MOVI alias for ORR (though the MOVI alias has now
6471     // been removed and MOV should be used). So these constraints have to
6472     // distinguish between bit patterns that are valid 32-bit or 64-bit
6473     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6474     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6475     // versa.
6476     case 'K':
6477       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6478         break;
6479       return;
6480     case 'L':
6481       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6482         break;
6483       return;
6484     // The M and N constraints are a superset of K and L respectively, for use
6485     // with the MOV (immediate) alias. As well as the logical immediates they
6486     // also match 32 or 64-bit immediates that can be loaded either using a
6487     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6488     // (M) or 64-bit 0x1234000000000000 (N) etc.
6489     // As a note some of this code is liberally stolen from the asm parser.
6490     case 'M': {
6491       if (!isUInt<32>(CVal))
6492         return;
6493       if (AArch64_AM::isLogicalImmediate(CVal, 32))
6494         break;
6495       if ((CVal & 0xFFFF) == CVal)
6496         break;
6497       if ((CVal & 0xFFFF0000ULL) == CVal)
6498         break;
6499       uint64_t NCVal = ~(uint32_t)CVal;
6500       if ((NCVal & 0xFFFFULL) == NCVal)
6501         break;
6502       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6503         break;
6504       return;
6505     }
6506     case 'N': {
6507       if (AArch64_AM::isLogicalImmediate(CVal, 64))
6508         break;
6509       if ((CVal & 0xFFFFULL) == CVal)
6510         break;
6511       if ((CVal & 0xFFFF0000ULL) == CVal)
6512         break;
6513       if ((CVal & 0xFFFF00000000ULL) == CVal)
6514         break;
6515       if ((CVal & 0xFFFF000000000000ULL) == CVal)
6516         break;
6517       uint64_t NCVal = ~CVal;
6518       if ((NCVal & 0xFFFFULL) == NCVal)
6519         break;
6520       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6521         break;
6522       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6523         break;
6524       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6525         break;
6526       return;
6527     }
6528     default:
6529       return;
6530     }
6531 
6532     // All assembler immediates are 64-bit integers.
6533     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6534     break;
6535   }
6536 
6537   if (Result.getNode()) {
6538     Ops.push_back(Result);
6539     return;
6540   }
6541 
6542   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6543 }
6544 
6545 //===----------------------------------------------------------------------===//
6546 //                     AArch64 Advanced SIMD Support
6547 //===----------------------------------------------------------------------===//
6548 
6549 /// WidenVector - Given a value in the V64 register class, produce the
6550 /// equivalent value in the V128 register class.
6551 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6552   EVT VT = V64Reg.getValueType();
6553   unsigned NarrowSize = VT.getVectorNumElements();
6554   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6555   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6556   SDLoc DL(V64Reg);
6557 
6558   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6559                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6560 }
6561 
6562 /// getExtFactor - Determine the adjustment factor for the position when
6563 /// generating an "extract from vector registers" instruction.
6564 static unsigned getExtFactor(SDValue &V) {
6565   EVT EltType = V.getValueType().getVectorElementType();
6566   return EltType.getSizeInBits() / 8;
6567 }
6568 
6569 /// NarrowVector - Given a value in the V128 register class, produce the
6570 /// equivalent value in the V64 register class.
6571 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6572   EVT VT = V128Reg.getValueType();
6573   unsigned WideSize = VT.getVectorNumElements();
6574   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6575   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6576   SDLoc DL(V128Reg);
6577 
6578   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6579 }
6580 
6581 // Gather data to see if the operation can be modelled as a
6582 // shuffle in combination with VEXTs.
6583 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6584                                                   SelectionDAG &DAG) const {
6585   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6586   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6587   SDLoc dl(Op);
6588   EVT VT = Op.getValueType();
6589   unsigned NumElts = VT.getVectorNumElements();
6590 
6591   struct ShuffleSourceInfo {
6592     SDValue Vec;
6593     unsigned MinElt;
6594     unsigned MaxElt;
6595 
6596     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6597     // be compatible with the shuffle we intend to construct. As a result
6598     // ShuffleVec will be some sliding window into the original Vec.
6599     SDValue ShuffleVec;
6600 
6601     // Code should guarantee that element i in Vec starts at element "WindowBase
6602     // + i * WindowScale in ShuffleVec".
6603     int WindowBase;
6604     int WindowScale;
6605 
6606     ShuffleSourceInfo(SDValue Vec)
6607       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6608           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6609 
6610     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6611   };
6612 
6613   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6614   // node.
6615   SmallVector<ShuffleSourceInfo, 2> Sources;
6616   for (unsigned i = 0; i < NumElts; ++i) {
6617     SDValue V = Op.getOperand(i);
6618     if (V.isUndef())
6619       continue;
6620     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6621              !isa<ConstantSDNode>(V.getOperand(1))) {
6622       LLVM_DEBUG(
6623           dbgs() << "Reshuffle failed: "
6624                     "a shuffle can only come from building a vector from "
6625                     "various elements of other vectors, provided their "
6626                     "indices are constant\n");
6627       return SDValue();
6628     }
6629 
6630     // Add this element source to the list if it's not already there.
6631     SDValue SourceVec = V.getOperand(0);
6632     auto Source = find(Sources, SourceVec);
6633     if (Source == Sources.end())
6634       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6635 
6636     // Update the minimum and maximum lane number seen.
6637     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6638     Source->MinElt = std::min(Source->MinElt, EltNo);
6639     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6640   }
6641 
6642   if (Sources.size() > 2) {
6643     LLVM_DEBUG(
6644         dbgs() << "Reshuffle failed: currently only do something sane when at "
6645                   "most two source vectors are involved\n");
6646     return SDValue();
6647   }
6648 
6649   // Find out the smallest element size among result and two sources, and use
6650   // it as element size to build the shuffle_vector.
6651   EVT SmallestEltTy = VT.getVectorElementType();
6652   for (auto &Source : Sources) {
6653     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6654     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6655       SmallestEltTy = SrcEltTy;
6656     }
6657   }
6658   unsigned ResMultiplier =
6659       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6660   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6661   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6662 
6663   // If the source vector is too wide or too narrow, we may nevertheless be able
6664   // to construct a compatible shuffle either by concatenating it with UNDEF or
6665   // extracting a suitable range of elements.
6666   for (auto &Src : Sources) {
6667     EVT SrcVT = Src.ShuffleVec.getValueType();
6668 
6669     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6670       continue;
6671 
6672     // This stage of the search produces a source with the same element type as
6673     // the original, but with a total width matching the BUILD_VECTOR output.
6674     EVT EltVT = SrcVT.getVectorElementType();
6675     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6676     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6677 
6678     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6679       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6680       // We can pad out the smaller vector for free, so if it's part of a
6681       // shuffle...
6682       Src.ShuffleVec =
6683           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6684                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6685       continue;
6686     }
6687 
6688     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6689 
6690     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6691       LLVM_DEBUG(
6692           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6693       return SDValue();
6694     }
6695 
6696     if (Src.MinElt >= NumSrcElts) {
6697       // The extraction can just take the second half
6698       Src.ShuffleVec =
6699           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6700                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6701       Src.WindowBase = -NumSrcElts;
6702     } else if (Src.MaxElt < NumSrcElts) {
6703       // The extraction can just take the first half
6704       Src.ShuffleVec =
6705           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6706                       DAG.getConstant(0, dl, MVT::i64));
6707     } else {
6708       // An actual VEXT is needed
6709       SDValue VEXTSrc1 =
6710           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6711                       DAG.getConstant(0, dl, MVT::i64));
6712       SDValue VEXTSrc2 =
6713           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6714                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6715       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6716 
6717       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6718                                    VEXTSrc2,
6719                                    DAG.getConstant(Imm, dl, MVT::i32));
6720       Src.WindowBase = -Src.MinElt;
6721     }
6722   }
6723 
6724   // Another possible incompatibility occurs from the vector element types. We
6725   // can fix this by bitcasting the source vectors to the same type we intend
6726   // for the shuffle.
6727   for (auto &Src : Sources) {
6728     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6729     if (SrcEltTy == SmallestEltTy)
6730       continue;
6731     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6732     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6733     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6734     Src.WindowBase *= Src.WindowScale;
6735   }
6736 
6737   // Final sanity check before we try to actually produce a shuffle.
6738   LLVM_DEBUG(for (auto Src
6739                   : Sources)
6740                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6741 
6742   // The stars all align, our next step is to produce the mask for the shuffle.
6743   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6744   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6745   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6746     SDValue Entry = Op.getOperand(i);
6747     if (Entry.isUndef())
6748       continue;
6749 
6750     auto Src = find(Sources, Entry.getOperand(0));
6751     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6752 
6753     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6754     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6755     // segment.
6756     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6757     int BitsDefined =
6758         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6759     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6760 
6761     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6762     // starting at the appropriate offset.
6763     int *LaneMask = &Mask[i * ResMultiplier];
6764 
6765     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6766     ExtractBase += NumElts * (Src - Sources.begin());
6767     for (int j = 0; j < LanesDefined; ++j)
6768       LaneMask[j] = ExtractBase + j;
6769   }
6770 
6771   // Final check before we try to produce nonsense...
6772   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6773     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6774     return SDValue();
6775   }
6776 
6777   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6778   for (unsigned i = 0; i < Sources.size(); ++i)
6779     ShuffleOps[i] = Sources[i].ShuffleVec;
6780 
6781   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6782                                          ShuffleOps[1], Mask);
6783   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6784 
6785   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6786              dbgs() << "Reshuffle, creating node: "; V.dump(););
6787 
6788   return V;
6789 }
6790 
6791 // check if an EXT instruction can handle the shuffle mask when the
6792 // vector sources of the shuffle are the same.
6793 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6794   unsigned NumElts = VT.getVectorNumElements();
6795 
6796   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6797   if (M[0] < 0)
6798     return false;
6799 
6800   Imm = M[0];
6801 
6802   // If this is a VEXT shuffle, the immediate value is the index of the first
6803   // element.  The other shuffle indices must be the successive elements after
6804   // the first one.
6805   unsigned ExpectedElt = Imm;
6806   for (unsigned i = 1; i < NumElts; ++i) {
6807     // Increment the expected index.  If it wraps around, just follow it
6808     // back to index zero and keep going.
6809     ++ExpectedElt;
6810     if (ExpectedElt == NumElts)
6811       ExpectedElt = 0;
6812 
6813     if (M[i] < 0)
6814       continue; // ignore UNDEF indices
6815     if (ExpectedElt != static_cast<unsigned>(M[i]))
6816       return false;
6817   }
6818 
6819   return true;
6820 }
6821 
6822 // check if an EXT instruction can handle the shuffle mask when the
6823 // vector sources of the shuffle are different.
6824 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6825                       unsigned &Imm) {
6826   // Look for the first non-undef element.
6827   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6828 
6829   // Benefit form APInt to handle overflow when calculating expected element.
6830   unsigned NumElts = VT.getVectorNumElements();
6831   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6832   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6833   // The following shuffle indices must be the successive elements after the
6834   // first real element.
6835   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6836       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6837   if (FirstWrongElt != M.end())
6838     return false;
6839 
6840   // The index of an EXT is the first element if it is not UNDEF.
6841   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6842   // value of the first element.  E.g.
6843   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6844   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6845   // ExpectedElt is the last mask index plus 1.
6846   Imm = ExpectedElt.getZExtValue();
6847 
6848   // There are two difference cases requiring to reverse input vectors.
6849   // For example, for vector <4 x i32> we have the following cases,
6850   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6851   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6852   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6853   // to reverse two input vectors.
6854   if (Imm < NumElts)
6855     ReverseEXT = true;
6856   else
6857     Imm -= NumElts;
6858 
6859   return true;
6860 }
6861 
6862 /// isREVMask - Check if a vector shuffle corresponds to a REV
6863 /// instruction with the specified blocksize.  (The order of the elements
6864 /// within each block of the vector is reversed.)
6865 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6866   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6867          "Only possible block sizes for REV are: 16, 32, 64");
6868 
6869   unsigned EltSz = VT.getScalarSizeInBits();
6870   if (EltSz == 64)
6871     return false;
6872 
6873   unsigned NumElts = VT.getVectorNumElements();
6874   unsigned BlockElts = M[0] + 1;
6875   // If the first shuffle index is UNDEF, be optimistic.
6876   if (M[0] < 0)
6877     BlockElts = BlockSize / EltSz;
6878 
6879   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6880     return false;
6881 
6882   for (unsigned i = 0; i < NumElts; ++i) {
6883     if (M[i] < 0)
6884       continue; // ignore UNDEF indices
6885     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6886       return false;
6887   }
6888 
6889   return true;
6890 }
6891 
6892 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6893   unsigned NumElts = VT.getVectorNumElements();
6894   if (NumElts % 2 != 0)
6895     return false;
6896   WhichResult = (M[0] == 0 ? 0 : 1);
6897   unsigned Idx = WhichResult * NumElts / 2;
6898   for (unsigned i = 0; i != NumElts; i += 2) {
6899     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6900         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6901       return false;
6902     Idx += 1;
6903   }
6904 
6905   return true;
6906 }
6907 
6908 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6909   unsigned NumElts = VT.getVectorNumElements();
6910   WhichResult = (M[0] == 0 ? 0 : 1);
6911   for (unsigned i = 0; i != NumElts; ++i) {
6912     if (M[i] < 0)
6913       continue; // ignore UNDEF indices
6914     if ((unsigned)M[i] != 2 * i + WhichResult)
6915       return false;
6916   }
6917 
6918   return true;
6919 }
6920 
6921 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6922   unsigned NumElts = VT.getVectorNumElements();
6923   if (NumElts % 2 != 0)
6924     return false;
6925   WhichResult = (M[0] == 0 ? 0 : 1);
6926   for (unsigned i = 0; i < NumElts; i += 2) {
6927     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6928         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6929       return false;
6930   }
6931   return true;
6932 }
6933 
6934 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6935 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6936 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6937 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6938   unsigned NumElts = VT.getVectorNumElements();
6939   if (NumElts % 2 != 0)
6940     return false;
6941   WhichResult = (M[0] == 0 ? 0 : 1);
6942   unsigned Idx = WhichResult * NumElts / 2;
6943   for (unsigned i = 0; i != NumElts; i += 2) {
6944     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6945         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6946       return false;
6947     Idx += 1;
6948   }
6949 
6950   return true;
6951 }
6952 
6953 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6954 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6955 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6956 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6957   unsigned Half = VT.getVectorNumElements() / 2;
6958   WhichResult = (M[0] == 0 ? 0 : 1);
6959   for (unsigned j = 0; j != 2; ++j) {
6960     unsigned Idx = WhichResult;
6961     for (unsigned i = 0; i != Half; ++i) {
6962       int MIdx = M[i + j * Half];
6963       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6964         return false;
6965       Idx += 2;
6966     }
6967   }
6968 
6969   return true;
6970 }
6971 
6972 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6973 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6974 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6975 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6976   unsigned NumElts = VT.getVectorNumElements();
6977   if (NumElts % 2 != 0)
6978     return false;
6979   WhichResult = (M[0] == 0 ? 0 : 1);
6980   for (unsigned i = 0; i < NumElts; i += 2) {
6981     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6982         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6983       return false;
6984   }
6985   return true;
6986 }
6987 
6988 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6989                       bool &DstIsLeft, int &Anomaly) {
6990   if (M.size() != static_cast<size_t>(NumInputElements))
6991     return false;
6992 
6993   int NumLHSMatch = 0, NumRHSMatch = 0;
6994   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6995 
6996   for (int i = 0; i < NumInputElements; ++i) {
6997     if (M[i] == -1) {
6998       ++NumLHSMatch;
6999       ++NumRHSMatch;
7000       continue;
7001     }
7002 
7003     if (M[i] == i)
7004       ++NumLHSMatch;
7005     else
7006       LastLHSMismatch = i;
7007 
7008     if (M[i] == i + NumInputElements)
7009       ++NumRHSMatch;
7010     else
7011       LastRHSMismatch = i;
7012   }
7013 
7014   if (NumLHSMatch == NumInputElements - 1) {
7015     DstIsLeft = true;
7016     Anomaly = LastLHSMismatch;
7017     return true;
7018   } else if (NumRHSMatch == NumInputElements - 1) {
7019     DstIsLeft = false;
7020     Anomaly = LastRHSMismatch;
7021     return true;
7022   }
7023 
7024   return false;
7025 }
7026 
7027 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7028   if (VT.getSizeInBits() != 128)
7029     return false;
7030 
7031   unsigned NumElts = VT.getVectorNumElements();
7032 
7033   for (int I = 0, E = NumElts / 2; I != E; I++) {
7034     if (Mask[I] != I)
7035       return false;
7036   }
7037 
7038   int Offset = NumElts / 2;
7039   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7040     if (Mask[I] != I + SplitLHS * Offset)
7041       return false;
7042   }
7043 
7044   return true;
7045 }
7046 
7047 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7048   SDLoc DL(Op);
7049   EVT VT = Op.getValueType();
7050   SDValue V0 = Op.getOperand(0);
7051   SDValue V1 = Op.getOperand(1);
7052   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7053 
7054   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7055       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7056     return SDValue();
7057 
7058   bool SplitV0 = V0.getValueSizeInBits() == 128;
7059 
7060   if (!isConcatMask(Mask, VT, SplitV0))
7061     return SDValue();
7062 
7063   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7064   if (SplitV0) {
7065     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7066                      DAG.getConstant(0, DL, MVT::i64));
7067   }
7068   if (V1.getValueSizeInBits() == 128) {
7069     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7070                      DAG.getConstant(0, DL, MVT::i64));
7071   }
7072   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7073 }
7074 
7075 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7076 /// the specified operations to build the shuffle.
7077 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7078                                       SDValue RHS, SelectionDAG &DAG,
7079                                       const SDLoc &dl) {
7080   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7081   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7082   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7083 
7084   enum {
7085     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7086     OP_VREV,
7087     OP_VDUP0,
7088     OP_VDUP1,
7089     OP_VDUP2,
7090     OP_VDUP3,
7091     OP_VEXT1,
7092     OP_VEXT2,
7093     OP_VEXT3,
7094     OP_VUZPL, // VUZP, left result
7095     OP_VUZPR, // VUZP, right result
7096     OP_VZIPL, // VZIP, left result
7097     OP_VZIPR, // VZIP, right result
7098     OP_VTRNL, // VTRN, left result
7099     OP_VTRNR  // VTRN, right result
7100   };
7101 
7102   if (OpNum == OP_COPY) {
7103     if (LHSID == (1 * 9 + 2) * 9 + 3)
7104       return LHS;
7105     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7106     return RHS;
7107   }
7108 
7109   SDValue OpLHS, OpRHS;
7110   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7111   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7112   EVT VT = OpLHS.getValueType();
7113 
7114   switch (OpNum) {
7115   default:
7116     llvm_unreachable("Unknown shuffle opcode!");
7117   case OP_VREV:
7118     // VREV divides the vector in half and swaps within the half.
7119     if (VT.getVectorElementType() == MVT::i32 ||
7120         VT.getVectorElementType() == MVT::f32)
7121       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7122     // vrev <4 x i16> -> REV32
7123     if (VT.getVectorElementType() == MVT::i16 ||
7124         VT.getVectorElementType() == MVT::f16)
7125       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7126     // vrev <4 x i8> -> REV16
7127     assert(VT.getVectorElementType() == MVT::i8);
7128     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7129   case OP_VDUP0:
7130   case OP_VDUP1:
7131   case OP_VDUP2:
7132   case OP_VDUP3: {
7133     EVT EltTy = VT.getVectorElementType();
7134     unsigned Opcode;
7135     if (EltTy == MVT::i8)
7136       Opcode = AArch64ISD::DUPLANE8;
7137     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7138       Opcode = AArch64ISD::DUPLANE16;
7139     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7140       Opcode = AArch64ISD::DUPLANE32;
7141     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7142       Opcode = AArch64ISD::DUPLANE64;
7143     else
7144       llvm_unreachable("Invalid vector element type?");
7145 
7146     if (VT.getSizeInBits() == 64)
7147       OpLHS = WidenVector(OpLHS, DAG);
7148     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7149     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7150   }
7151   case OP_VEXT1:
7152   case OP_VEXT2:
7153   case OP_VEXT3: {
7154     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7155     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7156                        DAG.getConstant(Imm, dl, MVT::i32));
7157   }
7158   case OP_VUZPL:
7159     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7160                        OpRHS);
7161   case OP_VUZPR:
7162     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7163                        OpRHS);
7164   case OP_VZIPL:
7165     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7166                        OpRHS);
7167   case OP_VZIPR:
7168     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7169                        OpRHS);
7170   case OP_VTRNL:
7171     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7172                        OpRHS);
7173   case OP_VTRNR:
7174     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7175                        OpRHS);
7176   }
7177 }
7178 
7179 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7180                            SelectionDAG &DAG) {
7181   // Check to see if we can use the TBL instruction.
7182   SDValue V1 = Op.getOperand(0);
7183   SDValue V2 = Op.getOperand(1);
7184   SDLoc DL(Op);
7185 
7186   EVT EltVT = Op.getValueType().getVectorElementType();
7187   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7188 
7189   SmallVector<SDValue, 8> TBLMask;
7190   for (int Val : ShuffleMask) {
7191     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7192       unsigned Offset = Byte + Val * BytesPerElt;
7193       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7194     }
7195   }
7196 
7197   MVT IndexVT = MVT::v8i8;
7198   unsigned IndexLen = 8;
7199   if (Op.getValueSizeInBits() == 128) {
7200     IndexVT = MVT::v16i8;
7201     IndexLen = 16;
7202   }
7203 
7204   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7205   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7206 
7207   SDValue Shuffle;
7208   if (V2.getNode()->isUndef()) {
7209     if (IndexLen == 8)
7210       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7211     Shuffle = DAG.getNode(
7212         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7213         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7214         DAG.getBuildVector(IndexVT, DL,
7215                            makeArrayRef(TBLMask.data(), IndexLen)));
7216   } else {
7217     if (IndexLen == 8) {
7218       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7219       Shuffle = DAG.getNode(
7220           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7221           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7222           DAG.getBuildVector(IndexVT, DL,
7223                              makeArrayRef(TBLMask.data(), IndexLen)));
7224     } else {
7225       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7226       // cannot currently represent the register constraints on the input
7227       // table registers.
7228       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7229       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7230       //                   IndexLen));
7231       Shuffle = DAG.getNode(
7232           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7233           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7234           V2Cst, DAG.getBuildVector(IndexVT, DL,
7235                                     makeArrayRef(TBLMask.data(), IndexLen)));
7236     }
7237   }
7238   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7239 }
7240 
7241 static unsigned getDUPLANEOp(EVT EltType) {
7242   if (EltType == MVT::i8)
7243     return AArch64ISD::DUPLANE8;
7244   if (EltType == MVT::i16 || EltType == MVT::f16)
7245     return AArch64ISD::DUPLANE16;
7246   if (EltType == MVT::i32 || EltType == MVT::f32)
7247     return AArch64ISD::DUPLANE32;
7248   if (EltType == MVT::i64 || EltType == MVT::f64)
7249     return AArch64ISD::DUPLANE64;
7250 
7251   llvm_unreachable("Invalid vector element type?");
7252 }
7253 
7254 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7255                                                    SelectionDAG &DAG) const {
7256   SDLoc dl(Op);
7257   EVT VT = Op.getValueType();
7258 
7259   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7260 
7261   // Convert shuffles that are directly supported on NEON to target-specific
7262   // DAG nodes, instead of keeping them as shuffles and matching them again
7263   // during code selection.  This is more efficient and avoids the possibility
7264   // of inconsistencies between legalization and selection.
7265   ArrayRef<int> ShuffleMask = SVN->getMask();
7266 
7267   SDValue V1 = Op.getOperand(0);
7268   SDValue V2 = Op.getOperand(1);
7269 
7270   if (SVN->isSplat()) {
7271     int Lane = SVN->getSplatIndex();
7272     // If this is undef splat, generate it via "just" vdup, if possible.
7273     if (Lane == -1)
7274       Lane = 0;
7275 
7276     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7277       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7278                          V1.getOperand(0));
7279     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7280     // constant. If so, we can just reference the lane's definition directly.
7281     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7282         !isa<ConstantSDNode>(V1.getOperand(Lane)))
7283       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7284 
7285     // Otherwise, duplicate from the lane of the input vector.
7286     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7287 
7288     // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7289     auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7290       // Match: dup (bitcast (extract_subv X, C)), LaneC
7291       if (BitCast.getOpcode() != ISD::BITCAST ||
7292           BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7293         return false;
7294 
7295       // The extract index must align in the destination type. That may not
7296       // happen if the bitcast is from narrow to wide type.
7297       SDValue Extract = BitCast.getOperand(0);
7298       unsigned ExtIdx = Extract.getConstantOperandVal(1);
7299       unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7300       unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7301       unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7302       if (ExtIdxInBits % CastedEltBitWidth != 0)
7303         return false;
7304 
7305       // Update the lane value by offsetting with the scaled extract index.
7306       LaneC += ExtIdxInBits / CastedEltBitWidth;
7307 
7308       // Determine the casted vector type of the wide vector input.
7309       // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7310       // Examples:
7311       // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7312       // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7313       unsigned SrcVecNumElts =
7314           Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7315       CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7316                                 SrcVecNumElts);
7317       return true;
7318     };
7319     MVT CastVT;
7320     if (getScaledOffsetDup(V1, Lane, CastVT)) {
7321       V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7322     } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7323       // The lane is incremented by the index of the extract.
7324       // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7325       Lane += V1.getConstantOperandVal(1);
7326       V1 = V1.getOperand(0);
7327     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7328       // The lane is decremented if we are splatting from the 2nd operand.
7329       // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7330       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7331       Lane -= Idx * VT.getVectorNumElements() / 2;
7332       V1 = WidenVector(V1.getOperand(Idx), DAG);
7333     } else if (VT.getSizeInBits() == 64) {
7334       // Widen the operand to 128-bit register with undef.
7335       V1 = WidenVector(V1, DAG);
7336     }
7337     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7338   }
7339 
7340   if (isREVMask(ShuffleMask, VT, 64))
7341     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7342   if (isREVMask(ShuffleMask, VT, 32))
7343     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7344   if (isREVMask(ShuffleMask, VT, 16))
7345     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7346 
7347   bool ReverseEXT = false;
7348   unsigned Imm;
7349   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7350     if (ReverseEXT)
7351       std::swap(V1, V2);
7352     Imm *= getExtFactor(V1);
7353     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7354                        DAG.getConstant(Imm, dl, MVT::i32));
7355   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7356     Imm *= getExtFactor(V1);
7357     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7358                        DAG.getConstant(Imm, dl, MVT::i32));
7359   }
7360 
7361   unsigned WhichResult;
7362   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7363     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7364     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7365   }
7366   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7367     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7368     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7369   }
7370   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7371     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7372     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7373   }
7374 
7375   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7376     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7377     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7378   }
7379   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7380     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7381     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7382   }
7383   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7384     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7385     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7386   }
7387 
7388   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7389     return Concat;
7390 
7391   bool DstIsLeft;
7392   int Anomaly;
7393   int NumInputElements = V1.getValueType().getVectorNumElements();
7394   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7395     SDValue DstVec = DstIsLeft ? V1 : V2;
7396     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7397 
7398     SDValue SrcVec = V1;
7399     int SrcLane = ShuffleMask[Anomaly];
7400     if (SrcLane >= NumInputElements) {
7401       SrcVec = V2;
7402       SrcLane -= VT.getVectorNumElements();
7403     }
7404     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7405 
7406     EVT ScalarVT = VT.getVectorElementType();
7407 
7408     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7409       ScalarVT = MVT::i32;
7410 
7411     return DAG.getNode(
7412         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7413         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7414         DstLaneV);
7415   }
7416 
7417   // If the shuffle is not directly supported and it has 4 elements, use
7418   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7419   unsigned NumElts = VT.getVectorNumElements();
7420   if (NumElts == 4) {
7421     unsigned PFIndexes[4];
7422     for (unsigned i = 0; i != 4; ++i) {
7423       if (ShuffleMask[i] < 0)
7424         PFIndexes[i] = 8;
7425       else
7426         PFIndexes[i] = ShuffleMask[i];
7427     }
7428 
7429     // Compute the index in the perfect shuffle table.
7430     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7431                             PFIndexes[2] * 9 + PFIndexes[3];
7432     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7433     unsigned Cost = (PFEntry >> 30);
7434 
7435     if (Cost <= 4)
7436       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7437   }
7438 
7439   return GenerateTBL(Op, ShuffleMask, DAG);
7440 }
7441 
7442 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7443                                                  SelectionDAG &DAG) const {
7444   SDLoc dl(Op);
7445   EVT VT = Op.getValueType();
7446   EVT ElemVT = VT.getScalarType();
7447 
7448   SDValue SplatVal = Op.getOperand(0);
7449 
7450   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7451   // FPRs don't have this restriction.
7452   switch (ElemVT.getSimpleVT().SimpleTy) {
7453   case MVT::i8:
7454   case MVT::i16:
7455   case MVT::i32:
7456     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7457     return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7458   case MVT::i64:
7459     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7460     return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7461   case MVT::i1: {
7462     // The general case of i1.  There isn't any natural way to do this,
7463     // so we use some trickery with whilelo.
7464     // TODO: Add special cases for splat of constant true/false.
7465     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7466     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7467                            DAG.getValueType(MVT::i1));
7468     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7469                                        MVT::i64);
7470     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7471                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
7472   }
7473   // TODO: we can support float types, but haven't added patterns yet.
7474   case MVT::f16:
7475   case MVT::f32:
7476   case MVT::f64:
7477   default:
7478     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7479   }
7480 }
7481 
7482 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7483                                APInt &UndefBits) {
7484   EVT VT = BVN->getValueType(0);
7485   APInt SplatBits, SplatUndef;
7486   unsigned SplatBitSize;
7487   bool HasAnyUndefs;
7488   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7489     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7490 
7491     for (unsigned i = 0; i < NumSplats; ++i) {
7492       CnstBits <<= SplatBitSize;
7493       UndefBits <<= SplatBitSize;
7494       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7495       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7496     }
7497 
7498     return true;
7499   }
7500 
7501   return false;
7502 }
7503 
7504 // Try 64-bit splatted SIMD immediate.
7505 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7506                                  const APInt &Bits) {
7507   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7508     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7509     EVT VT = Op.getValueType();
7510     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7511 
7512     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7513       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7514 
7515       SDLoc dl(Op);
7516       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7517                                 DAG.getConstant(Value, dl, MVT::i32));
7518       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7519     }
7520   }
7521 
7522   return SDValue();
7523 }
7524 
7525 // Try 32-bit splatted SIMD immediate.
7526 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7527                                   const APInt &Bits,
7528                                   const SDValue *LHS = nullptr) {
7529   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7530     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7531     EVT VT = Op.getValueType();
7532     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7533     bool isAdvSIMDModImm = false;
7534     uint64_t Shift;
7535 
7536     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7537       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7538       Shift = 0;
7539     }
7540     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7541       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7542       Shift = 8;
7543     }
7544     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7545       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7546       Shift = 16;
7547     }
7548     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7549       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7550       Shift = 24;
7551     }
7552 
7553     if (isAdvSIMDModImm) {
7554       SDLoc dl(Op);
7555       SDValue Mov;
7556 
7557       if (LHS)
7558         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7559                           DAG.getConstant(Value, dl, MVT::i32),
7560                           DAG.getConstant(Shift, dl, MVT::i32));
7561       else
7562         Mov = DAG.getNode(NewOp, dl, MovTy,
7563                           DAG.getConstant(Value, dl, MVT::i32),
7564                           DAG.getConstant(Shift, dl, MVT::i32));
7565 
7566       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7567     }
7568   }
7569 
7570   return SDValue();
7571 }
7572 
7573 // Try 16-bit splatted SIMD immediate.
7574 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7575                                   const APInt &Bits,
7576                                   const SDValue *LHS = nullptr) {
7577   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7578     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7579     EVT VT = Op.getValueType();
7580     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7581     bool isAdvSIMDModImm = false;
7582     uint64_t Shift;
7583 
7584     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7585       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7586       Shift = 0;
7587     }
7588     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7589       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7590       Shift = 8;
7591     }
7592 
7593     if (isAdvSIMDModImm) {
7594       SDLoc dl(Op);
7595       SDValue Mov;
7596 
7597       if (LHS)
7598         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7599                           DAG.getConstant(Value, dl, MVT::i32),
7600                           DAG.getConstant(Shift, dl, MVT::i32));
7601       else
7602         Mov = DAG.getNode(NewOp, dl, MovTy,
7603                           DAG.getConstant(Value, dl, MVT::i32),
7604                           DAG.getConstant(Shift, dl, MVT::i32));
7605 
7606       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7607     }
7608   }
7609 
7610   return SDValue();
7611 }
7612 
7613 // Try 32-bit splatted SIMD immediate with shifted ones.
7614 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7615                                     SelectionDAG &DAG, const APInt &Bits) {
7616   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7617     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7618     EVT VT = Op.getValueType();
7619     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7620     bool isAdvSIMDModImm = false;
7621     uint64_t Shift;
7622 
7623     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7624       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7625       Shift = 264;
7626     }
7627     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7628       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7629       Shift = 272;
7630     }
7631 
7632     if (isAdvSIMDModImm) {
7633       SDLoc dl(Op);
7634       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7635                                 DAG.getConstant(Value, dl, MVT::i32),
7636                                 DAG.getConstant(Shift, dl, MVT::i32));
7637       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7638     }
7639   }
7640 
7641   return SDValue();
7642 }
7643 
7644 // Try 8-bit splatted SIMD immediate.
7645 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7646                                  const APInt &Bits) {
7647   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7648     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7649     EVT VT = Op.getValueType();
7650     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7651 
7652     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7653       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7654 
7655       SDLoc dl(Op);
7656       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7657                                 DAG.getConstant(Value, dl, MVT::i32));
7658       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7659     }
7660   }
7661 
7662   return SDValue();
7663 }
7664 
7665 // Try FP splatted SIMD immediate.
7666 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7667                                   const APInt &Bits) {
7668   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7669     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7670     EVT VT = Op.getValueType();
7671     bool isWide = (VT.getSizeInBits() == 128);
7672     MVT MovTy;
7673     bool isAdvSIMDModImm = false;
7674 
7675     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7676       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7677       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7678     }
7679     else if (isWide &&
7680              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7681       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7682       MovTy = MVT::v2f64;
7683     }
7684 
7685     if (isAdvSIMDModImm) {
7686       SDLoc dl(Op);
7687       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7688                                 DAG.getConstant(Value, dl, MVT::i32));
7689       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7690     }
7691   }
7692 
7693   return SDValue();
7694 }
7695 
7696 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7697 // consists of only the same constant int value, returned in reference arg
7698 // ConstVal
7699 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7700                                      uint64_t &ConstVal) {
7701   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7702   if (!Bvec)
7703     return false;
7704   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7705   if (!FirstElt)
7706     return false;
7707   EVT VT = Bvec->getValueType(0);
7708   unsigned NumElts = VT.getVectorNumElements();
7709   for (unsigned i = 1; i < NumElts; ++i)
7710     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7711       return false;
7712   ConstVal = FirstElt->getZExtValue();
7713   return true;
7714 }
7715 
7716 static unsigned getIntrinsicID(const SDNode *N) {
7717   unsigned Opcode = N->getOpcode();
7718   switch (Opcode) {
7719   default:
7720     return Intrinsic::not_intrinsic;
7721   case ISD::INTRINSIC_WO_CHAIN: {
7722     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7723     if (IID < Intrinsic::num_intrinsics)
7724       return IID;
7725     return Intrinsic::not_intrinsic;
7726   }
7727   }
7728 }
7729 
7730 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7731 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7732 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7733 // Also, logical shift right -> sri, with the same structure.
7734 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7735   EVT VT = N->getValueType(0);
7736 
7737   if (!VT.isVector())
7738     return SDValue();
7739 
7740   SDLoc DL(N);
7741 
7742   // Is the first op an AND?
7743   const SDValue And = N->getOperand(0);
7744   if (And.getOpcode() != ISD::AND)
7745     return SDValue();
7746 
7747   // Is the second op an shl or lshr?
7748   SDValue Shift = N->getOperand(1);
7749   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7750   // or AArch64ISD::VLSHR vector, #shift
7751   unsigned ShiftOpc = Shift.getOpcode();
7752   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7753     return SDValue();
7754   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7755 
7756   // Is the shift amount constant?
7757   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7758   if (!C2node)
7759     return SDValue();
7760 
7761   // Is the and mask vector all constant?
7762   uint64_t C1;
7763   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7764     return SDValue();
7765 
7766   // Is C1 == ~C2, taking into account how much one can shift elements of a
7767   // particular size?
7768   uint64_t C2 = C2node->getZExtValue();
7769   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7770   if (C2 > ElemSizeInBits)
7771     return SDValue();
7772   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7773   if ((C1 & ElemMask) != (~C2 & ElemMask))
7774     return SDValue();
7775 
7776   SDValue X = And.getOperand(0);
7777   SDValue Y = Shift.getOperand(0);
7778 
7779   unsigned Intrin =
7780       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7781   SDValue ResultSLI =
7782       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7783                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7784                   Shift.getOperand(1));
7785 
7786   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7787   LLVM_DEBUG(N->dump(&DAG));
7788   LLVM_DEBUG(dbgs() << "into: \n");
7789   LLVM_DEBUG(ResultSLI->dump(&DAG));
7790 
7791   ++NumShiftInserts;
7792   return ResultSLI;
7793 }
7794 
7795 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7796                                              SelectionDAG &DAG) const {
7797   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7798   if (EnableAArch64SlrGeneration) {
7799     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7800       return Res;
7801   }
7802 
7803   EVT VT = Op.getValueType();
7804 
7805   SDValue LHS = Op.getOperand(0);
7806   BuildVectorSDNode *BVN =
7807       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7808   if (!BVN) {
7809     // OR commutes, so try swapping the operands.
7810     LHS = Op.getOperand(1);
7811     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7812   }
7813   if (!BVN)
7814     return Op;
7815 
7816   APInt DefBits(VT.getSizeInBits(), 0);
7817   APInt UndefBits(VT.getSizeInBits(), 0);
7818   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7819     SDValue NewOp;
7820 
7821     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7822                                     DefBits, &LHS)) ||
7823         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7824                                     DefBits, &LHS)))
7825       return NewOp;
7826 
7827     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7828                                     UndefBits, &LHS)) ||
7829         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7830                                     UndefBits, &LHS)))
7831       return NewOp;
7832   }
7833 
7834   // We can always fall back to a non-immediate OR.
7835   return Op;
7836 }
7837 
7838 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7839 // be truncated to fit element width.
7840 static SDValue NormalizeBuildVector(SDValue Op,
7841                                     SelectionDAG &DAG) {
7842   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7843   SDLoc dl(Op);
7844   EVT VT = Op.getValueType();
7845   EVT EltTy= VT.getVectorElementType();
7846 
7847   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7848     return Op;
7849 
7850   SmallVector<SDValue, 16> Ops;
7851   for (SDValue Lane : Op->ops()) {
7852     // For integer vectors, type legalization would have promoted the
7853     // operands already. Otherwise, if Op is a floating-point splat
7854     // (with operands cast to integers), then the only possibilities
7855     // are constants and UNDEFs.
7856     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7857       APInt LowBits(EltTy.getSizeInBits(),
7858                     CstLane->getZExtValue());
7859       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7860     } else if (Lane.getNode()->isUndef()) {
7861       Lane = DAG.getUNDEF(MVT::i32);
7862     } else {
7863       assert(Lane.getValueType() == MVT::i32 &&
7864              "Unexpected BUILD_VECTOR operand type");
7865     }
7866     Ops.push_back(Lane);
7867   }
7868   return DAG.getBuildVector(VT, dl, Ops);
7869 }
7870 
7871 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7872   EVT VT = Op.getValueType();
7873 
7874   APInt DefBits(VT.getSizeInBits(), 0);
7875   APInt UndefBits(VT.getSizeInBits(), 0);
7876   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7877   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7878     SDValue NewOp;
7879     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7880         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7881         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7882         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7883         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7884         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7885       return NewOp;
7886 
7887     DefBits = ~DefBits;
7888     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7889         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7890         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7891       return NewOp;
7892 
7893     DefBits = UndefBits;
7894     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7895         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7896         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7897         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7898         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7899         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7900       return NewOp;
7901 
7902     DefBits = ~UndefBits;
7903     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7904         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7905         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7906       return NewOp;
7907   }
7908 
7909   return SDValue();
7910 }
7911 
7912 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7913                                                  SelectionDAG &DAG) const {
7914   EVT VT = Op.getValueType();
7915 
7916   // Try to build a simple constant vector.
7917   Op = NormalizeBuildVector(Op, DAG);
7918   if (VT.isInteger()) {
7919     // Certain vector constants, used to express things like logical NOT and
7920     // arithmetic NEG, are passed through unmodified.  This allows special
7921     // patterns for these operations to match, which will lower these constants
7922     // to whatever is proven necessary.
7923     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7924     if (BVN->isConstant())
7925       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7926         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7927         APInt Val(BitSize,
7928                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7929         if (Val.isNullValue() || Val.isAllOnesValue())
7930           return Op;
7931       }
7932   }
7933 
7934   if (SDValue V = ConstantBuildVector(Op, DAG))
7935     return V;
7936 
7937   // Scan through the operands to find some interesting properties we can
7938   // exploit:
7939   //   1) If only one value is used, we can use a DUP, or
7940   //   2) if only the low element is not undef, we can just insert that, or
7941   //   3) if only one constant value is used (w/ some non-constant lanes),
7942   //      we can splat the constant value into the whole vector then fill
7943   //      in the non-constant lanes.
7944   //   4) FIXME: If different constant values are used, but we can intelligently
7945   //             select the values we'll be overwriting for the non-constant
7946   //             lanes such that we can directly materialize the vector
7947   //             some other way (MOVI, e.g.), we can be sneaky.
7948   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7949   SDLoc dl(Op);
7950   unsigned NumElts = VT.getVectorNumElements();
7951   bool isOnlyLowElement = true;
7952   bool usesOnlyOneValue = true;
7953   bool usesOnlyOneConstantValue = true;
7954   bool isConstant = true;
7955   bool AllLanesExtractElt = true;
7956   unsigned NumConstantLanes = 0;
7957   SDValue Value;
7958   SDValue ConstantValue;
7959   for (unsigned i = 0; i < NumElts; ++i) {
7960     SDValue V = Op.getOperand(i);
7961     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7962       AllLanesExtractElt = false;
7963     if (V.isUndef())
7964       continue;
7965     if (i > 0)
7966       isOnlyLowElement = false;
7967     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7968       isConstant = false;
7969 
7970     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7971       ++NumConstantLanes;
7972       if (!ConstantValue.getNode())
7973         ConstantValue = V;
7974       else if (ConstantValue != V)
7975         usesOnlyOneConstantValue = false;
7976     }
7977 
7978     if (!Value.getNode())
7979       Value = V;
7980     else if (V != Value)
7981       usesOnlyOneValue = false;
7982   }
7983 
7984   if (!Value.getNode()) {
7985     LLVM_DEBUG(
7986         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7987     return DAG.getUNDEF(VT);
7988   }
7989 
7990   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7991   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7992   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7993   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7994     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7995                          "SCALAR_TO_VECTOR node\n");
7996     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7997   }
7998 
7999   if (AllLanesExtractElt) {
8000     SDNode *Vector = nullptr;
8001     bool Even = false;
8002     bool Odd = false;
8003     // Check whether the extract elements match the Even pattern <0,2,4,...> or
8004     // the Odd pattern <1,3,5,...>.
8005     for (unsigned i = 0; i < NumElts; ++i) {
8006       SDValue V = Op.getOperand(i);
8007       const SDNode *N = V.getNode();
8008       if (!isa<ConstantSDNode>(N->getOperand(1)))
8009         break;
8010       SDValue N0 = N->getOperand(0);
8011 
8012       // All elements are extracted from the same vector.
8013       if (!Vector) {
8014         Vector = N0.getNode();
8015         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8016         // BUILD_VECTOR.
8017         if (VT.getVectorElementType() !=
8018             N0.getValueType().getVectorElementType())
8019           break;
8020       } else if (Vector != N0.getNode()) {
8021         Odd = false;
8022         Even = false;
8023         break;
8024       }
8025 
8026       // Extracted values are either at Even indices <0,2,4,...> or at Odd
8027       // indices <1,3,5,...>.
8028       uint64_t Val = N->getConstantOperandVal(1);
8029       if (Val == 2 * i) {
8030         Even = true;
8031         continue;
8032       }
8033       if (Val - 1 == 2 * i) {
8034         Odd = true;
8035         continue;
8036       }
8037 
8038       // Something does not match: abort.
8039       Odd = false;
8040       Even = false;
8041       break;
8042     }
8043     if (Even || Odd) {
8044       SDValue LHS =
8045           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8046                       DAG.getConstant(0, dl, MVT::i64));
8047       SDValue RHS =
8048           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8049                       DAG.getConstant(NumElts, dl, MVT::i64));
8050 
8051       if (Even && !Odd)
8052         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8053                            RHS);
8054       if (Odd && !Even)
8055         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8056                            RHS);
8057     }
8058   }
8059 
8060   // Use DUP for non-constant splats. For f32 constant splats, reduce to
8061   // i32 and try again.
8062   if (usesOnlyOneValue) {
8063     if (!isConstant) {
8064       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8065           Value.getValueType() != VT) {
8066         LLVM_DEBUG(
8067             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8068         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8069       }
8070 
8071       // This is actually a DUPLANExx operation, which keeps everything vectory.
8072 
8073       SDValue Lane = Value.getOperand(1);
8074       Value = Value.getOperand(0);
8075       if (Value.getValueSizeInBits() == 64) {
8076         LLVM_DEBUG(
8077             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8078                       "widening it\n");
8079         Value = WidenVector(Value, DAG);
8080       }
8081 
8082       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8083       return DAG.getNode(Opcode, dl, VT, Value, Lane);
8084     }
8085 
8086     if (VT.getVectorElementType().isFloatingPoint()) {
8087       SmallVector<SDValue, 8> Ops;
8088       EVT EltTy = VT.getVectorElementType();
8089       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
8090               "Unsupported floating-point vector type");
8091       LLVM_DEBUG(
8092           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8093                     "BITCASTS, and try again\n");
8094       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8095       for (unsigned i = 0; i < NumElts; ++i)
8096         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8097       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8098       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8099       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8100                  Val.dump(););
8101       Val = LowerBUILD_VECTOR(Val, DAG);
8102       if (Val.getNode())
8103         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8104     }
8105   }
8106 
8107   // If there was only one constant value used and for more than one lane,
8108   // start by splatting that value, then replace the non-constant lanes. This
8109   // is better than the default, which will perform a separate initialization
8110   // for each lane.
8111   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8112     // Firstly, try to materialize the splat constant.
8113     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8114             Val = ConstantBuildVector(Vec, DAG);
8115     if (!Val) {
8116       // Otherwise, materialize the constant and splat it.
8117       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8118       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8119     }
8120 
8121     // Now insert the non-constant lanes.
8122     for (unsigned i = 0; i < NumElts; ++i) {
8123       SDValue V = Op.getOperand(i);
8124       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8125       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8126         // Note that type legalization likely mucked about with the VT of the
8127         // source operand, so we may have to convert it here before inserting.
8128         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8129     }
8130     return Val;
8131   }
8132 
8133   // This will generate a load from the constant pool.
8134   if (isConstant) {
8135     LLVM_DEBUG(
8136         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8137                   "expansion\n");
8138     return SDValue();
8139   }
8140 
8141   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8142   if (NumElts >= 4) {
8143     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8144       return shuffle;
8145   }
8146 
8147   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8148   // know the default expansion would otherwise fall back on something even
8149   // worse. For a vector with one or two non-undef values, that's
8150   // scalar_to_vector for the elements followed by a shuffle (provided the
8151   // shuffle is valid for the target) and materialization element by element
8152   // on the stack followed by a load for everything else.
8153   if (!isConstant && !usesOnlyOneValue) {
8154     LLVM_DEBUG(
8155         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8156                   "of INSERT_VECTOR_ELT\n");
8157 
8158     SDValue Vec = DAG.getUNDEF(VT);
8159     SDValue Op0 = Op.getOperand(0);
8160     unsigned i = 0;
8161 
8162     // Use SCALAR_TO_VECTOR for lane zero to
8163     // a) Avoid a RMW dependency on the full vector register, and
8164     // b) Allow the register coalescer to fold away the copy if the
8165     //    value is already in an S or D register, and we're forced to emit an
8166     //    INSERT_SUBREG that we can't fold anywhere.
8167     //
8168     // We also allow types like i8 and i16 which are illegal scalar but legal
8169     // vector element types. After type-legalization the inserted value is
8170     // extended (i32) and it is safe to cast them to the vector type by ignoring
8171     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8172     if (!Op0.isUndef()) {
8173       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8174       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8175       ++i;
8176     }
8177     LLVM_DEBUG(if (i < NumElts) dbgs()
8178                    << "Creating nodes for the other vector elements:\n";);
8179     for (; i < NumElts; ++i) {
8180       SDValue V = Op.getOperand(i);
8181       if (V.isUndef())
8182         continue;
8183       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8184       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8185     }
8186     return Vec;
8187   }
8188 
8189   LLVM_DEBUG(
8190       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8191                 "better alternative\n");
8192   return SDValue();
8193 }
8194 
8195 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8196                                                       SelectionDAG &DAG) const {
8197   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8198 
8199   // Check for non-constant or out of range lane.
8200   EVT VT = Op.getOperand(0).getValueType();
8201   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8202   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8203     return SDValue();
8204 
8205 
8206   // Insertion/extraction are legal for V128 types.
8207   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8208       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8209       VT == MVT::v8f16)
8210     return Op;
8211 
8212   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8213       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8214     return SDValue();
8215 
8216   // For V64 types, we perform insertion by expanding the value
8217   // to a V128 type and perform the insertion on that.
8218   SDLoc DL(Op);
8219   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8220   EVT WideTy = WideVec.getValueType();
8221 
8222   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8223                              Op.getOperand(1), Op.getOperand(2));
8224   // Re-narrow the resultant vector.
8225   return NarrowVector(Node, DAG);
8226 }
8227 
8228 SDValue
8229 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8230                                                SelectionDAG &DAG) const {
8231   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8232 
8233   // Check for non-constant or out of range lane.
8234   EVT VT = Op.getOperand(0).getValueType();
8235   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8236   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8237     return SDValue();
8238 
8239 
8240   // Insertion/extraction are legal for V128 types.
8241   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8242       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8243       VT == MVT::v8f16)
8244     return Op;
8245 
8246   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8247       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8248     return SDValue();
8249 
8250   // For V64 types, we perform extraction by expanding the value
8251   // to a V128 type and perform the extraction on that.
8252   SDLoc DL(Op);
8253   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8254   EVT WideTy = WideVec.getValueType();
8255 
8256   EVT ExtrTy = WideTy.getVectorElementType();
8257   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8258     ExtrTy = MVT::i32;
8259 
8260   // For extractions, we just return the result directly.
8261   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8262                      Op.getOperand(1));
8263 }
8264 
8265 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8266                                                       SelectionDAG &DAG) const {
8267   EVT VT = Op.getOperand(0).getValueType();
8268   SDLoc dl(Op);
8269   // Just in case...
8270   if (!VT.isVector())
8271     return SDValue();
8272 
8273   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8274   if (!Cst)
8275     return SDValue();
8276   unsigned Val = Cst->getZExtValue();
8277 
8278   unsigned Size = Op.getValueSizeInBits();
8279 
8280   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8281   if (Val == 0)
8282     return Op;
8283 
8284   // If this is extracting the upper 64-bits of a 128-bit vector, we match
8285   // that directly.
8286   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8287     return Op;
8288 
8289   return SDValue();
8290 }
8291 
8292 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8293   if (VT.getVectorNumElements() == 4 &&
8294       (VT.is128BitVector() || VT.is64BitVector())) {
8295     unsigned PFIndexes[4];
8296     for (unsigned i = 0; i != 4; ++i) {
8297       if (M[i] < 0)
8298         PFIndexes[i] = 8;
8299       else
8300         PFIndexes[i] = M[i];
8301     }
8302 
8303     // Compute the index in the perfect shuffle table.
8304     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8305                             PFIndexes[2] * 9 + PFIndexes[3];
8306     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8307     unsigned Cost = (PFEntry >> 30);
8308 
8309     if (Cost <= 4)
8310       return true;
8311   }
8312 
8313   bool DummyBool;
8314   int DummyInt;
8315   unsigned DummyUnsigned;
8316 
8317   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8318           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8319           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8320           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8321           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8322           isZIPMask(M, VT, DummyUnsigned) ||
8323           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8324           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8325           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8326           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8327           isConcatMask(M, VT, VT.getSizeInBits() == 128));
8328 }
8329 
8330 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8331 /// operand of a vector shift operation, where all the elements of the
8332 /// build_vector must have the same constant integer value.
8333 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8334   // Ignore bit_converts.
8335   while (Op.getOpcode() == ISD::BITCAST)
8336     Op = Op.getOperand(0);
8337   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8338   APInt SplatBits, SplatUndef;
8339   unsigned SplatBitSize;
8340   bool HasAnyUndefs;
8341   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8342                                     HasAnyUndefs, ElementBits) ||
8343       SplatBitSize > ElementBits)
8344     return false;
8345   Cnt = SplatBits.getSExtValue();
8346   return true;
8347 }
8348 
8349 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8350 /// operand of a vector shift left operation.  That value must be in the range:
8351 ///   0 <= Value < ElementBits for a left shift; or
8352 ///   0 <= Value <= ElementBits for a long left shift.
8353 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8354   assert(VT.isVector() && "vector shift count is not a vector type");
8355   int64_t ElementBits = VT.getScalarSizeInBits();
8356   if (!getVShiftImm(Op, ElementBits, Cnt))
8357     return false;
8358   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8359 }
8360 
8361 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8362 /// operand of a vector shift right operation. The value must be in the range:
8363 ///   1 <= Value <= ElementBits for a right shift; or
8364 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8365   assert(VT.isVector() && "vector shift count is not a vector type");
8366   int64_t ElementBits = VT.getScalarSizeInBits();
8367   if (!getVShiftImm(Op, ElementBits, Cnt))
8368     return false;
8369   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8370 }
8371 
8372 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8373                                                       SelectionDAG &DAG) const {
8374   EVT VT = Op.getValueType();
8375   SDLoc DL(Op);
8376   int64_t Cnt;
8377 
8378   if (!Op.getOperand(1).getValueType().isVector())
8379     return Op;
8380   unsigned EltSize = VT.getScalarSizeInBits();
8381 
8382   switch (Op.getOpcode()) {
8383   default:
8384     llvm_unreachable("unexpected shift opcode");
8385 
8386   case ISD::SHL:
8387     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8388       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8389                          DAG.getConstant(Cnt, DL, MVT::i32));
8390     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8391                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8392                                        MVT::i32),
8393                        Op.getOperand(0), Op.getOperand(1));
8394   case ISD::SRA:
8395   case ISD::SRL:
8396     // Right shift immediate
8397     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8398       unsigned Opc =
8399           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8400       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8401                          DAG.getConstant(Cnt, DL, MVT::i32));
8402     }
8403 
8404     // Right shift register.  Note, there is not a shift right register
8405     // instruction, but the shift left register instruction takes a signed
8406     // value, where negative numbers specify a right shift.
8407     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8408                                                 : Intrinsic::aarch64_neon_ushl;
8409     // negate the shift amount
8410     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8411     SDValue NegShiftLeft =
8412         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8413                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8414                     NegShift);
8415     return NegShiftLeft;
8416   }
8417 
8418   return SDValue();
8419 }
8420 
8421 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8422                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
8423                                     const SDLoc &dl, SelectionDAG &DAG) {
8424   EVT SrcVT = LHS.getValueType();
8425   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8426          "function only supposed to emit natural comparisons");
8427 
8428   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8429   APInt CnstBits(VT.getSizeInBits(), 0);
8430   APInt UndefBits(VT.getSizeInBits(), 0);
8431   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8432   bool IsZero = IsCnst && (CnstBits == 0);
8433 
8434   if (SrcVT.getVectorElementType().isFloatingPoint()) {
8435     switch (CC) {
8436     default:
8437       return SDValue();
8438     case AArch64CC::NE: {
8439       SDValue Fcmeq;
8440       if (IsZero)
8441         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8442       else
8443         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8444       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8445     }
8446     case AArch64CC::EQ:
8447       if (IsZero)
8448         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8449       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8450     case AArch64CC::GE:
8451       if (IsZero)
8452         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8453       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8454     case AArch64CC::GT:
8455       if (IsZero)
8456         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8457       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8458     case AArch64CC::LS:
8459       if (IsZero)
8460         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8461       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8462     case AArch64CC::LT:
8463       if (!NoNans)
8464         return SDValue();
8465       // If we ignore NaNs then we can use to the MI implementation.
8466       LLVM_FALLTHROUGH;
8467     case AArch64CC::MI:
8468       if (IsZero)
8469         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8470       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8471     }
8472   }
8473 
8474   switch (CC) {
8475   default:
8476     return SDValue();
8477   case AArch64CC::NE: {
8478     SDValue Cmeq;
8479     if (IsZero)
8480       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8481     else
8482       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8483     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8484   }
8485   case AArch64CC::EQ:
8486     if (IsZero)
8487       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8488     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8489   case AArch64CC::GE:
8490     if (IsZero)
8491       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8492     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8493   case AArch64CC::GT:
8494     if (IsZero)
8495       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8496     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8497   case AArch64CC::LE:
8498     if (IsZero)
8499       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8500     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8501   case AArch64CC::LS:
8502     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8503   case AArch64CC::LO:
8504     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8505   case AArch64CC::LT:
8506     if (IsZero)
8507       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8508     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8509   case AArch64CC::HI:
8510     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8511   case AArch64CC::HS:
8512     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8513   }
8514 }
8515 
8516 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8517                                            SelectionDAG &DAG) const {
8518   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8519   SDValue LHS = Op.getOperand(0);
8520   SDValue RHS = Op.getOperand(1);
8521   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8522   SDLoc dl(Op);
8523 
8524   if (LHS.getValueType().getVectorElementType().isInteger()) {
8525     assert(LHS.getValueType() == RHS.getValueType());
8526     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8527     SDValue Cmp =
8528         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8529     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8530   }
8531 
8532   const bool FullFP16 =
8533     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8534 
8535   // Make v4f16 (only) fcmp operations utilise vector instructions
8536   // v8f16 support will be a litle more complicated
8537   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8538     if (LHS.getValueType().getVectorNumElements() == 4) {
8539       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8540       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8541       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8542       DAG.ReplaceAllUsesWith(Op, NewSetcc);
8543       CmpVT = MVT::v4i32;
8544     } else
8545       return SDValue();
8546   }
8547 
8548   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8549           LHS.getValueType().getVectorElementType() != MVT::f128);
8550 
8551   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8552   // clean.  Some of them require two branches to implement.
8553   AArch64CC::CondCode CC1, CC2;
8554   bool ShouldInvert;
8555   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8556 
8557   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8558   SDValue Cmp =
8559       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8560   if (!Cmp.getNode())
8561     return SDValue();
8562 
8563   if (CC2 != AArch64CC::AL) {
8564     SDValue Cmp2 =
8565         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8566     if (!Cmp2.getNode())
8567       return SDValue();
8568 
8569     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8570   }
8571 
8572   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8573 
8574   if (ShouldInvert)
8575     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8576 
8577   return Cmp;
8578 }
8579 
8580 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8581                                   SelectionDAG &DAG) {
8582   SDValue VecOp = ScalarOp.getOperand(0);
8583   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8584   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8585                      DAG.getConstant(0, DL, MVT::i64));
8586 }
8587 
8588 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8589                                               SelectionDAG &DAG) const {
8590   SDLoc dl(Op);
8591   switch (Op.getOpcode()) {
8592   case ISD::VECREDUCE_ADD:
8593     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8594   case ISD::VECREDUCE_SMAX:
8595     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8596   case ISD::VECREDUCE_SMIN:
8597     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8598   case ISD::VECREDUCE_UMAX:
8599     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8600   case ISD::VECREDUCE_UMIN:
8601     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8602   case ISD::VECREDUCE_FMAX: {
8603     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8604     return DAG.getNode(
8605         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8606         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8607         Op.getOperand(0));
8608   }
8609   case ISD::VECREDUCE_FMIN: {
8610     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8611     return DAG.getNode(
8612         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8613         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8614         Op.getOperand(0));
8615   }
8616   default:
8617     llvm_unreachable("Unhandled reduction");
8618   }
8619 }
8620 
8621 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8622                                                     SelectionDAG &DAG) const {
8623   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8624   if (!Subtarget.hasLSE())
8625     return SDValue();
8626 
8627   // LSE has an atomic load-add instruction, but not a load-sub.
8628   SDLoc dl(Op);
8629   MVT VT = Op.getSimpleValueType();
8630   SDValue RHS = Op.getOperand(2);
8631   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8632   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8633   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8634                        Op.getOperand(0), Op.getOperand(1), RHS,
8635                        AN->getMemOperand());
8636 }
8637 
8638 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8639                                                     SelectionDAG &DAG) const {
8640   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8641   if (!Subtarget.hasLSE())
8642     return SDValue();
8643 
8644   // LSE has an atomic load-clear instruction, but not a load-and.
8645   SDLoc dl(Op);
8646   MVT VT = Op.getSimpleValueType();
8647   SDValue RHS = Op.getOperand(2);
8648   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8649   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8650   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8651                        Op.getOperand(0), Op.getOperand(1), RHS,
8652                        AN->getMemOperand());
8653 }
8654 
8655 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8656     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8657   SDLoc dl(Op);
8658   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8659   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8660 
8661   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8662   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8663   if (Subtarget->hasCustomCallingConv())
8664     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8665 
8666   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8667                      DAG.getConstant(4, dl, MVT::i64));
8668   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8669   Chain =
8670       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8671                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8672                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8673   // To match the actual intent better, we should read the output from X15 here
8674   // again (instead of potentially spilling it to the stack), but rereading Size
8675   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8676   // here.
8677 
8678   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8679                      DAG.getConstant(4, dl, MVT::i64));
8680   return Chain;
8681 }
8682 
8683 SDValue
8684 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8685                                                SelectionDAG &DAG) const {
8686   assert(Subtarget->isTargetWindows() &&
8687          "Only Windows alloca probing supported");
8688   SDLoc dl(Op);
8689   // Get the inputs.
8690   SDNode *Node = Op.getNode();
8691   SDValue Chain = Op.getOperand(0);
8692   SDValue Size = Op.getOperand(1);
8693   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8694   EVT VT = Node->getValueType(0);
8695 
8696   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8697           "no-stack-arg-probe")) {
8698     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8699     Chain = SP.getValue(1);
8700     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8701     if (Align)
8702       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8703                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8704     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8705     SDValue Ops[2] = {SP, Chain};
8706     return DAG.getMergeValues(Ops, dl);
8707   }
8708 
8709   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8710 
8711   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8712 
8713   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8714   Chain = SP.getValue(1);
8715   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8716   if (Align)
8717     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8718                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8719   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8720 
8721   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8722                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8723 
8724   SDValue Ops[2] = {SP, Chain};
8725   return DAG.getMergeValues(Ops, dl);
8726 }
8727 
8728 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
8729                                            SelectionDAG &DAG) const {
8730   EVT VT = Op.getValueType();
8731   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
8732 
8733   SDLoc DL(Op);
8734   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
8735   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
8736                             DL, VT);
8737 }
8738 
8739 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8740 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8741 /// specified in the intrinsic calls.
8742 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8743                                                const CallInst &I,
8744                                                MachineFunction &MF,
8745                                                unsigned Intrinsic) const {
8746   auto &DL = I.getModule()->getDataLayout();
8747   switch (Intrinsic) {
8748   case Intrinsic::aarch64_neon_ld2:
8749   case Intrinsic::aarch64_neon_ld3:
8750   case Intrinsic::aarch64_neon_ld4:
8751   case Intrinsic::aarch64_neon_ld1x2:
8752   case Intrinsic::aarch64_neon_ld1x3:
8753   case Intrinsic::aarch64_neon_ld1x4:
8754   case Intrinsic::aarch64_neon_ld2lane:
8755   case Intrinsic::aarch64_neon_ld3lane:
8756   case Intrinsic::aarch64_neon_ld4lane:
8757   case Intrinsic::aarch64_neon_ld2r:
8758   case Intrinsic::aarch64_neon_ld3r:
8759   case Intrinsic::aarch64_neon_ld4r: {
8760     Info.opc = ISD::INTRINSIC_W_CHAIN;
8761     // Conservatively set memVT to the entire set of vectors loaded.
8762     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8763     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8764     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8765     Info.offset = 0;
8766     Info.align.reset();
8767     // volatile loads with NEON intrinsics not supported
8768     Info.flags = MachineMemOperand::MOLoad;
8769     return true;
8770   }
8771   case Intrinsic::aarch64_neon_st2:
8772   case Intrinsic::aarch64_neon_st3:
8773   case Intrinsic::aarch64_neon_st4:
8774   case Intrinsic::aarch64_neon_st1x2:
8775   case Intrinsic::aarch64_neon_st1x3:
8776   case Intrinsic::aarch64_neon_st1x4:
8777   case Intrinsic::aarch64_neon_st2lane:
8778   case Intrinsic::aarch64_neon_st3lane:
8779   case Intrinsic::aarch64_neon_st4lane: {
8780     Info.opc = ISD::INTRINSIC_VOID;
8781     // Conservatively set memVT to the entire set of vectors stored.
8782     unsigned NumElts = 0;
8783     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8784       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8785       if (!ArgTy->isVectorTy())
8786         break;
8787       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8788     }
8789     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8790     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8791     Info.offset = 0;
8792     Info.align.reset();
8793     // volatile stores with NEON intrinsics not supported
8794     Info.flags = MachineMemOperand::MOStore;
8795     return true;
8796   }
8797   case Intrinsic::aarch64_ldaxr:
8798   case Intrinsic::aarch64_ldxr: {
8799     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8800     Info.opc = ISD::INTRINSIC_W_CHAIN;
8801     Info.memVT = MVT::getVT(PtrTy->getElementType());
8802     Info.ptrVal = I.getArgOperand(0);
8803     Info.offset = 0;
8804     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8805     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8806     return true;
8807   }
8808   case Intrinsic::aarch64_stlxr:
8809   case Intrinsic::aarch64_stxr: {
8810     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8811     Info.opc = ISD::INTRINSIC_W_CHAIN;
8812     Info.memVT = MVT::getVT(PtrTy->getElementType());
8813     Info.ptrVal = I.getArgOperand(1);
8814     Info.offset = 0;
8815     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8816     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8817     return true;
8818   }
8819   case Intrinsic::aarch64_ldaxp:
8820   case Intrinsic::aarch64_ldxp:
8821     Info.opc = ISD::INTRINSIC_W_CHAIN;
8822     Info.memVT = MVT::i128;
8823     Info.ptrVal = I.getArgOperand(0);
8824     Info.offset = 0;
8825     Info.align = Align(16);
8826     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8827     return true;
8828   case Intrinsic::aarch64_stlxp:
8829   case Intrinsic::aarch64_stxp:
8830     Info.opc = ISD::INTRINSIC_W_CHAIN;
8831     Info.memVT = MVT::i128;
8832     Info.ptrVal = I.getArgOperand(2);
8833     Info.offset = 0;
8834     Info.align = Align(16);
8835     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8836     return true;
8837   case Intrinsic::aarch64_sve_ldnt1: {
8838     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8839     Info.opc = ISD::INTRINSIC_W_CHAIN;
8840     Info.memVT = MVT::getVT(PtrTy->getElementType());
8841     Info.ptrVal = I.getArgOperand(1);
8842     Info.offset = 0;
8843     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8844     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
8845     return true;
8846   }
8847   case Intrinsic::aarch64_sve_stnt1: {
8848     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
8849     Info.opc = ISD::INTRINSIC_W_CHAIN;
8850     Info.memVT = MVT::getVT(PtrTy->getElementType());
8851     Info.ptrVal = I.getArgOperand(2);
8852     Info.offset = 0;
8853     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8854     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
8855     return true;
8856   }
8857   default:
8858     break;
8859   }
8860 
8861   return false;
8862 }
8863 
8864 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8865                                                   ISD::LoadExtType ExtTy,
8866                                                   EVT NewVT) const {
8867   // TODO: This may be worth removing. Check regression tests for diffs.
8868   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8869     return false;
8870 
8871   // If we're reducing the load width in order to avoid having to use an extra
8872   // instruction to do extension then it's probably a good idea.
8873   if (ExtTy != ISD::NON_EXTLOAD)
8874     return true;
8875   // Don't reduce load width if it would prevent us from combining a shift into
8876   // the offset.
8877   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8878   assert(Mem);
8879   const SDValue &Base = Mem->getBasePtr();
8880   if (Base.getOpcode() == ISD::ADD &&
8881       Base.getOperand(1).getOpcode() == ISD::SHL &&
8882       Base.getOperand(1).hasOneUse() &&
8883       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8884     // The shift can be combined if it matches the size of the value being
8885     // loaded (and so reducing the width would make it not match).
8886     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8887     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8888     if (ShiftAmount == Log2_32(LoadBytes))
8889       return false;
8890   }
8891   // We have no reason to disallow reducing the load width, so allow it.
8892   return true;
8893 }
8894 
8895 // Truncations from 64-bit GPR to 32-bit GPR is free.
8896 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8897   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8898     return false;
8899   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8900   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8901   return NumBits1 > NumBits2;
8902 }
8903 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8904   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8905     return false;
8906   unsigned NumBits1 = VT1.getSizeInBits();
8907   unsigned NumBits2 = VT2.getSizeInBits();
8908   return NumBits1 > NumBits2;
8909 }
8910 
8911 /// Check if it is profitable to hoist instruction in then/else to if.
8912 /// Not profitable if I and it's user can form a FMA instruction
8913 /// because we prefer FMSUB/FMADD.
8914 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8915   if (I->getOpcode() != Instruction::FMul)
8916     return true;
8917 
8918   if (!I->hasOneUse())
8919     return true;
8920 
8921   Instruction *User = I->user_back();
8922 
8923   if (User &&
8924       !(User->getOpcode() == Instruction::FSub ||
8925         User->getOpcode() == Instruction::FAdd))
8926     return true;
8927 
8928   const TargetOptions &Options = getTargetMachine().Options;
8929   const Function *F = I->getFunction();
8930   const DataLayout &DL = F->getParent()->getDataLayout();
8931   Type *Ty = User->getOperand(0)->getType();
8932 
8933   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
8934            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
8935            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8936             Options.UnsafeFPMath));
8937 }
8938 
8939 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8940 // 64-bit GPR.
8941 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8942   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8943     return false;
8944   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8945   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8946   return NumBits1 == 32 && NumBits2 == 64;
8947 }
8948 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8949   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8950     return false;
8951   unsigned NumBits1 = VT1.getSizeInBits();
8952   unsigned NumBits2 = VT2.getSizeInBits();
8953   return NumBits1 == 32 && NumBits2 == 64;
8954 }
8955 
8956 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8957   EVT VT1 = Val.getValueType();
8958   if (isZExtFree(VT1, VT2)) {
8959     return true;
8960   }
8961 
8962   if (Val.getOpcode() != ISD::LOAD)
8963     return false;
8964 
8965   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8966   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8967           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8968           VT1.getSizeInBits() <= 32);
8969 }
8970 
8971 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8972   if (isa<FPExtInst>(Ext))
8973     return false;
8974 
8975   // Vector types are not free.
8976   if (Ext->getType()->isVectorTy())
8977     return false;
8978 
8979   for (const Use &U : Ext->uses()) {
8980     // The extension is free if we can fold it with a left shift in an
8981     // addressing mode or an arithmetic operation: add, sub, and cmp.
8982 
8983     // Is there a shift?
8984     const Instruction *Instr = cast<Instruction>(U.getUser());
8985 
8986     // Is this a constant shift?
8987     switch (Instr->getOpcode()) {
8988     case Instruction::Shl:
8989       if (!isa<ConstantInt>(Instr->getOperand(1)))
8990         return false;
8991       break;
8992     case Instruction::GetElementPtr: {
8993       gep_type_iterator GTI = gep_type_begin(Instr);
8994       auto &DL = Ext->getModule()->getDataLayout();
8995       std::advance(GTI, U.getOperandNo()-1);
8996       Type *IdxTy = GTI.getIndexedType();
8997       // This extension will end up with a shift because of the scaling factor.
8998       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8999       // Get the shift amount based on the scaling factor:
9000       // log2(sizeof(IdxTy)) - log2(8).
9001       uint64_t ShiftAmt =
9002         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9003       // Is the constant foldable in the shift of the addressing mode?
9004       // I.e., shift amount is between 1 and 4 inclusive.
9005       if (ShiftAmt == 0 || ShiftAmt > 4)
9006         return false;
9007       break;
9008     }
9009     case Instruction::Trunc:
9010       // Check if this is a noop.
9011       // trunc(sext ty1 to ty2) to ty1.
9012       if (Instr->getType() == Ext->getOperand(0)->getType())
9013         continue;
9014       LLVM_FALLTHROUGH;
9015     default:
9016       return false;
9017     }
9018 
9019     // At this point we can use the bfm family, so this extension is free
9020     // for that use.
9021   }
9022   return true;
9023 }
9024 
9025 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9026 /// or upper half of the vector elements.
9027 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9028   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9029     auto *FullVT = cast<VectorType>(FullV->getType());
9030     auto *HalfVT = cast<VectorType>(HalfV->getType());
9031     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
9032   };
9033 
9034   auto extractHalf = [](Value *FullV, Value *HalfV) {
9035     auto *FullVT = cast<VectorType>(FullV->getType());
9036     auto *HalfVT = cast<VectorType>(HalfV->getType());
9037     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9038   };
9039 
9040   Constant *M1, *M2;
9041   Value *S1Op1, *S2Op1;
9042   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
9043       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
9044     return false;
9045 
9046   // Check that the operands are half as wide as the result and we extract
9047   // half of the elements of the input vectors.
9048   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9049       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9050     return false;
9051 
9052   // Check the mask extracts either the lower or upper half of vector
9053   // elements.
9054   int M1Start = -1;
9055   int M2Start = -1;
9056   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
9057   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9058       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9059       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9060     return false;
9061 
9062   return true;
9063 }
9064 
9065 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9066 /// of the vector elements.
9067 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9068   auto areExtDoubled = [](Instruction *Ext) {
9069     return Ext->getType()->getScalarSizeInBits() ==
9070            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9071   };
9072 
9073   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9074       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9075       !areExtDoubled(cast<Instruction>(Ext1)) ||
9076       !areExtDoubled(cast<Instruction>(Ext2)))
9077     return false;
9078 
9079   return true;
9080 }
9081 
9082 /// Check if sinking \p I's operands to I's basic block is profitable, because
9083 /// the operands can be folded into a target instruction, e.g.
9084 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9085 bool AArch64TargetLowering::shouldSinkOperands(
9086     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9087   if (!I->getType()->isVectorTy())
9088     return false;
9089 
9090   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9091     switch (II->getIntrinsicID()) {
9092     case Intrinsic::aarch64_neon_umull:
9093       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9094         return false;
9095       Ops.push_back(&II->getOperandUse(0));
9096       Ops.push_back(&II->getOperandUse(1));
9097       return true;
9098     default:
9099       return false;
9100     }
9101   }
9102 
9103   switch (I->getOpcode()) {
9104   case Instruction::Sub:
9105   case Instruction::Add: {
9106     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9107       return false;
9108 
9109     // If the exts' operands extract either the lower or upper elements, we
9110     // can sink them too.
9111     auto Ext1 = cast<Instruction>(I->getOperand(0));
9112     auto Ext2 = cast<Instruction>(I->getOperand(1));
9113     if (areExtractShuffleVectors(Ext1, Ext2)) {
9114       Ops.push_back(&Ext1->getOperandUse(0));
9115       Ops.push_back(&Ext2->getOperandUse(0));
9116     }
9117 
9118     Ops.push_back(&I->getOperandUse(0));
9119     Ops.push_back(&I->getOperandUse(1));
9120 
9121     return true;
9122   }
9123   default:
9124     return false;
9125   }
9126   return false;
9127 }
9128 
9129 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9130                                           unsigned &RequiredAligment) const {
9131   if (!LoadedType.isSimple() ||
9132       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9133     return false;
9134   // Cyclone supports unaligned accesses.
9135   RequiredAligment = 0;
9136   unsigned NumBits = LoadedType.getSizeInBits();
9137   return NumBits == 32 || NumBits == 64;
9138 }
9139 
9140 /// A helper function for determining the number of interleaved accesses we
9141 /// will generate when lowering accesses of the given type.
9142 unsigned
9143 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9144                                                  const DataLayout &DL) const {
9145   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9146 }
9147 
9148 MachineMemOperand::Flags
9149 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9150   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9151       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9152     return MOStridedAccess;
9153   return MachineMemOperand::MONone;
9154 }
9155 
9156 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9157     VectorType *VecTy, const DataLayout &DL) const {
9158 
9159   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9160   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9161 
9162   // Ensure the number of vector elements is greater than 1.
9163   if (VecTy->getNumElements() < 2)
9164     return false;
9165 
9166   // Ensure the element type is legal.
9167   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9168     return false;
9169 
9170   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9171   // 128 will be split into multiple interleaved accesses.
9172   return VecSize == 64 || VecSize % 128 == 0;
9173 }
9174 
9175 /// Lower an interleaved load into a ldN intrinsic.
9176 ///
9177 /// E.g. Lower an interleaved load (Factor = 2):
9178 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9179 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
9180 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
9181 ///
9182 ///      Into:
9183 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9184 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9185 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9186 bool AArch64TargetLowering::lowerInterleavedLoad(
9187     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9188     ArrayRef<unsigned> Indices, unsigned Factor) const {
9189   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9190          "Invalid interleave factor");
9191   assert(!Shuffles.empty() && "Empty shufflevector input");
9192   assert(Shuffles.size() == Indices.size() &&
9193          "Unmatched number of shufflevectors and indices");
9194 
9195   const DataLayout &DL = LI->getModule()->getDataLayout();
9196 
9197   VectorType *VecTy = Shuffles[0]->getType();
9198 
9199   // Skip if we do not have NEON and skip illegal vector types. We can
9200   // "legalize" wide vector types into multiple interleaved accesses as long as
9201   // the vector types are divisible by 128.
9202   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9203     return false;
9204 
9205   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9206 
9207   // A pointer vector can not be the return type of the ldN intrinsics. Need to
9208   // load integer vectors first and then convert to pointer vectors.
9209   Type *EltTy = VecTy->getVectorElementType();
9210   if (EltTy->isPointerTy())
9211     VecTy =
9212         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
9213 
9214   IRBuilder<> Builder(LI);
9215 
9216   // The base address of the load.
9217   Value *BaseAddr = LI->getPointerOperand();
9218 
9219   if (NumLoads > 1) {
9220     // If we're going to generate more than one load, reset the sub-vector type
9221     // to something legal.
9222     VecTy = VectorType::get(VecTy->getVectorElementType(),
9223                             VecTy->getVectorNumElements() / NumLoads);
9224 
9225     // We will compute the pointer operand of each load from the original base
9226     // address using GEPs. Cast the base address to a pointer to the scalar
9227     // element type.
9228     BaseAddr = Builder.CreateBitCast(
9229         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
9230                       LI->getPointerAddressSpace()));
9231   }
9232 
9233   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9234   Type *Tys[2] = {VecTy, PtrTy};
9235   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9236                                             Intrinsic::aarch64_neon_ld3,
9237                                             Intrinsic::aarch64_neon_ld4};
9238   Function *LdNFunc =
9239       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9240 
9241   // Holds sub-vectors extracted from the load intrinsic return values. The
9242   // sub-vectors are associated with the shufflevector instructions they will
9243   // replace.
9244   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9245 
9246   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9247 
9248     // If we're generating more than one load, compute the base address of
9249     // subsequent loads as an offset from the previous.
9250     if (LoadCount > 0)
9251       BaseAddr =
9252           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
9253                                      VecTy->getVectorNumElements() * Factor);
9254 
9255     CallInst *LdN = Builder.CreateCall(
9256         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9257 
9258     // Extract and store the sub-vectors returned by the load intrinsic.
9259     for (unsigned i = 0; i < Shuffles.size(); i++) {
9260       ShuffleVectorInst *SVI = Shuffles[i];
9261       unsigned Index = Indices[i];
9262 
9263       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9264 
9265       // Convert the integer vector to pointer vector if the element is pointer.
9266       if (EltTy->isPointerTy())
9267         SubVec = Builder.CreateIntToPtr(
9268             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
9269                                     VecTy->getVectorNumElements()));
9270       SubVecs[SVI].push_back(SubVec);
9271     }
9272   }
9273 
9274   // Replace uses of the shufflevector instructions with the sub-vectors
9275   // returned by the load intrinsic. If a shufflevector instruction is
9276   // associated with more than one sub-vector, those sub-vectors will be
9277   // concatenated into a single wide vector.
9278   for (ShuffleVectorInst *SVI : Shuffles) {
9279     auto &SubVec = SubVecs[SVI];
9280     auto *WideVec =
9281         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9282     SVI->replaceAllUsesWith(WideVec);
9283   }
9284 
9285   return true;
9286 }
9287 
9288 /// Lower an interleaved store into a stN intrinsic.
9289 ///
9290 /// E.g. Lower an interleaved store (Factor = 3):
9291 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9292 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9293 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9294 ///
9295 ///      Into:
9296 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9297 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9298 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9299 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9300 ///
9301 /// Note that the new shufflevectors will be removed and we'll only generate one
9302 /// st3 instruction in CodeGen.
9303 ///
9304 /// Example for a more general valid mask (Factor 3). Lower:
9305 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9306 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9307 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
9308 ///
9309 ///      Into:
9310 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9311 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9312 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9313 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9314 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9315                                                   ShuffleVectorInst *SVI,
9316                                                   unsigned Factor) const {
9317   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9318          "Invalid interleave factor");
9319 
9320   VectorType *VecTy = SVI->getType();
9321   assert(VecTy->getVectorNumElements() % Factor == 0 &&
9322          "Invalid interleaved store");
9323 
9324   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
9325   Type *EltTy = VecTy->getVectorElementType();
9326   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9327 
9328   const DataLayout &DL = SI->getModule()->getDataLayout();
9329 
9330   // Skip if we do not have NEON and skip illegal vector types. We can
9331   // "legalize" wide vector types into multiple interleaved accesses as long as
9332   // the vector types are divisible by 128.
9333   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9334     return false;
9335 
9336   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9337 
9338   Value *Op0 = SVI->getOperand(0);
9339   Value *Op1 = SVI->getOperand(1);
9340   IRBuilder<> Builder(SI);
9341 
9342   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9343   // vectors to integer vectors.
9344   if (EltTy->isPointerTy()) {
9345     Type *IntTy = DL.getIntPtrType(EltTy);
9346     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
9347 
9348     // Convert to the corresponding integer vector.
9349     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9350     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9351     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9352 
9353     SubVecTy = VectorType::get(IntTy, LaneLen);
9354   }
9355 
9356   // The base address of the store.
9357   Value *BaseAddr = SI->getPointerOperand();
9358 
9359   if (NumStores > 1) {
9360     // If we're going to generate more than one store, reset the lane length
9361     // and sub-vector type to something legal.
9362     LaneLen /= NumStores;
9363     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
9364 
9365     // We will compute the pointer operand of each store from the original base
9366     // address using GEPs. Cast the base address to a pointer to the scalar
9367     // element type.
9368     BaseAddr = Builder.CreateBitCast(
9369         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
9370                       SI->getPointerAddressSpace()));
9371   }
9372 
9373   auto Mask = SVI->getShuffleMask();
9374 
9375   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9376   Type *Tys[2] = {SubVecTy, PtrTy};
9377   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9378                                              Intrinsic::aarch64_neon_st3,
9379                                              Intrinsic::aarch64_neon_st4};
9380   Function *StNFunc =
9381       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9382 
9383   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9384 
9385     SmallVector<Value *, 5> Ops;
9386 
9387     // Split the shufflevector operands into sub vectors for the new stN call.
9388     for (unsigned i = 0; i < Factor; i++) {
9389       unsigned IdxI = StoreCount * LaneLen * Factor + i;
9390       if (Mask[IdxI] >= 0) {
9391         Ops.push_back(Builder.CreateShuffleVector(
9392             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9393       } else {
9394         unsigned StartMask = 0;
9395         for (unsigned j = 1; j < LaneLen; j++) {
9396           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9397           if (Mask[IdxJ * Factor + IdxI] >= 0) {
9398             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9399             break;
9400           }
9401         }
9402         // Note: Filling undef gaps with random elements is ok, since
9403         // those elements were being written anyway (with undefs).
9404         // In the case of all undefs we're defaulting to using elems from 0
9405         // Note: StartMask cannot be negative, it's checked in
9406         // isReInterleaveMask
9407         Ops.push_back(Builder.CreateShuffleVector(
9408             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9409       }
9410     }
9411 
9412     // If we generating more than one store, we compute the base address of
9413     // subsequent stores as an offset from the previous.
9414     if (StoreCount > 0)
9415       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9416                                             BaseAddr, LaneLen * Factor);
9417 
9418     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9419     Builder.CreateCall(StNFunc, Ops);
9420   }
9421   return true;
9422 }
9423 
9424 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9425                        unsigned AlignCheck) {
9426   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9427           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9428 }
9429 
9430 EVT AArch64TargetLowering::getOptimalMemOpType(
9431     const MemOp &Op, const AttributeList &FuncAttributes) const {
9432   bool CanImplicitFloat =
9433       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9434   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9435   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9436   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9437   // taken one instruction to materialize the v2i64 zero and one store (with
9438   // restrictive addressing mode). Just do i64 stores.
9439   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9440   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9441     if (memOpAlign(Op.getSrcAlign(), Op.getDstAlign(), AlignCheck))
9442       return true;
9443     bool Fast;
9444     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9445                                           &Fast) &&
9446            Fast;
9447   };
9448 
9449   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9450       AlignmentIsAcceptable(MVT::v2i64, 16))
9451     return MVT::v2i64;
9452   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9453     return MVT::f128;
9454   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9455     return MVT::i64;
9456   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9457     return MVT::i32;
9458   return MVT::Other;
9459 }
9460 
9461 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9462     const MemOp &Op, const AttributeList &FuncAttributes) const {
9463   bool CanImplicitFloat =
9464       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9465   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9466   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9467   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9468   // taken one instruction to materialize the v2i64 zero and one store (with
9469   // restrictive addressing mode). Just do i64 stores.
9470   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
9471   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9472     if (memOpAlign(Op.getSrcAlign(), Op.getDstAlign(), AlignCheck))
9473       return true;
9474     bool Fast;
9475     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9476                                           &Fast) &&
9477            Fast;
9478   };
9479 
9480   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
9481       AlignmentIsAcceptable(MVT::v2i64, 16))
9482     return LLT::vector(2, 64);
9483   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9484     return LLT::scalar(128);
9485   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9486     return LLT::scalar(64);
9487   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9488     return LLT::scalar(32);
9489   return LLT();
9490 }
9491 
9492 // 12-bit optionally shifted immediates are legal for adds.
9493 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9494   if (Immed == std::numeric_limits<int64_t>::min()) {
9495     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9496                       << ": avoid UB for INT64_MIN\n");
9497     return false;
9498   }
9499   // Same encoding for add/sub, just flip the sign.
9500   Immed = std::abs(Immed);
9501   bool IsLegal = ((Immed >> 12) == 0 ||
9502                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9503   LLVM_DEBUG(dbgs() << "Is " << Immed
9504                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9505   return IsLegal;
9506 }
9507 
9508 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9509 // immediates is the same as for an add or a sub.
9510 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9511   return isLegalAddImmediate(Immed);
9512 }
9513 
9514 /// isLegalAddressingMode - Return true if the addressing mode represented
9515 /// by AM is legal for this target, for a load/store of the specified type.
9516 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9517                                                   const AddrMode &AM, Type *Ty,
9518                                                   unsigned AS, Instruction *I) const {
9519   // AArch64 has five basic addressing modes:
9520   //  reg
9521   //  reg + 9-bit signed offset
9522   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
9523   //  reg1 + reg2
9524   //  reg + SIZE_IN_BYTES * reg
9525 
9526   // No global is ever allowed as a base.
9527   if (AM.BaseGV)
9528     return false;
9529 
9530   // No reg+reg+imm addressing.
9531   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9532     return false;
9533 
9534   // FIXME: Update this method to support scalable addressing modes.
9535   if (Ty->isVectorTy() && Ty->getVectorIsScalable())
9536     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
9537 
9538   // check reg + imm case:
9539   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9540   uint64_t NumBytes = 0;
9541   if (Ty->isSized()) {
9542     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9543     NumBytes = NumBits / 8;
9544     if (!isPowerOf2_64(NumBits))
9545       NumBytes = 0;
9546   }
9547 
9548   if (!AM.Scale) {
9549     int64_t Offset = AM.BaseOffs;
9550 
9551     // 9-bit signed offset
9552     if (isInt<9>(Offset))
9553       return true;
9554 
9555     // 12-bit unsigned offset
9556     unsigned shift = Log2_64(NumBytes);
9557     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9558         // Must be a multiple of NumBytes (NumBytes is a power of 2)
9559         (Offset >> shift) << shift == Offset)
9560       return true;
9561     return false;
9562   }
9563 
9564   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9565 
9566   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9567 }
9568 
9569 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9570   // Consider splitting large offset of struct or array.
9571   return true;
9572 }
9573 
9574 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9575                                                 const AddrMode &AM, Type *Ty,
9576                                                 unsigned AS) const {
9577   // Scaling factors are not free at all.
9578   // Operands                     | Rt Latency
9579   // -------------------------------------------
9580   // Rt, [Xn, Xm]                 | 4
9581   // -------------------------------------------
9582   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
9583   // Rt, [Xn, Wm, <extend> #imm]  |
9584   if (isLegalAddressingMode(DL, AM, Ty, AS))
9585     // Scale represents reg2 * scale, thus account for 1 if
9586     // it is not equal to 0 or 1.
9587     return AM.Scale != 0 && AM.Scale != 1;
9588   return -1;
9589 }
9590 
9591 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9592     const MachineFunction &MF, EVT VT) const {
9593   VT = VT.getScalarType();
9594 
9595   if (!VT.isSimple())
9596     return false;
9597 
9598   switch (VT.getSimpleVT().SimpleTy) {
9599   case MVT::f32:
9600   case MVT::f64:
9601     return true;
9602   default:
9603     break;
9604   }
9605 
9606   return false;
9607 }
9608 
9609 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9610                                                        Type *Ty) const {
9611   switch (Ty->getScalarType()->getTypeID()) {
9612   case Type::FloatTyID:
9613   case Type::DoubleTyID:
9614     return true;
9615   default:
9616     return false;
9617   }
9618 }
9619 
9620 const MCPhysReg *
9621 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9622   // LR is a callee-save register, but we must treat it as clobbered by any call
9623   // site. Hence we include LR in the scratch registers, which are in turn added
9624   // as implicit-defs for stackmaps and patchpoints.
9625   static const MCPhysReg ScratchRegs[] = {
9626     AArch64::X16, AArch64::X17, AArch64::LR, 0
9627   };
9628   return ScratchRegs;
9629 }
9630 
9631 bool
9632 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9633                                                      CombineLevel Level) const {
9634   N = N->getOperand(0).getNode();
9635   EVT VT = N->getValueType(0);
9636     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9637     // it with shift to let it be lowered to UBFX.
9638   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9639       isa<ConstantSDNode>(N->getOperand(1))) {
9640     uint64_t TruncMask = N->getConstantOperandVal(1);
9641     if (isMask_64(TruncMask) &&
9642       N->getOperand(0).getOpcode() == ISD::SRL &&
9643       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9644       return false;
9645   }
9646   return true;
9647 }
9648 
9649 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9650                                                               Type *Ty) const {
9651   assert(Ty->isIntegerTy());
9652 
9653   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9654   if (BitSize == 0)
9655     return false;
9656 
9657   int64_t Val = Imm.getSExtValue();
9658   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9659     return true;
9660 
9661   if ((int64_t)Val < 0)
9662     Val = ~Val;
9663   if (BitSize == 32)
9664     Val &= (1LL << 32) - 1;
9665 
9666   unsigned LZ = countLeadingZeros((uint64_t)Val);
9667   unsigned Shift = (63 - LZ) / 16;
9668   // MOVZ is free so return true for one or fewer MOVK.
9669   return Shift < 3;
9670 }
9671 
9672 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9673                                                     unsigned Index) const {
9674   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9675     return false;
9676 
9677   return (Index == 0 || Index == ResVT.getVectorNumElements());
9678 }
9679 
9680 /// Turn vector tests of the signbit in the form of:
9681 ///   xor (sra X, elt_size(X)-1), -1
9682 /// into:
9683 ///   cmge X, X, #0
9684 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9685                                          const AArch64Subtarget *Subtarget) {
9686   EVT VT = N->getValueType(0);
9687   if (!Subtarget->hasNEON() || !VT.isVector())
9688     return SDValue();
9689 
9690   // There must be a shift right algebraic before the xor, and the xor must be a
9691   // 'not' operation.
9692   SDValue Shift = N->getOperand(0);
9693   SDValue Ones = N->getOperand(1);
9694   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9695       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9696     return SDValue();
9697 
9698   // The shift should be smearing the sign bit across each vector element.
9699   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9700   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9701   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9702     return SDValue();
9703 
9704   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9705 }
9706 
9707 // Generate SUBS and CSEL for integer abs.
9708 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9709   EVT VT = N->getValueType(0);
9710 
9711   SDValue N0 = N->getOperand(0);
9712   SDValue N1 = N->getOperand(1);
9713   SDLoc DL(N);
9714 
9715   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9716   // and change it to SUB and CSEL.
9717   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9718       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9719       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9720     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9721       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9722         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9723                                   N0.getOperand(0));
9724         // Generate SUBS & CSEL.
9725         SDValue Cmp =
9726             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9727                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9728         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9729                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9730                            SDValue(Cmp.getNode(), 1));
9731       }
9732   return SDValue();
9733 }
9734 
9735 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9736                                  TargetLowering::DAGCombinerInfo &DCI,
9737                                  const AArch64Subtarget *Subtarget) {
9738   if (DCI.isBeforeLegalizeOps())
9739     return SDValue();
9740 
9741   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9742     return Cmp;
9743 
9744   return performIntegerAbsCombine(N, DAG);
9745 }
9746 
9747 SDValue
9748 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9749                                      SelectionDAG &DAG,
9750                                      SmallVectorImpl<SDNode *> &Created) const {
9751   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9752   if (isIntDivCheap(N->getValueType(0), Attr))
9753     return SDValue(N,0); // Lower SDIV as SDIV
9754 
9755   // fold (sdiv X, pow2)
9756   EVT VT = N->getValueType(0);
9757   if ((VT != MVT::i32 && VT != MVT::i64) ||
9758       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9759     return SDValue();
9760 
9761   SDLoc DL(N);
9762   SDValue N0 = N->getOperand(0);
9763   unsigned Lg2 = Divisor.countTrailingZeros();
9764   SDValue Zero = DAG.getConstant(0, DL, VT);
9765   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9766 
9767   // Add (N0 < 0) ? Pow2 - 1 : 0;
9768   SDValue CCVal;
9769   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9770   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9771   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9772 
9773   Created.push_back(Cmp.getNode());
9774   Created.push_back(Add.getNode());
9775   Created.push_back(CSel.getNode());
9776 
9777   // Divide by pow2.
9778   SDValue SRA =
9779       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9780 
9781   // If we're dividing by a positive value, we're done.  Otherwise, we must
9782   // negate the result.
9783   if (Divisor.isNonNegative())
9784     return SRA;
9785 
9786   Created.push_back(SRA.getNode());
9787   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9788 }
9789 
9790 static bool IsSVECntIntrinsic(SDValue S) {
9791   switch(getIntrinsicID(S.getNode())) {
9792   default:
9793     break;
9794   case Intrinsic::aarch64_sve_cntb:
9795   case Intrinsic::aarch64_sve_cnth:
9796   case Intrinsic::aarch64_sve_cntw:
9797   case Intrinsic::aarch64_sve_cntd:
9798     return true;
9799   }
9800   return false;
9801 }
9802 
9803 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9804                                  TargetLowering::DAGCombinerInfo &DCI,
9805                                  const AArch64Subtarget *Subtarget) {
9806   if (DCI.isBeforeLegalizeOps())
9807     return SDValue();
9808 
9809   // The below optimizations require a constant RHS.
9810   if (!isa<ConstantSDNode>(N->getOperand(1)))
9811     return SDValue();
9812 
9813   SDValue N0 = N->getOperand(0);
9814   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9815   const APInt &ConstValue = C->getAPIntValue();
9816 
9817   // Allow the scaling to be folded into the `cnt` instruction by preventing
9818   // the scaling to be obscured here. This makes it easier to pattern match.
9819   if (IsSVECntIntrinsic(N0) ||
9820      (N0->getOpcode() == ISD::TRUNCATE &&
9821       (IsSVECntIntrinsic(N0->getOperand(0)))))
9822        if (ConstValue.sge(1) && ConstValue.sle(16))
9823          return SDValue();
9824 
9825   // Multiplication of a power of two plus/minus one can be done more
9826   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9827   // future CPUs have a cheaper MADD instruction, this may need to be
9828   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9829   // 64-bit is 5 cycles, so this is always a win.
9830   // More aggressively, some multiplications N0 * C can be lowered to
9831   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9832   // e.g. 6=3*2=(2+1)*2.
9833   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9834   // which equals to (1+2)*16-(1+2).
9835   // TrailingZeroes is used to test if the mul can be lowered to
9836   // shift+add+shift.
9837   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9838   if (TrailingZeroes) {
9839     // Conservatively do not lower to shift+add+shift if the mul might be
9840     // folded into smul or umul.
9841     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9842                             isZeroExtended(N0.getNode(), DAG)))
9843       return SDValue();
9844     // Conservatively do not lower to shift+add+shift if the mul might be
9845     // folded into madd or msub.
9846     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9847                            N->use_begin()->getOpcode() == ISD::SUB))
9848       return SDValue();
9849   }
9850   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9851   // and shift+add+shift.
9852   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9853 
9854   unsigned ShiftAmt, AddSubOpc;
9855   // Is the shifted value the LHS operand of the add/sub?
9856   bool ShiftValUseIsN0 = true;
9857   // Do we need to negate the result?
9858   bool NegateResult = false;
9859 
9860   if (ConstValue.isNonNegative()) {
9861     // (mul x, 2^N + 1) => (add (shl x, N), x)
9862     // (mul x, 2^N - 1) => (sub (shl x, N), x)
9863     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9864     APInt SCVMinus1 = ShiftedConstValue - 1;
9865     APInt CVPlus1 = ConstValue + 1;
9866     if (SCVMinus1.isPowerOf2()) {
9867       ShiftAmt = SCVMinus1.logBase2();
9868       AddSubOpc = ISD::ADD;
9869     } else if (CVPlus1.isPowerOf2()) {
9870       ShiftAmt = CVPlus1.logBase2();
9871       AddSubOpc = ISD::SUB;
9872     } else
9873       return SDValue();
9874   } else {
9875     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9876     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9877     APInt CVNegPlus1 = -ConstValue + 1;
9878     APInt CVNegMinus1 = -ConstValue - 1;
9879     if (CVNegPlus1.isPowerOf2()) {
9880       ShiftAmt = CVNegPlus1.logBase2();
9881       AddSubOpc = ISD::SUB;
9882       ShiftValUseIsN0 = false;
9883     } else if (CVNegMinus1.isPowerOf2()) {
9884       ShiftAmt = CVNegMinus1.logBase2();
9885       AddSubOpc = ISD::ADD;
9886       NegateResult = true;
9887     } else
9888       return SDValue();
9889   }
9890 
9891   SDLoc DL(N);
9892   EVT VT = N->getValueType(0);
9893   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9894                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
9895 
9896   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9897   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9898   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9899   assert(!(NegateResult && TrailingZeroes) &&
9900          "NegateResult and TrailingZeroes cannot both be true for now.");
9901   // Negate the result.
9902   if (NegateResult)
9903     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9904   // Shift the result.
9905   if (TrailingZeroes)
9906     return DAG.getNode(ISD::SHL, DL, VT, Res,
9907                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9908   return Res;
9909 }
9910 
9911 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9912                                                          SelectionDAG &DAG) {
9913   // Take advantage of vector comparisons producing 0 or -1 in each lane to
9914   // optimize away operation when it's from a constant.
9915   //
9916   // The general transformation is:
9917   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9918   //       AND(VECTOR_CMP(x,y), constant2)
9919   //    constant2 = UNARYOP(constant)
9920 
9921   // Early exit if this isn't a vector operation, the operand of the
9922   // unary operation isn't a bitwise AND, or if the sizes of the operations
9923   // aren't the same.
9924   EVT VT = N->getValueType(0);
9925   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9926       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9927       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9928     return SDValue();
9929 
9930   // Now check that the other operand of the AND is a constant. We could
9931   // make the transformation for non-constant splats as well, but it's unclear
9932   // that would be a benefit as it would not eliminate any operations, just
9933   // perform one more step in scalar code before moving to the vector unit.
9934   if (BuildVectorSDNode *BV =
9935           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9936     // Bail out if the vector isn't a constant.
9937     if (!BV->isConstant())
9938       return SDValue();
9939 
9940     // Everything checks out. Build up the new and improved node.
9941     SDLoc DL(N);
9942     EVT IntVT = BV->getValueType(0);
9943     // Create a new constant of the appropriate type for the transformed
9944     // DAG.
9945     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9946     // The AND node needs bitcasts to/from an integer vector type around it.
9947     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9948     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9949                                  N->getOperand(0)->getOperand(0), MaskConst);
9950     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9951     return Res;
9952   }
9953 
9954   return SDValue();
9955 }
9956 
9957 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9958                                      const AArch64Subtarget *Subtarget) {
9959   // First try to optimize away the conversion when it's conditionally from
9960   // a constant. Vectors only.
9961   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9962     return Res;
9963 
9964   EVT VT = N->getValueType(0);
9965   if (VT != MVT::f32 && VT != MVT::f64)
9966     return SDValue();
9967 
9968   // Only optimize when the source and destination types have the same width.
9969   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9970     return SDValue();
9971 
9972   // If the result of an integer load is only used by an integer-to-float
9973   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9974   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9975   SDValue N0 = N->getOperand(0);
9976   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9977       // Do not change the width of a volatile load.
9978       !cast<LoadSDNode>(N0)->isVolatile()) {
9979     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9980     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9981                                LN0->getPointerInfo(), LN0->getAlignment(),
9982                                LN0->getMemOperand()->getFlags());
9983 
9984     // Make sure successors of the original load stay after it by updating them
9985     // to use the new Chain.
9986     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9987 
9988     unsigned Opcode =
9989         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9990     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9991   }
9992 
9993   return SDValue();
9994 }
9995 
9996 /// Fold a floating-point multiply by power of two into floating-point to
9997 /// fixed-point conversion.
9998 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9999                                      TargetLowering::DAGCombinerInfo &DCI,
10000                                      const AArch64Subtarget *Subtarget) {
10001   if (!Subtarget->hasNEON())
10002     return SDValue();
10003 
10004   if (!N->getValueType(0).isSimple())
10005     return SDValue();
10006 
10007   SDValue Op = N->getOperand(0);
10008   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10009       Op.getOpcode() != ISD::FMUL)
10010     return SDValue();
10011 
10012   SDValue ConstVec = Op->getOperand(1);
10013   if (!isa<BuildVectorSDNode>(ConstVec))
10014     return SDValue();
10015 
10016   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10017   uint32_t FloatBits = FloatTy.getSizeInBits();
10018   if (FloatBits != 32 && FloatBits != 64)
10019     return SDValue();
10020 
10021   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10022   uint32_t IntBits = IntTy.getSizeInBits();
10023   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10024     return SDValue();
10025 
10026   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10027   if (IntBits > FloatBits)
10028     return SDValue();
10029 
10030   BitVector UndefElements;
10031   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10032   int32_t Bits = IntBits == 64 ? 64 : 32;
10033   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10034   if (C == -1 || C == 0 || C > Bits)
10035     return SDValue();
10036 
10037   MVT ResTy;
10038   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10039   switch (NumLanes) {
10040   default:
10041     return SDValue();
10042   case 2:
10043     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10044     break;
10045   case 4:
10046     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10047     break;
10048   }
10049 
10050   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10051     return SDValue();
10052 
10053   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10054          "Illegal vector type after legalization");
10055 
10056   SDLoc DL(N);
10057   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10058   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10059                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
10060   SDValue FixConv =
10061       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10062                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10063                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10064   // We can handle smaller integers by generating an extra trunc.
10065   if (IntBits < FloatBits)
10066     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10067 
10068   return FixConv;
10069 }
10070 
10071 /// Fold a floating-point divide by power of two into fixed-point to
10072 /// floating-point conversion.
10073 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10074                                   TargetLowering::DAGCombinerInfo &DCI,
10075                                   const AArch64Subtarget *Subtarget) {
10076   if (!Subtarget->hasNEON())
10077     return SDValue();
10078 
10079   SDValue Op = N->getOperand(0);
10080   unsigned Opc = Op->getOpcode();
10081   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10082       !Op.getOperand(0).getValueType().isSimple() ||
10083       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10084     return SDValue();
10085 
10086   SDValue ConstVec = N->getOperand(1);
10087   if (!isa<BuildVectorSDNode>(ConstVec))
10088     return SDValue();
10089 
10090   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10091   int32_t IntBits = IntTy.getSizeInBits();
10092   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10093     return SDValue();
10094 
10095   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10096   int32_t FloatBits = FloatTy.getSizeInBits();
10097   if (FloatBits != 32 && FloatBits != 64)
10098     return SDValue();
10099 
10100   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10101   if (IntBits > FloatBits)
10102     return SDValue();
10103 
10104   BitVector UndefElements;
10105   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10106   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10107   if (C == -1 || C == 0 || C > FloatBits)
10108     return SDValue();
10109 
10110   MVT ResTy;
10111   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10112   switch (NumLanes) {
10113   default:
10114     return SDValue();
10115   case 2:
10116     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10117     break;
10118   case 4:
10119     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10120     break;
10121   }
10122 
10123   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10124     return SDValue();
10125 
10126   SDLoc DL(N);
10127   SDValue ConvInput = Op.getOperand(0);
10128   bool IsSigned = Opc == ISD::SINT_TO_FP;
10129   if (IntBits < FloatBits)
10130     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10131                             ResTy, ConvInput);
10132 
10133   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10134                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
10135   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10136                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10137                      DAG.getConstant(C, DL, MVT::i32));
10138 }
10139 
10140 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10141 /// searches for and classifies those shifts.
10142 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10143                          bool &FromHi) {
10144   if (N.getOpcode() == ISD::SHL)
10145     FromHi = false;
10146   else if (N.getOpcode() == ISD::SRL)
10147     FromHi = true;
10148   else
10149     return false;
10150 
10151   if (!isa<ConstantSDNode>(N.getOperand(1)))
10152     return false;
10153 
10154   ShiftAmount = N->getConstantOperandVal(1);
10155   Src = N->getOperand(0);
10156   return true;
10157 }
10158 
10159 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10160 /// registers viewed as a high/low pair. This function looks for the pattern:
10161 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10162 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10163 /// aren't independent.
10164 static SDValue tryCombineToEXTR(SDNode *N,
10165                                 TargetLowering::DAGCombinerInfo &DCI) {
10166   SelectionDAG &DAG = DCI.DAG;
10167   SDLoc DL(N);
10168   EVT VT = N->getValueType(0);
10169 
10170   assert(N->getOpcode() == ISD::OR && "Unexpected root");
10171 
10172   if (VT != MVT::i32 && VT != MVT::i64)
10173     return SDValue();
10174 
10175   SDValue LHS;
10176   uint32_t ShiftLHS = 0;
10177   bool LHSFromHi = false;
10178   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10179     return SDValue();
10180 
10181   SDValue RHS;
10182   uint32_t ShiftRHS = 0;
10183   bool RHSFromHi = false;
10184   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10185     return SDValue();
10186 
10187   // If they're both trying to come from the high part of the register, they're
10188   // not really an EXTR.
10189   if (LHSFromHi == RHSFromHi)
10190     return SDValue();
10191 
10192   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10193     return SDValue();
10194 
10195   if (LHSFromHi) {
10196     std::swap(LHS, RHS);
10197     std::swap(ShiftLHS, ShiftRHS);
10198   }
10199 
10200   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10201                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
10202 }
10203 
10204 static SDValue tryCombineToBSL(SDNode *N,
10205                                 TargetLowering::DAGCombinerInfo &DCI) {
10206   EVT VT = N->getValueType(0);
10207   SelectionDAG &DAG = DCI.DAG;
10208   SDLoc DL(N);
10209 
10210   if (!VT.isVector())
10211     return SDValue();
10212 
10213   SDValue N0 = N->getOperand(0);
10214   if (N0.getOpcode() != ISD::AND)
10215     return SDValue();
10216 
10217   SDValue N1 = N->getOperand(1);
10218   if (N1.getOpcode() != ISD::AND)
10219     return SDValue();
10220 
10221   // We only have to look for constant vectors here since the general, variable
10222   // case can be handled in TableGen.
10223   unsigned Bits = VT.getScalarSizeInBits();
10224   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10225   for (int i = 1; i >= 0; --i)
10226     for (int j = 1; j >= 0; --j) {
10227       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10228       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10229       if (!BVN0 || !BVN1)
10230         continue;
10231 
10232       bool FoundMatch = true;
10233       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10234         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10235         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10236         if (!CN0 || !CN1 ||
10237             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10238           FoundMatch = false;
10239           break;
10240         }
10241       }
10242 
10243       if (FoundMatch)
10244         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
10245                            N0->getOperand(1 - i), N1->getOperand(1 - j));
10246     }
10247 
10248   return SDValue();
10249 }
10250 
10251 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10252                                 const AArch64Subtarget *Subtarget) {
10253   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10254   SelectionDAG &DAG = DCI.DAG;
10255   EVT VT = N->getValueType(0);
10256 
10257   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10258     return SDValue();
10259 
10260   if (SDValue Res = tryCombineToEXTR(N, DCI))
10261     return Res;
10262 
10263   if (SDValue Res = tryCombineToBSL(N, DCI))
10264     return Res;
10265 
10266   return SDValue();
10267 }
10268 
10269 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10270   if (!MemVT.getVectorElementType().isSimple())
10271     return false;
10272 
10273   uint64_t MaskForTy = 0ull;
10274   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10275   case MVT::i8:
10276     MaskForTy = 0xffull;
10277     break;
10278   case MVT::i16:
10279     MaskForTy = 0xffffull;
10280     break;
10281   case MVT::i32:
10282     MaskForTy = 0xffffffffull;
10283     break;
10284   default:
10285     return false;
10286     break;
10287   }
10288 
10289   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10290     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10291       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10292 
10293   return false;
10294 }
10295 
10296 static SDValue performSVEAndCombine(SDNode *N,
10297                                     TargetLowering::DAGCombinerInfo &DCI) {
10298   if (DCI.isBeforeLegalizeOps())
10299     return SDValue();
10300 
10301   SDValue Src = N->getOperand(0);
10302   SDValue Mask = N->getOperand(1);
10303 
10304   if (!Src.hasOneUse())
10305     return SDValue();
10306 
10307   EVT MemVT;
10308 
10309   // SVE load instructions perform an implicit zero-extend, which makes them
10310   // perfect candidates for combining.
10311   switch (Src->getOpcode()) {
10312   case AArch64ISD::LDNF1:
10313   case AArch64ISD::LDFF1:
10314     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
10315     break;
10316   case AArch64ISD::GLD1:
10317   case AArch64ISD::GLD1_SCALED:
10318   case AArch64ISD::GLD1_SXTW:
10319   case AArch64ISD::GLD1_SXTW_SCALED:
10320   case AArch64ISD::GLD1_UXTW:
10321   case AArch64ISD::GLD1_UXTW_SCALED:
10322   case AArch64ISD::GLD1_IMM:
10323     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10324     break;
10325   default:
10326     return SDValue();
10327   }
10328 
10329   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10330     return Src;
10331 
10332   return SDValue();
10333 }
10334 
10335 static SDValue performANDCombine(SDNode *N,
10336                                  TargetLowering::DAGCombinerInfo &DCI) {
10337   SelectionDAG &DAG = DCI.DAG;
10338   SDValue LHS = N->getOperand(0);
10339   EVT VT = N->getValueType(0);
10340   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10341     return SDValue();
10342 
10343   if (VT.isScalableVector())
10344     return performSVEAndCombine(N, DCI);
10345 
10346   BuildVectorSDNode *BVN =
10347       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10348   if (!BVN)
10349     return SDValue();
10350 
10351   // AND does not accept an immediate, so check if we can use a BIC immediate
10352   // instruction instead. We do this here instead of using a (and x, (mvni imm))
10353   // pattern in isel, because some immediates may be lowered to the preferred
10354   // (and x, (movi imm)) form, even though an mvni representation also exists.
10355   APInt DefBits(VT.getSizeInBits(), 0);
10356   APInt UndefBits(VT.getSizeInBits(), 0);
10357   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10358     SDValue NewOp;
10359 
10360     DefBits = ~DefBits;
10361     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10362                                     DefBits, &LHS)) ||
10363         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10364                                     DefBits, &LHS)))
10365       return NewOp;
10366 
10367     UndefBits = ~UndefBits;
10368     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10369                                     UndefBits, &LHS)) ||
10370         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10371                                     UndefBits, &LHS)))
10372       return NewOp;
10373   }
10374 
10375   return SDValue();
10376 }
10377 
10378 static SDValue performSRLCombine(SDNode *N,
10379                                  TargetLowering::DAGCombinerInfo &DCI) {
10380   SelectionDAG &DAG = DCI.DAG;
10381   EVT VT = N->getValueType(0);
10382   if (VT != MVT::i32 && VT != MVT::i64)
10383     return SDValue();
10384 
10385   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10386   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10387   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10388   SDValue N0 = N->getOperand(0);
10389   if (N0.getOpcode() == ISD::BSWAP) {
10390     SDLoc DL(N);
10391     SDValue N1 = N->getOperand(1);
10392     SDValue N00 = N0.getOperand(0);
10393     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10394       uint64_t ShiftAmt = C->getZExtValue();
10395       if (VT == MVT::i32 && ShiftAmt == 16 &&
10396           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10397         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10398       if (VT == MVT::i64 && ShiftAmt == 32 &&
10399           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10400         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10401     }
10402   }
10403   return SDValue();
10404 }
10405 
10406 static SDValue performConcatVectorsCombine(SDNode *N,
10407                                            TargetLowering::DAGCombinerInfo &DCI,
10408                                            SelectionDAG &DAG) {
10409   SDLoc dl(N);
10410   EVT VT = N->getValueType(0);
10411   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10412 
10413   // Optimize concat_vectors of truncated vectors, where the intermediate
10414   // type is illegal, to avoid said illegality,  e.g.,
10415   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10416   //                          (v2i16 (truncate (v2i64)))))
10417   // ->
10418   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10419   //                                    (v4i32 (bitcast (v2i64))),
10420   //                                    <0, 2, 4, 6>)))
10421   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10422   // on both input and result type, so we might generate worse code.
10423   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10424   if (N->getNumOperands() == 2 &&
10425       N0->getOpcode() == ISD::TRUNCATE &&
10426       N1->getOpcode() == ISD::TRUNCATE) {
10427     SDValue N00 = N0->getOperand(0);
10428     SDValue N10 = N1->getOperand(0);
10429     EVT N00VT = N00.getValueType();
10430 
10431     if (N00VT == N10.getValueType() &&
10432         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10433         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10434       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10435       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10436       for (size_t i = 0; i < Mask.size(); ++i)
10437         Mask[i] = i * 2;
10438       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10439                          DAG.getVectorShuffle(
10440                              MidVT, dl,
10441                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10442                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10443     }
10444   }
10445 
10446   // Wait 'til after everything is legalized to try this. That way we have
10447   // legal vector types and such.
10448   if (DCI.isBeforeLegalizeOps())
10449     return SDValue();
10450 
10451   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10452   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10453   // canonicalise to that.
10454   if (N0 == N1 && VT.getVectorNumElements() == 2) {
10455     assert(VT.getScalarSizeInBits() == 64);
10456     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10457                        DAG.getConstant(0, dl, MVT::i64));
10458   }
10459 
10460   // Canonicalise concat_vectors so that the right-hand vector has as few
10461   // bit-casts as possible before its real operation. The primary matching
10462   // destination for these operations will be the narrowing "2" instructions,
10463   // which depend on the operation being performed on this right-hand vector.
10464   // For example,
10465   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
10466   // becomes
10467   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10468 
10469   if (N1->getOpcode() != ISD::BITCAST)
10470     return SDValue();
10471   SDValue RHS = N1->getOperand(0);
10472   MVT RHSTy = RHS.getValueType().getSimpleVT();
10473   // If the RHS is not a vector, this is not the pattern we're looking for.
10474   if (!RHSTy.isVector())
10475     return SDValue();
10476 
10477   LLVM_DEBUG(
10478       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10479 
10480   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10481                                   RHSTy.getVectorNumElements() * 2);
10482   return DAG.getNode(ISD::BITCAST, dl, VT,
10483                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10484                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10485                                  RHS));
10486 }
10487 
10488 static SDValue tryCombineFixedPointConvert(SDNode *N,
10489                                            TargetLowering::DAGCombinerInfo &DCI,
10490                                            SelectionDAG &DAG) {
10491   // Wait until after everything is legalized to try this. That way we have
10492   // legal vector types and such.
10493   if (DCI.isBeforeLegalizeOps())
10494     return SDValue();
10495   // Transform a scalar conversion of a value from a lane extract into a
10496   // lane extract of a vector conversion. E.g., from foo1 to foo2:
10497   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10498   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10499   //
10500   // The second form interacts better with instruction selection and the
10501   // register allocator to avoid cross-class register copies that aren't
10502   // coalescable due to a lane reference.
10503 
10504   // Check the operand and see if it originates from a lane extract.
10505   SDValue Op1 = N->getOperand(1);
10506   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10507     // Yep, no additional predication needed. Perform the transform.
10508     SDValue IID = N->getOperand(0);
10509     SDValue Shift = N->getOperand(2);
10510     SDValue Vec = Op1.getOperand(0);
10511     SDValue Lane = Op1.getOperand(1);
10512     EVT ResTy = N->getValueType(0);
10513     EVT VecResTy;
10514     SDLoc DL(N);
10515 
10516     // The vector width should be 128 bits by the time we get here, even
10517     // if it started as 64 bits (the extract_vector handling will have
10518     // done so).
10519     assert(Vec.getValueSizeInBits() == 128 &&
10520            "unexpected vector size on extract_vector_elt!");
10521     if (Vec.getValueType() == MVT::v4i32)
10522       VecResTy = MVT::v4f32;
10523     else if (Vec.getValueType() == MVT::v2i64)
10524       VecResTy = MVT::v2f64;
10525     else
10526       llvm_unreachable("unexpected vector type!");
10527 
10528     SDValue Convert =
10529         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10530     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10531   }
10532   return SDValue();
10533 }
10534 
10535 // AArch64 high-vector "long" operations are formed by performing the non-high
10536 // version on an extract_subvector of each operand which gets the high half:
10537 //
10538 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10539 //
10540 // However, there are cases which don't have an extract_high explicitly, but
10541 // have another operation that can be made compatible with one for free. For
10542 // example:
10543 //
10544 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
10545 //
10546 // This routine does the actual conversion of such DUPs, once outer routines
10547 // have determined that everything else is in order.
10548 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10549 // similarly here.
10550 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10551   switch (N.getOpcode()) {
10552   case AArch64ISD::DUP:
10553   case AArch64ISD::DUPLANE8:
10554   case AArch64ISD::DUPLANE16:
10555   case AArch64ISD::DUPLANE32:
10556   case AArch64ISD::DUPLANE64:
10557   case AArch64ISD::MOVI:
10558   case AArch64ISD::MOVIshift:
10559   case AArch64ISD::MOVIedit:
10560   case AArch64ISD::MOVImsl:
10561   case AArch64ISD::MVNIshift:
10562   case AArch64ISD::MVNImsl:
10563     break;
10564   default:
10565     // FMOV could be supported, but isn't very useful, as it would only occur
10566     // if you passed a bitcast' floating point immediate to an eligible long
10567     // integer op (addl, smull, ...).
10568     return SDValue();
10569   }
10570 
10571   MVT NarrowTy = N.getSimpleValueType();
10572   if (!NarrowTy.is64BitVector())
10573     return SDValue();
10574 
10575   MVT ElementTy = NarrowTy.getVectorElementType();
10576   unsigned NumElems = NarrowTy.getVectorNumElements();
10577   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10578 
10579   SDLoc dl(N);
10580   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10581                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10582                      DAG.getConstant(NumElems, dl, MVT::i64));
10583 }
10584 
10585 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10586   if (N.getOpcode() == ISD::BITCAST)
10587     N = N.getOperand(0);
10588   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10589     return false;
10590   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10591          N.getOperand(0).getValueType().getVectorNumElements() / 2;
10592 }
10593 
10594 /// Helper structure to keep track of ISD::SET_CC operands.
10595 struct GenericSetCCInfo {
10596   const SDValue *Opnd0;
10597   const SDValue *Opnd1;
10598   ISD::CondCode CC;
10599 };
10600 
10601 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10602 struct AArch64SetCCInfo {
10603   const SDValue *Cmp;
10604   AArch64CC::CondCode CC;
10605 };
10606 
10607 /// Helper structure to keep track of SetCC information.
10608 union SetCCInfo {
10609   GenericSetCCInfo Generic;
10610   AArch64SetCCInfo AArch64;
10611 };
10612 
10613 /// Helper structure to be able to read SetCC information.  If set to
10614 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10615 /// GenericSetCCInfo.
10616 struct SetCCInfoAndKind {
10617   SetCCInfo Info;
10618   bool IsAArch64;
10619 };
10620 
10621 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10622 /// an
10623 /// AArch64 lowered one.
10624 /// \p SetCCInfo is filled accordingly.
10625 /// \post SetCCInfo is meanginfull only when this function returns true.
10626 /// \return True when Op is a kind of SET_CC operation.
10627 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10628   // If this is a setcc, this is straight forward.
10629   if (Op.getOpcode() == ISD::SETCC) {
10630     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10631     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10632     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10633     SetCCInfo.IsAArch64 = false;
10634     return true;
10635   }
10636   // Otherwise, check if this is a matching csel instruction.
10637   // In other words:
10638   // - csel 1, 0, cc
10639   // - csel 0, 1, !cc
10640   if (Op.getOpcode() != AArch64ISD::CSEL)
10641     return false;
10642   // Set the information about the operands.
10643   // TODO: we want the operands of the Cmp not the csel
10644   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10645   SetCCInfo.IsAArch64 = true;
10646   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10647       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10648 
10649   // Check that the operands matches the constraints:
10650   // (1) Both operands must be constants.
10651   // (2) One must be 1 and the other must be 0.
10652   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10653   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10654 
10655   // Check (1).
10656   if (!TValue || !FValue)
10657     return false;
10658 
10659   // Check (2).
10660   if (!TValue->isOne()) {
10661     // Update the comparison when we are interested in !cc.
10662     std::swap(TValue, FValue);
10663     SetCCInfo.Info.AArch64.CC =
10664         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10665   }
10666   return TValue->isOne() && FValue->isNullValue();
10667 }
10668 
10669 // Returns true if Op is setcc or zext of setcc.
10670 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10671   if (isSetCC(Op, Info))
10672     return true;
10673   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10674     isSetCC(Op->getOperand(0), Info));
10675 }
10676 
10677 // The folding we want to perform is:
10678 // (add x, [zext] (setcc cc ...) )
10679 //   -->
10680 // (csel x, (add x, 1), !cc ...)
10681 //
10682 // The latter will get matched to a CSINC instruction.
10683 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10684   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10685   SDValue LHS = Op->getOperand(0);
10686   SDValue RHS = Op->getOperand(1);
10687   SetCCInfoAndKind InfoAndKind;
10688 
10689   // If neither operand is a SET_CC, give up.
10690   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10691     std::swap(LHS, RHS);
10692     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10693       return SDValue();
10694   }
10695 
10696   // FIXME: This could be generatized to work for FP comparisons.
10697   EVT CmpVT = InfoAndKind.IsAArch64
10698                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10699                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10700   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10701     return SDValue();
10702 
10703   SDValue CCVal;
10704   SDValue Cmp;
10705   SDLoc dl(Op);
10706   if (InfoAndKind.IsAArch64) {
10707     CCVal = DAG.getConstant(
10708         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10709         MVT::i32);
10710     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10711   } else
10712     Cmp = getAArch64Cmp(
10713         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10714         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10715         dl);
10716 
10717   EVT VT = Op->getValueType(0);
10718   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10719   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10720 }
10721 
10722 // The basic add/sub long vector instructions have variants with "2" on the end
10723 // which act on the high-half of their inputs. They are normally matched by
10724 // patterns like:
10725 //
10726 // (add (zeroext (extract_high LHS)),
10727 //      (zeroext (extract_high RHS)))
10728 // -> uaddl2 vD, vN, vM
10729 //
10730 // However, if one of the extracts is something like a duplicate, this
10731 // instruction can still be used profitably. This function puts the DAG into a
10732 // more appropriate form for those patterns to trigger.
10733 static SDValue performAddSubLongCombine(SDNode *N,
10734                                         TargetLowering::DAGCombinerInfo &DCI,
10735                                         SelectionDAG &DAG) {
10736   if (DCI.isBeforeLegalizeOps())
10737     return SDValue();
10738 
10739   MVT VT = N->getSimpleValueType(0);
10740   if (!VT.is128BitVector()) {
10741     if (N->getOpcode() == ISD::ADD)
10742       return performSetccAddFolding(N, DAG);
10743     return SDValue();
10744   }
10745 
10746   // Make sure both branches are extended in the same way.
10747   SDValue LHS = N->getOperand(0);
10748   SDValue RHS = N->getOperand(1);
10749   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10750        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10751       LHS.getOpcode() != RHS.getOpcode())
10752     return SDValue();
10753 
10754   unsigned ExtType = LHS.getOpcode();
10755 
10756   // It's not worth doing if at least one of the inputs isn't already an
10757   // extract, but we don't know which it'll be so we have to try both.
10758   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10759     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10760     if (!RHS.getNode())
10761       return SDValue();
10762 
10763     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10764   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10765     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10766     if (!LHS.getNode())
10767       return SDValue();
10768 
10769     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10770   }
10771 
10772   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10773 }
10774 
10775 // Massage DAGs which we can use the high-half "long" operations on into
10776 // something isel will recognize better. E.g.
10777 //
10778 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10779 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10780 //                     (extract_high (v2i64 (dup128 scalar)))))
10781 //
10782 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10783                                        TargetLowering::DAGCombinerInfo &DCI,
10784                                        SelectionDAG &DAG) {
10785   if (DCI.isBeforeLegalizeOps())
10786     return SDValue();
10787 
10788   SDValue LHS = N->getOperand(1);
10789   SDValue RHS = N->getOperand(2);
10790   assert(LHS.getValueType().is64BitVector() &&
10791          RHS.getValueType().is64BitVector() &&
10792          "unexpected shape for long operation");
10793 
10794   // Either node could be a DUP, but it's not worth doing both of them (you'd
10795   // just as well use the non-high version) so look for a corresponding extract
10796   // operation on the other "wing".
10797   if (isEssentiallyExtractHighSubvector(LHS)) {
10798     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10799     if (!RHS.getNode())
10800       return SDValue();
10801   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10802     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10803     if (!LHS.getNode())
10804       return SDValue();
10805   }
10806 
10807   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10808                      N->getOperand(0), LHS, RHS);
10809 }
10810 
10811 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10812   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10813   unsigned ElemBits = ElemTy.getSizeInBits();
10814 
10815   int64_t ShiftAmount;
10816   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10817     APInt SplatValue, SplatUndef;
10818     unsigned SplatBitSize;
10819     bool HasAnyUndefs;
10820     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10821                               HasAnyUndefs, ElemBits) ||
10822         SplatBitSize != ElemBits)
10823       return SDValue();
10824 
10825     ShiftAmount = SplatValue.getSExtValue();
10826   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10827     ShiftAmount = CVN->getSExtValue();
10828   } else
10829     return SDValue();
10830 
10831   unsigned Opcode;
10832   bool IsRightShift;
10833   switch (IID) {
10834   default:
10835     llvm_unreachable("Unknown shift intrinsic");
10836   case Intrinsic::aarch64_neon_sqshl:
10837     Opcode = AArch64ISD::SQSHL_I;
10838     IsRightShift = false;
10839     break;
10840   case Intrinsic::aarch64_neon_uqshl:
10841     Opcode = AArch64ISD::UQSHL_I;
10842     IsRightShift = false;
10843     break;
10844   case Intrinsic::aarch64_neon_srshl:
10845     Opcode = AArch64ISD::SRSHR_I;
10846     IsRightShift = true;
10847     break;
10848   case Intrinsic::aarch64_neon_urshl:
10849     Opcode = AArch64ISD::URSHR_I;
10850     IsRightShift = true;
10851     break;
10852   case Intrinsic::aarch64_neon_sqshlu:
10853     Opcode = AArch64ISD::SQSHLU_I;
10854     IsRightShift = false;
10855     break;
10856   case Intrinsic::aarch64_neon_sshl:
10857   case Intrinsic::aarch64_neon_ushl:
10858     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10859     // left shift for positive shift amounts. Below, we only replace the current
10860     // node with VSHL, if this condition is met.
10861     Opcode = AArch64ISD::VSHL;
10862     IsRightShift = false;
10863     break;
10864   }
10865 
10866   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10867     SDLoc dl(N);
10868     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10869                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10870   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10871     SDLoc dl(N);
10872     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10873                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
10874   }
10875 
10876   return SDValue();
10877 }
10878 
10879 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10880 // the intrinsics must be legal and take an i32, this means there's almost
10881 // certainly going to be a zext in the DAG which we can eliminate.
10882 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10883   SDValue AndN = N->getOperand(2);
10884   if (AndN.getOpcode() != ISD::AND)
10885     return SDValue();
10886 
10887   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10888   if (!CMask || CMask->getZExtValue() != Mask)
10889     return SDValue();
10890 
10891   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10892                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10893 }
10894 
10895 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10896                                            SelectionDAG &DAG) {
10897   SDLoc dl(N);
10898   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10899                      DAG.getNode(Opc, dl,
10900                                  N->getOperand(1).getSimpleValueType(),
10901                                  N->getOperand(1)),
10902                      DAG.getConstant(0, dl, MVT::i64));
10903 }
10904 
10905 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
10906                                     SelectionDAG &DAG) {
10907   SDLoc dl(N);
10908   LLVMContext &Ctx = *DAG.getContext();
10909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10910 
10911   EVT VT = N->getValueType(0);
10912   SDValue Pred = N->getOperand(1);
10913   SDValue Data = N->getOperand(2);
10914   EVT DataVT = Data.getValueType();
10915 
10916   if (DataVT.getVectorElementType().isScalarInteger() &&
10917       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
10918     if (!TLI.isTypeLegal(DataVT))
10919       return SDValue();
10920 
10921     EVT OutputVT = EVT::getVectorVT(Ctx, VT,
10922       AArch64::NeonBitsPerVector / VT.getSizeInBits());
10923     SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
10924     SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
10925     SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
10926 
10927     return Result;
10928   }
10929 
10930   return SDValue();
10931 }
10932 
10933 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
10934   SDLoc dl(N);
10935   LLVMContext &Ctx = *DAG.getContext();
10936   EVT VT = N->getValueType(0);
10937 
10938   assert(VT.isScalableVector() && "Expected a scalable vector.");
10939 
10940   // Current lowering only supports the SVE-ACLE types.
10941   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
10942     return SDValue();
10943 
10944   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
10945   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
10946   EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
10947 
10948   // Convert everything to the domain of EXT (i.e bytes).
10949   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
10950   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
10951   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
10952                             DAG.getConstant(ElemSize, dl, MVT::i32));
10953 
10954   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
10955   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
10956 }
10957 
10958 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
10959                                         bool Invert,
10960                                         TargetLowering::DAGCombinerInfo &DCI,
10961                                         SelectionDAG &DAG) {
10962   if (DCI.isBeforeLegalize())
10963     return SDValue();
10964 
10965   SDValue Comparator = N->getOperand(3);
10966   if (Comparator.getOpcode() == AArch64ISD::DUP ||
10967       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
10968     unsigned IID = getIntrinsicID(N);
10969     EVT VT = N->getValueType(0);
10970     EVT CmpVT = N->getOperand(2).getValueType();
10971     SDValue Pred = N->getOperand(1);
10972     SDValue Imm;
10973     SDLoc DL(N);
10974 
10975     switch (IID) {
10976     default:
10977       llvm_unreachable("Called with wrong intrinsic!");
10978       break;
10979 
10980     // Signed comparisons
10981     case Intrinsic::aarch64_sve_cmpeq_wide:
10982     case Intrinsic::aarch64_sve_cmpne_wide:
10983     case Intrinsic::aarch64_sve_cmpge_wide:
10984     case Intrinsic::aarch64_sve_cmpgt_wide:
10985     case Intrinsic::aarch64_sve_cmplt_wide:
10986     case Intrinsic::aarch64_sve_cmple_wide: {
10987       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10988         int64_t ImmVal = CN->getSExtValue();
10989         if (ImmVal >= -16 && ImmVal <= 15)
10990           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10991         else
10992           return SDValue();
10993       }
10994       break;
10995     }
10996     // Unsigned comparisons
10997     case Intrinsic::aarch64_sve_cmphs_wide:
10998     case Intrinsic::aarch64_sve_cmphi_wide:
10999     case Intrinsic::aarch64_sve_cmplo_wide:
11000     case Intrinsic::aarch64_sve_cmpls_wide:  {
11001       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11002         uint64_t ImmVal = CN->getZExtValue();
11003         if (ImmVal <= 127)
11004           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11005         else
11006           return SDValue();
11007       }
11008       break;
11009     }
11010     }
11011 
11012     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11013     SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
11014     SDValue Op0, Op1;
11015     if (Invert) {
11016       Op0 = Splat;
11017       Op1 = N->getOperand(2);
11018     } else {
11019       Op0 = N->getOperand(2);
11020       Op1 = Splat;
11021     }
11022     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11023                        ID, Pred, Op0, Op1);
11024   }
11025 
11026   return SDValue();
11027 }
11028 
11029 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11030                         AArch64CC::CondCode Cond) {
11031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11032 
11033   SDLoc DL(Op);
11034   assert(Op.getValueType().isScalableVector() &&
11035          TLI.isTypeLegal(Op.getValueType()) &&
11036          "Expected legal scalable vector type!");
11037 
11038   // Ensure target specific opcodes are using legal type.
11039   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11040   SDValue TVal = DAG.getConstant(1, DL, OutVT);
11041   SDValue FVal = DAG.getConstant(0, DL, OutVT);
11042 
11043   // Set condition code (CC) flags.
11044   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11045 
11046   // Convert CC to integer based on requested condition.
11047   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11048   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11049   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11050   return DAG.getZExtOrTrunc(Res, DL, VT);
11051 }
11052 
11053 static SDValue performIntrinsicCombine(SDNode *N,
11054                                        TargetLowering::DAGCombinerInfo &DCI,
11055                                        const AArch64Subtarget *Subtarget) {
11056   SelectionDAG &DAG = DCI.DAG;
11057   unsigned IID = getIntrinsicID(N);
11058   switch (IID) {
11059   default:
11060     break;
11061   case Intrinsic::aarch64_neon_vcvtfxs2fp:
11062   case Intrinsic::aarch64_neon_vcvtfxu2fp:
11063     return tryCombineFixedPointConvert(N, DCI, DAG);
11064   case Intrinsic::aarch64_neon_saddv:
11065     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11066   case Intrinsic::aarch64_neon_uaddv:
11067     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11068   case Intrinsic::aarch64_neon_sminv:
11069     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11070   case Intrinsic::aarch64_neon_uminv:
11071     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11072   case Intrinsic::aarch64_neon_smaxv:
11073     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11074   case Intrinsic::aarch64_neon_umaxv:
11075     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11076   case Intrinsic::aarch64_neon_fmax:
11077     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11078                        N->getOperand(1), N->getOperand(2));
11079   case Intrinsic::aarch64_neon_fmin:
11080     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11081                        N->getOperand(1), N->getOperand(2));
11082   case Intrinsic::aarch64_neon_fmaxnm:
11083     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11084                        N->getOperand(1), N->getOperand(2));
11085   case Intrinsic::aarch64_neon_fminnm:
11086     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11087                        N->getOperand(1), N->getOperand(2));
11088   case Intrinsic::aarch64_neon_smull:
11089   case Intrinsic::aarch64_neon_umull:
11090   case Intrinsic::aarch64_neon_pmull:
11091   case Intrinsic::aarch64_neon_sqdmull:
11092     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11093   case Intrinsic::aarch64_neon_sqshl:
11094   case Intrinsic::aarch64_neon_uqshl:
11095   case Intrinsic::aarch64_neon_sqshlu:
11096   case Intrinsic::aarch64_neon_srshl:
11097   case Intrinsic::aarch64_neon_urshl:
11098   case Intrinsic::aarch64_neon_sshl:
11099   case Intrinsic::aarch64_neon_ushl:
11100     return tryCombineShiftImm(IID, N, DAG);
11101   case Intrinsic::aarch64_crc32b:
11102   case Intrinsic::aarch64_crc32cb:
11103     return tryCombineCRC32(0xff, N, DAG);
11104   case Intrinsic::aarch64_crc32h:
11105   case Intrinsic::aarch64_crc32ch:
11106     return tryCombineCRC32(0xffff, N, DAG);
11107   case Intrinsic::aarch64_sve_smaxv:
11108     return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11109   case Intrinsic::aarch64_sve_umaxv:
11110     return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11111   case Intrinsic::aarch64_sve_sminv:
11112     return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11113   case Intrinsic::aarch64_sve_uminv:
11114     return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11115   case Intrinsic::aarch64_sve_orv:
11116     return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11117   case Intrinsic::aarch64_sve_eorv:
11118     return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11119   case Intrinsic::aarch64_sve_andv:
11120     return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11121   case Intrinsic::aarch64_sve_ext:
11122     return LowerSVEIntrinsicEXT(N, DAG);
11123   case Intrinsic::aarch64_sve_cmpeq_wide:
11124     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
11125                                     false, DCI, DAG);
11126   case Intrinsic::aarch64_sve_cmpne_wide:
11127     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
11128                                     false, DCI, DAG);
11129   case Intrinsic::aarch64_sve_cmpge_wide:
11130     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11131                                     false, DCI, DAG);
11132   case Intrinsic::aarch64_sve_cmpgt_wide:
11133     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11134                                     false, DCI, DAG);
11135   case Intrinsic::aarch64_sve_cmplt_wide:
11136     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11137                                     true, DCI, DAG);
11138   case Intrinsic::aarch64_sve_cmple_wide:
11139     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11140                                     true, DCI, DAG);
11141   case Intrinsic::aarch64_sve_cmphs_wide:
11142     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11143                                     false, DCI, DAG);
11144   case Intrinsic::aarch64_sve_cmphi_wide:
11145     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11146                                     false, DCI, DAG);
11147   case Intrinsic::aarch64_sve_cmplo_wide:
11148     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11149                                     DCI, DAG);
11150   case Intrinsic::aarch64_sve_cmpls_wide:
11151     return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11152                                     DCI, DAG);
11153   case Intrinsic::aarch64_sve_ptest_any:
11154     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11155                     AArch64CC::ANY_ACTIVE);
11156   case Intrinsic::aarch64_sve_ptest_first:
11157     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11158                     AArch64CC::FIRST_ACTIVE);
11159   case Intrinsic::aarch64_sve_ptest_last:
11160     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11161                     AArch64CC::LAST_ACTIVE);
11162   }
11163   return SDValue();
11164 }
11165 
11166 static SDValue performExtendCombine(SDNode *N,
11167                                     TargetLowering::DAGCombinerInfo &DCI,
11168                                     SelectionDAG &DAG) {
11169   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11170   // we can convert that DUP into another extract_high (of a bigger DUP), which
11171   // helps the backend to decide that an sabdl2 would be useful, saving a real
11172   // extract_high operation.
11173   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11174       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11175     SDNode *ABDNode = N->getOperand(0).getNode();
11176     unsigned IID = getIntrinsicID(ABDNode);
11177     if (IID == Intrinsic::aarch64_neon_sabd ||
11178         IID == Intrinsic::aarch64_neon_uabd) {
11179       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11180       if (!NewABD.getNode())
11181         return SDValue();
11182 
11183       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11184                          NewABD);
11185     }
11186   }
11187 
11188   // This is effectively a custom type legalization for AArch64.
11189   //
11190   // Type legalization will split an extend of a small, legal, type to a larger
11191   // illegal type by first splitting the destination type, often creating
11192   // illegal source types, which then get legalized in isel-confusing ways,
11193   // leading to really terrible codegen. E.g.,
11194   //   %result = v8i32 sext v8i8 %value
11195   // becomes
11196   //   %losrc = extract_subreg %value, ...
11197   //   %hisrc = extract_subreg %value, ...
11198   //   %lo = v4i32 sext v4i8 %losrc
11199   //   %hi = v4i32 sext v4i8 %hisrc
11200   // Things go rapidly downhill from there.
11201   //
11202   // For AArch64, the [sz]ext vector instructions can only go up one element
11203   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11204   // take two instructions.
11205   //
11206   // This implies that the most efficient way to do the extend from v8i8
11207   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11208   // the normal splitting to happen for the v8i16->v8i32.
11209 
11210   // This is pre-legalization to catch some cases where the default
11211   // type legalization will create ill-tempered code.
11212   if (!DCI.isBeforeLegalizeOps())
11213     return SDValue();
11214 
11215   // We're only interested in cleaning things up for non-legal vector types
11216   // here. If both the source and destination are legal, things will just
11217   // work naturally without any fiddling.
11218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11219   EVT ResVT = N->getValueType(0);
11220   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11221     return SDValue();
11222   // If the vector type isn't a simple VT, it's beyond the scope of what
11223   // we're  worried about here. Let legalization do its thing and hope for
11224   // the best.
11225   SDValue Src = N->getOperand(0);
11226   EVT SrcVT = Src->getValueType(0);
11227   if (!ResVT.isSimple() || !SrcVT.isSimple())
11228     return SDValue();
11229 
11230   // If the source VT is a 64-bit vector, we can play games and get the
11231   // better results we want.
11232   if (SrcVT.getSizeInBits() != 64)
11233     return SDValue();
11234 
11235   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11236   unsigned ElementCount = SrcVT.getVectorNumElements();
11237   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11238   SDLoc DL(N);
11239   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11240 
11241   // Now split the rest of the operation into two halves, each with a 64
11242   // bit source.
11243   EVT LoVT, HiVT;
11244   SDValue Lo, Hi;
11245   unsigned NumElements = ResVT.getVectorNumElements();
11246   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11247   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11248                                  ResVT.getVectorElementType(), NumElements / 2);
11249 
11250   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11251                                LoVT.getVectorNumElements());
11252   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11253                    DAG.getConstant(0, DL, MVT::i64));
11254   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11255                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11256   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11257   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11258 
11259   // Now combine the parts back together so we still have a single result
11260   // like the combiner expects.
11261   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11262 }
11263 
11264 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11265                                SDValue SplatVal, unsigned NumVecElts) {
11266   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11267   unsigned OrigAlignment = St.getAlignment();
11268   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11269 
11270   // Create scalar stores. This is at least as good as the code sequence for a
11271   // split unaligned store which is a dup.s, ext.b, and two stores.
11272   // Most of the time the three stores should be replaced by store pair
11273   // instructions (stp).
11274   SDLoc DL(&St);
11275   SDValue BasePtr = St.getBasePtr();
11276   uint64_t BaseOffset = 0;
11277 
11278   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11279   SDValue NewST1 =
11280       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11281                    OrigAlignment, St.getMemOperand()->getFlags());
11282 
11283   // As this in ISel, we will not merge this add which may degrade results.
11284   if (BasePtr->getOpcode() == ISD::ADD &&
11285       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11286     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11287     BasePtr = BasePtr->getOperand(0);
11288   }
11289 
11290   unsigned Offset = EltOffset;
11291   while (--NumVecElts) {
11292     unsigned Alignment = MinAlign(OrigAlignment, Offset);
11293     SDValue OffsetPtr =
11294         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11295                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11296     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11297                           PtrInfo.getWithOffset(Offset), Alignment,
11298                           St.getMemOperand()->getFlags());
11299     Offset += EltOffset;
11300   }
11301   return NewST1;
11302 }
11303 
11304 // Returns an SVE type that ContentTy can be trivially sign or zero extended
11305 // into.
11306 static MVT getSVEContainerType(EVT ContentTy) {
11307   assert(ContentTy.isSimple() && "No SVE containers for extended types");
11308 
11309   switch (ContentTy.getSimpleVT().SimpleTy) {
11310   default:
11311     llvm_unreachable("No known SVE container for this MVT type");
11312   case MVT::nxv2i8:
11313   case MVT::nxv2i16:
11314   case MVT::nxv2i32:
11315   case MVT::nxv2i64:
11316   case MVT::nxv2f32:
11317   case MVT::nxv2f64:
11318     return MVT::nxv2i64;
11319   case MVT::nxv4i8:
11320   case MVT::nxv4i16:
11321   case MVT::nxv4i32:
11322   case MVT::nxv4f32:
11323     return MVT::nxv4i32;
11324   case MVT::nxv8i8:
11325   case MVT::nxv8i16:
11326   case MVT::nxv8f16:
11327     return MVT::nxv8i16;
11328   case MVT::nxv16i8:
11329     return MVT::nxv16i8;
11330   }
11331 }
11332 
11333 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
11334   SDLoc DL(N);
11335   EVT VT = N->getValueType(0);
11336   EVT PtrTy = N->getOperand(3).getValueType();
11337 
11338   EVT LoadVT = VT;
11339   if (VT.isFloatingPoint())
11340     LoadVT = VT.changeTypeToInteger();
11341 
11342   auto *MINode = cast<MemIntrinsicSDNode>(N);
11343   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11344   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11345                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11346                                 MINode->getOperand(2), PassThru,
11347                                 MINode->getMemoryVT(), MINode->getMemOperand(),
11348                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11349 
11350    if (VT.isFloatingPoint()) {
11351      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11352      return DAG.getMergeValues(Ops, DL);
11353    }
11354 
11355   return L;
11356 }
11357 
11358 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
11359   SDLoc DL(N);
11360 
11361   SDValue Data = N->getOperand(2);
11362   EVT DataVT = Data.getValueType();
11363   EVT PtrTy = N->getOperand(4).getValueType();
11364 
11365   if (DataVT.isFloatingPoint())
11366     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11367 
11368   auto *MINode = cast<MemIntrinsicSDNode>(N);
11369   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11370                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11371                             MINode->getMemoryVT(), MINode->getMemOperand(),
11372                             ISD::UNINDEXED, false, false);
11373 }
11374 
11375 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
11376   SDLoc DL(N);
11377   EVT VT = N->getValueType(0);
11378 
11379   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
11380     return SDValue();
11381 
11382   EVT ContainerVT = VT;
11383   if (ContainerVT.isInteger())
11384     ContainerVT = getSVEContainerType(ContainerVT);
11385 
11386   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
11387   SDValue Ops[] = { N->getOperand(0), // Chain
11388                     N->getOperand(2), // Pg
11389                     N->getOperand(3), // Base
11390                     DAG.getValueType(VT) };
11391 
11392   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
11393   SDValue LoadChain = SDValue(Load.getNode(), 1);
11394 
11395   if (ContainerVT.isInteger() && (VT != ContainerVT))
11396     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
11397 
11398   return DAG.getMergeValues({ Load, LoadChain }, DL);
11399 }
11400 
11401 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
11402 /// load store optimizer pass will merge them to store pair stores.  This should
11403 /// be better than a movi to create the vector zero followed by a vector store
11404 /// if the zero constant is not re-used, since one instructions and one register
11405 /// live range will be removed.
11406 ///
11407 /// For example, the final generated code should be:
11408 ///
11409 ///   stp xzr, xzr, [x0]
11410 ///
11411 /// instead of:
11412 ///
11413 ///   movi v0.2d, #0
11414 ///   str q0, [x0]
11415 ///
11416 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11417   SDValue StVal = St.getValue();
11418   EVT VT = StVal.getValueType();
11419 
11420   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11421   // 2, 3 or 4 i32 elements.
11422   int NumVecElts = VT.getVectorNumElements();
11423   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11424          VT.getVectorElementType().getSizeInBits() == 64) ||
11425         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11426          VT.getVectorElementType().getSizeInBits() == 32)))
11427     return SDValue();
11428 
11429   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11430     return SDValue();
11431 
11432   // If the zero constant has more than one use then the vector store could be
11433   // better since the constant mov will be amortized and stp q instructions
11434   // should be able to be formed.
11435   if (!StVal.hasOneUse())
11436     return SDValue();
11437 
11438   // If the store is truncating then it's going down to i16 or smaller, which
11439   // means it can be implemented in a single store anyway.
11440   if (St.isTruncatingStore())
11441     return SDValue();
11442 
11443   // If the immediate offset of the address operand is too large for the stp
11444   // instruction, then bail out.
11445   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11446     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11447     if (Offset < -512 || Offset > 504)
11448       return SDValue();
11449   }
11450 
11451   for (int I = 0; I < NumVecElts; ++I) {
11452     SDValue EltVal = StVal.getOperand(I);
11453     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11454       return SDValue();
11455   }
11456 
11457   // Use a CopyFromReg WZR/XZR here to prevent
11458   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11459   SDLoc DL(&St);
11460   unsigned ZeroReg;
11461   EVT ZeroVT;
11462   if (VT.getVectorElementType().getSizeInBits() == 32) {
11463     ZeroReg = AArch64::WZR;
11464     ZeroVT = MVT::i32;
11465   } else {
11466     ZeroReg = AArch64::XZR;
11467     ZeroVT = MVT::i64;
11468   }
11469   SDValue SplatVal =
11470       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11471   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11472 }
11473 
11474 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11475 /// value. The load store optimizer pass will merge them to store pair stores.
11476 /// This has better performance than a splat of the scalar followed by a split
11477 /// vector store. Even if the stores are not merged it is four stores vs a dup,
11478 /// followed by an ext.b and two stores.
11479 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11480   SDValue StVal = St.getValue();
11481   EVT VT = StVal.getValueType();
11482 
11483   // Don't replace floating point stores, they possibly won't be transformed to
11484   // stp because of the store pair suppress pass.
11485   if (VT.isFloatingPoint())
11486     return SDValue();
11487 
11488   // We can express a splat as store pair(s) for 2 or 4 elements.
11489   unsigned NumVecElts = VT.getVectorNumElements();
11490   if (NumVecElts != 4 && NumVecElts != 2)
11491     return SDValue();
11492 
11493   // If the store is truncating then it's going down to i16 or smaller, which
11494   // means it can be implemented in a single store anyway.
11495   if (St.isTruncatingStore())
11496     return SDValue();
11497 
11498   // Check that this is a splat.
11499   // Make sure that each of the relevant vector element locations are inserted
11500   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11501   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11502   SDValue SplatVal;
11503   for (unsigned I = 0; I < NumVecElts; ++I) {
11504     // Check for insert vector elements.
11505     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11506       return SDValue();
11507 
11508     // Check that same value is inserted at each vector element.
11509     if (I == 0)
11510       SplatVal = StVal.getOperand(1);
11511     else if (StVal.getOperand(1) != SplatVal)
11512       return SDValue();
11513 
11514     // Check insert element index.
11515     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11516     if (!CIndex)
11517       return SDValue();
11518     uint64_t IndexVal = CIndex->getZExtValue();
11519     if (IndexVal >= NumVecElts)
11520       return SDValue();
11521     IndexNotInserted.reset(IndexVal);
11522 
11523     StVal = StVal.getOperand(0);
11524   }
11525   // Check that all vector element locations were inserted to.
11526   if (IndexNotInserted.any())
11527       return SDValue();
11528 
11529   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11530 }
11531 
11532 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11533                            SelectionDAG &DAG,
11534                            const AArch64Subtarget *Subtarget) {
11535 
11536   StoreSDNode *S = cast<StoreSDNode>(N);
11537   if (S->isVolatile() || S->isIndexed())
11538     return SDValue();
11539 
11540   SDValue StVal = S->getValue();
11541   EVT VT = StVal.getValueType();
11542   if (!VT.isVector())
11543     return SDValue();
11544 
11545   // If we get a splat of zeros, convert this vector store to a store of
11546   // scalars. They will be merged into store pairs of xzr thereby removing one
11547   // instruction and one register.
11548   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11549     return ReplacedZeroSplat;
11550 
11551   // FIXME: The logic for deciding if an unaligned store should be split should
11552   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11553   // a call to that function here.
11554 
11555   if (!Subtarget->isMisaligned128StoreSlow())
11556     return SDValue();
11557 
11558   // Don't split at -Oz.
11559   if (DAG.getMachineFunction().getFunction().hasMinSize())
11560     return SDValue();
11561 
11562   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11563   // those up regresses performance on micro-benchmarks and olden/bh.
11564   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11565     return SDValue();
11566 
11567   // Split unaligned 16B stores. They are terrible for performance.
11568   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11569   // extensions can use this to mark that it does not want splitting to happen
11570   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11571   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11572   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11573       S->getAlignment() <= 2)
11574     return SDValue();
11575 
11576   // If we get a splat of a scalar convert this vector store to a store of
11577   // scalars. They will be merged into store pairs thereby removing two
11578   // instructions.
11579   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11580     return ReplacedSplat;
11581 
11582   SDLoc DL(S);
11583 
11584   // Split VT into two.
11585   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11586   unsigned NumElts = HalfVT.getVectorNumElements();
11587   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11588                                    DAG.getConstant(0, DL, MVT::i64));
11589   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11590                                    DAG.getConstant(NumElts, DL, MVT::i64));
11591   SDValue BasePtr = S->getBasePtr();
11592   SDValue NewST1 =
11593       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11594                    S->getAlignment(), S->getMemOperand()->getFlags());
11595   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11596                                   DAG.getConstant(8, DL, MVT::i64));
11597   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11598                       S->getPointerInfo(), S->getAlignment(),
11599                       S->getMemOperand()->getFlags());
11600 }
11601 
11602 /// Target-specific DAG combine function for post-increment LD1 (lane) and
11603 /// post-increment LD1R.
11604 static SDValue performPostLD1Combine(SDNode *N,
11605                                      TargetLowering::DAGCombinerInfo &DCI,
11606                                      bool IsLaneOp) {
11607   if (DCI.isBeforeLegalizeOps())
11608     return SDValue();
11609 
11610   SelectionDAG &DAG = DCI.DAG;
11611   EVT VT = N->getValueType(0);
11612 
11613   unsigned LoadIdx = IsLaneOp ? 1 : 0;
11614   SDNode *LD = N->getOperand(LoadIdx).getNode();
11615   // If it is not LOAD, can not do such combine.
11616   if (LD->getOpcode() != ISD::LOAD)
11617     return SDValue();
11618 
11619   // The vector lane must be a constant in the LD1LANE opcode.
11620   SDValue Lane;
11621   if (IsLaneOp) {
11622     Lane = N->getOperand(2);
11623     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11624     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11625       return SDValue();
11626   }
11627 
11628   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11629   EVT MemVT = LoadSDN->getMemoryVT();
11630   // Check if memory operand is the same type as the vector element.
11631   if (MemVT != VT.getVectorElementType())
11632     return SDValue();
11633 
11634   // Check if there are other uses. If so, do not combine as it will introduce
11635   // an extra load.
11636   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11637        ++UI) {
11638     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11639       continue;
11640     if (*UI != N)
11641       return SDValue();
11642   }
11643 
11644   SDValue Addr = LD->getOperand(1);
11645   SDValue Vector = N->getOperand(0);
11646   // Search for a use of the address operand that is an increment.
11647   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11648        Addr.getNode()->use_end(); UI != UE; ++UI) {
11649     SDNode *User = *UI;
11650     if (User->getOpcode() != ISD::ADD
11651         || UI.getUse().getResNo() != Addr.getResNo())
11652       continue;
11653 
11654     // If the increment is a constant, it must match the memory ref size.
11655     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11656     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11657       uint32_t IncVal = CInc->getZExtValue();
11658       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11659       if (IncVal != NumBytes)
11660         continue;
11661       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11662     }
11663 
11664     // To avoid cycle construction make sure that neither the load nor the add
11665     // are predecessors to each other or the Vector.
11666     SmallPtrSet<const SDNode *, 32> Visited;
11667     SmallVector<const SDNode *, 16> Worklist;
11668     Visited.insert(Addr.getNode());
11669     Worklist.push_back(User);
11670     Worklist.push_back(LD);
11671     Worklist.push_back(Vector.getNode());
11672     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11673         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11674       continue;
11675 
11676     SmallVector<SDValue, 8> Ops;
11677     Ops.push_back(LD->getOperand(0));  // Chain
11678     if (IsLaneOp) {
11679       Ops.push_back(Vector);           // The vector to be inserted
11680       Ops.push_back(Lane);             // The lane to be inserted in the vector
11681     }
11682     Ops.push_back(Addr);
11683     Ops.push_back(Inc);
11684 
11685     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11686     SDVTList SDTys = DAG.getVTList(Tys);
11687     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11688     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11689                                            MemVT,
11690                                            LoadSDN->getMemOperand());
11691 
11692     // Update the uses.
11693     SDValue NewResults[] = {
11694         SDValue(LD, 0),            // The result of load
11695         SDValue(UpdN.getNode(), 2) // Chain
11696     };
11697     DCI.CombineTo(LD, NewResults);
11698     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
11699     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
11700 
11701     break;
11702   }
11703   return SDValue();
11704 }
11705 
11706 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11707 /// address translation.
11708 static bool performTBISimplification(SDValue Addr,
11709                                      TargetLowering::DAGCombinerInfo &DCI,
11710                                      SelectionDAG &DAG) {
11711   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11712   KnownBits Known;
11713   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11714                                         !DCI.isBeforeLegalizeOps());
11715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11716   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11717     DCI.CommitTargetLoweringOpt(TLO);
11718     return true;
11719   }
11720   return false;
11721 }
11722 
11723 static SDValue performSTORECombine(SDNode *N,
11724                                    TargetLowering::DAGCombinerInfo &DCI,
11725                                    SelectionDAG &DAG,
11726                                    const AArch64Subtarget *Subtarget) {
11727   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11728     return Split;
11729 
11730   if (Subtarget->supportsAddressTopByteIgnored() &&
11731       performTBISimplification(N->getOperand(2), DCI, DAG))
11732     return SDValue(N, 0);
11733 
11734   return SDValue();
11735 }
11736 
11737 
11738 /// Target-specific DAG combine function for NEON load/store intrinsics
11739 /// to merge base address updates.
11740 static SDValue performNEONPostLDSTCombine(SDNode *N,
11741                                           TargetLowering::DAGCombinerInfo &DCI,
11742                                           SelectionDAG &DAG) {
11743   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11744     return SDValue();
11745 
11746   unsigned AddrOpIdx = N->getNumOperands() - 1;
11747   SDValue Addr = N->getOperand(AddrOpIdx);
11748 
11749   // Search for a use of the address operand that is an increment.
11750   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11751        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11752     SDNode *User = *UI;
11753     if (User->getOpcode() != ISD::ADD ||
11754         UI.getUse().getResNo() != Addr.getResNo())
11755       continue;
11756 
11757     // Check that the add is independent of the load/store.  Otherwise, folding
11758     // it would create a cycle.
11759     SmallPtrSet<const SDNode *, 32> Visited;
11760     SmallVector<const SDNode *, 16> Worklist;
11761     Visited.insert(Addr.getNode());
11762     Worklist.push_back(N);
11763     Worklist.push_back(User);
11764     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11765         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11766       continue;
11767 
11768     // Find the new opcode for the updating load/store.
11769     bool IsStore = false;
11770     bool IsLaneOp = false;
11771     bool IsDupOp = false;
11772     unsigned NewOpc = 0;
11773     unsigned NumVecs = 0;
11774     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11775     switch (IntNo) {
11776     default: llvm_unreachable("unexpected intrinsic for Neon base update");
11777     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
11778       NumVecs = 2; break;
11779     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
11780       NumVecs = 3; break;
11781     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
11782       NumVecs = 4; break;
11783     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
11784       NumVecs = 2; IsStore = true; break;
11785     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
11786       NumVecs = 3; IsStore = true; break;
11787     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
11788       NumVecs = 4; IsStore = true; break;
11789     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
11790       NumVecs = 2; break;
11791     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
11792       NumVecs = 3; break;
11793     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
11794       NumVecs = 4; break;
11795     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
11796       NumVecs = 2; IsStore = true; break;
11797     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
11798       NumVecs = 3; IsStore = true; break;
11799     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
11800       NumVecs = 4; IsStore = true; break;
11801     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
11802       NumVecs = 2; IsDupOp = true; break;
11803     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
11804       NumVecs = 3; IsDupOp = true; break;
11805     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
11806       NumVecs = 4; IsDupOp = true; break;
11807     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
11808       NumVecs = 2; IsLaneOp = true; break;
11809     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
11810       NumVecs = 3; IsLaneOp = true; break;
11811     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
11812       NumVecs = 4; IsLaneOp = true; break;
11813     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
11814       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11815     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
11816       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11817     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
11818       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11819     }
11820 
11821     EVT VecTy;
11822     if (IsStore)
11823       VecTy = N->getOperand(2).getValueType();
11824     else
11825       VecTy = N->getValueType(0);
11826 
11827     // If the increment is a constant, it must match the memory ref size.
11828     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11829     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11830       uint32_t IncVal = CInc->getZExtValue();
11831       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11832       if (IsLaneOp || IsDupOp)
11833         NumBytes /= VecTy.getVectorNumElements();
11834       if (IncVal != NumBytes)
11835         continue;
11836       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11837     }
11838     SmallVector<SDValue, 8> Ops;
11839     Ops.push_back(N->getOperand(0)); // Incoming chain
11840     // Load lane and store have vector list as input.
11841     if (IsLaneOp || IsStore)
11842       for (unsigned i = 2; i < AddrOpIdx; ++i)
11843         Ops.push_back(N->getOperand(i));
11844     Ops.push_back(Addr); // Base register
11845     Ops.push_back(Inc);
11846 
11847     // Return Types.
11848     EVT Tys[6];
11849     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11850     unsigned n;
11851     for (n = 0; n < NumResultVecs; ++n)
11852       Tys[n] = VecTy;
11853     Tys[n++] = MVT::i64;  // Type of write back register
11854     Tys[n] = MVT::Other;  // Type of the chain
11855     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11856 
11857     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11858     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11859                                            MemInt->getMemoryVT(),
11860                                            MemInt->getMemOperand());
11861 
11862     // Update the uses.
11863     std::vector<SDValue> NewResults;
11864     for (unsigned i = 0; i < NumResultVecs; ++i) {
11865       NewResults.push_back(SDValue(UpdN.getNode(), i));
11866     }
11867     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11868     DCI.CombineTo(N, NewResults);
11869     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11870 
11871     break;
11872   }
11873   return SDValue();
11874 }
11875 
11876 // Checks to see if the value is the prescribed width and returns information
11877 // about its extension mode.
11878 static
11879 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11880   ExtType = ISD::NON_EXTLOAD;
11881   switch(V.getNode()->getOpcode()) {
11882   default:
11883     return false;
11884   case ISD::LOAD: {
11885     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11886     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11887        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11888       ExtType = LoadNode->getExtensionType();
11889       return true;
11890     }
11891     return false;
11892   }
11893   case ISD::AssertSext: {
11894     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11895     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11896        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11897       ExtType = ISD::SEXTLOAD;
11898       return true;
11899     }
11900     return false;
11901   }
11902   case ISD::AssertZext: {
11903     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11904     if ((TypeNode->getVT() == MVT::i8 && width == 8)
11905        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11906       ExtType = ISD::ZEXTLOAD;
11907       return true;
11908     }
11909     return false;
11910   }
11911   case ISD::Constant:
11912   case ISD::TargetConstant: {
11913     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11914            1LL << (width - 1);
11915   }
11916   }
11917 
11918   return true;
11919 }
11920 
11921 // This function does a whole lot of voodoo to determine if the tests are
11922 // equivalent without and with a mask. Essentially what happens is that given a
11923 // DAG resembling:
11924 //
11925 //  +-------------+ +-------------+ +-------------+ +-------------+
11926 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
11927 //  +-------------+ +-------------+ +-------------+ +-------------+
11928 //           |           |           |               |
11929 //           V           V           |    +----------+
11930 //          +-------------+  +----+  |    |
11931 //          |     ADD     |  |0xff|  |    |
11932 //          +-------------+  +----+  |    |
11933 //                  |           |    |    |
11934 //                  V           V    |    |
11935 //                 +-------------+   |    |
11936 //                 |     AND     |   |    |
11937 //                 +-------------+   |    |
11938 //                      |            |    |
11939 //                      +-----+      |    |
11940 //                            |      |    |
11941 //                            V      V    V
11942 //                           +-------------+
11943 //                           |     CMP     |
11944 //                           +-------------+
11945 //
11946 // The AND node may be safely removed for some combinations of inputs. In
11947 // particular we need to take into account the extension type of the Input,
11948 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
11949 // width of the input (this can work for any width inputs, the above graph is
11950 // specific to 8 bits.
11951 //
11952 // The specific equations were worked out by generating output tables for each
11953 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11954 // problem was simplified by working with 4 bit inputs, which means we only
11955 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11956 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11957 // patterns present in both extensions (0,7). For every distinct set of
11958 // AddConstant and CompConstants bit patterns we can consider the masked and
11959 // unmasked versions to be equivalent if the result of this function is true for
11960 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11961 //
11962 //   sub      w8, w0, w1
11963 //   and      w10, w8, #0x0f
11964 //   cmp      w8, w2
11965 //   cset     w9, AArch64CC
11966 //   cmp      w10, w2
11967 //   cset     w11, AArch64CC
11968 //   cmp      w9, w11
11969 //   cset     w0, eq
11970 //   ret
11971 //
11972 // Since the above function shows when the outputs are equivalent it defines
11973 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11974 // would be expensive to run during compiles. The equations below were written
11975 // in a test harness that confirmed they gave equivalent outputs to the above
11976 // for all inputs function, so they can be used determine if the removal is
11977 // legal instead.
11978 //
11979 // isEquivalentMaskless() is the code for testing if the AND can be removed
11980 // factored out of the DAG recognition as the DAG can take several forms.
11981 
11982 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11983                                  ISD::LoadExtType ExtType, int AddConstant,
11984                                  int CompConstant) {
11985   // By being careful about our equations and only writing the in term
11986   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11987   // make them generally applicable to all bit widths.
11988   int MaxUInt = (1 << width);
11989 
11990   // For the purposes of these comparisons sign extending the type is
11991   // equivalent to zero extending the add and displacing it by half the integer
11992   // width. Provided we are careful and make sure our equations are valid over
11993   // the whole range we can just adjust the input and avoid writing equations
11994   // for sign extended inputs.
11995   if (ExtType == ISD::SEXTLOAD)
11996     AddConstant -= (1 << (width-1));
11997 
11998   switch(CC) {
11999   case AArch64CC::LE:
12000   case AArch64CC::GT:
12001     if ((AddConstant == 0) ||
12002         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
12003         (AddConstant >= 0 && CompConstant < 0) ||
12004         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
12005       return true;
12006     break;
12007   case AArch64CC::LT:
12008   case AArch64CC::GE:
12009     if ((AddConstant == 0) ||
12010         (AddConstant >= 0 && CompConstant <= 0) ||
12011         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
12012       return true;
12013     break;
12014   case AArch64CC::HI:
12015   case AArch64CC::LS:
12016     if ((AddConstant >= 0 && CompConstant < 0) ||
12017        (AddConstant <= 0 && CompConstant >= -1 &&
12018         CompConstant < AddConstant + MaxUInt))
12019       return true;
12020    break;
12021   case AArch64CC::PL:
12022   case AArch64CC::MI:
12023     if ((AddConstant == 0) ||
12024         (AddConstant > 0 && CompConstant <= 0) ||
12025         (AddConstant < 0 && CompConstant <= AddConstant))
12026       return true;
12027     break;
12028   case AArch64CC::LO:
12029   case AArch64CC::HS:
12030     if ((AddConstant >= 0 && CompConstant <= 0) ||
12031         (AddConstant <= 0 && CompConstant >= 0 &&
12032          CompConstant <= AddConstant + MaxUInt))
12033       return true;
12034     break;
12035   case AArch64CC::EQ:
12036   case AArch64CC::NE:
12037     if ((AddConstant > 0 && CompConstant < 0) ||
12038         (AddConstant < 0 && CompConstant >= 0 &&
12039          CompConstant < AddConstant + MaxUInt) ||
12040         (AddConstant >= 0 && CompConstant >= 0 &&
12041          CompConstant >= AddConstant) ||
12042         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
12043       return true;
12044     break;
12045   case AArch64CC::VS:
12046   case AArch64CC::VC:
12047   case AArch64CC::AL:
12048   case AArch64CC::NV:
12049     return true;
12050   case AArch64CC::Invalid:
12051     break;
12052   }
12053 
12054   return false;
12055 }
12056 
12057 static
12058 SDValue performCONDCombine(SDNode *N,
12059                            TargetLowering::DAGCombinerInfo &DCI,
12060                            SelectionDAG &DAG, unsigned CCIndex,
12061                            unsigned CmpIndex) {
12062   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
12063   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
12064   unsigned CondOpcode = SubsNode->getOpcode();
12065 
12066   if (CondOpcode != AArch64ISD::SUBS)
12067     return SDValue();
12068 
12069   // There is a SUBS feeding this condition. Is it fed by a mask we can
12070   // use?
12071 
12072   SDNode *AndNode = SubsNode->getOperand(0).getNode();
12073   unsigned MaskBits = 0;
12074 
12075   if (AndNode->getOpcode() != ISD::AND)
12076     return SDValue();
12077 
12078   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
12079     uint32_t CNV = CN->getZExtValue();
12080     if (CNV == 255)
12081       MaskBits = 8;
12082     else if (CNV == 65535)
12083       MaskBits = 16;
12084   }
12085 
12086   if (!MaskBits)
12087     return SDValue();
12088 
12089   SDValue AddValue = AndNode->getOperand(0);
12090 
12091   if (AddValue.getOpcode() != ISD::ADD)
12092     return SDValue();
12093 
12094   // The basic dag structure is correct, grab the inputs and validate them.
12095 
12096   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
12097   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
12098   SDValue SubsInputValue = SubsNode->getOperand(1);
12099 
12100   // The mask is present and the provenance of all the values is a smaller type,
12101   // lets see if the mask is superfluous.
12102 
12103   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
12104       !isa<ConstantSDNode>(SubsInputValue.getNode()))
12105     return SDValue();
12106 
12107   ISD::LoadExtType ExtType;
12108 
12109   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
12110       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
12111       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
12112     return SDValue();
12113 
12114   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
12115                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
12116                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
12117     return SDValue();
12118 
12119   // The AND is not necessary, remove it.
12120 
12121   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
12122                                SubsNode->getValueType(1));
12123   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
12124 
12125   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
12126   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
12127 
12128   return SDValue(N, 0);
12129 }
12130 
12131 // Optimize compare with zero and branch.
12132 static SDValue performBRCONDCombine(SDNode *N,
12133                                     TargetLowering::DAGCombinerInfo &DCI,
12134                                     SelectionDAG &DAG) {
12135   MachineFunction &MF = DAG.getMachineFunction();
12136   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
12137   // will not be produced, as they are conditional branch instructions that do
12138   // not set flags.
12139   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
12140     return SDValue();
12141 
12142   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
12143     N = NV.getNode();
12144   SDValue Chain = N->getOperand(0);
12145   SDValue Dest = N->getOperand(1);
12146   SDValue CCVal = N->getOperand(2);
12147   SDValue Cmp = N->getOperand(3);
12148 
12149   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
12150   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
12151   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
12152     return SDValue();
12153 
12154   unsigned CmpOpc = Cmp.getOpcode();
12155   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
12156     return SDValue();
12157 
12158   // Only attempt folding if there is only one use of the flag and no use of the
12159   // value.
12160   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
12161     return SDValue();
12162 
12163   SDValue LHS = Cmp.getOperand(0);
12164   SDValue RHS = Cmp.getOperand(1);
12165 
12166   assert(LHS.getValueType() == RHS.getValueType() &&
12167          "Expected the value type to be the same for both operands!");
12168   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
12169     return SDValue();
12170 
12171   if (isNullConstant(LHS))
12172     std::swap(LHS, RHS);
12173 
12174   if (!isNullConstant(RHS))
12175     return SDValue();
12176 
12177   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
12178       LHS.getOpcode() == ISD::SRL)
12179     return SDValue();
12180 
12181   // Fold the compare into the branch instruction.
12182   SDValue BR;
12183   if (CC == AArch64CC::EQ)
12184     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12185   else
12186     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12187 
12188   // Do not add new nodes to DAG combiner worklist.
12189   DCI.CombineTo(N, BR, false);
12190 
12191   return SDValue();
12192 }
12193 
12194 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
12195 // as well as whether the test should be inverted.  This code is required to
12196 // catch these cases (as opposed to standard dag combines) because
12197 // AArch64ISD::TBZ is matched during legalization.
12198 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12199                                  SelectionDAG &DAG) {
12200 
12201   if (!Op->hasOneUse())
12202     return Op;
12203 
12204   // We don't handle undef/constant-fold cases below, as they should have
12205   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12206   // etc.)
12207 
12208   // (tbz (trunc x), b) -> (tbz x, b)
12209   // This case is just here to enable more of the below cases to be caught.
12210   if (Op->getOpcode() == ISD::TRUNCATE &&
12211       Bit < Op->getValueType(0).getSizeInBits()) {
12212     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12213   }
12214 
12215   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12216   if (Op->getOpcode() == ISD::ANY_EXTEND &&
12217       Bit < Op->getOperand(0).getValueSizeInBits()) {
12218     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12219   }
12220 
12221   if (Op->getNumOperands() != 2)
12222     return Op;
12223 
12224   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12225   if (!C)
12226     return Op;
12227 
12228   switch (Op->getOpcode()) {
12229   default:
12230     return Op;
12231 
12232   // (tbz (and x, m), b) -> (tbz x, b)
12233   case ISD::AND:
12234     if ((C->getZExtValue() >> Bit) & 1)
12235       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12236     return Op;
12237 
12238   // (tbz (shl x, c), b) -> (tbz x, b-c)
12239   case ISD::SHL:
12240     if (C->getZExtValue() <= Bit &&
12241         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12242       Bit = Bit - C->getZExtValue();
12243       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12244     }
12245     return Op;
12246 
12247   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12248   case ISD::SRA:
12249     Bit = Bit + C->getZExtValue();
12250     if (Bit >= Op->getValueType(0).getSizeInBits())
12251       Bit = Op->getValueType(0).getSizeInBits() - 1;
12252     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12253 
12254   // (tbz (srl x, c), b) -> (tbz x, b+c)
12255   case ISD::SRL:
12256     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12257       Bit = Bit + C->getZExtValue();
12258       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12259     }
12260     return Op;
12261 
12262   // (tbz (xor x, -1), b) -> (tbnz x, b)
12263   case ISD::XOR:
12264     if ((C->getZExtValue() >> Bit) & 1)
12265       Invert = !Invert;
12266     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12267   }
12268 }
12269 
12270 // Optimize test single bit zero/non-zero and branch.
12271 static SDValue performTBZCombine(SDNode *N,
12272                                  TargetLowering::DAGCombinerInfo &DCI,
12273                                  SelectionDAG &DAG) {
12274   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12275   bool Invert = false;
12276   SDValue TestSrc = N->getOperand(1);
12277   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12278 
12279   if (TestSrc == NewTestSrc)
12280     return SDValue();
12281 
12282   unsigned NewOpc = N->getOpcode();
12283   if (Invert) {
12284     if (NewOpc == AArch64ISD::TBZ)
12285       NewOpc = AArch64ISD::TBNZ;
12286     else {
12287       assert(NewOpc == AArch64ISD::TBNZ);
12288       NewOpc = AArch64ISD::TBZ;
12289     }
12290   }
12291 
12292   SDLoc DL(N);
12293   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12294                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12295 }
12296 
12297 // vselect (v1i1 setcc) ->
12298 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
12299 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12300 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12301 // such VSELECT.
12302 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12303   SDValue N0 = N->getOperand(0);
12304   EVT CCVT = N0.getValueType();
12305 
12306   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12307       CCVT.getVectorElementType() != MVT::i1)
12308     return SDValue();
12309 
12310   EVT ResVT = N->getValueType(0);
12311   EVT CmpVT = N0.getOperand(0).getValueType();
12312   // Only combine when the result type is of the same size as the compared
12313   // operands.
12314   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12315     return SDValue();
12316 
12317   SDValue IfTrue = N->getOperand(1);
12318   SDValue IfFalse = N->getOperand(2);
12319   SDValue SetCC =
12320       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12321                    N0.getOperand(0), N0.getOperand(1),
12322                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
12323   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12324                      IfTrue, IfFalse);
12325 }
12326 
12327 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12328 /// the compare-mask instructions rather than going via NZCV, even if LHS and
12329 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
12330 /// with a vector one followed by a DUP shuffle on the result.
12331 static SDValue performSelectCombine(SDNode *N,
12332                                     TargetLowering::DAGCombinerInfo &DCI) {
12333   SelectionDAG &DAG = DCI.DAG;
12334   SDValue N0 = N->getOperand(0);
12335   EVT ResVT = N->getValueType(0);
12336 
12337   if (N0.getOpcode() != ISD::SETCC)
12338     return SDValue();
12339 
12340   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12341   // scalar SetCCResultType. We also don't expect vectors, because we assume
12342   // that selects fed by vector SETCCs are canonicalized to VSELECT.
12343   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12344          "Scalar-SETCC feeding SELECT has unexpected result type!");
12345 
12346   // If NumMaskElts == 0, the comparison is larger than select result. The
12347   // largest real NEON comparison is 64-bits per lane, which means the result is
12348   // at most 32-bits and an illegal vector. Just bail out for now.
12349   EVT SrcVT = N0.getOperand(0).getValueType();
12350 
12351   // Don't try to do this optimization when the setcc itself has i1 operands.
12352   // There are no legal vectors of i1, so this would be pointless.
12353   if (SrcVT == MVT::i1)
12354     return SDValue();
12355 
12356   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12357   if (!ResVT.isVector() || NumMaskElts == 0)
12358     return SDValue();
12359 
12360   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12361   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12362 
12363   // Also bail out if the vector CCVT isn't the same size as ResVT.
12364   // This can happen if the SETCC operand size doesn't divide the ResVT size
12365   // (e.g., f64 vs v3f32).
12366   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12367     return SDValue();
12368 
12369   // Make sure we didn't create illegal types, if we're not supposed to.
12370   assert(DCI.isBeforeLegalize() ||
12371          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12372 
12373   // First perform a vector comparison, where lane 0 is the one we're interested
12374   // in.
12375   SDLoc DL(N0);
12376   SDValue LHS =
12377       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12378   SDValue RHS =
12379       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12380   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12381 
12382   // Now duplicate the comparison mask we want across all other lanes.
12383   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12384   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12385   Mask = DAG.getNode(ISD::BITCAST, DL,
12386                      ResVT.changeVectorElementTypeToInteger(), Mask);
12387 
12388   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12389 }
12390 
12391 /// Get rid of unnecessary NVCASTs (that don't change the type).
12392 static SDValue performNVCASTCombine(SDNode *N) {
12393   if (N->getValueType(0) == N->getOperand(0).getValueType())
12394     return N->getOperand(0);
12395 
12396   return SDValue();
12397 }
12398 
12399 // If all users of the globaladdr are of the form (globaladdr + constant), find
12400 // the smallest constant, fold it into the globaladdr's offset and rewrite the
12401 // globaladdr as (globaladdr + constant) - constant.
12402 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12403                                            const AArch64Subtarget *Subtarget,
12404                                            const TargetMachine &TM) {
12405   auto *GN = cast<GlobalAddressSDNode>(N);
12406   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12407       AArch64II::MO_NO_FLAG)
12408     return SDValue();
12409 
12410   uint64_t MinOffset = -1ull;
12411   for (SDNode *N : GN->uses()) {
12412     if (N->getOpcode() != ISD::ADD)
12413       return SDValue();
12414     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12415     if (!C)
12416       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12417     if (!C)
12418       return SDValue();
12419     MinOffset = std::min(MinOffset, C->getZExtValue());
12420   }
12421   uint64_t Offset = MinOffset + GN->getOffset();
12422 
12423   // Require that the new offset is larger than the existing one. Otherwise, we
12424   // can end up oscillating between two possible DAGs, for example,
12425   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12426   if (Offset <= uint64_t(GN->getOffset()))
12427     return SDValue();
12428 
12429   // Check whether folding this offset is legal. It must not go out of bounds of
12430   // the referenced object to avoid violating the code model, and must be
12431   // smaller than 2^21 because this is the largest offset expressible in all
12432   // object formats.
12433   //
12434   // This check also prevents us from folding negative offsets, which will end
12435   // up being treated in the same way as large positive ones. They could also
12436   // cause code model violations, and aren't really common enough to matter.
12437   if (Offset >= (1 << 21))
12438     return SDValue();
12439 
12440   const GlobalValue *GV = GN->getGlobal();
12441   Type *T = GV->getValueType();
12442   if (!T->isSized() ||
12443       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12444     return SDValue();
12445 
12446   SDLoc DL(GN);
12447   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12448   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12449                      DAG.getConstant(MinOffset, DL, MVT::i64));
12450 }
12451 
12452 static SDValue performST1ScatterCombine(SDNode *N, SelectionDAG &DAG,
12453                                         unsigned Opcode,
12454                                         bool OnlyPackedOffsets = true) {
12455   const SDValue Src = N->getOperand(2);
12456   const EVT SrcVT = Src->getValueType(0);
12457   assert(SrcVT.isScalableVector() &&
12458          "Scatter stores are only possible for SVE vectors");
12459 
12460   SDLoc DL(N);
12461   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12462 
12463   // Make sure that source data will fit into an SVE register
12464   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12465     return SDValue();
12466 
12467   // For FPs, ACLE only supports _packed_ single and double precision types.
12468   if (SrcElVT.isFloatingPoint())
12469     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12470       return SDValue();
12471 
12472   // Depending on the addressing mode, this is either a pointer or a vector of
12473   // pointers (that fits into one register)
12474   SDValue Base = N->getOperand(4);
12475   // Depending on the addressing mode, this is either a single offset or a
12476   // vector of offsets  (that fits into one register)
12477   SDValue Offset = N->getOperand(5);
12478 
12479   // SST1_IMM requires that the offset is an immediate:
12480   // * multiple of #SizeInBytes
12481   // * in the range [0, 31 x #SizeInBytes]
12482   // where #SizeInBytes is the size in bytes of the stored
12483   // items. For immediates outside that range and non-immediate scalar offsets use
12484   // SST1 or SST1_UXTW instead.
12485   if (Opcode == AArch64ISD::SST1_IMM) {
12486     uint64_t MaxIndex = 31;
12487     uint64_t SrcElSize = SrcElVT.getStoreSize().getKnownMinSize();
12488 
12489     ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12490     if (nullptr == OffsetConst ||
12491         OffsetConst->getZExtValue() > MaxIndex * SrcElSize ||
12492         OffsetConst->getZExtValue() % SrcElSize) {
12493       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12494         Opcode = AArch64ISD::SST1_UXTW;
12495       else
12496         Opcode = AArch64ISD::SST1;
12497 
12498       std::swap(Base, Offset);
12499     }
12500   }
12501 
12502   auto &TLI = DAG.getTargetLoweringInfo();
12503   if (!TLI.isTypeLegal(Base.getValueType()))
12504     return SDValue();
12505 
12506   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12507   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12508   // nxv2i64. Legalize accordingly.
12509   if (!OnlyPackedOffsets &&
12510       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12511     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12512 
12513   if (!TLI.isTypeLegal(Offset.getValueType()))
12514     return SDValue();
12515 
12516   // Source value type that is representable in hardware
12517   EVT HwSrcVt = getSVEContainerType(SrcVT);
12518 
12519   // Keep the original type of the input data to store - this is needed to
12520   // differentiate between ST1B, ST1H, ST1W and ST1D. For FP values we want the
12521   // integer equivalent, so just use HwSrcVt.
12522   SDValue InputVT = DAG.getValueType(SrcVT);
12523   if (SrcVT.isFloatingPoint())
12524     InputVT = DAG.getValueType(HwSrcVt);
12525 
12526   SDVTList VTs = DAG.getVTList(MVT::Other);
12527   SDValue SrcNew;
12528 
12529   if (Src.getValueType().isFloatingPoint())
12530     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12531   else
12532     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12533 
12534   SDValue Ops[] = {N->getOperand(0), // Chain
12535                    SrcNew,
12536                    N->getOperand(3), // Pg
12537                    Base,
12538                    Offset,
12539                    InputVT};
12540 
12541   return DAG.getNode(Opcode, DL, VTs, Ops);
12542 }
12543 
12544 static SDValue performLD1GatherCombine(SDNode *N, SelectionDAG &DAG,
12545                                        unsigned Opcode,
12546                                        bool OnlyPackedOffsets = true) {
12547   EVT RetVT = N->getValueType(0);
12548   assert(RetVT.isScalableVector() &&
12549          "Gather loads are only possible for SVE vectors");
12550   SDLoc DL(N);
12551 
12552   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12553     return SDValue();
12554 
12555   // Depending on the addressing mode, this is either a pointer or a vector of
12556   // pointers (that fits into one register)
12557   SDValue Base = N->getOperand(3);
12558   // Depending on the addressing mode, this is either a single offset or a
12559   // vector of offsets  (that fits into one register)
12560   SDValue Offset = N->getOperand(4);
12561 
12562   // GLD1_IMM requires that the offset is an immediate:
12563   // * multiple of #SizeInBytes
12564   // * in the range [0, 31 x #SizeInBytes]
12565   // where #SizeInBytes is the size in bytes of the loaded items.  For immediates
12566   // outside that range and non-immediate scalar offsets use GLD1 or GLD1_UXTW
12567   // instead.
12568   if (Opcode == AArch64ISD::GLD1_IMM) {
12569     uint64_t MaxIndex = 31;
12570     uint64_t RetElSize = RetVT.getVectorElementType()
12571                              .getSimpleVT()
12572                              .getStoreSize()
12573                              .getKnownMinSize();
12574 
12575     ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12576     if (nullptr == OffsetConst ||
12577         OffsetConst->getZExtValue() > MaxIndex * RetElSize ||
12578         OffsetConst->getZExtValue() % RetElSize) {
12579       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12580         Opcode = AArch64ISD::GLD1_UXTW;
12581       else
12582         Opcode = AArch64ISD::GLD1;
12583 
12584       std::swap(Base, Offset);
12585     }
12586   }
12587 
12588   auto &TLI = DAG.getTargetLoweringInfo();
12589   if (!TLI.isTypeLegal(Base.getValueType()))
12590     return SDValue();
12591 
12592   // Some gather load variants allow unpacked offsets, but only as nxv2i32
12593   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12594   // nxv2i64. Legalize accordingly.
12595   if (!OnlyPackedOffsets &&
12596       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12597     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12598 
12599   // Return value type that is representable in hardware
12600   EVT HwRetVt = getSVEContainerType(RetVT);
12601 
12602   // Keep the original output value type around - this will better inform
12603   // optimisations (e.g. instruction folding when load is followed by
12604   // zext/sext). This will only be used for ints, so the value for FPs
12605   // doesn't matter.
12606   SDValue OutVT = DAG.getValueType(RetVT);
12607   if (RetVT.isFloatingPoint())
12608     OutVT = DAG.getValueType(HwRetVt);
12609 
12610   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12611   SDValue Ops[] = {N->getOperand(0), // Chain
12612                    N->getOperand(2), // Pg
12613                    Base, Offset, OutVT};
12614 
12615   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12616   SDValue LoadChain = SDValue(Load.getNode(), 1);
12617 
12618   if (RetVT.isInteger() && (RetVT != HwRetVt))
12619     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12620 
12621   // If the original return value was FP, bitcast accordingly. Doing it here
12622   // means that we can avoid adding TableGen patterns for FPs.
12623   if (RetVT.isFloatingPoint())
12624     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12625 
12626   return DAG.getMergeValues({Load, LoadChain}, DL);
12627 }
12628 
12629 
12630 static SDValue
12631 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12632                               SelectionDAG &DAG) {
12633   if (DCI.isBeforeLegalizeOps())
12634     return SDValue();
12635 
12636   SDValue Src = N->getOperand(0);
12637   unsigned Opc = Src->getOpcode();
12638 
12639   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12640   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12641   unsigned NewOpc;
12642   unsigned MemVTOpNum = 4;
12643   switch (Opc) {
12644   case AArch64ISD::LDNF1:
12645     NewOpc = AArch64ISD::LDNF1S;
12646     MemVTOpNum = 3;
12647     break;
12648   case AArch64ISD::LDFF1:
12649     NewOpc = AArch64ISD::LDFF1S;
12650     MemVTOpNum = 3;
12651     break;
12652   case AArch64ISD::GLD1:
12653     NewOpc = AArch64ISD::GLD1S;
12654     break;
12655   case AArch64ISD::GLD1_SCALED:
12656     NewOpc = AArch64ISD::GLD1S_SCALED;
12657     break;
12658   case AArch64ISD::GLD1_SXTW:
12659     NewOpc = AArch64ISD::GLD1S_SXTW;
12660     break;
12661   case AArch64ISD::GLD1_SXTW_SCALED:
12662     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12663     break;
12664   case AArch64ISD::GLD1_UXTW:
12665     NewOpc = AArch64ISD::GLD1S_UXTW;
12666     break;
12667   case AArch64ISD::GLD1_UXTW_SCALED:
12668     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12669     break;
12670   case AArch64ISD::GLD1_IMM:
12671     NewOpc = AArch64ISD::GLD1S_IMM;
12672     break;
12673   default:
12674     return SDValue();
12675   }
12676 
12677   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12678   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
12679 
12680   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
12681     return SDValue();
12682 
12683   EVT DstVT = N->getValueType(0);
12684   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12685 
12686   SmallVector<SDValue, 5> Ops;
12687   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
12688     Ops.push_back(Src->getOperand(I));
12689 
12690   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12691   DCI.CombineTo(N, ExtLoad);
12692   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12693 
12694   // Return N so it doesn't get rechecked
12695   return SDValue(N, 0);
12696 }
12697 
12698 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
12699                                                  DAGCombinerInfo &DCI) const {
12700   SelectionDAG &DAG = DCI.DAG;
12701   switch (N->getOpcode()) {
12702   default:
12703     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
12704     break;
12705   case ISD::ADD:
12706   case ISD::SUB:
12707     return performAddSubLongCombine(N, DCI, DAG);
12708   case ISD::XOR:
12709     return performXorCombine(N, DAG, DCI, Subtarget);
12710   case ISD::MUL:
12711     return performMulCombine(N, DAG, DCI, Subtarget);
12712   case ISD::SINT_TO_FP:
12713   case ISD::UINT_TO_FP:
12714     return performIntToFpCombine(N, DAG, Subtarget);
12715   case ISD::FP_TO_SINT:
12716   case ISD::FP_TO_UINT:
12717     return performFpToIntCombine(N, DAG, DCI, Subtarget);
12718   case ISD::FDIV:
12719     return performFDivCombine(N, DAG, DCI, Subtarget);
12720   case ISD::OR:
12721     return performORCombine(N, DCI, Subtarget);
12722   case ISD::AND:
12723     return performANDCombine(N, DCI);
12724   case ISD::SRL:
12725     return performSRLCombine(N, DCI);
12726   case ISD::INTRINSIC_WO_CHAIN:
12727     return performIntrinsicCombine(N, DCI, Subtarget);
12728   case ISD::ANY_EXTEND:
12729   case ISD::ZERO_EXTEND:
12730   case ISD::SIGN_EXTEND:
12731     return performExtendCombine(N, DCI, DAG);
12732   case ISD::SIGN_EXTEND_INREG:
12733     return performSignExtendInRegCombine(N, DCI, DAG);
12734   case ISD::CONCAT_VECTORS:
12735     return performConcatVectorsCombine(N, DCI, DAG);
12736   case ISD::SELECT:
12737     return performSelectCombine(N, DCI);
12738   case ISD::VSELECT:
12739     return performVSelectCombine(N, DCI.DAG);
12740   case ISD::LOAD:
12741     if (performTBISimplification(N->getOperand(1), DCI, DAG))
12742       return SDValue(N, 0);
12743     break;
12744   case ISD::STORE:
12745     return performSTORECombine(N, DCI, DAG, Subtarget);
12746   case AArch64ISD::BRCOND:
12747     return performBRCONDCombine(N, DCI, DAG);
12748   case AArch64ISD::TBNZ:
12749   case AArch64ISD::TBZ:
12750     return performTBZCombine(N, DCI, DAG);
12751   case AArch64ISD::CSEL:
12752     return performCONDCombine(N, DCI, DAG, 2, 3);
12753   case AArch64ISD::DUP:
12754     return performPostLD1Combine(N, DCI, false);
12755   case AArch64ISD::NVCAST:
12756     return performNVCASTCombine(N);
12757   case ISD::INSERT_VECTOR_ELT:
12758     return performPostLD1Combine(N, DCI, true);
12759   case ISD::INTRINSIC_VOID:
12760   case ISD::INTRINSIC_W_CHAIN:
12761     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12762     case Intrinsic::aarch64_neon_ld2:
12763     case Intrinsic::aarch64_neon_ld3:
12764     case Intrinsic::aarch64_neon_ld4:
12765     case Intrinsic::aarch64_neon_ld1x2:
12766     case Intrinsic::aarch64_neon_ld1x3:
12767     case Intrinsic::aarch64_neon_ld1x4:
12768     case Intrinsic::aarch64_neon_ld2lane:
12769     case Intrinsic::aarch64_neon_ld3lane:
12770     case Intrinsic::aarch64_neon_ld4lane:
12771     case Intrinsic::aarch64_neon_ld2r:
12772     case Intrinsic::aarch64_neon_ld3r:
12773     case Intrinsic::aarch64_neon_ld4r:
12774     case Intrinsic::aarch64_neon_st2:
12775     case Intrinsic::aarch64_neon_st3:
12776     case Intrinsic::aarch64_neon_st4:
12777     case Intrinsic::aarch64_neon_st1x2:
12778     case Intrinsic::aarch64_neon_st1x3:
12779     case Intrinsic::aarch64_neon_st1x4:
12780     case Intrinsic::aarch64_neon_st2lane:
12781     case Intrinsic::aarch64_neon_st3lane:
12782     case Intrinsic::aarch64_neon_st4lane:
12783       return performNEONPostLDSTCombine(N, DCI, DAG);
12784     case Intrinsic::aarch64_sve_ldnt1:
12785       return performLDNT1Combine(N, DAG);
12786     case Intrinsic::aarch64_sve_ldnf1:
12787       return performLDNF1Combine(N, DAG, AArch64ISD::LDNF1);
12788     case Intrinsic::aarch64_sve_ldff1:
12789       return performLDNF1Combine(N, DAG, AArch64ISD::LDFF1);
12790     case Intrinsic::aarch64_sve_stnt1:
12791       return performSTNT1Combine(N, DAG);
12792     case Intrinsic::aarch64_sve_ld1_gather:
12793       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1);
12794     case Intrinsic::aarch64_sve_ld1_gather_index:
12795       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SCALED);
12796     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
12797       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW,
12798                                       /*OnlyPackedOffsets=*/false);
12799     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
12800       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW,
12801                                       /*OnlyPackedOffsets=*/false);
12802     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
12803       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
12804                                       /*OnlyPackedOffsets=*/false);
12805     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
12806       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
12807                                       /*OnlyPackedOffsets=*/false);
12808     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
12809       return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_IMM);
12810     case Intrinsic::aarch64_sve_st1_scatter:
12811       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1);
12812     case Intrinsic::aarch64_sve_st1_scatter_index:
12813       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SCALED);
12814     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
12815       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW,
12816                                       /*OnlyPackedOffsets=*/false);
12817     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
12818       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW,
12819                                       /*OnlyPackedOffsets=*/false);
12820     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
12821       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
12822                                       /*OnlyPackedOffsets=*/false);
12823     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
12824       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
12825                                       /*OnlyPackedOffsets=*/false);
12826     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
12827       return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_IMM);
12828     default:
12829       break;
12830     }
12831     break;
12832   case ISD::GlobalAddress:
12833     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
12834   }
12835   return SDValue();
12836 }
12837 
12838 // Check if the return value is used as only a return value, as otherwise
12839 // we can't perform a tail-call. In particular, we need to check for
12840 // target ISD nodes that are returns and any other "odd" constructs
12841 // that the generic analysis code won't necessarily catch.
12842 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
12843                                                SDValue &Chain) const {
12844   if (N->getNumValues() != 1)
12845     return false;
12846   if (!N->hasNUsesOfValue(1, 0))
12847     return false;
12848 
12849   SDValue TCChain = Chain;
12850   SDNode *Copy = *N->use_begin();
12851   if (Copy->getOpcode() == ISD::CopyToReg) {
12852     // If the copy has a glue operand, we conservatively assume it isn't safe to
12853     // perform a tail call.
12854     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
12855         MVT::Glue)
12856       return false;
12857     TCChain = Copy->getOperand(0);
12858   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
12859     return false;
12860 
12861   bool HasRet = false;
12862   for (SDNode *Node : Copy->uses()) {
12863     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
12864       return false;
12865     HasRet = true;
12866   }
12867 
12868   if (!HasRet)
12869     return false;
12870 
12871   Chain = TCChain;
12872   return true;
12873 }
12874 
12875 // Return whether the an instruction can potentially be optimized to a tail
12876 // call. This will cause the optimizers to attempt to move, or duplicate,
12877 // return instructions to help enable tail call optimizations for this
12878 // instruction.
12879 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
12880   return CI->isTailCall();
12881 }
12882 
12883 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
12884                                                    SDValue &Offset,
12885                                                    ISD::MemIndexedMode &AM,
12886                                                    bool &IsInc,
12887                                                    SelectionDAG &DAG) const {
12888   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
12889     return false;
12890 
12891   Base = Op->getOperand(0);
12892   // All of the indexed addressing mode instructions take a signed
12893   // 9 bit immediate offset.
12894   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
12895     int64_t RHSC = RHS->getSExtValue();
12896     if (Op->getOpcode() == ISD::SUB)
12897       RHSC = -(uint64_t)RHSC;
12898     if (!isInt<9>(RHSC))
12899       return false;
12900     IsInc = (Op->getOpcode() == ISD::ADD);
12901     Offset = Op->getOperand(1);
12902     return true;
12903   }
12904   return false;
12905 }
12906 
12907 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12908                                                       SDValue &Offset,
12909                                                       ISD::MemIndexedMode &AM,
12910                                                       SelectionDAG &DAG) const {
12911   EVT VT;
12912   SDValue Ptr;
12913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12914     VT = LD->getMemoryVT();
12915     Ptr = LD->getBasePtr();
12916   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12917     VT = ST->getMemoryVT();
12918     Ptr = ST->getBasePtr();
12919   } else
12920     return false;
12921 
12922   bool IsInc;
12923   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
12924     return false;
12925   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
12926   return true;
12927 }
12928 
12929 bool AArch64TargetLowering::getPostIndexedAddressParts(
12930     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
12931     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
12932   EVT VT;
12933   SDValue Ptr;
12934   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12935     VT = LD->getMemoryVT();
12936     Ptr = LD->getBasePtr();
12937   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12938     VT = ST->getMemoryVT();
12939     Ptr = ST->getBasePtr();
12940   } else
12941     return false;
12942 
12943   bool IsInc;
12944   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
12945     return false;
12946   // Post-indexing updates the base, so it's not a valid transform
12947   // if that's not the same as the load's pointer.
12948   if (Ptr != Base)
12949     return false;
12950   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
12951   return true;
12952 }
12953 
12954 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
12955                                   SelectionDAG &DAG) {
12956   SDLoc DL(N);
12957   SDValue Op = N->getOperand(0);
12958 
12959   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
12960     return;
12961 
12962   Op = SDValue(
12963       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
12964                          DAG.getUNDEF(MVT::i32), Op,
12965                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
12966       0);
12967   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
12968   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
12969 }
12970 
12971 static void ReplaceReductionResults(SDNode *N,
12972                                     SmallVectorImpl<SDValue> &Results,
12973                                     SelectionDAG &DAG, unsigned InterOp,
12974                                     unsigned AcrossOp) {
12975   EVT LoVT, HiVT;
12976   SDValue Lo, Hi;
12977   SDLoc dl(N);
12978   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
12979   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
12980   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
12981   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
12982   Results.push_back(SplitVal);
12983 }
12984 
12985 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
12986   SDLoc DL(N);
12987   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
12988   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
12989                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
12990                                        DAG.getConstant(64, DL, MVT::i64)));
12991   return std::make_pair(Lo, Hi);
12992 }
12993 
12994 // Create an even/odd pair of X registers holding integer value V.
12995 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
12996   SDLoc dl(V.getNode());
12997   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
12998   SDValue VHi = DAG.getAnyExtOrTrunc(
12999       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
13000       dl, MVT::i64);
13001   if (DAG.getDataLayout().isBigEndian())
13002     std::swap (VLo, VHi);
13003   SDValue RegClass =
13004       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
13005   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
13006   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
13007   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
13008   return SDValue(
13009       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
13010 }
13011 
13012 static void ReplaceCMP_SWAP_128Results(SDNode *N,
13013                                        SmallVectorImpl<SDValue> &Results,
13014                                        SelectionDAG &DAG,
13015                                        const AArch64Subtarget *Subtarget) {
13016   assert(N->getValueType(0) == MVT::i128 &&
13017          "AtomicCmpSwap on types less than 128 should be legal");
13018 
13019   if (Subtarget->hasLSE()) {
13020     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
13021     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
13022     SDValue Ops[] = {
13023         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
13024         createGPRPairNode(DAG, N->getOperand(3)), // Store value
13025         N->getOperand(1), // Ptr
13026         N->getOperand(0), // Chain in
13027     };
13028 
13029     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13030 
13031     unsigned Opcode;
13032     switch (MemOp->getOrdering()) {
13033     case AtomicOrdering::Monotonic:
13034       Opcode = AArch64::CASPX;
13035       break;
13036     case AtomicOrdering::Acquire:
13037       Opcode = AArch64::CASPAX;
13038       break;
13039     case AtomicOrdering::Release:
13040       Opcode = AArch64::CASPLX;
13041       break;
13042     case AtomicOrdering::AcquireRelease:
13043     case AtomicOrdering::SequentiallyConsistent:
13044       Opcode = AArch64::CASPALX;
13045       break;
13046     default:
13047       llvm_unreachable("Unexpected ordering!");
13048     }
13049 
13050     MachineSDNode *CmpSwap = DAG.getMachineNode(
13051         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
13052     DAG.setNodeMemRefs(CmpSwap, {MemOp});
13053 
13054     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
13055     if (DAG.getDataLayout().isBigEndian())
13056       std::swap(SubReg1, SubReg2);
13057     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
13058                                                  SDValue(CmpSwap, 0)));
13059     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
13060                                                  SDValue(CmpSwap, 0)));
13061     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
13062     return;
13063   }
13064 
13065   auto Desired = splitInt128(N->getOperand(2), DAG);
13066   auto New = splitInt128(N->getOperand(3), DAG);
13067   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
13068                    New.first,        New.second,    N->getOperand(0)};
13069   SDNode *CmpSwap = DAG.getMachineNode(
13070       AArch64::CMP_SWAP_128, SDLoc(N),
13071       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
13072 
13073   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
13074   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
13075 
13076   Results.push_back(SDValue(CmpSwap, 0));
13077   Results.push_back(SDValue(CmpSwap, 1));
13078   Results.push_back(SDValue(CmpSwap, 3));
13079 }
13080 
13081 void AArch64TargetLowering::ReplaceNodeResults(
13082     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
13083   switch (N->getOpcode()) {
13084   default:
13085     llvm_unreachable("Don't know how to custom expand this");
13086   case ISD::BITCAST:
13087     ReplaceBITCASTResults(N, Results, DAG);
13088     return;
13089   case ISD::VECREDUCE_ADD:
13090   case ISD::VECREDUCE_SMAX:
13091   case ISD::VECREDUCE_SMIN:
13092   case ISD::VECREDUCE_UMAX:
13093   case ISD::VECREDUCE_UMIN:
13094     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
13095     return;
13096 
13097   case AArch64ISD::SADDV:
13098     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
13099     return;
13100   case AArch64ISD::UADDV:
13101     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
13102     return;
13103   case AArch64ISD::SMINV:
13104     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
13105     return;
13106   case AArch64ISD::UMINV:
13107     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
13108     return;
13109   case AArch64ISD::SMAXV:
13110     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
13111     return;
13112   case AArch64ISD::UMAXV:
13113     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
13114     return;
13115   case ISD::FP_TO_UINT:
13116   case ISD::FP_TO_SINT:
13117     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
13118     // Let normal code take care of it by not adding anything to Results.
13119     return;
13120   case ISD::ATOMIC_CMP_SWAP:
13121     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
13122     return;
13123   case ISD::LOAD: {
13124     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
13125            "unexpected load's value type");
13126     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
13127     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
13128       // Non-volatile loads are optimized later in AArch64's load/store
13129       // optimizer.
13130       return;
13131     }
13132 
13133     SDValue Result = DAG.getMemIntrinsicNode(
13134         AArch64ISD::LDP, SDLoc(N),
13135         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
13136         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
13137         LoadNode->getMemOperand());
13138 
13139     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13140                                Result.getValue(0), Result.getValue(1));
13141     Results.append({Pair, Result.getValue(2) /* Chain */});
13142     return;
13143   }
13144   case ISD::INTRINSIC_WO_CHAIN: {
13145     EVT VT = N->getValueType(0);
13146     assert((VT == MVT::i8 || VT == MVT::i16) &&
13147            "custom lowering for unexpected type");
13148 
13149     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
13150     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13151     switch (IntID) {
13152     default:
13153       return;
13154     case Intrinsic::aarch64_sve_clasta_n: {
13155       SDLoc DL(N);
13156       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13157       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
13158                            N->getOperand(1), Op2, N->getOperand(3));
13159       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13160       return;
13161     }
13162     case Intrinsic::aarch64_sve_clastb_n: {
13163       SDLoc DL(N);
13164       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13165       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
13166                            N->getOperand(1), Op2, N->getOperand(3));
13167       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13168       return;
13169     }
13170     case Intrinsic::aarch64_sve_lasta: {
13171       SDLoc DL(N);
13172       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
13173                            N->getOperand(1), N->getOperand(2));
13174       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13175       return;
13176     }
13177     case Intrinsic::aarch64_sve_lastb: {
13178       SDLoc DL(N);
13179       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
13180                            N->getOperand(1), N->getOperand(2));
13181       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13182       return;
13183     }
13184     }
13185   }
13186   }
13187 }
13188 
13189 bool AArch64TargetLowering::useLoadStackGuardNode() const {
13190   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
13191     return TargetLowering::useLoadStackGuardNode();
13192   return true;
13193 }
13194 
13195 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
13196   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13197   // reciprocal if there are three or more FDIVs.
13198   return 3;
13199 }
13200 
13201 TargetLoweringBase::LegalizeTypeAction
13202 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
13203   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
13204   // v4i16, v2i32 instead of to promote.
13205   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
13206       VT == MVT::v1f32)
13207     return TypeWidenVector;
13208 
13209   return TargetLoweringBase::getPreferredVectorAction(VT);
13210 }
13211 
13212 // Loads and stores less than 128-bits are already atomic; ones above that
13213 // are doomed anyway, so defer to the default libcall and blame the OS when
13214 // things go wrong.
13215 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13216   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13217   return Size == 128;
13218 }
13219 
13220 // Loads and stores less than 128-bits are already atomic; ones above that
13221 // are doomed anyway, so defer to the default libcall and blame the OS when
13222 // things go wrong.
13223 TargetLowering::AtomicExpansionKind
13224 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13225   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13226   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
13227 }
13228 
13229 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
13230 TargetLowering::AtomicExpansionKind
13231 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13232   if (AI->isFloatingPointOperation())
13233     return AtomicExpansionKind::CmpXChg;
13234 
13235   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13236   if (Size > 128) return AtomicExpansionKind::None;
13237   // Nand not supported in LSE.
13238   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13239   // Leave 128 bits to LLSC.
13240   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13241 }
13242 
13243 TargetLowering::AtomicExpansionKind
13244 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13245     AtomicCmpXchgInst *AI) const {
13246   // If subtarget has LSE, leave cmpxchg intact for codegen.
13247   if (Subtarget->hasLSE())
13248     return AtomicExpansionKind::None;
13249   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13250   // implement cmpxchg without spilling. If the address being exchanged is also
13251   // on the stack and close enough to the spill slot, this can lead to a
13252   // situation where the monitor always gets cleared and the atomic operation
13253   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13254   if (getTargetMachine().getOptLevel() == 0)
13255     return AtomicExpansionKind::None;
13256   return AtomicExpansionKind::LLSC;
13257 }
13258 
13259 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13260                                              AtomicOrdering Ord) const {
13261   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13262   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13263   bool IsAcquire = isAcquireOrStronger(Ord);
13264 
13265   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13266   // intrinsic must return {i64, i64} and we have to recombine them into a
13267   // single i128 here.
13268   if (ValTy->getPrimitiveSizeInBits() == 128) {
13269     Intrinsic::ID Int =
13270         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13271     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13272 
13273     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13274     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13275 
13276     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13277     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13278     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13279     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13280     return Builder.CreateOr(
13281         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13282   }
13283 
13284   Type *Tys[] = { Addr->getType() };
13285   Intrinsic::ID Int =
13286       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13287   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13288 
13289   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13290 
13291   const DataLayout &DL = M->getDataLayout();
13292   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13293   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13294 
13295   return Builder.CreateBitCast(Trunc, EltTy);
13296 }
13297 
13298 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13299     IRBuilder<> &Builder) const {
13300   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13301   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13302 }
13303 
13304 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13305                                                    Value *Val, Value *Addr,
13306                                                    AtomicOrdering Ord) const {
13307   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13308   bool IsRelease = isReleaseOrStronger(Ord);
13309 
13310   // Since the intrinsics must have legal type, the i128 intrinsics take two
13311   // parameters: "i64, i64". We must marshal Val into the appropriate form
13312   // before the call.
13313   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13314     Intrinsic::ID Int =
13315         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13316     Function *Stxr = Intrinsic::getDeclaration(M, Int);
13317     Type *Int64Ty = Type::getInt64Ty(M->getContext());
13318 
13319     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13320     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13321     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13322     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13323   }
13324 
13325   Intrinsic::ID Int =
13326       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13327   Type *Tys[] = { Addr->getType() };
13328   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13329 
13330   const DataLayout &DL = M->getDataLayout();
13331   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13332   Val = Builder.CreateBitCast(Val, IntValTy);
13333 
13334   return Builder.CreateCall(Stxr,
13335                             {Builder.CreateZExtOrBitCast(
13336                                  Val, Stxr->getFunctionType()->getParamType(0)),
13337                              Addr});
13338 }
13339 
13340 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13341     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13342   return Ty->isArrayTy();
13343 }
13344 
13345 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13346                                                             EVT) const {
13347   return false;
13348 }
13349 
13350 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13351   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13352   Function *ThreadPointerFunc =
13353       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13354   return IRB.CreatePointerCast(
13355       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13356                              Offset),
13357       IRB.getInt8PtrTy()->getPointerTo(0));
13358 }
13359 
13360 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13361   // Android provides a fixed TLS slot for the stack cookie. See the definition
13362   // of TLS_SLOT_STACK_GUARD in
13363   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13364   if (Subtarget->isTargetAndroid())
13365     return UseTlsOffset(IRB, 0x28);
13366 
13367   // Fuchsia is similar.
13368   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13369   if (Subtarget->isTargetFuchsia())
13370     return UseTlsOffset(IRB, -0x10);
13371 
13372   return TargetLowering::getIRStackGuard(IRB);
13373 }
13374 
13375 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13376   // MSVC CRT provides functionalities for stack protection.
13377   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13378     // MSVC CRT has a global variable holding security cookie.
13379     M.getOrInsertGlobal("__security_cookie",
13380                         Type::getInt8PtrTy(M.getContext()));
13381 
13382     // MSVC CRT has a function to validate security cookie.
13383     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13384         "__security_check_cookie", Type::getVoidTy(M.getContext()),
13385         Type::getInt8PtrTy(M.getContext()));
13386     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13387       F->setCallingConv(CallingConv::Win64);
13388       F->addAttribute(1, Attribute::AttrKind::InReg);
13389     }
13390     return;
13391   }
13392   TargetLowering::insertSSPDeclarations(M);
13393 }
13394 
13395 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13396   // MSVC CRT has a global variable holding security cookie.
13397   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13398     return M.getGlobalVariable("__security_cookie");
13399   return TargetLowering::getSDagStackGuard(M);
13400 }
13401 
13402 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13403   // MSVC CRT has a function to validate security cookie.
13404   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13405     return M.getFunction("__security_check_cookie");
13406   return TargetLowering::getSSPStackGuardCheck(M);
13407 }
13408 
13409 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13410   // Android provides a fixed TLS slot for the SafeStack pointer. See the
13411   // definition of TLS_SLOT_SAFESTACK in
13412   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13413   if (Subtarget->isTargetAndroid())
13414     return UseTlsOffset(IRB, 0x48);
13415 
13416   // Fuchsia is similar.
13417   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13418   if (Subtarget->isTargetFuchsia())
13419     return UseTlsOffset(IRB, -0x8);
13420 
13421   return TargetLowering::getSafeStackPointerLocation(IRB);
13422 }
13423 
13424 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13425     const Instruction &AndI) const {
13426   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13427   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
13428   // may be beneficial to sink in other cases, but we would have to check that
13429   // the cmp would not get folded into the br to form a cbz for these to be
13430   // beneficial.
13431   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13432   if (!Mask)
13433     return false;
13434   return Mask->getValue().isPowerOf2();
13435 }
13436 
13437 bool AArch64TargetLowering::
13438     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13439         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13440         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13441         SelectionDAG &DAG) const {
13442   // Does baseline recommend not to perform the fold by default?
13443   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13444           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13445     return false;
13446   // Else, if this is a vector shift, prefer 'shl'.
13447   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13448 }
13449 
13450 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13451                                               SDNode *N) const {
13452   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13453       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13454     return false;
13455   return true;
13456 }
13457 
13458 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13459   // Update IsSplitCSR in AArch64unctionInfo.
13460   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13461   AFI->setIsSplitCSR(true);
13462 }
13463 
13464 void AArch64TargetLowering::insertCopiesSplitCSR(
13465     MachineBasicBlock *Entry,
13466     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13467   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13468   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13469   if (!IStart)
13470     return;
13471 
13472   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13473   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13474   MachineBasicBlock::iterator MBBI = Entry->begin();
13475   for (const MCPhysReg *I = IStart; *I; ++I) {
13476     const TargetRegisterClass *RC = nullptr;
13477     if (AArch64::GPR64RegClass.contains(*I))
13478       RC = &AArch64::GPR64RegClass;
13479     else if (AArch64::FPR64RegClass.contains(*I))
13480       RC = &AArch64::FPR64RegClass;
13481     else
13482       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13483 
13484     Register NewVR = MRI->createVirtualRegister(RC);
13485     // Create copy from CSR to a virtual register.
13486     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13487     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13488     // nounwind. If we want to generalize this later, we may need to emit
13489     // CFI pseudo-instructions.
13490     assert(Entry->getParent()->getFunction().hasFnAttribute(
13491                Attribute::NoUnwind) &&
13492            "Function should be nounwind in insertCopiesSplitCSR!");
13493     Entry->addLiveIn(*I);
13494     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13495         .addReg(*I);
13496 
13497     // Insert the copy-back instructions right before the terminator.
13498     for (auto *Exit : Exits)
13499       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13500               TII->get(TargetOpcode::COPY), *I)
13501           .addReg(NewVR);
13502   }
13503 }
13504 
13505 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13506   // Integer division on AArch64 is expensive. However, when aggressively
13507   // optimizing for code size, we prefer to use a div instruction, as it is
13508   // usually smaller than the alternative sequence.
13509   // The exception to this is vector division. Since AArch64 doesn't have vector
13510   // integer division, leaving the division as-is is a loss even in terms of
13511   // size, because it will have to be scalarized, while the alternative code
13512   // sequence can be performed in vector form.
13513   bool OptSize =
13514       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13515   return OptSize && !VT.isVector();
13516 }
13517 
13518 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13519   // We want inc-of-add for scalars and sub-of-not for vectors.
13520   return VT.isScalarInteger();
13521 }
13522 
13523 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13524   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13525 }
13526 
13527 unsigned
13528 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13529   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13530     return getPointerTy(DL).getSizeInBits();
13531 
13532   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13533 }
13534 
13535 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13536   MF.getFrameInfo().computeMaxCallFrameSize(MF);
13537   TargetLoweringBase::finalizeLowering(MF);
13538 }
13539 
13540 // Unlike X86, we let frame lowering assign offsets to all catch objects.
13541 bool AArch64TargetLowering::needsFixedCatchObjects() const {
13542   return false;
13543 }
13544