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 "AArch64ExpandImm.h"
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.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/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/Use.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Target/TargetMachine.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <algorithm>
80 #include <bitset>
81 #include <cassert>
82 #include <cctype>
83 #include <cstdint>
84 #include <cstdlib>
85 #include <iterator>
86 #include <limits>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 using namespace llvm::PatternMatch;
93 
94 #define DEBUG_TYPE "aarch64-lower"
95 
96 STATISTIC(NumTailCalls, "Number of tail calls");
97 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
98 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
99 
100 static cl::opt<bool>
101 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
102                            cl::desc("Allow AArch64 SLI/SRI formation"),
103                            cl::init(false));
104 
105 // FIXME: The necessary dtprel relocations don't seem to be supported
106 // well in the GNU bfd and gold linkers at the moment. Therefore, by
107 // default, for now, fall back to GeneralDynamic code generation.
108 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109     "aarch64-elf-ldtls-generation", cl::Hidden,
110     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111     cl::init(false));
112 
113 static cl::opt<bool>
114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115                          cl::desc("Enable AArch64 logical imm instruction "
116                                   "optimization"),
117                          cl::init(true));
118 
119 /// Value type used for condition codes.
120 static const MVT MVT_CC = MVT::i32;
121 
122 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123                                              const AArch64Subtarget &STI)
124     : TargetLowering(TM), Subtarget(&STI) {
125   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126   // we have to make something up. Arbitrarily, choose ZeroOrOne.
127   setBooleanContents(ZeroOrOneBooleanContent);
128   // When comparing vectors the result sets the different elements in the
129   // vector to all-one or all-zero.
130   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
131 
132   // Set up the register classes.
133   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
135 
136   if (Subtarget->hasFPARMv8()) {
137     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
141   }
142 
143   if (Subtarget->hasNEON()) {
144     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146     // Someone set us up the NEON.
147     addDRTypeForNEON(MVT::v2f32);
148     addDRTypeForNEON(MVT::v8i8);
149     addDRTypeForNEON(MVT::v4i16);
150     addDRTypeForNEON(MVT::v2i32);
151     addDRTypeForNEON(MVT::v1i64);
152     addDRTypeForNEON(MVT::v1f64);
153     addDRTypeForNEON(MVT::v4f16);
154 
155     addQRTypeForNEON(MVT::v4f32);
156     addQRTypeForNEON(MVT::v2f64);
157     addQRTypeForNEON(MVT::v16i8);
158     addQRTypeForNEON(MVT::v8i16);
159     addQRTypeForNEON(MVT::v4i32);
160     addQRTypeForNEON(MVT::v2i64);
161     addQRTypeForNEON(MVT::v8f16);
162   }
163 
164   if (Subtarget->hasSVE()) {
165     // Add legal sve predicate types
166     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
167     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
168     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
169     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
170 
171     // Add legal sve data types
172     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
173     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
174     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
175     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
176 
177     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
178     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
179     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
180     addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
181     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
182     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
183     addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
184     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
185   }
186 
187   // Compute derived properties from the register classes
188   computeRegisterProperties(Subtarget->getRegisterInfo());
189 
190   // Provide all sorts of operation actions
191   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
192   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
193   setOperationAction(ISD::SETCC, MVT::i32, Custom);
194   setOperationAction(ISD::SETCC, MVT::i64, Custom);
195   setOperationAction(ISD::SETCC, MVT::f16, Custom);
196   setOperationAction(ISD::SETCC, MVT::f32, Custom);
197   setOperationAction(ISD::SETCC, MVT::f64, Custom);
198   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
199   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
200   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
201   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
202   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
203   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
204   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
205   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
206   setOperationAction(ISD::SELECT, MVT::i32, Custom);
207   setOperationAction(ISD::SELECT, MVT::i64, Custom);
208   setOperationAction(ISD::SELECT, MVT::f16, Custom);
209   setOperationAction(ISD::SELECT, MVT::f32, Custom);
210   setOperationAction(ISD::SELECT, MVT::f64, Custom);
211   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
212   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
213   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
214   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
215   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
216   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
217   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
218 
219   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
220   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
221   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
222 
223   setOperationAction(ISD::FREM, MVT::f32, Expand);
224   setOperationAction(ISD::FREM, MVT::f64, Expand);
225   setOperationAction(ISD::FREM, MVT::f80, Expand);
226 
227   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
228 
229   // Custom lowering hooks are needed for XOR
230   // to fold it into CSINC/CSINV.
231   setOperationAction(ISD::XOR, MVT::i32, Custom);
232   setOperationAction(ISD::XOR, MVT::i64, Custom);
233 
234   // Virtually no operation on f128 is legal, but LLVM can't expand them when
235   // there's a valid register class, so we need custom operations in most cases.
236   setOperationAction(ISD::FABS, MVT::f128, Expand);
237   setOperationAction(ISD::FADD, MVT::f128, Custom);
238   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
239   setOperationAction(ISD::FCOS, MVT::f128, Expand);
240   setOperationAction(ISD::FDIV, MVT::f128, Custom);
241   setOperationAction(ISD::FMA, MVT::f128, Expand);
242   setOperationAction(ISD::FMUL, MVT::f128, Custom);
243   setOperationAction(ISD::FNEG, MVT::f128, Expand);
244   setOperationAction(ISD::FPOW, MVT::f128, Expand);
245   setOperationAction(ISD::FREM, MVT::f128, Expand);
246   setOperationAction(ISD::FRINT, MVT::f128, Expand);
247   setOperationAction(ISD::FSIN, MVT::f128, Expand);
248   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
249   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
250   setOperationAction(ISD::FSUB, MVT::f128, Custom);
251   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
252   setOperationAction(ISD::SETCC, MVT::f128, Custom);
253   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
254   setOperationAction(ISD::SELECT, MVT::f128, Custom);
255   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
256   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
257 
258   // Lowering for many of the conversions is actually specified by the non-f128
259   // type. The LowerXXX function will be trivial when f128 isn't involved.
260   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
262   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
263   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
264   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
265   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
266   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
267   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
268   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
269   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
270   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
271   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
272   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
273   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
274 
275   // Variable arguments.
276   setOperationAction(ISD::VASTART, MVT::Other, Custom);
277   setOperationAction(ISD::VAARG, MVT::Other, Custom);
278   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
279   setOperationAction(ISD::VAEND, MVT::Other, Expand);
280 
281   // Variable-sized objects.
282   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
283   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
284 
285   if (Subtarget->isTargetWindows())
286     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
287   else
288     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
289 
290   // Constant pool entries
291   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
292 
293   // BlockAddress
294   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
295 
296   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
297   setOperationAction(ISD::ADDC, MVT::i32, Custom);
298   setOperationAction(ISD::ADDE, MVT::i32, Custom);
299   setOperationAction(ISD::SUBC, MVT::i32, Custom);
300   setOperationAction(ISD::SUBE, MVT::i32, Custom);
301   setOperationAction(ISD::ADDC, MVT::i64, Custom);
302   setOperationAction(ISD::ADDE, MVT::i64, Custom);
303   setOperationAction(ISD::SUBC, MVT::i64, Custom);
304   setOperationAction(ISD::SUBE, MVT::i64, Custom);
305 
306   // AArch64 lacks both left-rotate and popcount instructions.
307   setOperationAction(ISD::ROTL, MVT::i32, Expand);
308   setOperationAction(ISD::ROTL, MVT::i64, Expand);
309   for (MVT VT : MVT::vector_valuetypes()) {
310     setOperationAction(ISD::ROTL, VT, Expand);
311     setOperationAction(ISD::ROTR, VT, Expand);
312   }
313 
314   // AArch64 doesn't have {U|S}MUL_LOHI.
315   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
316   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
317 
318   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
319   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
320 
321   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
322   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
323   for (MVT VT : MVT::vector_valuetypes()) {
324     setOperationAction(ISD::SDIVREM, VT, Expand);
325     setOperationAction(ISD::UDIVREM, VT, Expand);
326   }
327   setOperationAction(ISD::SREM, MVT::i32, Expand);
328   setOperationAction(ISD::SREM, MVT::i64, Expand);
329   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
330   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
331   setOperationAction(ISD::UREM, MVT::i32, Expand);
332   setOperationAction(ISD::UREM, MVT::i64, Expand);
333 
334   // Custom lower Add/Sub/Mul with overflow.
335   setOperationAction(ISD::SADDO, MVT::i32, Custom);
336   setOperationAction(ISD::SADDO, MVT::i64, Custom);
337   setOperationAction(ISD::UADDO, MVT::i32, Custom);
338   setOperationAction(ISD::UADDO, MVT::i64, Custom);
339   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
340   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
341   setOperationAction(ISD::USUBO, MVT::i32, Custom);
342   setOperationAction(ISD::USUBO, MVT::i64, Custom);
343   setOperationAction(ISD::SMULO, MVT::i32, Custom);
344   setOperationAction(ISD::SMULO, MVT::i64, Custom);
345   setOperationAction(ISD::UMULO, MVT::i32, Custom);
346   setOperationAction(ISD::UMULO, MVT::i64, Custom);
347 
348   setOperationAction(ISD::FSIN, MVT::f32, Expand);
349   setOperationAction(ISD::FSIN, MVT::f64, Expand);
350   setOperationAction(ISD::FCOS, MVT::f32, Expand);
351   setOperationAction(ISD::FCOS, MVT::f64, Expand);
352   setOperationAction(ISD::FPOW, MVT::f32, Expand);
353   setOperationAction(ISD::FPOW, MVT::f64, Expand);
354   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
355   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
356   if (Subtarget->hasFullFP16())
357     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
358   else
359     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
360 
361   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
362   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
363   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
364   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
365   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
366   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
367   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
368   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
369   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
370   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
371   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
372   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
373   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
374   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
375   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
376   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
377   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
378   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
379   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
380   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
381   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
382   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
383   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
384   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
385   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
386   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
387   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
388   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
389   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
390   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
391   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
392   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
393   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
394 
395   if (!Subtarget->hasFullFP16()) {
396     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
397     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
398     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
399     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
400     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
401     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
402     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
403     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
404     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
405     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
406     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
407     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
408     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
409     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
410     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
411     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
412     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
413     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
414     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
415     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
416     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
417     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
418 
419     // promote v4f16 to v4f32 when that is known to be safe.
420     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
421     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
422     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
423     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
424     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
425     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
426     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
427     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
428     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
429     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
430     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
431     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
432 
433     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
434     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
435     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
436     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
437     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
438     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
439     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
440     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
441     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
442     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
443     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
444     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
445     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
446     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
447     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
448 
449     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
450     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
451     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
452     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
453     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
454     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
455     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
456     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
457     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
458     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
459     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
460     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
461     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
462     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
463     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
464     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
465     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
466     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
467     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
468     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
469   }
470 
471   // AArch64 has implementations of a lot of rounding-like FP operations.
472   for (MVT Ty : {MVT::f32, MVT::f64}) {
473     setOperationAction(ISD::FFLOOR, Ty, Legal);
474     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
475     setOperationAction(ISD::FCEIL, Ty, Legal);
476     setOperationAction(ISD::FRINT, Ty, Legal);
477     setOperationAction(ISD::FTRUNC, Ty, Legal);
478     setOperationAction(ISD::FROUND, Ty, Legal);
479     setOperationAction(ISD::FMINNUM, Ty, Legal);
480     setOperationAction(ISD::FMAXNUM, Ty, Legal);
481     setOperationAction(ISD::FMINIMUM, Ty, Legal);
482     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
483     setOperationAction(ISD::LROUND, Ty, Legal);
484     setOperationAction(ISD::LLROUND, Ty, Legal);
485     setOperationAction(ISD::LRINT, Ty, Legal);
486     setOperationAction(ISD::LLRINT, Ty, Legal);
487   }
488 
489   if (Subtarget->hasFullFP16()) {
490     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
491     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
492     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
493     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
494     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
495     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
496     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
497     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
498     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
499     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
500   }
501 
502   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
503 
504   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
505 
506   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
507   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
508   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
509   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
510   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
511 
512   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
513   // This requires the Performance Monitors extension.
514   if (Subtarget->hasPerfMon())
515     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
516 
517   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
518       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
519     // Issue __sincos_stret if available.
520     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
521     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
522   } else {
523     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
524     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
525   }
526 
527   // Make floating-point constants legal for the large code model, so they don't
528   // become loads from the constant pool.
529   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
530     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
531     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
532   }
533 
534   // AArch64 does not have floating-point extending loads, i1 sign-extending
535   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
536   for (MVT VT : MVT::fp_valuetypes()) {
537     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
538     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
539     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
540     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
541   }
542   for (MVT VT : MVT::integer_valuetypes())
543     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
544 
545   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
546   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
547   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
548   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
549   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
550   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
551   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
552 
553   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
554   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
555 
556   // Indexed loads and stores are supported.
557   for (unsigned im = (unsigned)ISD::PRE_INC;
558        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
559     setIndexedLoadAction(im, MVT::i8, Legal);
560     setIndexedLoadAction(im, MVT::i16, Legal);
561     setIndexedLoadAction(im, MVT::i32, Legal);
562     setIndexedLoadAction(im, MVT::i64, Legal);
563     setIndexedLoadAction(im, MVT::f64, Legal);
564     setIndexedLoadAction(im, MVT::f32, Legal);
565     setIndexedLoadAction(im, MVT::f16, Legal);
566     setIndexedStoreAction(im, MVT::i8, Legal);
567     setIndexedStoreAction(im, MVT::i16, Legal);
568     setIndexedStoreAction(im, MVT::i32, Legal);
569     setIndexedStoreAction(im, MVT::i64, Legal);
570     setIndexedStoreAction(im, MVT::f64, Legal);
571     setIndexedStoreAction(im, MVT::f32, Legal);
572     setIndexedStoreAction(im, MVT::f16, Legal);
573   }
574 
575   // Trap.
576   setOperationAction(ISD::TRAP, MVT::Other, Legal);
577   if (Subtarget->isTargetWindows())
578     setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
579 
580   // We combine OR nodes for bitfield operations.
581   setTargetDAGCombine(ISD::OR);
582   // Try to create BICs for vector ANDs.
583   setTargetDAGCombine(ISD::AND);
584 
585   // Vector add and sub nodes may conceal a high-half opportunity.
586   // Also, try to fold ADD into CSINC/CSINV..
587   setTargetDAGCombine(ISD::ADD);
588   setTargetDAGCombine(ISD::SUB);
589   setTargetDAGCombine(ISD::SRL);
590   setTargetDAGCombine(ISD::XOR);
591   setTargetDAGCombine(ISD::SINT_TO_FP);
592   setTargetDAGCombine(ISD::UINT_TO_FP);
593 
594   setTargetDAGCombine(ISD::FP_TO_SINT);
595   setTargetDAGCombine(ISD::FP_TO_UINT);
596   setTargetDAGCombine(ISD::FDIV);
597 
598   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
599 
600   setTargetDAGCombine(ISD::ANY_EXTEND);
601   setTargetDAGCombine(ISD::ZERO_EXTEND);
602   setTargetDAGCombine(ISD::SIGN_EXTEND);
603   setTargetDAGCombine(ISD::BITCAST);
604   setTargetDAGCombine(ISD::CONCAT_VECTORS);
605   setTargetDAGCombine(ISD::STORE);
606   if (Subtarget->supportsAddressTopByteIgnored())
607     setTargetDAGCombine(ISD::LOAD);
608 
609   setTargetDAGCombine(ISD::MUL);
610 
611   setTargetDAGCombine(ISD::SELECT);
612   setTargetDAGCombine(ISD::VSELECT);
613 
614   setTargetDAGCombine(ISD::INTRINSIC_VOID);
615   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
616   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
617 
618   setTargetDAGCombine(ISD::GlobalAddress);
619 
620   // In case of strict alignment, avoid an excessive number of byte wide stores.
621   MaxStoresPerMemsetOptSize = 8;
622   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
623                        ? MaxStoresPerMemsetOptSize : 32;
624 
625   MaxGluedStoresPerMemcpy = 4;
626   MaxStoresPerMemcpyOptSize = 4;
627   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
628                        ? MaxStoresPerMemcpyOptSize : 16;
629 
630   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
631 
632   MaxLoadsPerMemcmpOptSize = 4;
633   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
634                       ? MaxLoadsPerMemcmpOptSize : 8;
635 
636   setStackPointerRegisterToSaveRestore(AArch64::SP);
637 
638   setSchedulingPreference(Sched::Hybrid);
639 
640   EnableExtLdPromotion = true;
641 
642   // Set required alignment.
643   setMinFunctionAlignment(2);
644   // Set preferred alignments.
645   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
646   setPrefLoopAlignment(STI.getPrefLoopAlignment());
647 
648   // Only change the limit for entries in a jump table if specified by
649   // the sub target, but not at the command line.
650   unsigned MaxJT = STI.getMaximumJumpTableSize();
651   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
652     setMaximumJumpTableSize(MaxJT);
653 
654   setHasExtractBitsInsn(true);
655 
656   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
657 
658   if (Subtarget->hasNEON()) {
659     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
660     // silliness like this:
661     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
662     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
663     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
664     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
665     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
666     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
667     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
668     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
669     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
670     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
671     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
672     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
673     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
674     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
675     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
676     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
678     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
679     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
680     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
681     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
682     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
683     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
684     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
685     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
686 
687     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
688     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
689     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
690     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
691     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
692 
693     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
694 
695     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
696     // elements smaller than i32, so promote the input to i32 first.
697     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
698     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
699     // i8 vector elements also need promotion to i32 for v8i8
700     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
701     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
702     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
703     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
704     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
705     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
706     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
707     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
708     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
709     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
710     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
711 
712     if (Subtarget->hasFullFP16()) {
713       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
714       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
715       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
716       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
717     } else {
718       // when AArch64 doesn't have fullfp16 support, promote the input
719       // to i32 first.
720       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
721       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
722       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
723       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
724     }
725 
726     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
727     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
728 
729     // AArch64 doesn't have MUL.2d:
730     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
731     // Custom handling for some quad-vector types to detect MULL.
732     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
733     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
734     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
735 
736     // Vector reductions
737     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
738                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
739       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
740       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
741       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
742       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
743       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
744     }
745     for (MVT VT : { MVT::v4f16, MVT::v2f32,
746                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
747       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
748       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
749     }
750 
751     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
752     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
753     // Likewise, narrowing and extending vector loads/stores aren't handled
754     // directly.
755     for (MVT VT : MVT::vector_valuetypes()) {
756       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
757 
758       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
759         setOperationAction(ISD::MULHS, VT, Legal);
760         setOperationAction(ISD::MULHU, VT, Legal);
761       } else {
762         setOperationAction(ISD::MULHS, VT, Expand);
763         setOperationAction(ISD::MULHU, VT, Expand);
764       }
765       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
766       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
767 
768       setOperationAction(ISD::BSWAP, VT, Expand);
769       setOperationAction(ISD::CTTZ, VT, Expand);
770 
771       for (MVT InnerVT : MVT::vector_valuetypes()) {
772         setTruncStoreAction(VT, InnerVT, Expand);
773         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
774         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
775         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
776       }
777     }
778 
779     // AArch64 has implementations of a lot of rounding-like FP operations.
780     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
781       setOperationAction(ISD::FFLOOR, Ty, Legal);
782       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
783       setOperationAction(ISD::FCEIL, Ty, Legal);
784       setOperationAction(ISD::FRINT, Ty, Legal);
785       setOperationAction(ISD::FTRUNC, Ty, Legal);
786       setOperationAction(ISD::FROUND, Ty, Legal);
787     }
788 
789     if (Subtarget->hasFullFP16()) {
790       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
791         setOperationAction(ISD::FFLOOR, Ty, Legal);
792         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
793         setOperationAction(ISD::FCEIL, Ty, Legal);
794         setOperationAction(ISD::FRINT, Ty, Legal);
795         setOperationAction(ISD::FTRUNC, Ty, Legal);
796         setOperationAction(ISD::FROUND, Ty, Legal);
797       }
798     }
799 
800     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
801   }
802 
803   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
804 }
805 
806 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
807   assert(VT.isVector() && "VT should be a vector type");
808 
809   if (VT.isFloatingPoint()) {
810     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
811     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
812     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
813   }
814 
815   // Mark vector float intrinsics as expand.
816   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
817     setOperationAction(ISD::FSIN, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FPOW, VT, Expand);
820     setOperationAction(ISD::FLOG, VT, Expand);
821     setOperationAction(ISD::FLOG2, VT, Expand);
822     setOperationAction(ISD::FLOG10, VT, Expand);
823     setOperationAction(ISD::FEXP, VT, Expand);
824     setOperationAction(ISD::FEXP2, VT, Expand);
825 
826     // But we do support custom-lowering for FCOPYSIGN.
827     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
828   }
829 
830   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
831   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
832   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
833   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
834   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
835   setOperationAction(ISD::SRA, VT, Custom);
836   setOperationAction(ISD::SRL, VT, Custom);
837   setOperationAction(ISD::SHL, VT, Custom);
838   setOperationAction(ISD::OR, VT, Custom);
839   setOperationAction(ISD::SETCC, VT, Custom);
840   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
841 
842   setOperationAction(ISD::SELECT, VT, Expand);
843   setOperationAction(ISD::SELECT_CC, VT, Expand);
844   setOperationAction(ISD::VSELECT, VT, Expand);
845   for (MVT InnerVT : MVT::all_valuetypes())
846     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
847 
848   // CNT supports only B element sizes, then use UADDLP to widen.
849   if (VT != MVT::v8i8 && VT != MVT::v16i8)
850     setOperationAction(ISD::CTPOP, VT, Custom);
851 
852   setOperationAction(ISD::UDIV, VT, Expand);
853   setOperationAction(ISD::SDIV, VT, Expand);
854   setOperationAction(ISD::UREM, VT, Expand);
855   setOperationAction(ISD::SREM, VT, Expand);
856   setOperationAction(ISD::FREM, VT, Expand);
857 
858   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
859   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
860 
861   if (!VT.isFloatingPoint())
862     setOperationAction(ISD::ABS, VT, Legal);
863 
864   // [SU][MIN|MAX] are available for all NEON types apart from i64.
865   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
866     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
867       setOperationAction(Opcode, VT, Legal);
868 
869   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
870   if (VT.isFloatingPoint() &&
871       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
872     for (unsigned Opcode :
873          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
874       setOperationAction(Opcode, VT, Legal);
875 
876   if (Subtarget->isLittleEndian()) {
877     for (unsigned im = (unsigned)ISD::PRE_INC;
878          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
879       setIndexedLoadAction(im, VT, Legal);
880       setIndexedStoreAction(im, VT, Legal);
881     }
882   }
883 }
884 
885 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
886   addRegisterClass(VT, &AArch64::FPR64RegClass);
887   addTypeForNEON(VT, MVT::v2i32);
888 }
889 
890 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
891   addRegisterClass(VT, &AArch64::FPR128RegClass);
892   addTypeForNEON(VT, MVT::v4i32);
893 }
894 
895 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
896                                               EVT VT) const {
897   if (!VT.isVector())
898     return MVT::i32;
899   return VT.changeVectorElementTypeToInteger();
900 }
901 
902 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
903                                const APInt &Demanded,
904                                TargetLowering::TargetLoweringOpt &TLO,
905                                unsigned NewOpc) {
906   uint64_t OldImm = Imm, NewImm, Enc;
907   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
908 
909   // Return if the immediate is already all zeros, all ones, a bimm32 or a
910   // bimm64.
911   if (Imm == 0 || Imm == Mask ||
912       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
913     return false;
914 
915   unsigned EltSize = Size;
916   uint64_t DemandedBits = Demanded.getZExtValue();
917 
918   // Clear bits that are not demanded.
919   Imm &= DemandedBits;
920 
921   while (true) {
922     // The goal here is to set the non-demanded bits in a way that minimizes
923     // the number of switching between 0 and 1. In order to achieve this goal,
924     // we set the non-demanded bits to the value of the preceding demanded bits.
925     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
926     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
927     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
928     // The final result is 0b11000011.
929     uint64_t NonDemandedBits = ~DemandedBits;
930     uint64_t InvertedImm = ~Imm & DemandedBits;
931     uint64_t RotatedImm =
932         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
933         NonDemandedBits;
934     uint64_t Sum = RotatedImm + NonDemandedBits;
935     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
936     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
937     NewImm = (Imm | Ones) & Mask;
938 
939     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
940     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
941     // we halve the element size and continue the search.
942     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
943       break;
944 
945     // We cannot shrink the element size any further if it is 2-bits.
946     if (EltSize == 2)
947       return false;
948 
949     EltSize /= 2;
950     Mask >>= EltSize;
951     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
952 
953     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
954     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
955       return false;
956 
957     // Merge the upper and lower halves of Imm and DemandedBits.
958     Imm |= Hi;
959     DemandedBits |= DemandedBitsHi;
960   }
961 
962   ++NumOptimizedImms;
963 
964   // Replicate the element across the register width.
965   while (EltSize < Size) {
966     NewImm |= NewImm << EltSize;
967     EltSize *= 2;
968   }
969 
970   (void)OldImm;
971   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
972          "demanded bits should never be altered");
973   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
974 
975   // Create the new constant immediate node.
976   EVT VT = Op.getValueType();
977   SDLoc DL(Op);
978   SDValue New;
979 
980   // If the new constant immediate is all-zeros or all-ones, let the target
981   // independent DAG combine optimize this node.
982   if (NewImm == 0 || NewImm == OrigMask) {
983     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
984                           TLO.DAG.getConstant(NewImm, DL, VT));
985   // Otherwise, create a machine node so that target independent DAG combine
986   // doesn't undo this optimization.
987   } else {
988     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
989     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
990     New = SDValue(
991         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
992   }
993 
994   return TLO.CombineTo(Op, New);
995 }
996 
997 bool AArch64TargetLowering::targetShrinkDemandedConstant(
998     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
999   // Delay this optimization to as late as possible.
1000   if (!TLO.LegalOps)
1001     return false;
1002 
1003   if (!EnableOptimizeLogicalImm)
1004     return false;
1005 
1006   EVT VT = Op.getValueType();
1007   if (VT.isVector())
1008     return false;
1009 
1010   unsigned Size = VT.getSizeInBits();
1011   assert((Size == 32 || Size == 64) &&
1012          "i32 or i64 is expected after legalization.");
1013 
1014   // Exit early if we demand all bits.
1015   if (Demanded.countPopulation() == Size)
1016     return false;
1017 
1018   unsigned NewOpc;
1019   switch (Op.getOpcode()) {
1020   default:
1021     return false;
1022   case ISD::AND:
1023     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1024     break;
1025   case ISD::OR:
1026     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1027     break;
1028   case ISD::XOR:
1029     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1030     break;
1031   }
1032   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1033   if (!C)
1034     return false;
1035   uint64_t Imm = C->getZExtValue();
1036   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1037 }
1038 
1039 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1040 /// Mask are known to be either zero or one and return them Known.
1041 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1042     const SDValue Op, KnownBits &Known,
1043     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1044   switch (Op.getOpcode()) {
1045   default:
1046     break;
1047   case AArch64ISD::CSEL: {
1048     KnownBits Known2;
1049     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1050     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1051     Known.Zero &= Known2.Zero;
1052     Known.One &= Known2.One;
1053     break;
1054   }
1055   case ISD::INTRINSIC_W_CHAIN: {
1056     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1057     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1058     switch (IntID) {
1059     default: return;
1060     case Intrinsic::aarch64_ldaxr:
1061     case Intrinsic::aarch64_ldxr: {
1062       unsigned BitWidth = Known.getBitWidth();
1063       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1064       unsigned MemBits = VT.getScalarSizeInBits();
1065       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1066       return;
1067     }
1068     }
1069     break;
1070   }
1071   case ISD::INTRINSIC_WO_CHAIN:
1072   case ISD::INTRINSIC_VOID: {
1073     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1074     switch (IntNo) {
1075     default:
1076       break;
1077     case Intrinsic::aarch64_neon_umaxv:
1078     case Intrinsic::aarch64_neon_uminv: {
1079       // Figure out the datatype of the vector operand. The UMINV instruction
1080       // will zero extend the result, so we can mark as known zero all the
1081       // bits larger than the element datatype. 32-bit or larget doesn't need
1082       // this as those are legal types and will be handled by isel directly.
1083       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1084       unsigned BitWidth = Known.getBitWidth();
1085       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1086         assert(BitWidth >= 8 && "Unexpected width!");
1087         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1088         Known.Zero |= Mask;
1089       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1090         assert(BitWidth >= 16 && "Unexpected width!");
1091         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1092         Known.Zero |= Mask;
1093       }
1094       break;
1095     } break;
1096     }
1097   }
1098   }
1099 }
1100 
1101 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1102                                                   EVT) const {
1103   return MVT::i64;
1104 }
1105 
1106 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1107     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1108     bool *Fast) const {
1109   if (Subtarget->requiresStrictAlign())
1110     return false;
1111 
1112   if (Fast) {
1113     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1114     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1115             // See comments in performSTORECombine() for more details about
1116             // these conditions.
1117 
1118             // Code that uses clang vector extensions can mark that it
1119             // wants unaligned accesses to be treated as fast by
1120             // underspecifying alignment to be 1 or 2.
1121             Align <= 2 ||
1122 
1123             // Disregard v2i64. Memcpy lowering produces those and splitting
1124             // them regresses performance on micro-benchmarks and olden/bh.
1125             VT == MVT::v2i64;
1126   }
1127   return true;
1128 }
1129 
1130 // Same as above but handling LLTs instead.
1131 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1132     LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1133     bool *Fast) const {
1134   if (Subtarget->requiresStrictAlign())
1135     return false;
1136 
1137   if (Fast) {
1138     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1139     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1140             Ty.getSizeInBytes() != 16 ||
1141             // See comments in performSTORECombine() for more details about
1142             // these conditions.
1143 
1144             // Code that uses clang vector extensions can mark that it
1145             // wants unaligned accesses to be treated as fast by
1146             // underspecifying alignment to be 1 or 2.
1147             Align <= 2 ||
1148 
1149             // Disregard v2i64. Memcpy lowering produces those and splitting
1150             // them regresses performance on micro-benchmarks and olden/bh.
1151             Ty == LLT::vector(2, 64);
1152   }
1153   return true;
1154 }
1155 
1156 FastISel *
1157 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1158                                       const TargetLibraryInfo *libInfo) const {
1159   return AArch64::createFastISel(funcInfo, libInfo);
1160 }
1161 
1162 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1163   switch ((AArch64ISD::NodeType)Opcode) {
1164   case AArch64ISD::FIRST_NUMBER:      break;
1165   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1166   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1167   case AArch64ISD::ADR:               return "AArch64ISD::ADR";
1168   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1169   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1170   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1171   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1172   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1173   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1174   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1175   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1176   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1177   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1178   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1179   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1180   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1181   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1182   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1183   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1184   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1185   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1186   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1187   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1188   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1189   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1190   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1191   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1192   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1193   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1194   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1195   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1196   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1197   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1198   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1199   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1200   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1201   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1202   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1203   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1204   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1205   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1206   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1207   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1208   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1209   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1210   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1211   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1212   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1213   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1214   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1215   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1216   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1217   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1218   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1219   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1220   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1221   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1222   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1223   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1224   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1225   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1226   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1227   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1228   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1229   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1230   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1231   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1232   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1233   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1234   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1235   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1236   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1237   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1238   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1239   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1240   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1241   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1242   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1243   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1244   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1245   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1246   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1247   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1248   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1249   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1250   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1251   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1252   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1253   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1254   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1255   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1256   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1257   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1258   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1259   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1260   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1261   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1262   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1263   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1264   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1265   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1266   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1267   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1268   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1269   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1270   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1271   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1272   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1273   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1274   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1275   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1276   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1277   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1278   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1279   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1280   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1281   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1282   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1283   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1284   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1285   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1286   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1287   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1288   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1289   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1290   case AArch64ISD::STG:               return "AArch64ISD::STG";
1291   case AArch64ISD::STZG:              return "AArch64ISD::STZG";
1292   case AArch64ISD::ST2G:              return "AArch64ISD::ST2G";
1293   case AArch64ISD::STZ2G:             return "AArch64ISD::STZ2G";
1294   }
1295   return nullptr;
1296 }
1297 
1298 MachineBasicBlock *
1299 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1300                                     MachineBasicBlock *MBB) const {
1301   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1302   // phi node:
1303 
1304   // OrigBB:
1305   //     [... previous instrs leading to comparison ...]
1306   //     b.ne TrueBB
1307   //     b EndBB
1308   // TrueBB:
1309   //     ; Fallthrough
1310   // EndBB:
1311   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1312 
1313   MachineFunction *MF = MBB->getParent();
1314   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1315   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1316   DebugLoc DL = MI.getDebugLoc();
1317   MachineFunction::iterator It = ++MBB->getIterator();
1318 
1319   Register DestReg = MI.getOperand(0).getReg();
1320   Register IfTrueReg = MI.getOperand(1).getReg();
1321   Register IfFalseReg = MI.getOperand(2).getReg();
1322   unsigned CondCode = MI.getOperand(3).getImm();
1323   bool NZCVKilled = MI.getOperand(4).isKill();
1324 
1325   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1326   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1327   MF->insert(It, TrueBB);
1328   MF->insert(It, EndBB);
1329 
1330   // Transfer rest of current basic-block to EndBB
1331   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1332                 MBB->end());
1333   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1334 
1335   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1336   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1337   MBB->addSuccessor(TrueBB);
1338   MBB->addSuccessor(EndBB);
1339 
1340   // TrueBB falls through to the end.
1341   TrueBB->addSuccessor(EndBB);
1342 
1343   if (!NZCVKilled) {
1344     TrueBB->addLiveIn(AArch64::NZCV);
1345     EndBB->addLiveIn(AArch64::NZCV);
1346   }
1347 
1348   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1349       .addReg(IfTrueReg)
1350       .addMBB(TrueBB)
1351       .addReg(IfFalseReg)
1352       .addMBB(MBB);
1353 
1354   MI.eraseFromParent();
1355   return EndBB;
1356 }
1357 
1358 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1359        MachineInstr &MI, MachineBasicBlock *BB) const {
1360   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1361              BB->getParent()->getFunction().getPersonalityFn())) &&
1362          "SEH does not use catchret!");
1363   return BB;
1364 }
1365 
1366 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1367      MachineInstr &MI, MachineBasicBlock *BB) const {
1368   MI.eraseFromParent();
1369   return BB;
1370 }
1371 
1372 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1373     MachineInstr &MI, MachineBasicBlock *BB) const {
1374   switch (MI.getOpcode()) {
1375   default:
1376 #ifndef NDEBUG
1377     MI.dump();
1378 #endif
1379     llvm_unreachable("Unexpected instruction for custom inserter!");
1380 
1381   case AArch64::F128CSEL:
1382     return EmitF128CSEL(MI, BB);
1383 
1384   case TargetOpcode::STACKMAP:
1385   case TargetOpcode::PATCHPOINT:
1386     return emitPatchPoint(MI, BB);
1387 
1388   case AArch64::CATCHRET:
1389     return EmitLoweredCatchRet(MI, BB);
1390   case AArch64::CATCHPAD:
1391     return EmitLoweredCatchPad(MI, BB);
1392   }
1393 }
1394 
1395 //===----------------------------------------------------------------------===//
1396 // AArch64 Lowering private implementation.
1397 //===----------------------------------------------------------------------===//
1398 
1399 //===----------------------------------------------------------------------===//
1400 // Lowering Code
1401 //===----------------------------------------------------------------------===//
1402 
1403 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1404 /// CC
1405 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1406   switch (CC) {
1407   default:
1408     llvm_unreachable("Unknown condition code!");
1409   case ISD::SETNE:
1410     return AArch64CC::NE;
1411   case ISD::SETEQ:
1412     return AArch64CC::EQ;
1413   case ISD::SETGT:
1414     return AArch64CC::GT;
1415   case ISD::SETGE:
1416     return AArch64CC::GE;
1417   case ISD::SETLT:
1418     return AArch64CC::LT;
1419   case ISD::SETLE:
1420     return AArch64CC::LE;
1421   case ISD::SETUGT:
1422     return AArch64CC::HI;
1423   case ISD::SETUGE:
1424     return AArch64CC::HS;
1425   case ISD::SETULT:
1426     return AArch64CC::LO;
1427   case ISD::SETULE:
1428     return AArch64CC::LS;
1429   }
1430 }
1431 
1432 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1433 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1434                                   AArch64CC::CondCode &CondCode,
1435                                   AArch64CC::CondCode &CondCode2) {
1436   CondCode2 = AArch64CC::AL;
1437   switch (CC) {
1438   default:
1439     llvm_unreachable("Unknown FP condition!");
1440   case ISD::SETEQ:
1441   case ISD::SETOEQ:
1442     CondCode = AArch64CC::EQ;
1443     break;
1444   case ISD::SETGT:
1445   case ISD::SETOGT:
1446     CondCode = AArch64CC::GT;
1447     break;
1448   case ISD::SETGE:
1449   case ISD::SETOGE:
1450     CondCode = AArch64CC::GE;
1451     break;
1452   case ISD::SETOLT:
1453     CondCode = AArch64CC::MI;
1454     break;
1455   case ISD::SETOLE:
1456     CondCode = AArch64CC::LS;
1457     break;
1458   case ISD::SETONE:
1459     CondCode = AArch64CC::MI;
1460     CondCode2 = AArch64CC::GT;
1461     break;
1462   case ISD::SETO:
1463     CondCode = AArch64CC::VC;
1464     break;
1465   case ISD::SETUO:
1466     CondCode = AArch64CC::VS;
1467     break;
1468   case ISD::SETUEQ:
1469     CondCode = AArch64CC::EQ;
1470     CondCode2 = AArch64CC::VS;
1471     break;
1472   case ISD::SETUGT:
1473     CondCode = AArch64CC::HI;
1474     break;
1475   case ISD::SETUGE:
1476     CondCode = AArch64CC::PL;
1477     break;
1478   case ISD::SETLT:
1479   case ISD::SETULT:
1480     CondCode = AArch64CC::LT;
1481     break;
1482   case ISD::SETLE:
1483   case ISD::SETULE:
1484     CondCode = AArch64CC::LE;
1485     break;
1486   case ISD::SETNE:
1487   case ISD::SETUNE:
1488     CondCode = AArch64CC::NE;
1489     break;
1490   }
1491 }
1492 
1493 /// Convert a DAG fp condition code to an AArch64 CC.
1494 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1495 /// should be AND'ed instead of OR'ed.
1496 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1497                                      AArch64CC::CondCode &CondCode,
1498                                      AArch64CC::CondCode &CondCode2) {
1499   CondCode2 = AArch64CC::AL;
1500   switch (CC) {
1501   default:
1502     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1503     assert(CondCode2 == AArch64CC::AL);
1504     break;
1505   case ISD::SETONE:
1506     // (a one b)
1507     // == ((a olt b) || (a ogt b))
1508     // == ((a ord b) && (a une b))
1509     CondCode = AArch64CC::VC;
1510     CondCode2 = AArch64CC::NE;
1511     break;
1512   case ISD::SETUEQ:
1513     // (a ueq b)
1514     // == ((a uno b) || (a oeq b))
1515     // == ((a ule b) && (a uge b))
1516     CondCode = AArch64CC::PL;
1517     CondCode2 = AArch64CC::LE;
1518     break;
1519   }
1520 }
1521 
1522 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1523 /// CC usable with the vector instructions. Fewer operations are available
1524 /// without a real NZCV register, so we have to use less efficient combinations
1525 /// to get the same effect.
1526 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1527                                         AArch64CC::CondCode &CondCode,
1528                                         AArch64CC::CondCode &CondCode2,
1529                                         bool &Invert) {
1530   Invert = false;
1531   switch (CC) {
1532   default:
1533     // Mostly the scalar mappings work fine.
1534     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1535     break;
1536   case ISD::SETUO:
1537     Invert = true;
1538     LLVM_FALLTHROUGH;
1539   case ISD::SETO:
1540     CondCode = AArch64CC::MI;
1541     CondCode2 = AArch64CC::GE;
1542     break;
1543   case ISD::SETUEQ:
1544   case ISD::SETULT:
1545   case ISD::SETULE:
1546   case ISD::SETUGT:
1547   case ISD::SETUGE:
1548     // All of the compare-mask comparisons are ordered, but we can switch
1549     // between the two by a double inversion. E.g. ULE == !OGT.
1550     Invert = true;
1551     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1552     break;
1553   }
1554 }
1555 
1556 static bool isLegalArithImmed(uint64_t C) {
1557   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1558   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1559   LLVM_DEBUG(dbgs() << "Is imm " << C
1560                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1561   return IsLegal;
1562 }
1563 
1564 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1565 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1566 // can be set differently by this operation. It comes down to whether
1567 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1568 // everything is fine. If not then the optimization is wrong. Thus general
1569 // comparisons are only valid if op2 != 0.
1570 //
1571 // So, finally, the only LLVM-native comparisons that don't mention C and V
1572 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1573 // the absence of information about op2.
1574 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1575   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1576          (CC == ISD::SETEQ || CC == ISD::SETNE);
1577 }
1578 
1579 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1580                               const SDLoc &dl, SelectionDAG &DAG) {
1581   EVT VT = LHS.getValueType();
1582   const bool FullFP16 =
1583     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1584 
1585   if (VT.isFloatingPoint()) {
1586     assert(VT != MVT::f128);
1587     if (VT == MVT::f16 && !FullFP16) {
1588       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1589       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1590       VT = MVT::f32;
1591     }
1592     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1593   }
1594 
1595   // The CMP instruction is just an alias for SUBS, and representing it as
1596   // SUBS means that it's possible to get CSE with subtract operations.
1597   // A later phase can perform the optimization of setting the destination
1598   // register to WZR/XZR if it ends up being unused.
1599   unsigned Opcode = AArch64ISD::SUBS;
1600 
1601   if (isCMN(RHS, CC)) {
1602     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1603     Opcode = AArch64ISD::ADDS;
1604     RHS = RHS.getOperand(1);
1605   } else if (isCMN(LHS, CC)) {
1606     // As we are looking for EQ/NE compares, the operands can be commuted ; can
1607     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1608     Opcode = AArch64ISD::ADDS;
1609     LHS = LHS.getOperand(1);
1610   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1611              !isUnsignedIntSetCC(CC)) {
1612     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1613     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1614     // of the signed comparisons.
1615     Opcode = AArch64ISD::ANDS;
1616     RHS = LHS.getOperand(1);
1617     LHS = LHS.getOperand(0);
1618   }
1619 
1620   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1621       .getValue(1);
1622 }
1623 
1624 /// \defgroup AArch64CCMP CMP;CCMP matching
1625 ///
1626 /// These functions deal with the formation of CMP;CCMP;... sequences.
1627 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1628 /// a comparison. They set the NZCV flags to a predefined value if their
1629 /// predicate is false. This allows to express arbitrary conjunctions, for
1630 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1631 /// expressed as:
1632 ///   cmp A
1633 ///   ccmp B, inv(CB), CA
1634 ///   check for CB flags
1635 ///
1636 /// This naturally lets us implement chains of AND operations with SETCC
1637 /// operands. And we can even implement some other situations by transforming
1638 /// them:
1639 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
1640 ///     negating the flags used in a CCMP/FCCMP operations.
1641 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1642 ///     by negating the flags we test for afterwards. i.e.
1643 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
1644 ///   - Note that we can only ever negate all previously processed results.
1645 ///     What we can not implement by flipping the flags to test is a negation
1646 ///     of two sub-trees (because the negation affects all sub-trees emitted so
1647 ///     far, so the 2nd sub-tree we emit would also affect the first).
1648 /// With those tools we can implement some OR operations:
1649 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
1650 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1651 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
1652 ///     elimination rules from earlier to implement the whole thing as a
1653 ///     CCMP/FCCMP chain.
1654 ///
1655 /// As complete example:
1656 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
1657 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
1658 /// can be reassociated to:
1659 ///     or (and (setCC (cmp C)) setCD (cmp D))
1660 //         (or (setCA (cmp A)) (setCB (cmp B)))
1661 /// can be transformed to:
1662 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1663 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1664 /// which can be implemented as:
1665 ///   cmp C
1666 ///   ccmp D, inv(CD), CC
1667 ///   ccmp A, CA, inv(CD)
1668 ///   ccmp B, CB, inv(CA)
1669 ///   check for CB flags
1670 ///
1671 /// A counterexample is "or (and A B) (and C D)" which translates to
1672 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1673 /// can only implement 1 of the inner (not) operations, but not both!
1674 /// @{
1675 
1676 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1677 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1678                                          ISD::CondCode CC, SDValue CCOp,
1679                                          AArch64CC::CondCode Predicate,
1680                                          AArch64CC::CondCode OutCC,
1681                                          const SDLoc &DL, SelectionDAG &DAG) {
1682   unsigned Opcode = 0;
1683   const bool FullFP16 =
1684     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1685 
1686   if (LHS.getValueType().isFloatingPoint()) {
1687     assert(LHS.getValueType() != MVT::f128);
1688     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1689       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1690       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1691     }
1692     Opcode = AArch64ISD::FCCMP;
1693   } else if (RHS.getOpcode() == ISD::SUB) {
1694     SDValue SubOp0 = RHS.getOperand(0);
1695     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1696       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1697       Opcode = AArch64ISD::CCMN;
1698       RHS = RHS.getOperand(1);
1699     }
1700   }
1701   if (Opcode == 0)
1702     Opcode = AArch64ISD::CCMP;
1703 
1704   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1705   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1706   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1707   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1708   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1709 }
1710 
1711 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1712 /// expressed as a conjunction. See \ref AArch64CCMP.
1713 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
1714 ///                     changing the conditions on the SETCC tests.
1715 ///                     (this means we can call emitConjunctionRec() with
1716 ///                      Negate==true on this sub-tree)
1717 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
1718 ///                     cannot do the negation naturally. We are required to
1719 ///                     emit the subtree first in this case.
1720 /// \param WillNegate   Is true if are called when the result of this
1721 ///                     subexpression must be negated. This happens when the
1722 ///                     outer expression is an OR. We can use this fact to know
1723 ///                     that we have a double negation (or (or ...) ...) that
1724 ///                     can be implemented for free.
1725 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1726                                bool &MustBeFirst, bool WillNegate,
1727                                unsigned Depth = 0) {
1728   if (!Val.hasOneUse())
1729     return false;
1730   unsigned Opcode = Val->getOpcode();
1731   if (Opcode == ISD::SETCC) {
1732     if (Val->getOperand(0).getValueType() == MVT::f128)
1733       return false;
1734     CanNegate = true;
1735     MustBeFirst = false;
1736     return true;
1737   }
1738   // Protect against exponential runtime and stack overflow.
1739   if (Depth > 6)
1740     return false;
1741   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1742     bool IsOR = Opcode == ISD::OR;
1743     SDValue O0 = Val->getOperand(0);
1744     SDValue O1 = Val->getOperand(1);
1745     bool CanNegateL;
1746     bool MustBeFirstL;
1747     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1748       return false;
1749     bool CanNegateR;
1750     bool MustBeFirstR;
1751     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1752       return false;
1753 
1754     if (MustBeFirstL && MustBeFirstR)
1755       return false;
1756 
1757     if (IsOR) {
1758       // For an OR expression we need to be able to naturally negate at least
1759       // one side or we cannot do the transformation at all.
1760       if (!CanNegateL && !CanNegateR)
1761         return false;
1762       // If we the result of the OR will be negated and we can naturally negate
1763       // the leafs, then this sub-tree as a whole negates naturally.
1764       CanNegate = WillNegate && CanNegateL && CanNegateR;
1765       // If we cannot naturally negate the whole sub-tree, then this must be
1766       // emitted first.
1767       MustBeFirst = !CanNegate;
1768     } else {
1769       assert(Opcode == ISD::AND && "Must be OR or AND");
1770       // We cannot naturally negate an AND operation.
1771       CanNegate = false;
1772       MustBeFirst = MustBeFirstL || MustBeFirstR;
1773     }
1774     return true;
1775   }
1776   return false;
1777 }
1778 
1779 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1780 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1781 /// Tries to transform the given i1 producing node @p Val to a series compare
1782 /// and conditional compare operations. @returns an NZCV flags producing node
1783 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1784 /// transformation was not possible.
1785 /// \p Negate is true if we want this sub-tree being negated just by changing
1786 /// SETCC conditions.
1787 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1788     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1789     AArch64CC::CondCode Predicate) {
1790   // We're at a tree leaf, produce a conditional comparison operation.
1791   unsigned Opcode = Val->getOpcode();
1792   if (Opcode == ISD::SETCC) {
1793     SDValue LHS = Val->getOperand(0);
1794     SDValue RHS = Val->getOperand(1);
1795     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1796     bool isInteger = LHS.getValueType().isInteger();
1797     if (Negate)
1798       CC = getSetCCInverse(CC, isInteger);
1799     SDLoc DL(Val);
1800     // Determine OutCC and handle FP special case.
1801     if (isInteger) {
1802       OutCC = changeIntCCToAArch64CC(CC);
1803     } else {
1804       assert(LHS.getValueType().isFloatingPoint());
1805       AArch64CC::CondCode ExtraCC;
1806       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1807       // Some floating point conditions can't be tested with a single condition
1808       // code. Construct an additional comparison in this case.
1809       if (ExtraCC != AArch64CC::AL) {
1810         SDValue ExtraCmp;
1811         if (!CCOp.getNode())
1812           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1813         else
1814           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1815                                                ExtraCC, DL, DAG);
1816         CCOp = ExtraCmp;
1817         Predicate = ExtraCC;
1818       }
1819     }
1820 
1821     // Produce a normal comparison if we are first in the chain
1822     if (!CCOp)
1823       return emitComparison(LHS, RHS, CC, DL, DAG);
1824     // Otherwise produce a ccmp.
1825     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1826                                      DAG);
1827   }
1828   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1829 
1830   bool IsOR = Opcode == ISD::OR;
1831 
1832   SDValue LHS = Val->getOperand(0);
1833   bool CanNegateL;
1834   bool MustBeFirstL;
1835   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1836   assert(ValidL && "Valid conjunction/disjunction tree");
1837   (void)ValidL;
1838 
1839   SDValue RHS = Val->getOperand(1);
1840   bool CanNegateR;
1841   bool MustBeFirstR;
1842   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1843   assert(ValidR && "Valid conjunction/disjunction tree");
1844   (void)ValidR;
1845 
1846   // Swap sub-tree that must come first to the right side.
1847   if (MustBeFirstL) {
1848     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1849     std::swap(LHS, RHS);
1850     std::swap(CanNegateL, CanNegateR);
1851     std::swap(MustBeFirstL, MustBeFirstR);
1852   }
1853 
1854   bool NegateR;
1855   bool NegateAfterR;
1856   bool NegateL;
1857   bool NegateAfterAll;
1858   if (Opcode == ISD::OR) {
1859     // Swap the sub-tree that we can negate naturally to the left.
1860     if (!CanNegateL) {
1861       assert(CanNegateR && "at least one side must be negatable");
1862       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1863       assert(!Negate);
1864       std::swap(LHS, RHS);
1865       NegateR = false;
1866       NegateAfterR = true;
1867     } else {
1868       // Negate the left sub-tree if possible, otherwise negate the result.
1869       NegateR = CanNegateR;
1870       NegateAfterR = !CanNegateR;
1871     }
1872     NegateL = true;
1873     NegateAfterAll = !Negate;
1874   } else {
1875     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1876     assert(!Negate && "Valid conjunction/disjunction tree");
1877 
1878     NegateL = false;
1879     NegateR = false;
1880     NegateAfterR = false;
1881     NegateAfterAll = false;
1882   }
1883 
1884   // Emit sub-trees.
1885   AArch64CC::CondCode RHSCC;
1886   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1887   if (NegateAfterR)
1888     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1889   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1890   if (NegateAfterAll)
1891     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1892   return CmpL;
1893 }
1894 
1895 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1896 /// In some cases this is even possible with OR operations in the expression.
1897 /// See \ref AArch64CCMP.
1898 /// \see emitConjunctionRec().
1899 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1900                                AArch64CC::CondCode &OutCC) {
1901   bool DummyCanNegate;
1902   bool DummyMustBeFirst;
1903   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1904     return SDValue();
1905 
1906   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1907 }
1908 
1909 /// @}
1910 
1911 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1912 /// extension operations.
1913 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1914   auto isSupportedExtend = [&](SDValue V) {
1915     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1916       return true;
1917 
1918     if (V.getOpcode() == ISD::AND)
1919       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1920         uint64_t Mask = MaskCst->getZExtValue();
1921         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1922       }
1923 
1924     return false;
1925   };
1926 
1927   if (!Op.hasOneUse())
1928     return 0;
1929 
1930   if (isSupportedExtend(Op))
1931     return 1;
1932 
1933   unsigned Opc = Op.getOpcode();
1934   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1935     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1936       uint64_t Shift = ShiftCst->getZExtValue();
1937       if (isSupportedExtend(Op.getOperand(0)))
1938         return (Shift <= 4) ? 2 : 1;
1939       EVT VT = Op.getValueType();
1940       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1941         return 1;
1942     }
1943 
1944   return 0;
1945 }
1946 
1947 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1948                              SDValue &AArch64cc, SelectionDAG &DAG,
1949                              const SDLoc &dl) {
1950   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1951     EVT VT = RHS.getValueType();
1952     uint64_t C = RHSC->getZExtValue();
1953     if (!isLegalArithImmed(C)) {
1954       // Constant does not fit, try adjusting it by one?
1955       switch (CC) {
1956       default:
1957         break;
1958       case ISD::SETLT:
1959       case ISD::SETGE:
1960         if ((VT == MVT::i32 && C != 0x80000000 &&
1961              isLegalArithImmed((uint32_t)(C - 1))) ||
1962             (VT == MVT::i64 && C != 0x80000000ULL &&
1963              isLegalArithImmed(C - 1ULL))) {
1964           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1965           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1966           RHS = DAG.getConstant(C, dl, VT);
1967         }
1968         break;
1969       case ISD::SETULT:
1970       case ISD::SETUGE:
1971         if ((VT == MVT::i32 && C != 0 &&
1972              isLegalArithImmed((uint32_t)(C - 1))) ||
1973             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1974           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1975           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1976           RHS = DAG.getConstant(C, dl, VT);
1977         }
1978         break;
1979       case ISD::SETLE:
1980       case ISD::SETGT:
1981         if ((VT == MVT::i32 && C != INT32_MAX &&
1982              isLegalArithImmed((uint32_t)(C + 1))) ||
1983             (VT == MVT::i64 && C != INT64_MAX &&
1984              isLegalArithImmed(C + 1ULL))) {
1985           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1986           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1987           RHS = DAG.getConstant(C, dl, VT);
1988         }
1989         break;
1990       case ISD::SETULE:
1991       case ISD::SETUGT:
1992         if ((VT == MVT::i32 && C != UINT32_MAX &&
1993              isLegalArithImmed((uint32_t)(C + 1))) ||
1994             (VT == MVT::i64 && C != UINT64_MAX &&
1995              isLegalArithImmed(C + 1ULL))) {
1996           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1997           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1998           RHS = DAG.getConstant(C, dl, VT);
1999         }
2000         break;
2001       }
2002     }
2003   }
2004 
2005   // Comparisons are canonicalized so that the RHS operand is simpler than the
2006   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2007   // can fold some shift+extend operations on the RHS operand, so swap the
2008   // operands if that can be done.
2009   //
2010   // For example:
2011   //    lsl     w13, w11, #1
2012   //    cmp     w13, w12
2013   // can be turned into:
2014   //    cmp     w12, w11, lsl #1
2015   if (!isa<ConstantSDNode>(RHS) ||
2016       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2017     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2018 
2019     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2020       std::swap(LHS, RHS);
2021       CC = ISD::getSetCCSwappedOperands(CC);
2022     }
2023   }
2024 
2025   SDValue Cmp;
2026   AArch64CC::CondCode AArch64CC;
2027   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2028     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2029 
2030     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2031     // For the i8 operand, the largest immediate is 255, so this can be easily
2032     // encoded in the compare instruction. For the i16 operand, however, the
2033     // largest immediate cannot be encoded in the compare.
2034     // Therefore, use a sign extending load and cmn to avoid materializing the
2035     // -1 constant. For example,
2036     // movz w1, #65535
2037     // ldrh w0, [x0, #0]
2038     // cmp w0, w1
2039     // >
2040     // ldrsh w0, [x0, #0]
2041     // cmn w0, #1
2042     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2043     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2044     // ensure both the LHS and RHS are truly zero extended and to make sure the
2045     // transformation is profitable.
2046     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2047         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2048         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2049         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2050       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2051       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2052         SDValue SExt =
2053             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2054                         DAG.getValueType(MVT::i16));
2055         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2056                                                    RHS.getValueType()),
2057                              CC, dl, DAG);
2058         AArch64CC = changeIntCCToAArch64CC(CC);
2059       }
2060     }
2061 
2062     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2063       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2064         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2065           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2066       }
2067     }
2068   }
2069 
2070   if (!Cmp) {
2071     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2072     AArch64CC = changeIntCCToAArch64CC(CC);
2073   }
2074   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2075   return Cmp;
2076 }
2077 
2078 static std::pair<SDValue, SDValue>
2079 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2080   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2081          "Unsupported value type");
2082   SDValue Value, Overflow;
2083   SDLoc DL(Op);
2084   SDValue LHS = Op.getOperand(0);
2085   SDValue RHS = Op.getOperand(1);
2086   unsigned Opc = 0;
2087   switch (Op.getOpcode()) {
2088   default:
2089     llvm_unreachable("Unknown overflow instruction!");
2090   case ISD::SADDO:
2091     Opc = AArch64ISD::ADDS;
2092     CC = AArch64CC::VS;
2093     break;
2094   case ISD::UADDO:
2095     Opc = AArch64ISD::ADDS;
2096     CC = AArch64CC::HS;
2097     break;
2098   case ISD::SSUBO:
2099     Opc = AArch64ISD::SUBS;
2100     CC = AArch64CC::VS;
2101     break;
2102   case ISD::USUBO:
2103     Opc = AArch64ISD::SUBS;
2104     CC = AArch64CC::LO;
2105     break;
2106   // Multiply needs a little bit extra work.
2107   case ISD::SMULO:
2108   case ISD::UMULO: {
2109     CC = AArch64CC::NE;
2110     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2111     if (Op.getValueType() == MVT::i32) {
2112       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2113       // For a 32 bit multiply with overflow check we want the instruction
2114       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2115       // need to generate the following pattern:
2116       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2117       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2118       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2119       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2120       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2121                                 DAG.getConstant(0, DL, MVT::i64));
2122       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2123       // operation. We need to clear out the upper 32 bits, because we used a
2124       // widening multiply that wrote all 64 bits. In the end this should be a
2125       // noop.
2126       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2127       if (IsSigned) {
2128         // The signed overflow check requires more than just a simple check for
2129         // any bit set in the upper 32 bits of the result. These bits could be
2130         // just the sign bits of a negative number. To perform the overflow
2131         // check we have to arithmetic shift right the 32nd bit of the result by
2132         // 31 bits. Then we compare the result to the upper 32 bits.
2133         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2134                                         DAG.getConstant(32, DL, MVT::i64));
2135         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2136         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2137                                         DAG.getConstant(31, DL, MVT::i64));
2138         // It is important that LowerBits is last, otherwise the arithmetic
2139         // shift will not be folded into the compare (SUBS).
2140         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2141         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2142                        .getValue(1);
2143       } else {
2144         // The overflow check for unsigned multiply is easy. We only need to
2145         // check if any of the upper 32 bits are set. This can be done with a
2146         // CMP (shifted register). For that we need to generate the following
2147         // pattern:
2148         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2149         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2150                                         DAG.getConstant(32, DL, MVT::i64));
2151         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2152         Overflow =
2153             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2154                         DAG.getConstant(0, DL, MVT::i64),
2155                         UpperBits).getValue(1);
2156       }
2157       break;
2158     }
2159     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2160     // For the 64 bit multiply
2161     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2162     if (IsSigned) {
2163       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2164       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2165                                       DAG.getConstant(63, DL, MVT::i64));
2166       // It is important that LowerBits is last, otherwise the arithmetic
2167       // shift will not be folded into the compare (SUBS).
2168       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2169       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2170                      .getValue(1);
2171     } else {
2172       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2173       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2174       Overflow =
2175           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2176                       DAG.getConstant(0, DL, MVT::i64),
2177                       UpperBits).getValue(1);
2178     }
2179     break;
2180   }
2181   } // switch (...)
2182 
2183   if (Opc) {
2184     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2185 
2186     // Emit the AArch64 operation with overflow check.
2187     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2188     Overflow = Value.getValue(1);
2189   }
2190   return std::make_pair(Value, Overflow);
2191 }
2192 
2193 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2194                                              RTLIB::Libcall Call) const {
2195   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2196   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
2197 }
2198 
2199 // Returns true if the given Op is the overflow flag result of an overflow
2200 // intrinsic operation.
2201 static bool isOverflowIntrOpRes(SDValue Op) {
2202   unsigned Opc = Op.getOpcode();
2203   return (Op.getResNo() == 1 &&
2204           (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2205            Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2206 }
2207 
2208 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2209   SDValue Sel = Op.getOperand(0);
2210   SDValue Other = Op.getOperand(1);
2211   SDLoc dl(Sel);
2212 
2213   // If the operand is an overflow checking operation, invert the condition
2214   // code and kill the Not operation. I.e., transform:
2215   // (xor (overflow_op_bool, 1))
2216   //   -->
2217   // (csel 1, 0, invert(cc), overflow_op_bool)
2218   // ... which later gets transformed to just a cset instruction with an
2219   // inverted condition code, rather than a cset + eor sequence.
2220   if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2221     // Only lower legal XALUO ops.
2222     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2223       return SDValue();
2224 
2225     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2226     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2227     AArch64CC::CondCode CC;
2228     SDValue Value, Overflow;
2229     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2230     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2231     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2232                        CCVal, Overflow);
2233   }
2234   // If neither operand is a SELECT_CC, give up.
2235   if (Sel.getOpcode() != ISD::SELECT_CC)
2236     std::swap(Sel, Other);
2237   if (Sel.getOpcode() != ISD::SELECT_CC)
2238     return Op;
2239 
2240   // The folding we want to perform is:
2241   // (xor x, (select_cc a, b, cc, 0, -1) )
2242   //   -->
2243   // (csel x, (xor x, -1), cc ...)
2244   //
2245   // The latter will get matched to a CSINV instruction.
2246 
2247   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2248   SDValue LHS = Sel.getOperand(0);
2249   SDValue RHS = Sel.getOperand(1);
2250   SDValue TVal = Sel.getOperand(2);
2251   SDValue FVal = Sel.getOperand(3);
2252 
2253   // FIXME: This could be generalized to non-integer comparisons.
2254   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2255     return Op;
2256 
2257   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2258   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2259 
2260   // The values aren't constants, this isn't the pattern we're looking for.
2261   if (!CFVal || !CTVal)
2262     return Op;
2263 
2264   // We can commute the SELECT_CC by inverting the condition.  This
2265   // might be needed to make this fit into a CSINV pattern.
2266   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2267     std::swap(TVal, FVal);
2268     std::swap(CTVal, CFVal);
2269     CC = ISD::getSetCCInverse(CC, true);
2270   }
2271 
2272   // If the constants line up, perform the transform!
2273   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2274     SDValue CCVal;
2275     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2276 
2277     FVal = Other;
2278     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2279                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2280 
2281     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2282                        CCVal, Cmp);
2283   }
2284 
2285   return Op;
2286 }
2287 
2288 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2289   EVT VT = Op.getValueType();
2290 
2291   // Let legalize expand this if it isn't a legal type yet.
2292   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2293     return SDValue();
2294 
2295   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2296 
2297   unsigned Opc;
2298   bool ExtraOp = false;
2299   switch (Op.getOpcode()) {
2300   default:
2301     llvm_unreachable("Invalid code");
2302   case ISD::ADDC:
2303     Opc = AArch64ISD::ADDS;
2304     break;
2305   case ISD::SUBC:
2306     Opc = AArch64ISD::SUBS;
2307     break;
2308   case ISD::ADDE:
2309     Opc = AArch64ISD::ADCS;
2310     ExtraOp = true;
2311     break;
2312   case ISD::SUBE:
2313     Opc = AArch64ISD::SBCS;
2314     ExtraOp = true;
2315     break;
2316   }
2317 
2318   if (!ExtraOp)
2319     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2320   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2321                      Op.getOperand(2));
2322 }
2323 
2324 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2325   // Let legalize expand this if it isn't a legal type yet.
2326   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2327     return SDValue();
2328 
2329   SDLoc dl(Op);
2330   AArch64CC::CondCode CC;
2331   // The actual operation that sets the overflow or carry flag.
2332   SDValue Value, Overflow;
2333   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2334 
2335   // We use 0 and 1 as false and true values.
2336   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2337   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2338 
2339   // We use an inverted condition, because the conditional select is inverted
2340   // too. This will allow it to be selected to a single instruction:
2341   // CSINC Wd, WZR, WZR, invert(cond).
2342   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2343   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2344                          CCVal, Overflow);
2345 
2346   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2347   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2348 }
2349 
2350 // Prefetch operands are:
2351 // 1: Address to prefetch
2352 // 2: bool isWrite
2353 // 3: int locality (0 = no locality ... 3 = extreme locality)
2354 // 4: bool isDataCache
2355 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2356   SDLoc DL(Op);
2357   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2358   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2359   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2360 
2361   bool IsStream = !Locality;
2362   // When the locality number is set
2363   if (Locality) {
2364     // The front-end should have filtered out the out-of-range values
2365     assert(Locality <= 3 && "Prefetch locality out-of-range");
2366     // The locality degree is the opposite of the cache speed.
2367     // Put the number the other way around.
2368     // The encoding starts at 0 for level 1
2369     Locality = 3 - Locality;
2370   }
2371 
2372   // built the mask value encoding the expected behavior.
2373   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2374                    (!IsData << 3) |     // IsDataCache bit
2375                    (Locality << 1) |    // Cache level bits
2376                    (unsigned)IsStream;  // Stream bit
2377   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2378                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2379 }
2380 
2381 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2382                                               SelectionDAG &DAG) const {
2383   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2384 
2385   RTLIB::Libcall LC;
2386   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2387 
2388   return LowerF128Call(Op, DAG, LC);
2389 }
2390 
2391 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2392                                              SelectionDAG &DAG) const {
2393   if (Op.getOperand(0).getValueType() != MVT::f128) {
2394     // It's legal except when f128 is involved
2395     return Op;
2396   }
2397 
2398   RTLIB::Libcall LC;
2399   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2400 
2401   // FP_ROUND node has a second operand indicating whether it is known to be
2402   // precise. That doesn't take part in the LibCall so we can't directly use
2403   // LowerF128Call.
2404   SDValue SrcVal = Op.getOperand(0);
2405   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2406                      SDLoc(Op)).first;
2407 }
2408 
2409 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2410                                                     SelectionDAG &DAG) const {
2411   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2412   // Any additional optimization in this function should be recorded
2413   // in the cost tables.
2414   EVT InVT = Op.getOperand(0).getValueType();
2415   EVT VT = Op.getValueType();
2416   unsigned NumElts = InVT.getVectorNumElements();
2417 
2418   // f16 conversions are promoted to f32 when full fp16 is not supported.
2419   if (InVT.getVectorElementType() == MVT::f16 &&
2420       !Subtarget->hasFullFP16()) {
2421     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2422     SDLoc dl(Op);
2423     return DAG.getNode(
2424         Op.getOpcode(), dl, Op.getValueType(),
2425         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2426   }
2427 
2428   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2429     SDLoc dl(Op);
2430     SDValue Cv =
2431         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2432                     Op.getOperand(0));
2433     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2434   }
2435 
2436   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2437     SDLoc dl(Op);
2438     MVT ExtVT =
2439         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2440                          VT.getVectorNumElements());
2441     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2442     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2443   }
2444 
2445   // Type changing conversions are illegal.
2446   return Op;
2447 }
2448 
2449 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2450                                               SelectionDAG &DAG) const {
2451   if (Op.getOperand(0).getValueType().isVector())
2452     return LowerVectorFP_TO_INT(Op, DAG);
2453 
2454   // f16 conversions are promoted to f32 when full fp16 is not supported.
2455   if (Op.getOperand(0).getValueType() == MVT::f16 &&
2456       !Subtarget->hasFullFP16()) {
2457     SDLoc dl(Op);
2458     return DAG.getNode(
2459         Op.getOpcode(), dl, Op.getValueType(),
2460         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2461   }
2462 
2463   if (Op.getOperand(0).getValueType() != MVT::f128) {
2464     // It's legal except when f128 is involved
2465     return Op;
2466   }
2467 
2468   RTLIB::Libcall LC;
2469   if (Op.getOpcode() == ISD::FP_TO_SINT)
2470     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2471   else
2472     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2473 
2474   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2475   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2476 }
2477 
2478 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2479   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2480   // Any additional optimization in this function should be recorded
2481   // in the cost tables.
2482   EVT VT = Op.getValueType();
2483   SDLoc dl(Op);
2484   SDValue In = Op.getOperand(0);
2485   EVT InVT = In.getValueType();
2486 
2487   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2488     MVT CastVT =
2489         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2490                          InVT.getVectorNumElements());
2491     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2492     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2493   }
2494 
2495   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2496     unsigned CastOpc =
2497         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2498     EVT CastVT = VT.changeVectorElementTypeToInteger();
2499     In = DAG.getNode(CastOpc, dl, CastVT, In);
2500     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2501   }
2502 
2503   return Op;
2504 }
2505 
2506 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2507                                             SelectionDAG &DAG) const {
2508   if (Op.getValueType().isVector())
2509     return LowerVectorINT_TO_FP(Op, DAG);
2510 
2511   // f16 conversions are promoted to f32 when full fp16 is not supported.
2512   if (Op.getValueType() == MVT::f16 &&
2513       !Subtarget->hasFullFP16()) {
2514     SDLoc dl(Op);
2515     return DAG.getNode(
2516         ISD::FP_ROUND, dl, MVT::f16,
2517         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2518         DAG.getIntPtrConstant(0, dl));
2519   }
2520 
2521   // i128 conversions are libcalls.
2522   if (Op.getOperand(0).getValueType() == MVT::i128)
2523     return SDValue();
2524 
2525   // Other conversions are legal, unless it's to the completely software-based
2526   // fp128.
2527   if (Op.getValueType() != MVT::f128)
2528     return Op;
2529 
2530   RTLIB::Libcall LC;
2531   if (Op.getOpcode() == ISD::SINT_TO_FP)
2532     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2533   else
2534     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2535 
2536   return LowerF128Call(Op, DAG, LC);
2537 }
2538 
2539 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2540                                             SelectionDAG &DAG) const {
2541   // For iOS, we want to call an alternative entry point: __sincos_stret,
2542   // which returns the values in two S / D registers.
2543   SDLoc dl(Op);
2544   SDValue Arg = Op.getOperand(0);
2545   EVT ArgVT = Arg.getValueType();
2546   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2547 
2548   ArgListTy Args;
2549   ArgListEntry Entry;
2550 
2551   Entry.Node = Arg;
2552   Entry.Ty = ArgTy;
2553   Entry.IsSExt = false;
2554   Entry.IsZExt = false;
2555   Args.push_back(Entry);
2556 
2557   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2558                                         : RTLIB::SINCOS_STRET_F32;
2559   const char *LibcallName = getLibcallName(LC);
2560   SDValue Callee =
2561       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2562 
2563   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2564   TargetLowering::CallLoweringInfo CLI(DAG);
2565   CLI.setDebugLoc(dl)
2566       .setChain(DAG.getEntryNode())
2567       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2568 
2569   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2570   return CallResult.first;
2571 }
2572 
2573 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2574   if (Op.getValueType() != MVT::f16)
2575     return SDValue();
2576 
2577   assert(Op.getOperand(0).getValueType() == MVT::i16);
2578   SDLoc DL(Op);
2579 
2580   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2581   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2582   return SDValue(
2583       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2584                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2585       0);
2586 }
2587 
2588 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2589   if (OrigVT.getSizeInBits() >= 64)
2590     return OrigVT;
2591 
2592   assert(OrigVT.isSimple() && "Expecting a simple value type");
2593 
2594   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2595   switch (OrigSimpleTy) {
2596   default: llvm_unreachable("Unexpected Vector Type");
2597   case MVT::v2i8:
2598   case MVT::v2i16:
2599      return MVT::v2i32;
2600   case MVT::v4i8:
2601     return  MVT::v4i16;
2602   }
2603 }
2604 
2605 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2606                                                  const EVT &OrigTy,
2607                                                  const EVT &ExtTy,
2608                                                  unsigned ExtOpcode) {
2609   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2610   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2611   // 64-bits we need to insert a new extension so that it will be 64-bits.
2612   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2613   if (OrigTy.getSizeInBits() >= 64)
2614     return N;
2615 
2616   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2617   EVT NewVT = getExtensionTo64Bits(OrigTy);
2618 
2619   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2620 }
2621 
2622 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2623                                    bool isSigned) {
2624   EVT VT = N->getValueType(0);
2625 
2626   if (N->getOpcode() != ISD::BUILD_VECTOR)
2627     return false;
2628 
2629   for (const SDValue &Elt : N->op_values()) {
2630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2631       unsigned EltSize = VT.getScalarSizeInBits();
2632       unsigned HalfSize = EltSize / 2;
2633       if (isSigned) {
2634         if (!isIntN(HalfSize, C->getSExtValue()))
2635           return false;
2636       } else {
2637         if (!isUIntN(HalfSize, C->getZExtValue()))
2638           return false;
2639       }
2640       continue;
2641     }
2642     return false;
2643   }
2644 
2645   return true;
2646 }
2647 
2648 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2649   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2650     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2651                                              N->getOperand(0)->getValueType(0),
2652                                              N->getValueType(0),
2653                                              N->getOpcode());
2654 
2655   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2656   EVT VT = N->getValueType(0);
2657   SDLoc dl(N);
2658   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2659   unsigned NumElts = VT.getVectorNumElements();
2660   MVT TruncVT = MVT::getIntegerVT(EltSize);
2661   SmallVector<SDValue, 8> Ops;
2662   for (unsigned i = 0; i != NumElts; ++i) {
2663     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2664     const APInt &CInt = C->getAPIntValue();
2665     // Element types smaller than 32 bits are not legal, so use i32 elements.
2666     // The values are implicitly truncated so sext vs. zext doesn't matter.
2667     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2668   }
2669   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2670 }
2671 
2672 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2673   return N->getOpcode() == ISD::SIGN_EXTEND ||
2674          isExtendedBUILD_VECTOR(N, DAG, true);
2675 }
2676 
2677 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2678   return N->getOpcode() == ISD::ZERO_EXTEND ||
2679          isExtendedBUILD_VECTOR(N, DAG, false);
2680 }
2681 
2682 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2683   unsigned Opcode = N->getOpcode();
2684   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2685     SDNode *N0 = N->getOperand(0).getNode();
2686     SDNode *N1 = N->getOperand(1).getNode();
2687     return N0->hasOneUse() && N1->hasOneUse() &&
2688       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2689   }
2690   return false;
2691 }
2692 
2693 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2694   unsigned Opcode = N->getOpcode();
2695   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2696     SDNode *N0 = N->getOperand(0).getNode();
2697     SDNode *N1 = N->getOperand(1).getNode();
2698     return N0->hasOneUse() && N1->hasOneUse() &&
2699       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2700   }
2701   return false;
2702 }
2703 
2704 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2705                                                 SelectionDAG &DAG) const {
2706   // The rounding mode is in bits 23:22 of the FPSCR.
2707   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2708   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2709   // so that the shift + and get folded into a bitfield extract.
2710   SDLoc dl(Op);
2711 
2712   SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2713                                 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2714                                                 MVT::i64));
2715   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2716   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2717                                   DAG.getConstant(1U << 22, dl, MVT::i32));
2718   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2719                               DAG.getConstant(22, dl, MVT::i32));
2720   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2721                      DAG.getConstant(3, dl, MVT::i32));
2722 }
2723 
2724 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2725   // Multiplications are only custom-lowered for 128-bit vectors so that
2726   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2727   EVT VT = Op.getValueType();
2728   assert(VT.is128BitVector() && VT.isInteger() &&
2729          "unexpected type for custom-lowering ISD::MUL");
2730   SDNode *N0 = Op.getOperand(0).getNode();
2731   SDNode *N1 = Op.getOperand(1).getNode();
2732   unsigned NewOpc = 0;
2733   bool isMLA = false;
2734   bool isN0SExt = isSignExtended(N0, DAG);
2735   bool isN1SExt = isSignExtended(N1, DAG);
2736   if (isN0SExt && isN1SExt)
2737     NewOpc = AArch64ISD::SMULL;
2738   else {
2739     bool isN0ZExt = isZeroExtended(N0, DAG);
2740     bool isN1ZExt = isZeroExtended(N1, DAG);
2741     if (isN0ZExt && isN1ZExt)
2742       NewOpc = AArch64ISD::UMULL;
2743     else if (isN1SExt || isN1ZExt) {
2744       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2745       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2746       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2747         NewOpc = AArch64ISD::SMULL;
2748         isMLA = true;
2749       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2750         NewOpc =  AArch64ISD::UMULL;
2751         isMLA = true;
2752       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2753         std::swap(N0, N1);
2754         NewOpc =  AArch64ISD::UMULL;
2755         isMLA = true;
2756       }
2757     }
2758 
2759     if (!NewOpc) {
2760       if (VT == MVT::v2i64)
2761         // Fall through to expand this.  It is not legal.
2762         return SDValue();
2763       else
2764         // Other vector multiplications are legal.
2765         return Op;
2766     }
2767   }
2768 
2769   // Legalize to a S/UMULL instruction
2770   SDLoc DL(Op);
2771   SDValue Op0;
2772   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2773   if (!isMLA) {
2774     Op0 = skipExtensionForVectorMULL(N0, DAG);
2775     assert(Op0.getValueType().is64BitVector() &&
2776            Op1.getValueType().is64BitVector() &&
2777            "unexpected types for extended operands to VMULL");
2778     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2779   }
2780   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2781   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2782   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2783   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2784   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2785   EVT Op1VT = Op1.getValueType();
2786   return DAG.getNode(N0->getOpcode(), DL, VT,
2787                      DAG.getNode(NewOpc, DL, VT,
2788                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2789                      DAG.getNode(NewOpc, DL, VT,
2790                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2791 }
2792 
2793 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2794                                                      SelectionDAG &DAG) const {
2795   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2796   SDLoc dl(Op);
2797   switch (IntNo) {
2798   default: return SDValue();    // Don't custom lower most intrinsics.
2799   case Intrinsic::thread_pointer: {
2800     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2801     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2802   }
2803   case Intrinsic::aarch64_neon_abs: {
2804     EVT Ty = Op.getValueType();
2805     if (Ty == MVT::i64) {
2806       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2807                                    Op.getOperand(1));
2808       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2809       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2810     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2811       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2812     } else {
2813       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2814     }
2815   }
2816   case Intrinsic::aarch64_neon_smax:
2817     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2818                        Op.getOperand(1), Op.getOperand(2));
2819   case Intrinsic::aarch64_neon_umax:
2820     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2821                        Op.getOperand(1), Op.getOperand(2));
2822   case Intrinsic::aarch64_neon_smin:
2823     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2824                        Op.getOperand(1), Op.getOperand(2));
2825   case Intrinsic::aarch64_neon_umin:
2826     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2827                        Op.getOperand(1), Op.getOperand(2));
2828 
2829   case Intrinsic::localaddress: {
2830     const auto &MF = DAG.getMachineFunction();
2831     const auto *RegInfo = Subtarget->getRegisterInfo();
2832     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2833     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2834                               Op.getSimpleValueType());
2835   }
2836 
2837   case Intrinsic::eh_recoverfp: {
2838     // FIXME: This needs to be implemented to correctly handle highly aligned
2839     // stack objects. For now we simply return the incoming FP. Refer D53541
2840     // for more details.
2841     SDValue FnOp = Op.getOperand(1);
2842     SDValue IncomingFPOp = Op.getOperand(2);
2843     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2844     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2845     if (!Fn)
2846       report_fatal_error(
2847           "llvm.eh.recoverfp must take a function as the first argument");
2848     return IncomingFPOp;
2849   }
2850   }
2851 }
2852 
2853 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2854 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2855                                         EVT VT, EVT MemVT,
2856                                         SelectionDAG &DAG) {
2857   assert(VT.isVector() && "VT should be a vector type");
2858   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2859 
2860   SDValue Value = ST->getValue();
2861 
2862   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2863   // the word lane which represent the v4i8 subvector.  It optimizes the store
2864   // to:
2865   //
2866   //   xtn  v0.8b, v0.8h
2867   //   str  s0, [x0]
2868 
2869   SDValue Undef = DAG.getUNDEF(MVT::i16);
2870   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2871                                         {Undef, Undef, Undef, Undef});
2872 
2873   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2874                                  Value, UndefVec);
2875   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2876 
2877   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2878   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2879                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
2880 
2881   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2882                       ST->getBasePtr(), ST->getMemOperand());
2883 }
2884 
2885 // Custom lowering for any store, vector or scalar and/or default or with
2886 // a truncate operations.  Currently only custom lower truncate operation
2887 // from vector v4i16 to v4i8.
2888 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2889                                           SelectionDAG &DAG) const {
2890   SDLoc Dl(Op);
2891   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2892   assert (StoreNode && "Can only custom lower store nodes");
2893 
2894   SDValue Value = StoreNode->getValue();
2895 
2896   EVT VT = Value.getValueType();
2897   EVT MemVT = StoreNode->getMemoryVT();
2898 
2899   assert (VT.isVector() && "Can only custom lower vector store types");
2900 
2901   unsigned AS = StoreNode->getAddressSpace();
2902   unsigned Align = StoreNode->getAlignment();
2903   if (Align < MemVT.getStoreSize() &&
2904       !allowsMisalignedMemoryAccesses(
2905           MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
2906     return scalarizeVectorStore(StoreNode, DAG);
2907   }
2908 
2909   if (StoreNode->isTruncatingStore()) {
2910     return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2911   }
2912 
2913   return SDValue();
2914 }
2915 
2916 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2917                                               SelectionDAG &DAG) const {
2918   LLVM_DEBUG(dbgs() << "Custom lowering: ");
2919   LLVM_DEBUG(Op.dump());
2920 
2921   switch (Op.getOpcode()) {
2922   default:
2923     llvm_unreachable("unimplemented operand");
2924     return SDValue();
2925   case ISD::BITCAST:
2926     return LowerBITCAST(Op, DAG);
2927   case ISD::GlobalAddress:
2928     return LowerGlobalAddress(Op, DAG);
2929   case ISD::GlobalTLSAddress:
2930     return LowerGlobalTLSAddress(Op, DAG);
2931   case ISD::SETCC:
2932     return LowerSETCC(Op, DAG);
2933   case ISD::BR_CC:
2934     return LowerBR_CC(Op, DAG);
2935   case ISD::SELECT:
2936     return LowerSELECT(Op, DAG);
2937   case ISD::SELECT_CC:
2938     return LowerSELECT_CC(Op, DAG);
2939   case ISD::JumpTable:
2940     return LowerJumpTable(Op, DAG);
2941   case ISD::BR_JT:
2942     return LowerBR_JT(Op, DAG);
2943   case ISD::ConstantPool:
2944     return LowerConstantPool(Op, DAG);
2945   case ISD::BlockAddress:
2946     return LowerBlockAddress(Op, DAG);
2947   case ISD::VASTART:
2948     return LowerVASTART(Op, DAG);
2949   case ISD::VACOPY:
2950     return LowerVACOPY(Op, DAG);
2951   case ISD::VAARG:
2952     return LowerVAARG(Op, DAG);
2953   case ISD::ADDC:
2954   case ISD::ADDE:
2955   case ISD::SUBC:
2956   case ISD::SUBE:
2957     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2958   case ISD::SADDO:
2959   case ISD::UADDO:
2960   case ISD::SSUBO:
2961   case ISD::USUBO:
2962   case ISD::SMULO:
2963   case ISD::UMULO:
2964     return LowerXALUO(Op, DAG);
2965   case ISD::FADD:
2966     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2967   case ISD::FSUB:
2968     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2969   case ISD::FMUL:
2970     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2971   case ISD::FDIV:
2972     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2973   case ISD::FP_ROUND:
2974     return LowerFP_ROUND(Op, DAG);
2975   case ISD::FP_EXTEND:
2976     return LowerFP_EXTEND(Op, DAG);
2977   case ISD::FRAMEADDR:
2978     return LowerFRAMEADDR(Op, DAG);
2979   case ISD::SPONENTRY:
2980     return LowerSPONENTRY(Op, DAG);
2981   case ISD::RETURNADDR:
2982     return LowerRETURNADDR(Op, DAG);
2983   case ISD::ADDROFRETURNADDR:
2984     return LowerADDROFRETURNADDR(Op, DAG);
2985   case ISD::INSERT_VECTOR_ELT:
2986     return LowerINSERT_VECTOR_ELT(Op, DAG);
2987   case ISD::EXTRACT_VECTOR_ELT:
2988     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2989   case ISD::BUILD_VECTOR:
2990     return LowerBUILD_VECTOR(Op, DAG);
2991   case ISD::VECTOR_SHUFFLE:
2992     return LowerVECTOR_SHUFFLE(Op, DAG);
2993   case ISD::EXTRACT_SUBVECTOR:
2994     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2995   case ISD::SRA:
2996   case ISD::SRL:
2997   case ISD::SHL:
2998     return LowerVectorSRA_SRL_SHL(Op, DAG);
2999   case ISD::SHL_PARTS:
3000     return LowerShiftLeftParts(Op, DAG);
3001   case ISD::SRL_PARTS:
3002   case ISD::SRA_PARTS:
3003     return LowerShiftRightParts(Op, DAG);
3004   case ISD::CTPOP:
3005     return LowerCTPOP(Op, DAG);
3006   case ISD::FCOPYSIGN:
3007     return LowerFCOPYSIGN(Op, DAG);
3008   case ISD::OR:
3009     return LowerVectorOR(Op, DAG);
3010   case ISD::XOR:
3011     return LowerXOR(Op, DAG);
3012   case ISD::PREFETCH:
3013     return LowerPREFETCH(Op, DAG);
3014   case ISD::SINT_TO_FP:
3015   case ISD::UINT_TO_FP:
3016     return LowerINT_TO_FP(Op, DAG);
3017   case ISD::FP_TO_SINT:
3018   case ISD::FP_TO_UINT:
3019     return LowerFP_TO_INT(Op, DAG);
3020   case ISD::FSINCOS:
3021     return LowerFSINCOS(Op, DAG);
3022   case ISD::FLT_ROUNDS_:
3023     return LowerFLT_ROUNDS_(Op, DAG);
3024   case ISD::MUL:
3025     return LowerMUL(Op, DAG);
3026   case ISD::INTRINSIC_WO_CHAIN:
3027     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3028   case ISD::STORE:
3029     return LowerSTORE(Op, DAG);
3030   case ISD::VECREDUCE_ADD:
3031   case ISD::VECREDUCE_SMAX:
3032   case ISD::VECREDUCE_SMIN:
3033   case ISD::VECREDUCE_UMAX:
3034   case ISD::VECREDUCE_UMIN:
3035   case ISD::VECREDUCE_FMAX:
3036   case ISD::VECREDUCE_FMIN:
3037     return LowerVECREDUCE(Op, DAG);
3038   case ISD::ATOMIC_LOAD_SUB:
3039     return LowerATOMIC_LOAD_SUB(Op, DAG);
3040   case ISD::ATOMIC_LOAD_AND:
3041     return LowerATOMIC_LOAD_AND(Op, DAG);
3042   case ISD::DYNAMIC_STACKALLOC:
3043     return LowerDYNAMIC_STACKALLOC(Op, DAG);
3044   }
3045 }
3046 
3047 //===----------------------------------------------------------------------===//
3048 //                      Calling Convention Implementation
3049 //===----------------------------------------------------------------------===//
3050 
3051 /// Selects the correct CCAssignFn for a given CallingConvention value.
3052 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3053                                                      bool IsVarArg) const {
3054   switch (CC) {
3055   default:
3056     report_fatal_error("Unsupported calling convention.");
3057   case CallingConv::WebKit_JS:
3058     return CC_AArch64_WebKit_JS;
3059   case CallingConv::GHC:
3060     return CC_AArch64_GHC;
3061   case CallingConv::C:
3062   case CallingConv::Fast:
3063   case CallingConv::PreserveMost:
3064   case CallingConv::CXX_FAST_TLS:
3065   case CallingConv::Swift:
3066     if (Subtarget->isTargetWindows() && IsVarArg)
3067       return CC_AArch64_Win64_VarArg;
3068     if (!Subtarget->isTargetDarwin())
3069       return CC_AArch64_AAPCS;
3070     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
3071   case CallingConv::Win64:
3072     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3073   case CallingConv::AArch64_VectorCall:
3074     return CC_AArch64_AAPCS;
3075   }
3076 }
3077 
3078 CCAssignFn *
3079 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3080   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3081                                       : RetCC_AArch64_AAPCS;
3082 }
3083 
3084 SDValue AArch64TargetLowering::LowerFormalArguments(
3085     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3086     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3087     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3088   MachineFunction &MF = DAG.getMachineFunction();
3089   MachineFrameInfo &MFI = MF.getFrameInfo();
3090   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3091 
3092   // Assign locations to all of the incoming arguments.
3093   SmallVector<CCValAssign, 16> ArgLocs;
3094   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3095                  *DAG.getContext());
3096 
3097   // At this point, Ins[].VT may already be promoted to i32. To correctly
3098   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3099   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3100   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3101   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3102   // LocVT.
3103   unsigned NumArgs = Ins.size();
3104   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3105   unsigned CurArgIdx = 0;
3106   for (unsigned i = 0; i != NumArgs; ++i) {
3107     MVT ValVT = Ins[i].VT;
3108     if (Ins[i].isOrigArg()) {
3109       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3110       CurArgIdx = Ins[i].getOrigArgIndex();
3111 
3112       // Get type of the original argument.
3113       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3114                                   /*AllowUnknown*/ true);
3115       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3116       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3117       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3118         ValVT = MVT::i8;
3119       else if (ActualMVT == MVT::i16)
3120         ValVT = MVT::i16;
3121     }
3122     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3123     bool Res =
3124         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3125     assert(!Res && "Call operand has unhandled type");
3126     (void)Res;
3127   }
3128   assert(ArgLocs.size() == Ins.size());
3129   SmallVector<SDValue, 16> ArgValues;
3130   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131     CCValAssign &VA = ArgLocs[i];
3132 
3133     if (Ins[i].Flags.isByVal()) {
3134       // Byval is used for HFAs in the PCS, but the system should work in a
3135       // non-compliant manner for larger structs.
3136       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3137       int Size = Ins[i].Flags.getByValSize();
3138       unsigned NumRegs = (Size + 7) / 8;
3139 
3140       // FIXME: This works on big-endian for composite byvals, which are the common
3141       // case. It should also work for fundamental types too.
3142       unsigned FrameIdx =
3143         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3144       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3145       InVals.push_back(FrameIdxN);
3146 
3147       continue;
3148     }
3149 
3150     if (VA.isRegLoc()) {
3151       // Arguments stored in registers.
3152       EVT RegVT = VA.getLocVT();
3153 
3154       SDValue ArgValue;
3155       const TargetRegisterClass *RC;
3156 
3157       if (RegVT == MVT::i32)
3158         RC = &AArch64::GPR32RegClass;
3159       else if (RegVT == MVT::i64)
3160         RC = &AArch64::GPR64RegClass;
3161       else if (RegVT == MVT::f16)
3162         RC = &AArch64::FPR16RegClass;
3163       else if (RegVT == MVT::f32)
3164         RC = &AArch64::FPR32RegClass;
3165       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3166         RC = &AArch64::FPR64RegClass;
3167       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3168         RC = &AArch64::FPR128RegClass;
3169       else if (RegVT.isScalableVector() &&
3170                RegVT.getVectorElementType() == MVT::i1)
3171         RC = &AArch64::PPRRegClass;
3172       else if (RegVT.isScalableVector())
3173         RC = &AArch64::ZPRRegClass;
3174       else
3175         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3176 
3177       // Transform the arguments in physical registers into virtual ones.
3178       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3179       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3180 
3181       // If this is an 8, 16 or 32-bit value, it is really passed promoted
3182       // to 64 bits.  Insert an assert[sz]ext to capture this, then
3183       // truncate to the right size.
3184       switch (VA.getLocInfo()) {
3185       default:
3186         llvm_unreachable("Unknown loc info!");
3187       case CCValAssign::Full:
3188         break;
3189       case CCValAssign::Indirect:
3190         assert(VA.getValVT().isScalableVector() &&
3191                "Only scalable vectors can be passed indirectly");
3192         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3193       case CCValAssign::BCvt:
3194         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3195         break;
3196       case CCValAssign::AExt:
3197       case CCValAssign::SExt:
3198       case CCValAssign::ZExt:
3199         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3200         // nodes after our lowering.
3201         assert(RegVT == Ins[i].VT && "incorrect register location selected");
3202         break;
3203       }
3204 
3205       InVals.push_back(ArgValue);
3206 
3207     } else { // VA.isRegLoc()
3208       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3209       unsigned ArgOffset = VA.getLocMemOffset();
3210       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3211 
3212       uint32_t BEAlign = 0;
3213       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3214           !Ins[i].Flags.isInConsecutiveRegs())
3215         BEAlign = 8 - ArgSize;
3216 
3217       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3218 
3219       // Create load nodes to retrieve arguments from the stack.
3220       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3221       SDValue ArgValue;
3222 
3223       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3224       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3225       MVT MemVT = VA.getValVT();
3226 
3227       switch (VA.getLocInfo()) {
3228       default:
3229         break;
3230       case CCValAssign::BCvt:
3231         MemVT = VA.getLocVT();
3232         break;
3233       case CCValAssign::Indirect:
3234         assert(VA.getValVT().isScalableVector() &&
3235                "Only scalable vectors can be passed indirectly");
3236         llvm_unreachable("Spilling of SVE vectors not yet implemented");
3237       case CCValAssign::SExt:
3238         ExtType = ISD::SEXTLOAD;
3239         break;
3240       case CCValAssign::ZExt:
3241         ExtType = ISD::ZEXTLOAD;
3242         break;
3243       case CCValAssign::AExt:
3244         ExtType = ISD::EXTLOAD;
3245         break;
3246       }
3247 
3248       ArgValue = DAG.getExtLoad(
3249           ExtType, DL, VA.getLocVT(), Chain, FIN,
3250           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3251           MemVT);
3252 
3253       InVals.push_back(ArgValue);
3254     }
3255   }
3256 
3257   // varargs
3258   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3259   if (isVarArg) {
3260     if (!Subtarget->isTargetDarwin() || IsWin64) {
3261       // The AAPCS variadic function ABI is identical to the non-variadic
3262       // one. As a result there may be more arguments in registers and we should
3263       // save them for future reference.
3264       // Win64 variadic functions also pass arguments in registers, but all float
3265       // arguments are passed in integer registers.
3266       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3267     }
3268 
3269     // This will point to the next argument passed via stack.
3270     unsigned StackOffset = CCInfo.getNextStackOffset();
3271     // We currently pass all varargs at 8-byte alignment.
3272     StackOffset = ((StackOffset + 7) & ~7);
3273     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3274 
3275     if (MFI.hasMustTailInVarArgFunc()) {
3276       SmallVector<MVT, 2> RegParmTypes;
3277       RegParmTypes.push_back(MVT::i64);
3278       RegParmTypes.push_back(MVT::f128);
3279       // Compute the set of forwarded registers. The rest are scratch.
3280       SmallVectorImpl<ForwardedRegister> &Forwards =
3281                                        FuncInfo->getForwardedMustTailRegParms();
3282       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3283                                                CC_AArch64_AAPCS);
3284 
3285       // Conservatively forward X8, since it might be used for aggregate return.
3286       if (!CCInfo.isAllocated(AArch64::X8)) {
3287         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3288         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3289       }
3290     }
3291   }
3292 
3293   // On Windows, InReg pointers must be returned, so record the pointer in a
3294   // virtual register at the start of the function so it can be returned in the
3295   // epilogue.
3296   if (IsWin64) {
3297     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3298       if (Ins[I].Flags.isInReg()) {
3299         assert(!FuncInfo->getSRetReturnReg());
3300 
3301         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3302         Register Reg =
3303             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3304         FuncInfo->setSRetReturnReg(Reg);
3305 
3306         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3307         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3308         break;
3309       }
3310     }
3311   }
3312 
3313   unsigned StackArgSize = CCInfo.getNextStackOffset();
3314   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3315   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3316     // This is a non-standard ABI so by fiat I say we're allowed to make full
3317     // use of the stack area to be popped, which must be aligned to 16 bytes in
3318     // any case:
3319     StackArgSize = alignTo(StackArgSize, 16);
3320 
3321     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3322     // a multiple of 16.
3323     FuncInfo->setArgumentStackToRestore(StackArgSize);
3324 
3325     // This realignment carries over to the available bytes below. Our own
3326     // callers will guarantee the space is free by giving an aligned value to
3327     // CALLSEQ_START.
3328   }
3329   // Even if we're not expected to free up the space, it's useful to know how
3330   // much is there while considering tail calls (because we can reuse it).
3331   FuncInfo->setBytesInStackArgArea(StackArgSize);
3332 
3333   if (Subtarget->hasCustomCallingConv())
3334     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3335 
3336   return Chain;
3337 }
3338 
3339 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3340                                                 SelectionDAG &DAG,
3341                                                 const SDLoc &DL,
3342                                                 SDValue &Chain) const {
3343   MachineFunction &MF = DAG.getMachineFunction();
3344   MachineFrameInfo &MFI = MF.getFrameInfo();
3345   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3346   auto PtrVT = getPointerTy(DAG.getDataLayout());
3347   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3348 
3349   SmallVector<SDValue, 8> MemOps;
3350 
3351   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3352                                           AArch64::X3, AArch64::X4, AArch64::X5,
3353                                           AArch64::X6, AArch64::X7 };
3354   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3355   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3356 
3357   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3358   int GPRIdx = 0;
3359   if (GPRSaveSize != 0) {
3360     if (IsWin64) {
3361       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3362       if (GPRSaveSize & 15)
3363         // The extra size here, if triggered, will always be 8.
3364         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3365     } else
3366       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3367 
3368     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3369 
3370     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3371       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3372       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3373       SDValue Store = DAG.getStore(
3374           Val.getValue(1), DL, Val, FIN,
3375           IsWin64
3376               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3377                                                   GPRIdx,
3378                                                   (i - FirstVariadicGPR) * 8)
3379               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3380       MemOps.push_back(Store);
3381       FIN =
3382           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3383     }
3384   }
3385   FuncInfo->setVarArgsGPRIndex(GPRIdx);
3386   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3387 
3388   if (Subtarget->hasFPARMv8() && !IsWin64) {
3389     static const MCPhysReg FPRArgRegs[] = {
3390         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3391         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3392     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3393     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3394 
3395     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3396     int FPRIdx = 0;
3397     if (FPRSaveSize != 0) {
3398       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3399 
3400       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3401 
3402       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3403         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3404         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3405 
3406         SDValue Store = DAG.getStore(
3407             Val.getValue(1), DL, Val, FIN,
3408             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3409         MemOps.push_back(Store);
3410         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3411                           DAG.getConstant(16, DL, PtrVT));
3412       }
3413     }
3414     FuncInfo->setVarArgsFPRIndex(FPRIdx);
3415     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3416   }
3417 
3418   if (!MemOps.empty()) {
3419     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3420   }
3421 }
3422 
3423 /// LowerCallResult - Lower the result values of a call into the
3424 /// appropriate copies out of appropriate physical registers.
3425 SDValue AArch64TargetLowering::LowerCallResult(
3426     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3427     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3428     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3429     SDValue ThisVal) const {
3430   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3431                           ? RetCC_AArch64_WebKit_JS
3432                           : RetCC_AArch64_AAPCS;
3433   // Assign locations to each value returned by this call.
3434   SmallVector<CCValAssign, 16> RVLocs;
3435   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3436                  *DAG.getContext());
3437   CCInfo.AnalyzeCallResult(Ins, RetCC);
3438 
3439   // Copy all of the result registers out of their specified physreg.
3440   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3441     CCValAssign VA = RVLocs[i];
3442 
3443     // Pass 'this' value directly from the argument to return value, to avoid
3444     // reg unit interference
3445     if (i == 0 && isThisReturn) {
3446       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3447              "unexpected return calling convention register assignment");
3448       InVals.push_back(ThisVal);
3449       continue;
3450     }
3451 
3452     SDValue Val =
3453         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3454     Chain = Val.getValue(1);
3455     InFlag = Val.getValue(2);
3456 
3457     switch (VA.getLocInfo()) {
3458     default:
3459       llvm_unreachable("Unknown loc info!");
3460     case CCValAssign::Full:
3461       break;
3462     case CCValAssign::BCvt:
3463       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3464       break;
3465     }
3466 
3467     InVals.push_back(Val);
3468   }
3469 
3470   return Chain;
3471 }
3472 
3473 /// Return true if the calling convention is one that we can guarantee TCO for.
3474 static bool canGuaranteeTCO(CallingConv::ID CC) {
3475   return CC == CallingConv::Fast;
3476 }
3477 
3478 /// Return true if we might ever do TCO for calls with this calling convention.
3479 static bool mayTailCallThisCC(CallingConv::ID CC) {
3480   switch (CC) {
3481   case CallingConv::C:
3482   case CallingConv::PreserveMost:
3483   case CallingConv::Swift:
3484     return true;
3485   default:
3486     return canGuaranteeTCO(CC);
3487   }
3488 }
3489 
3490 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3491     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3492     const SmallVectorImpl<ISD::OutputArg> &Outs,
3493     const SmallVectorImpl<SDValue> &OutVals,
3494     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3495   if (!mayTailCallThisCC(CalleeCC))
3496     return false;
3497 
3498   MachineFunction &MF = DAG.getMachineFunction();
3499   const Function &CallerF = MF.getFunction();
3500   CallingConv::ID CallerCC = CallerF.getCallingConv();
3501   bool CCMatch = CallerCC == CalleeCC;
3502 
3503   // Byval parameters hand the function a pointer directly into the stack area
3504   // we want to reuse during a tail call. Working around this *is* possible (see
3505   // X86) but less efficient and uglier in LowerCall.
3506   for (Function::const_arg_iterator i = CallerF.arg_begin(),
3507                                     e = CallerF.arg_end();
3508        i != e; ++i) {
3509     if (i->hasByValAttr())
3510       return false;
3511 
3512     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3513     // In this case, it is necessary to save/restore X0 in the callee. Tail
3514     // call opt interferes with this. So we disable tail call opt when the
3515     // caller has an argument with "inreg" attribute.
3516 
3517     // FIXME: Check whether the callee also has an "inreg" argument.
3518     if (i->hasInRegAttr())
3519       return false;
3520   }
3521 
3522   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3523     return canGuaranteeTCO(CalleeCC) && CCMatch;
3524 
3525   // Externally-defined functions with weak linkage should not be
3526   // tail-called on AArch64 when the OS does not support dynamic
3527   // pre-emption of symbols, as the AAELF spec requires normal calls
3528   // to undefined weak functions to be replaced with a NOP or jump to the
3529   // next instruction. The behaviour of branch instructions in this
3530   // situation (as used for tail calls) is implementation-defined, so we
3531   // cannot rely on the linker replacing the tail call with a return.
3532   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3533     const GlobalValue *GV = G->getGlobal();
3534     const Triple &TT = getTargetMachine().getTargetTriple();
3535     if (GV->hasExternalWeakLinkage() &&
3536         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3537       return false;
3538   }
3539 
3540   // Now we search for cases where we can use a tail call without changing the
3541   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3542   // concept.
3543 
3544   // I want anyone implementing a new calling convention to think long and hard
3545   // about this assert.
3546   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3547          "Unexpected variadic calling convention");
3548 
3549   LLVMContext &C = *DAG.getContext();
3550   if (isVarArg && !Outs.empty()) {
3551     // At least two cases here: if caller is fastcc then we can't have any
3552     // memory arguments (we'd be expected to clean up the stack afterwards). If
3553     // caller is C then we could potentially use its argument area.
3554 
3555     // FIXME: for now we take the most conservative of these in both cases:
3556     // disallow all variadic memory operands.
3557     SmallVector<CCValAssign, 16> ArgLocs;
3558     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3559 
3560     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3561     for (const CCValAssign &ArgLoc : ArgLocs)
3562       if (!ArgLoc.isRegLoc())
3563         return false;
3564   }
3565 
3566   // Check that the call results are passed in the same way.
3567   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3568                                   CCAssignFnForCall(CalleeCC, isVarArg),
3569                                   CCAssignFnForCall(CallerCC, isVarArg)))
3570     return false;
3571   // The callee has to preserve all registers the caller needs to preserve.
3572   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3573   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3574   if (!CCMatch) {
3575     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3576     if (Subtarget->hasCustomCallingConv()) {
3577       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3578       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3579     }
3580     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3581       return false;
3582   }
3583 
3584   // Nothing more to check if the callee is taking no arguments
3585   if (Outs.empty())
3586     return true;
3587 
3588   SmallVector<CCValAssign, 16> ArgLocs;
3589   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3590 
3591   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3592 
3593   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3594 
3595   // If the stack arguments for this call do not fit into our own save area then
3596   // the call cannot be made tail.
3597   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3598     return false;
3599 
3600   const MachineRegisterInfo &MRI = MF.getRegInfo();
3601   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3602     return false;
3603 
3604   return true;
3605 }
3606 
3607 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3608                                                    SelectionDAG &DAG,
3609                                                    MachineFrameInfo &MFI,
3610                                                    int ClobberedFI) const {
3611   SmallVector<SDValue, 8> ArgChains;
3612   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3613   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3614 
3615   // Include the original chain at the beginning of the list. When this is
3616   // used by target LowerCall hooks, this helps legalize find the
3617   // CALLSEQ_BEGIN node.
3618   ArgChains.push_back(Chain);
3619 
3620   // Add a chain value for each stack argument corresponding
3621   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3622                             UE = DAG.getEntryNode().getNode()->use_end();
3623        U != UE; ++U)
3624     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3625       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3626         if (FI->getIndex() < 0) {
3627           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3628           int64_t InLastByte = InFirstByte;
3629           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3630 
3631           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3632               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3633             ArgChains.push_back(SDValue(L, 1));
3634         }
3635 
3636   // Build a tokenfactor for all the chains.
3637   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3638 }
3639 
3640 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3641                                                    bool TailCallOpt) const {
3642   return CallCC == CallingConv::Fast && TailCallOpt;
3643 }
3644 
3645 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3646 /// and add input and output parameter nodes.
3647 SDValue
3648 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3649                                  SmallVectorImpl<SDValue> &InVals) const {
3650   SelectionDAG &DAG = CLI.DAG;
3651   SDLoc &DL = CLI.DL;
3652   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3653   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3654   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3655   SDValue Chain = CLI.Chain;
3656   SDValue Callee = CLI.Callee;
3657   bool &IsTailCall = CLI.IsTailCall;
3658   CallingConv::ID CallConv = CLI.CallConv;
3659   bool IsVarArg = CLI.IsVarArg;
3660 
3661   MachineFunction &MF = DAG.getMachineFunction();
3662   bool IsThisReturn = false;
3663 
3664   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3665   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3666   bool IsSibCall = false;
3667 
3668   if (IsTailCall) {
3669     // Check if it's really possible to do a tail call.
3670     IsTailCall = isEligibleForTailCallOptimization(
3671         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3672     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3673       report_fatal_error("failed to perform tail call elimination on a call "
3674                          "site marked musttail");
3675 
3676     // A sibling call is one where we're under the usual C ABI and not planning
3677     // to change that but can still do a tail call:
3678     if (!TailCallOpt && IsTailCall)
3679       IsSibCall = true;
3680 
3681     if (IsTailCall)
3682       ++NumTailCalls;
3683   }
3684 
3685   // Analyze operands of the call, assigning locations to each operand.
3686   SmallVector<CCValAssign, 16> ArgLocs;
3687   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3688                  *DAG.getContext());
3689 
3690   if (IsVarArg) {
3691     // Handle fixed and variable vector arguments differently.
3692     // Variable vector arguments always go into memory.
3693     unsigned NumArgs = Outs.size();
3694 
3695     for (unsigned i = 0; i != NumArgs; ++i) {
3696       MVT ArgVT = Outs[i].VT;
3697       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3698       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3699                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3700       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3701       assert(!Res && "Call operand has unhandled type");
3702       (void)Res;
3703     }
3704   } else {
3705     // At this point, Outs[].VT may already be promoted to i32. To correctly
3706     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3707     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3708     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3709     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3710     // LocVT.
3711     unsigned NumArgs = Outs.size();
3712     for (unsigned i = 0; i != NumArgs; ++i) {
3713       MVT ValVT = Outs[i].VT;
3714       // Get type of the original argument.
3715       EVT ActualVT = getValueType(DAG.getDataLayout(),
3716                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3717                                   /*AllowUnknown*/ true);
3718       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3719       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3720       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3721       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3722         ValVT = MVT::i8;
3723       else if (ActualMVT == MVT::i16)
3724         ValVT = MVT::i16;
3725 
3726       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3727       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3728       assert(!Res && "Call operand has unhandled type");
3729       (void)Res;
3730     }
3731   }
3732 
3733   // Get a count of how many bytes are to be pushed on the stack.
3734   unsigned NumBytes = CCInfo.getNextStackOffset();
3735 
3736   if (IsSibCall) {
3737     // Since we're not changing the ABI to make this a tail call, the memory
3738     // operands are already available in the caller's incoming argument space.
3739     NumBytes = 0;
3740   }
3741 
3742   // FPDiff is the byte offset of the call's argument area from the callee's.
3743   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3744   // by this amount for a tail call. In a sibling call it must be 0 because the
3745   // caller will deallocate the entire stack and the callee still expects its
3746   // arguments to begin at SP+0. Completely unused for non-tail calls.
3747   int FPDiff = 0;
3748 
3749   if (IsTailCall && !IsSibCall) {
3750     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3751 
3752     // Since callee will pop argument stack as a tail call, we must keep the
3753     // popped size 16-byte aligned.
3754     NumBytes = alignTo(NumBytes, 16);
3755 
3756     // FPDiff will be negative if this tail call requires more space than we
3757     // would automatically have in our incoming argument space. Positive if we
3758     // can actually shrink the stack.
3759     FPDiff = NumReusableBytes - NumBytes;
3760 
3761     // The stack pointer must be 16-byte aligned at all times it's used for a
3762     // memory operation, which in practice means at *all* times and in
3763     // particular across call boundaries. Therefore our own arguments started at
3764     // a 16-byte aligned SP and the delta applied for the tail call should
3765     // satisfy the same constraint.
3766     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3767   }
3768 
3769   // Adjust the stack pointer for the new arguments...
3770   // These operations are automatically eliminated by the prolog/epilog pass
3771   if (!IsSibCall)
3772     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3773 
3774   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3775                                         getPointerTy(DAG.getDataLayout()));
3776 
3777   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3778   SmallVector<SDValue, 8> MemOpChains;
3779   auto PtrVT = getPointerTy(DAG.getDataLayout());
3780 
3781   if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3782     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3783     for (const auto &F : Forwards) {
3784       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3785        RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3786     }
3787   }
3788 
3789   // Walk the register/memloc assignments, inserting copies/loads.
3790   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3791        ++i, ++realArgIdx) {
3792     CCValAssign &VA = ArgLocs[i];
3793     SDValue Arg = OutVals[realArgIdx];
3794     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3795 
3796     // Promote the value if needed.
3797     switch (VA.getLocInfo()) {
3798     default:
3799       llvm_unreachable("Unknown loc info!");
3800     case CCValAssign::Full:
3801       break;
3802     case CCValAssign::SExt:
3803       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3804       break;
3805     case CCValAssign::ZExt:
3806       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3807       break;
3808     case CCValAssign::AExt:
3809       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3810         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3811         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3812         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3813       }
3814       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3815       break;
3816     case CCValAssign::BCvt:
3817       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3818       break;
3819     case CCValAssign::FPExt:
3820       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3821       break;
3822     case CCValAssign::Indirect:
3823       assert(VA.getValVT().isScalableVector() &&
3824              "Only scalable vectors can be passed indirectly");
3825       llvm_unreachable("Spilling of SVE vectors not yet implemented");
3826     }
3827 
3828     if (VA.isRegLoc()) {
3829       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3830           Outs[0].VT == MVT::i64) {
3831         assert(VA.getLocVT() == MVT::i64 &&
3832                "unexpected calling convention register assignment");
3833         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3834                "unexpected use of 'returned'");
3835         IsThisReturn = true;
3836       }
3837       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3838     } else {
3839       assert(VA.isMemLoc());
3840 
3841       SDValue DstAddr;
3842       MachinePointerInfo DstInfo;
3843 
3844       // FIXME: This works on big-endian for composite byvals, which are the
3845       // common case. It should also work for fundamental types too.
3846       uint32_t BEAlign = 0;
3847       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3848                                         : VA.getValVT().getSizeInBits();
3849       OpSize = (OpSize + 7) / 8;
3850       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3851           !Flags.isInConsecutiveRegs()) {
3852         if (OpSize < 8)
3853           BEAlign = 8 - OpSize;
3854       }
3855       unsigned LocMemOffset = VA.getLocMemOffset();
3856       int32_t Offset = LocMemOffset + BEAlign;
3857       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3858       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3859 
3860       if (IsTailCall) {
3861         Offset = Offset + FPDiff;
3862         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3863 
3864         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3865         DstInfo =
3866             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3867 
3868         // Make sure any stack arguments overlapping with where we're storing
3869         // are loaded before this eventual operation. Otherwise they'll be
3870         // clobbered.
3871         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3872       } else {
3873         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3874 
3875         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3876         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3877                                                LocMemOffset);
3878       }
3879 
3880       if (Outs[i].Flags.isByVal()) {
3881         SDValue SizeNode =
3882             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3883         SDValue Cpy = DAG.getMemcpy(
3884             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3885             /*isVol = */ false, /*AlwaysInline = */ false,
3886             /*isTailCall = */ false,
3887             DstInfo, MachinePointerInfo());
3888 
3889         MemOpChains.push_back(Cpy);
3890       } else {
3891         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3892         // promoted to a legal register type i32, we should truncate Arg back to
3893         // i1/i8/i16.
3894         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3895             VA.getValVT() == MVT::i16)
3896           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3897 
3898         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3899         MemOpChains.push_back(Store);
3900       }
3901     }
3902   }
3903 
3904   if (!MemOpChains.empty())
3905     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3906 
3907   // Build a sequence of copy-to-reg nodes chained together with token chain
3908   // and flag operands which copy the outgoing args into the appropriate regs.
3909   SDValue InFlag;
3910   for (auto &RegToPass : RegsToPass) {
3911     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3912                              RegToPass.second, InFlag);
3913     InFlag = Chain.getValue(1);
3914   }
3915 
3916   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3917   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3918   // node so that legalize doesn't hack it.
3919   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3920     auto GV = G->getGlobal();
3921     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3922         AArch64II::MO_GOT) {
3923       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3924       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3925     } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3926       assert(Subtarget->isTargetWindows() &&
3927              "Windows is the only supported COFF target");
3928       Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3929     } else {
3930       const GlobalValue *GV = G->getGlobal();
3931       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3932     }
3933   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3934     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3935         Subtarget->isTargetMachO()) {
3936       const char *Sym = S->getSymbol();
3937       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3938       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3939     } else {
3940       const char *Sym = S->getSymbol();
3941       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3942     }
3943   }
3944 
3945   // We don't usually want to end the call-sequence here because we would tidy
3946   // the frame up *after* the call, however in the ABI-changing tail-call case
3947   // we've carefully laid out the parameters so that when sp is reset they'll be
3948   // in the correct location.
3949   if (IsTailCall && !IsSibCall) {
3950     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3951                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3952     InFlag = Chain.getValue(1);
3953   }
3954 
3955   std::vector<SDValue> Ops;
3956   Ops.push_back(Chain);
3957   Ops.push_back(Callee);
3958 
3959   if (IsTailCall) {
3960     // Each tail call may have to adjust the stack by a different amount, so
3961     // this information must travel along with the operation for eventual
3962     // consumption by emitEpilogue.
3963     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3964   }
3965 
3966   // Add argument registers to the end of the list so that they are known live
3967   // into the call.
3968   for (auto &RegToPass : RegsToPass)
3969     Ops.push_back(DAG.getRegister(RegToPass.first,
3970                                   RegToPass.second.getValueType()));
3971 
3972   // Check callee args/returns for SVE registers and set calling convention
3973   // accordingly.
3974   if (CallConv == CallingConv::C) {
3975     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
3976       return Out.VT.isScalableVector();
3977     });
3978     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
3979       return In.VT.isScalableVector();
3980     });
3981 
3982     if (CalleeInSVE || CalleeOutSVE)
3983       CallConv = CallingConv::AArch64_SVE_VectorCall;
3984   }
3985 
3986   // Add a register mask operand representing the call-preserved registers.
3987   const uint32_t *Mask;
3988   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3989   if (IsThisReturn) {
3990     // For 'this' returns, use the X0-preserving mask if applicable
3991     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3992     if (!Mask) {
3993       IsThisReturn = false;
3994       Mask = TRI->getCallPreservedMask(MF, CallConv);
3995     }
3996   } else
3997     Mask = TRI->getCallPreservedMask(MF, CallConv);
3998 
3999   if (Subtarget->hasCustomCallingConv())
4000     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4001 
4002   if (TRI->isAnyArgRegReserved(MF))
4003     TRI->emitReservedArgRegCallError(MF);
4004 
4005   assert(Mask && "Missing call preserved mask for calling convention");
4006   Ops.push_back(DAG.getRegisterMask(Mask));
4007 
4008   if (InFlag.getNode())
4009     Ops.push_back(InFlag);
4010 
4011   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4012 
4013   // If we're doing a tall call, use a TC_RETURN here rather than an
4014   // actual call instruction.
4015   if (IsTailCall) {
4016     MF.getFrameInfo().setHasTailCall();
4017     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4018   }
4019 
4020   // Returns a chain and a flag for retval copy to use.
4021   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4022   InFlag = Chain.getValue(1);
4023 
4024   uint64_t CalleePopBytes =
4025       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4026 
4027   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4028                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4029                              InFlag, DL);
4030   if (!Ins.empty())
4031     InFlag = Chain.getValue(1);
4032 
4033   // Handle result values, copying them out of physregs into vregs that we
4034   // return.
4035   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4036                          InVals, IsThisReturn,
4037                          IsThisReturn ? OutVals[0] : SDValue());
4038 }
4039 
4040 bool AArch64TargetLowering::CanLowerReturn(
4041     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4042     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4043   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4044                           ? RetCC_AArch64_WebKit_JS
4045                           : RetCC_AArch64_AAPCS;
4046   SmallVector<CCValAssign, 16> RVLocs;
4047   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4048   return CCInfo.CheckReturn(Outs, RetCC);
4049 }
4050 
4051 SDValue
4052 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4053                                    bool isVarArg,
4054                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
4055                                    const SmallVectorImpl<SDValue> &OutVals,
4056                                    const SDLoc &DL, SelectionDAG &DAG) const {
4057   auto &MF = DAG.getMachineFunction();
4058   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4059 
4060   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4061                           ? RetCC_AArch64_WebKit_JS
4062                           : RetCC_AArch64_AAPCS;
4063   SmallVector<CCValAssign, 16> RVLocs;
4064   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4065                  *DAG.getContext());
4066   CCInfo.AnalyzeReturn(Outs, RetCC);
4067 
4068   // Copy the result values into the output registers.
4069   SDValue Flag;
4070   SmallVector<SDValue, 4> RetOps(1, Chain);
4071   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4072        ++i, ++realRVLocIdx) {
4073     CCValAssign &VA = RVLocs[i];
4074     assert(VA.isRegLoc() && "Can only return in registers!");
4075     SDValue Arg = OutVals[realRVLocIdx];
4076 
4077     switch (VA.getLocInfo()) {
4078     default:
4079       llvm_unreachable("Unknown loc info!");
4080     case CCValAssign::Full:
4081       if (Outs[i].ArgVT == MVT::i1) {
4082         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4083         // value. This is strictly redundant on Darwin (which uses "zeroext
4084         // i1"), but will be optimised out before ISel.
4085         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4086         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4087       }
4088       break;
4089     case CCValAssign::BCvt:
4090       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4091       break;
4092     }
4093 
4094     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4095     Flag = Chain.getValue(1);
4096     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4097   }
4098 
4099   // Windows AArch64 ABIs require that for returning structs by value we copy
4100   // the sret argument into X0 for the return.
4101   // We saved the argument into a virtual register in the entry block,
4102   // so now we copy the value out and into X0.
4103   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4104     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4105                                      getPointerTy(MF.getDataLayout()));
4106 
4107     unsigned RetValReg = AArch64::X0;
4108     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4109     Flag = Chain.getValue(1);
4110 
4111     RetOps.push_back(
4112       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4113   }
4114 
4115   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4116   const MCPhysReg *I =
4117       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4118   if (I) {
4119     for (; *I; ++I) {
4120       if (AArch64::GPR64RegClass.contains(*I))
4121         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4122       else if (AArch64::FPR64RegClass.contains(*I))
4123         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4124       else
4125         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4126     }
4127   }
4128 
4129   RetOps[0] = Chain; // Update chain.
4130 
4131   // Add the flag if we have it.
4132   if (Flag.getNode())
4133     RetOps.push_back(Flag);
4134 
4135   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4136 }
4137 
4138 //===----------------------------------------------------------------------===//
4139 //  Other Lowering Code
4140 //===----------------------------------------------------------------------===//
4141 
4142 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4143                                              SelectionDAG &DAG,
4144                                              unsigned Flag) const {
4145   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4146                                     N->getOffset(), Flag);
4147 }
4148 
4149 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4150                                              SelectionDAG &DAG,
4151                                              unsigned Flag) const {
4152   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4153 }
4154 
4155 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4156                                              SelectionDAG &DAG,
4157                                              unsigned Flag) const {
4158   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4159                                    N->getOffset(), Flag);
4160 }
4161 
4162 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4163                                              SelectionDAG &DAG,
4164                                              unsigned Flag) const {
4165   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4166 }
4167 
4168 // (loadGOT sym)
4169 template <class NodeTy>
4170 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4171                                       unsigned Flags) const {
4172   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4173   SDLoc DL(N);
4174   EVT Ty = getPointerTy(DAG.getDataLayout());
4175   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4176   // FIXME: Once remat is capable of dealing with instructions with register
4177   // operands, expand this into two nodes instead of using a wrapper node.
4178   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4179 }
4180 
4181 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4182 template <class NodeTy>
4183 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4184                                             unsigned Flags) const {
4185   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4186   SDLoc DL(N);
4187   EVT Ty = getPointerTy(DAG.getDataLayout());
4188   const unsigned char MO_NC = AArch64II::MO_NC;
4189   return DAG.getNode(
4190       AArch64ISD::WrapperLarge, DL, Ty,
4191       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4192       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4193       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4194       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4195 }
4196 
4197 // (addlow (adrp %hi(sym)) %lo(sym))
4198 template <class NodeTy>
4199 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4200                                        unsigned Flags) const {
4201   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4202   SDLoc DL(N);
4203   EVT Ty = getPointerTy(DAG.getDataLayout());
4204   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4205   SDValue Lo = getTargetNode(N, Ty, DAG,
4206                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4207   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4208   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4209 }
4210 
4211 // (adr sym)
4212 template <class NodeTy>
4213 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4214                                            unsigned Flags) const {
4215   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4216   SDLoc DL(N);
4217   EVT Ty = getPointerTy(DAG.getDataLayout());
4218   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4219   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4220 }
4221 
4222 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4223                                                   SelectionDAG &DAG) const {
4224   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4225   const GlobalValue *GV = GN->getGlobal();
4226   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4227 
4228   if (OpFlags != AArch64II::MO_NO_FLAG)
4229     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4230            "unexpected offset in global node");
4231 
4232   // This also catches the large code model case for Darwin, and tiny code
4233   // model with got relocations.
4234   if ((OpFlags & AArch64II::MO_GOT) != 0) {
4235     return getGOT(GN, DAG, OpFlags);
4236   }
4237 
4238   SDValue Result;
4239   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4240     Result = getAddrLarge(GN, DAG, OpFlags);
4241   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4242     Result = getAddrTiny(GN, DAG, OpFlags);
4243   } else {
4244     Result = getAddr(GN, DAG, OpFlags);
4245   }
4246   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4247   SDLoc DL(GN);
4248   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4249     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4250                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4251   return Result;
4252 }
4253 
4254 /// Convert a TLS address reference into the correct sequence of loads
4255 /// and calls to compute the variable's address (for Darwin, currently) and
4256 /// return an SDValue containing the final node.
4257 
4258 /// Darwin only has one TLS scheme which must be capable of dealing with the
4259 /// fully general situation, in the worst case. This means:
4260 ///     + "extern __thread" declaration.
4261 ///     + Defined in a possibly unknown dynamic library.
4262 ///
4263 /// The general system is that each __thread variable has a [3 x i64] descriptor
4264 /// which contains information used by the runtime to calculate the address. The
4265 /// only part of this the compiler needs to know about is the first xword, which
4266 /// contains a function pointer that must be called with the address of the
4267 /// entire descriptor in "x0".
4268 ///
4269 /// Since this descriptor may be in a different unit, in general even the
4270 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4271 /// is:
4272 ///     adrp x0, _var@TLVPPAGE
4273 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
4274 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
4275 ///                                      ; the function pointer
4276 ///     blr x1                           ; Uses descriptor address in x0
4277 ///     ; Address of _var is now in x0.
4278 ///
4279 /// If the address of _var's descriptor *is* known to the linker, then it can
4280 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4281 /// a slight efficiency gain.
4282 SDValue
4283 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4284                                                    SelectionDAG &DAG) const {
4285   assert(Subtarget->isTargetDarwin() &&
4286          "This function expects a Darwin target");
4287 
4288   SDLoc DL(Op);
4289   MVT PtrVT = getPointerTy(DAG.getDataLayout());
4290   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4291 
4292   SDValue TLVPAddr =
4293       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4294   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4295 
4296   // The first entry in the descriptor is a function pointer that we must call
4297   // to obtain the address of the variable.
4298   SDValue Chain = DAG.getEntryNode();
4299   SDValue FuncTLVGet = DAG.getLoad(
4300       MVT::i64, DL, Chain, DescAddr,
4301       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4302       /* Alignment = */ 8,
4303       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4304   Chain = FuncTLVGet.getValue(1);
4305 
4306   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4307   MFI.setAdjustsStack(true);
4308 
4309   // TLS calls preserve all registers except those that absolutely must be
4310   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4311   // silly).
4312   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4313   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4314   if (Subtarget->hasCustomCallingConv())
4315     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4316 
4317   // Finally, we can make the call. This is just a degenerate version of a
4318   // normal AArch64 call node: x0 takes the address of the descriptor, and
4319   // returns the address of the variable in this thread.
4320   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4321   Chain =
4322       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4323                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4324                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4325   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4326 }
4327 
4328 /// When accessing thread-local variables under either the general-dynamic or
4329 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4330 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4331 /// is a function pointer to carry out the resolution.
4332 ///
4333 /// The sequence is:
4334 ///    adrp  x0, :tlsdesc:var
4335 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4336 ///    add   x0, x0, #:tlsdesc_lo12:var
4337 ///    .tlsdesccall var
4338 ///    blr   x1
4339 ///    (TPIDR_EL0 offset now in x0)
4340 ///
4341 ///  The above sequence must be produced unscheduled, to enable the linker to
4342 ///  optimize/relax this sequence.
4343 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4344 ///  above sequence, and expanded really late in the compilation flow, to ensure
4345 ///  the sequence is produced as per above.
4346 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4347                                                       const SDLoc &DL,
4348                                                       SelectionDAG &DAG) const {
4349   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4350 
4351   SDValue Chain = DAG.getEntryNode();
4352   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4353 
4354   Chain =
4355       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4356   SDValue Glue = Chain.getValue(1);
4357 
4358   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4359 }
4360 
4361 SDValue
4362 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4363                                                 SelectionDAG &DAG) const {
4364   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4365   if (getTargetMachine().getCodeModel() == CodeModel::Large)
4366     report_fatal_error("ELF TLS only supported in small memory model");
4367   // Different choices can be made for the maximum size of the TLS area for a
4368   // module. For the small address model, the default TLS size is 16MiB and the
4369   // maximum TLS size is 4GiB.
4370   // FIXME: add -mtls-size command line option and make it control the 16MiB
4371   // vs. 4GiB code sequence generation.
4372   // FIXME: add tiny codemodel support. We currently generate the same code as
4373   // small, which may be larger than needed.
4374   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4375 
4376   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4377 
4378   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4379     if (Model == TLSModel::LocalDynamic)
4380       Model = TLSModel::GeneralDynamic;
4381   }
4382 
4383   SDValue TPOff;
4384   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4385   SDLoc DL(Op);
4386   const GlobalValue *GV = GA->getGlobal();
4387 
4388   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4389 
4390   if (Model == TLSModel::LocalExec) {
4391     SDValue HiVar = DAG.getTargetGlobalAddress(
4392         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4393     SDValue LoVar = DAG.getTargetGlobalAddress(
4394         GV, DL, PtrVT, 0,
4395         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4396 
4397     SDValue TPWithOff_lo =
4398         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4399                                    HiVar,
4400                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4401                 0);
4402     SDValue TPWithOff =
4403         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4404                                    LoVar,
4405                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4406                 0);
4407     return TPWithOff;
4408   } else if (Model == TLSModel::InitialExec) {
4409     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4410     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4411   } else if (Model == TLSModel::LocalDynamic) {
4412     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4413     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4414     // the beginning of the module's TLS region, followed by a DTPREL offset
4415     // calculation.
4416 
4417     // These accesses will need deduplicating if there's more than one.
4418     AArch64FunctionInfo *MFI =
4419         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4420     MFI->incNumLocalDynamicTLSAccesses();
4421 
4422     // The call needs a relocation too for linker relaxation. It doesn't make
4423     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4424     // the address.
4425     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4426                                                   AArch64II::MO_TLS);
4427 
4428     // Now we can calculate the offset from TPIDR_EL0 to this module's
4429     // thread-local area.
4430     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4431 
4432     // Now use :dtprel_whatever: operations to calculate this variable's offset
4433     // in its thread-storage area.
4434     SDValue HiVar = DAG.getTargetGlobalAddress(
4435         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4436     SDValue LoVar = DAG.getTargetGlobalAddress(
4437         GV, DL, MVT::i64, 0,
4438         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4439 
4440     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4441                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4442                     0);
4443     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4444                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4445                     0);
4446   } else if (Model == TLSModel::GeneralDynamic) {
4447     // The call needs a relocation too for linker relaxation. It doesn't make
4448     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4449     // the address.
4450     SDValue SymAddr =
4451         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4452 
4453     // Finally we can make a call to calculate the offset from tpidr_el0.
4454     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4455   } else
4456     llvm_unreachable("Unsupported ELF TLS access model");
4457 
4458   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4459 }
4460 
4461 SDValue
4462 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4463                                                     SelectionDAG &DAG) const {
4464   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4465 
4466   SDValue Chain = DAG.getEntryNode();
4467   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4468   SDLoc DL(Op);
4469 
4470   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4471 
4472   // Load the ThreadLocalStoragePointer from the TEB
4473   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4474   SDValue TLSArray =
4475       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4476   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4477   Chain = TLSArray.getValue(1);
4478 
4479   // Load the TLS index from the C runtime;
4480   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4481   // This also does the same as LOADgot, but using a generic i32 load,
4482   // while LOADgot only loads i64.
4483   SDValue TLSIndexHi =
4484       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4485   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4486       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4487   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4488   SDValue TLSIndex =
4489       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4490   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4491   Chain = TLSIndex.getValue(1);
4492 
4493   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4494   // offset into the TLSArray.
4495   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4496   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4497                              DAG.getConstant(3, DL, PtrVT));
4498   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4499                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4500                             MachinePointerInfo());
4501   Chain = TLS.getValue(1);
4502 
4503   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4504   const GlobalValue *GV = GA->getGlobal();
4505   SDValue TGAHi = DAG.getTargetGlobalAddress(
4506       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4507   SDValue TGALo = DAG.getTargetGlobalAddress(
4508       GV, DL, PtrVT, 0,
4509       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4510 
4511   // Add the offset from the start of the .tls section (section base).
4512   SDValue Addr =
4513       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4514                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4515               0);
4516   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4517   return Addr;
4518 }
4519 
4520 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4521                                                      SelectionDAG &DAG) const {
4522   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4523   if (DAG.getTarget().useEmulatedTLS())
4524     return LowerToTLSEmulatedModel(GA, DAG);
4525 
4526   if (Subtarget->isTargetDarwin())
4527     return LowerDarwinGlobalTLSAddress(Op, DAG);
4528   if (Subtarget->isTargetELF())
4529     return LowerELFGlobalTLSAddress(Op, DAG);
4530   if (Subtarget->isTargetWindows())
4531     return LowerWindowsGlobalTLSAddress(Op, DAG);
4532 
4533   llvm_unreachable("Unexpected platform trying to use TLS");
4534 }
4535 
4536 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4537   SDValue Chain = Op.getOperand(0);
4538   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4539   SDValue LHS = Op.getOperand(2);
4540   SDValue RHS = Op.getOperand(3);
4541   SDValue Dest = Op.getOperand(4);
4542   SDLoc dl(Op);
4543 
4544   MachineFunction &MF = DAG.getMachineFunction();
4545   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4546   // will not be produced, as they are conditional branch instructions that do
4547   // not set flags.
4548   bool ProduceNonFlagSettingCondBr =
4549       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4550 
4551   // Handle f128 first, since lowering it will result in comparing the return
4552   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4553   // is expecting to deal with.
4554   if (LHS.getValueType() == MVT::f128) {
4555     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4556 
4557     // If softenSetCCOperands returned a scalar, we need to compare the result
4558     // against zero to select between true and false values.
4559     if (!RHS.getNode()) {
4560       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4561       CC = ISD::SETNE;
4562     }
4563   }
4564 
4565   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4566   // instruction.
4567   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4568       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4569     // Only lower legal XALUO ops.
4570     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4571       return SDValue();
4572 
4573     // The actual operation with overflow check.
4574     AArch64CC::CondCode OFCC;
4575     SDValue Value, Overflow;
4576     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4577 
4578     if (CC == ISD::SETNE)
4579       OFCC = getInvertedCondCode(OFCC);
4580     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4581 
4582     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4583                        Overflow);
4584   }
4585 
4586   if (LHS.getValueType().isInteger()) {
4587     assert((LHS.getValueType() == RHS.getValueType()) &&
4588            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4589 
4590     // If the RHS of the comparison is zero, we can potentially fold this
4591     // to a specialized branch.
4592     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4593     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4594       if (CC == ISD::SETEQ) {
4595         // See if we can use a TBZ to fold in an AND as well.
4596         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4597         // out of bounds, a late MI-layer pass rewrites branches.
4598         // 403.gcc is an example that hits this case.
4599         if (LHS.getOpcode() == ISD::AND &&
4600             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4601             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4602           SDValue Test = LHS.getOperand(0);
4603           uint64_t Mask = LHS.getConstantOperandVal(1);
4604           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4605                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4606                              Dest);
4607         }
4608 
4609         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4610       } else if (CC == ISD::SETNE) {
4611         // See if we can use a TBZ to fold in an AND as well.
4612         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4613         // out of bounds, a late MI-layer pass rewrites branches.
4614         // 403.gcc is an example that hits this case.
4615         if (LHS.getOpcode() == ISD::AND &&
4616             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4617             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4618           SDValue Test = LHS.getOperand(0);
4619           uint64_t Mask = LHS.getConstantOperandVal(1);
4620           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4621                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4622                              Dest);
4623         }
4624 
4625         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4626       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4627         // Don't combine AND since emitComparison converts the AND to an ANDS
4628         // (a.k.a. TST) and the test in the test bit and branch instruction
4629         // becomes redundant.  This would also increase register pressure.
4630         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4631         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4632                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4633       }
4634     }
4635     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4636         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4637       // Don't combine AND since emitComparison converts the AND to an ANDS
4638       // (a.k.a. TST) and the test in the test bit and branch instruction
4639       // becomes redundant.  This would also increase register pressure.
4640       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4641       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4642                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4643     }
4644 
4645     SDValue CCVal;
4646     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4647     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4648                        Cmp);
4649   }
4650 
4651   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4652          LHS.getValueType() == MVT::f64);
4653 
4654   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4655   // clean.  Some of them require two branches to implement.
4656   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4657   AArch64CC::CondCode CC1, CC2;
4658   changeFPCCToAArch64CC(CC, CC1, CC2);
4659   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4660   SDValue BR1 =
4661       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4662   if (CC2 != AArch64CC::AL) {
4663     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4664     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4665                        Cmp);
4666   }
4667 
4668   return BR1;
4669 }
4670 
4671 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4672                                               SelectionDAG &DAG) const {
4673   EVT VT = Op.getValueType();
4674   SDLoc DL(Op);
4675 
4676   SDValue In1 = Op.getOperand(0);
4677   SDValue In2 = Op.getOperand(1);
4678   EVT SrcVT = In2.getValueType();
4679 
4680   if (SrcVT.bitsLT(VT))
4681     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4682   else if (SrcVT.bitsGT(VT))
4683     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4684 
4685   EVT VecVT;
4686   uint64_t EltMask;
4687   SDValue VecVal1, VecVal2;
4688 
4689   auto setVecVal = [&] (int Idx) {
4690     if (!VT.isVector()) {
4691       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4692                                           DAG.getUNDEF(VecVT), In1);
4693       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4694                                           DAG.getUNDEF(VecVT), In2);
4695     } else {
4696       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4697       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4698     }
4699   };
4700 
4701   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4702     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4703     EltMask = 0x80000000ULL;
4704     setVecVal(AArch64::ssub);
4705   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4706     VecVT = MVT::v2i64;
4707 
4708     // We want to materialize a mask with the high bit set, but the AdvSIMD
4709     // immediate moves cannot materialize that in a single instruction for
4710     // 64-bit elements. Instead, materialize zero and then negate it.
4711     EltMask = 0;
4712 
4713     setVecVal(AArch64::dsub);
4714   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4715     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4716     EltMask = 0x8000ULL;
4717     setVecVal(AArch64::hsub);
4718   } else {
4719     llvm_unreachable("Invalid type for copysign!");
4720   }
4721 
4722   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4723 
4724   // If we couldn't materialize the mask above, then the mask vector will be
4725   // the zero vector, and we need to negate it here.
4726   if (VT == MVT::f64 || VT == MVT::v2f64) {
4727     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4728     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4729     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4730   }
4731 
4732   SDValue Sel =
4733       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4734 
4735   if (VT == MVT::f16)
4736     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4737   if (VT == MVT::f32)
4738     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4739   else if (VT == MVT::f64)
4740     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4741   else
4742     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4743 }
4744 
4745 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4746   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4747           Attribute::NoImplicitFloat))
4748     return SDValue();
4749 
4750   if (!Subtarget->hasNEON())
4751     return SDValue();
4752 
4753   // While there is no integer popcount instruction, it can
4754   // be more efficiently lowered to the following sequence that uses
4755   // AdvSIMD registers/instructions as long as the copies to/from
4756   // the AdvSIMD registers are cheap.
4757   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4758   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4759   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4760   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4761   SDValue Val = Op.getOperand(0);
4762   SDLoc DL(Op);
4763   EVT VT = Op.getValueType();
4764 
4765   if (VT == MVT::i32 || VT == MVT::i64) {
4766     if (VT == MVT::i32)
4767       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4768     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4769 
4770     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4771     SDValue UaddLV = DAG.getNode(
4772         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4773         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4774 
4775     if (VT == MVT::i64)
4776       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4777     return UaddLV;
4778   }
4779 
4780   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4781           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4782          "Unexpected type for custom ctpop lowering");
4783 
4784   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4785   Val = DAG.getBitcast(VT8Bit, Val);
4786   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4787 
4788   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4789   unsigned EltSize = 8;
4790   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4791   while (EltSize != VT.getScalarSizeInBits()) {
4792     EltSize *= 2;
4793     NumElts /= 2;
4794     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4795     Val = DAG.getNode(
4796         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4797         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4798   }
4799 
4800   return Val;
4801 }
4802 
4803 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4804 
4805   if (Op.getValueType().isVector())
4806     return LowerVSETCC(Op, DAG);
4807 
4808   SDValue LHS = Op.getOperand(0);
4809   SDValue RHS = Op.getOperand(1);
4810   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4811   SDLoc dl(Op);
4812 
4813   // We chose ZeroOrOneBooleanContents, so use zero and one.
4814   EVT VT = Op.getValueType();
4815   SDValue TVal = DAG.getConstant(1, dl, VT);
4816   SDValue FVal = DAG.getConstant(0, dl, VT);
4817 
4818   // Handle f128 first, since one possible outcome is a normal integer
4819   // comparison which gets picked up by the next if statement.
4820   if (LHS.getValueType() == MVT::f128) {
4821     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4822 
4823     // If softenSetCCOperands returned a scalar, use it.
4824     if (!RHS.getNode()) {
4825       assert(LHS.getValueType() == Op.getValueType() &&
4826              "Unexpected setcc expansion!");
4827       return LHS;
4828     }
4829   }
4830 
4831   if (LHS.getValueType().isInteger()) {
4832     SDValue CCVal;
4833     SDValue Cmp =
4834         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4835 
4836     // Note that we inverted the condition above, so we reverse the order of
4837     // the true and false operands here.  This will allow the setcc to be
4838     // matched to a single CSINC instruction.
4839     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4840   }
4841 
4842   // Now we know we're dealing with FP values.
4843   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4844          LHS.getValueType() == MVT::f64);
4845 
4846   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4847   // and do the comparison.
4848   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4849 
4850   AArch64CC::CondCode CC1, CC2;
4851   changeFPCCToAArch64CC(CC, CC1, CC2);
4852   if (CC2 == AArch64CC::AL) {
4853     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4854     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4855 
4856     // Note that we inverted the condition above, so we reverse the order of
4857     // the true and false operands here.  This will allow the setcc to be
4858     // matched to a single CSINC instruction.
4859     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4860   } else {
4861     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4862     // totally clean.  Some of them require two CSELs to implement.  As is in
4863     // this case, we emit the first CSEL and then emit a second using the output
4864     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4865 
4866     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4867     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4868     SDValue CS1 =
4869         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4870 
4871     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4872     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4873   }
4874 }
4875 
4876 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4877                                               SDValue RHS, SDValue TVal,
4878                                               SDValue FVal, const SDLoc &dl,
4879                                               SelectionDAG &DAG) const {
4880   // Handle f128 first, because it will result in a comparison of some RTLIB
4881   // call result against zero.
4882   if (LHS.getValueType() == MVT::f128) {
4883     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4884 
4885     // If softenSetCCOperands returned a scalar, we need to compare the result
4886     // against zero to select between true and false values.
4887     if (!RHS.getNode()) {
4888       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4889       CC = ISD::SETNE;
4890     }
4891   }
4892 
4893   // Also handle f16, for which we need to do a f32 comparison.
4894   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4895     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4896     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4897   }
4898 
4899   // Next, handle integers.
4900   if (LHS.getValueType().isInteger()) {
4901     assert((LHS.getValueType() == RHS.getValueType()) &&
4902            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4903 
4904     unsigned Opcode = AArch64ISD::CSEL;
4905 
4906     // If both the TVal and the FVal are constants, see if we can swap them in
4907     // order to for a CSINV or CSINC out of them.
4908     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4909     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4910 
4911     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4912       std::swap(TVal, FVal);
4913       std::swap(CTVal, CFVal);
4914       CC = ISD::getSetCCInverse(CC, true);
4915     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4916       std::swap(TVal, FVal);
4917       std::swap(CTVal, CFVal);
4918       CC = ISD::getSetCCInverse(CC, true);
4919     } else if (TVal.getOpcode() == ISD::XOR) {
4920       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4921       // with a CSINV rather than a CSEL.
4922       if (isAllOnesConstant(TVal.getOperand(1))) {
4923         std::swap(TVal, FVal);
4924         std::swap(CTVal, CFVal);
4925         CC = ISD::getSetCCInverse(CC, true);
4926       }
4927     } else if (TVal.getOpcode() == ISD::SUB) {
4928       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4929       // that we can match with a CSNEG rather than a CSEL.
4930       if (isNullConstant(TVal.getOperand(0))) {
4931         std::swap(TVal, FVal);
4932         std::swap(CTVal, CFVal);
4933         CC = ISD::getSetCCInverse(CC, true);
4934       }
4935     } else if (CTVal && CFVal) {
4936       const int64_t TrueVal = CTVal->getSExtValue();
4937       const int64_t FalseVal = CFVal->getSExtValue();
4938       bool Swap = false;
4939 
4940       // If both TVal and FVal are constants, see if FVal is the
4941       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4942       // instead of a CSEL in that case.
4943       if (TrueVal == ~FalseVal) {
4944         Opcode = AArch64ISD::CSINV;
4945       } else if (TrueVal == -FalseVal) {
4946         Opcode = AArch64ISD::CSNEG;
4947       } else if (TVal.getValueType() == MVT::i32) {
4948         // If our operands are only 32-bit wide, make sure we use 32-bit
4949         // arithmetic for the check whether we can use CSINC. This ensures that
4950         // the addition in the check will wrap around properly in case there is
4951         // an overflow (which would not be the case if we do the check with
4952         // 64-bit arithmetic).
4953         const uint32_t TrueVal32 = CTVal->getZExtValue();
4954         const uint32_t FalseVal32 = CFVal->getZExtValue();
4955 
4956         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4957           Opcode = AArch64ISD::CSINC;
4958 
4959           if (TrueVal32 > FalseVal32) {
4960             Swap = true;
4961           }
4962         }
4963         // 64-bit check whether we can use CSINC.
4964       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4965         Opcode = AArch64ISD::CSINC;
4966 
4967         if (TrueVal > FalseVal) {
4968           Swap = true;
4969         }
4970       }
4971 
4972       // Swap TVal and FVal if necessary.
4973       if (Swap) {
4974         std::swap(TVal, FVal);
4975         std::swap(CTVal, CFVal);
4976         CC = ISD::getSetCCInverse(CC, true);
4977       }
4978 
4979       if (Opcode != AArch64ISD::CSEL) {
4980         // Drop FVal since we can get its value by simply inverting/negating
4981         // TVal.
4982         FVal = TVal;
4983       }
4984     }
4985 
4986     // Avoid materializing a constant when possible by reusing a known value in
4987     // a register.  However, don't perform this optimization if the known value
4988     // is one, zero or negative one in the case of a CSEL.  We can always
4989     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4990     // FVal, respectively.
4991     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4992     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4993         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4994       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4995       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4996       // "a != C ? x : a" to avoid materializing C.
4997       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4998         TVal = LHS;
4999       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5000         FVal = LHS;
5001     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5002       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5003       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5004       // avoid materializing C.
5005       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5006       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5007         Opcode = AArch64ISD::CSINV;
5008         TVal = LHS;
5009         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5010       }
5011     }
5012 
5013     SDValue CCVal;
5014     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5015     EVT VT = TVal.getValueType();
5016     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5017   }
5018 
5019   // Now we know we're dealing with FP values.
5020   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5021          LHS.getValueType() == MVT::f64);
5022   assert(LHS.getValueType() == RHS.getValueType());
5023   EVT VT = TVal.getValueType();
5024   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5025 
5026   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5027   // clean.  Some of them require two CSELs to implement.
5028   AArch64CC::CondCode CC1, CC2;
5029   changeFPCCToAArch64CC(CC, CC1, CC2);
5030 
5031   if (DAG.getTarget().Options.UnsafeFPMath) {
5032     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5033     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5034     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5035     if (RHSVal && RHSVal->isZero()) {
5036       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5037       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5038 
5039       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5040           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5041         TVal = LHS;
5042       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5043                CFVal && CFVal->isZero() &&
5044                FVal.getValueType() == LHS.getValueType())
5045         FVal = LHS;
5046     }
5047   }
5048 
5049   // Emit first, and possibly only, CSEL.
5050   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5051   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5052 
5053   // If we need a second CSEL, emit it, using the output of the first as the
5054   // RHS.  We're effectively OR'ing the two CC's together.
5055   if (CC2 != AArch64CC::AL) {
5056     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5057     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5058   }
5059 
5060   // Otherwise, return the output of the first CSEL.
5061   return CS1;
5062 }
5063 
5064 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5065                                               SelectionDAG &DAG) const {
5066   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5067   SDValue LHS = Op.getOperand(0);
5068   SDValue RHS = Op.getOperand(1);
5069   SDValue TVal = Op.getOperand(2);
5070   SDValue FVal = Op.getOperand(3);
5071   SDLoc DL(Op);
5072   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5073 }
5074 
5075 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5076                                            SelectionDAG &DAG) const {
5077   SDValue CCVal = Op->getOperand(0);
5078   SDValue TVal = Op->getOperand(1);
5079   SDValue FVal = Op->getOperand(2);
5080   SDLoc DL(Op);
5081 
5082   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5083   // instruction.
5084   if (isOverflowIntrOpRes(CCVal)) {
5085     // Only lower legal XALUO ops.
5086     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5087       return SDValue();
5088 
5089     AArch64CC::CondCode OFCC;
5090     SDValue Value, Overflow;
5091     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5092     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5093 
5094     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5095                        CCVal, Overflow);
5096   }
5097 
5098   // Lower it the same way as we would lower a SELECT_CC node.
5099   ISD::CondCode CC;
5100   SDValue LHS, RHS;
5101   if (CCVal.getOpcode() == ISD::SETCC) {
5102     LHS = CCVal.getOperand(0);
5103     RHS = CCVal.getOperand(1);
5104     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5105   } else {
5106     LHS = CCVal;
5107     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5108     CC = ISD::SETNE;
5109   }
5110   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5111 }
5112 
5113 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5114                                               SelectionDAG &DAG) const {
5115   // Jump table entries as PC relative offsets. No additional tweaking
5116   // is necessary here. Just get the address of the jump table.
5117   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5118 
5119   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5120       !Subtarget->isTargetMachO()) {
5121     return getAddrLarge(JT, DAG);
5122   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5123     return getAddrTiny(JT, DAG);
5124   }
5125   return getAddr(JT, DAG);
5126 }
5127 
5128 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5129                                           SelectionDAG &DAG) const {
5130   // Jump table entries as PC relative offsets. No additional tweaking
5131   // is necessary here. Just get the address of the jump table.
5132   SDLoc DL(Op);
5133   SDValue JT = Op.getOperand(1);
5134   SDValue Entry = Op.getOperand(2);
5135   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5136 
5137   SDNode *Dest =
5138       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5139                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5140   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5141                      SDValue(Dest, 0));
5142 }
5143 
5144 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5145                                                  SelectionDAG &DAG) const {
5146   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5147 
5148   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5149     // Use the GOT for the large code model on iOS.
5150     if (Subtarget->isTargetMachO()) {
5151       return getGOT(CP, DAG);
5152     }
5153     return getAddrLarge(CP, DAG);
5154   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5155     return getAddrTiny(CP, DAG);
5156   } else {
5157     return getAddr(CP, DAG);
5158   }
5159 }
5160 
5161 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5162                                                SelectionDAG &DAG) const {
5163   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5164   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5165       !Subtarget->isTargetMachO()) {
5166     return getAddrLarge(BA, DAG);
5167   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5168     return getAddrTiny(BA, DAG);
5169   }
5170   return getAddr(BA, DAG);
5171 }
5172 
5173 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5174                                                  SelectionDAG &DAG) const {
5175   AArch64FunctionInfo *FuncInfo =
5176       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5177 
5178   SDLoc DL(Op);
5179   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5180                                  getPointerTy(DAG.getDataLayout()));
5181   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5182   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5183                       MachinePointerInfo(SV));
5184 }
5185 
5186 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5187                                                   SelectionDAG &DAG) const {
5188   AArch64FunctionInfo *FuncInfo =
5189       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5190 
5191   SDLoc DL(Op);
5192   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5193                                      ? FuncInfo->getVarArgsGPRIndex()
5194                                      : FuncInfo->getVarArgsStackIndex(),
5195                                  getPointerTy(DAG.getDataLayout()));
5196   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5197   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5198                       MachinePointerInfo(SV));
5199 }
5200 
5201 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5202                                                 SelectionDAG &DAG) const {
5203   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5204   // Standard, section B.3.
5205   MachineFunction &MF = DAG.getMachineFunction();
5206   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5207   auto PtrVT = getPointerTy(DAG.getDataLayout());
5208   SDLoc DL(Op);
5209 
5210   SDValue Chain = Op.getOperand(0);
5211   SDValue VAList = Op.getOperand(1);
5212   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5213   SmallVector<SDValue, 4> MemOps;
5214 
5215   // void *__stack at offset 0
5216   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5217   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5218                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5219 
5220   // void *__gr_top at offset 8
5221   int GPRSize = FuncInfo->getVarArgsGPRSize();
5222   if (GPRSize > 0) {
5223     SDValue GRTop, GRTopAddr;
5224 
5225     GRTopAddr =
5226         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5227 
5228     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5229     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5230                         DAG.getConstant(GPRSize, DL, PtrVT));
5231 
5232     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5233                                   MachinePointerInfo(SV, 8),
5234                                   /* Alignment = */ 8));
5235   }
5236 
5237   // void *__vr_top at offset 16
5238   int FPRSize = FuncInfo->getVarArgsFPRSize();
5239   if (FPRSize > 0) {
5240     SDValue VRTop, VRTopAddr;
5241     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5242                             DAG.getConstant(16, DL, PtrVT));
5243 
5244     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5245     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5246                         DAG.getConstant(FPRSize, DL, PtrVT));
5247 
5248     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5249                                   MachinePointerInfo(SV, 16),
5250                                   /* Alignment = */ 8));
5251   }
5252 
5253   // int __gr_offs at offset 24
5254   SDValue GROffsAddr =
5255       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5256   MemOps.push_back(DAG.getStore(
5257       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5258       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5259 
5260   // int __vr_offs at offset 28
5261   SDValue VROffsAddr =
5262       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5263   MemOps.push_back(DAG.getStore(
5264       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5265       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5266 
5267   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5268 }
5269 
5270 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5271                                             SelectionDAG &DAG) const {
5272   MachineFunction &MF = DAG.getMachineFunction();
5273 
5274   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5275     return LowerWin64_VASTART(Op, DAG);
5276   else if (Subtarget->isTargetDarwin())
5277     return LowerDarwin_VASTART(Op, DAG);
5278   else
5279     return LowerAAPCS_VASTART(Op, DAG);
5280 }
5281 
5282 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5283                                            SelectionDAG &DAG) const {
5284   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5285   // pointer.
5286   SDLoc DL(Op);
5287   unsigned VaListSize =
5288       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5289   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5290   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5291 
5292   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5293                        Op.getOperand(2),
5294                        DAG.getConstant(VaListSize, DL, MVT::i32),
5295                        8, false, false, false, MachinePointerInfo(DestSV),
5296                        MachinePointerInfo(SrcSV));
5297 }
5298 
5299 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5300   assert(Subtarget->isTargetDarwin() &&
5301          "automatic va_arg instruction only works on Darwin");
5302 
5303   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5304   EVT VT = Op.getValueType();
5305   SDLoc DL(Op);
5306   SDValue Chain = Op.getOperand(0);
5307   SDValue Addr = Op.getOperand(1);
5308   unsigned Align = Op.getConstantOperandVal(3);
5309   auto PtrVT = getPointerTy(DAG.getDataLayout());
5310 
5311   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5312   Chain = VAList.getValue(1);
5313 
5314   if (Align > 8) {
5315     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5316     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5317                          DAG.getConstant(Align - 1, DL, PtrVT));
5318     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5319                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5320   }
5321 
5322   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5323   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5324 
5325   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5326   // up to 64 bits.  At the very least, we have to increase the striding of the
5327   // vaargs list to match this, and for FP values we need to introduce
5328   // FP_ROUND nodes as well.
5329   if (VT.isInteger() && !VT.isVector())
5330     ArgSize = 8;
5331   bool NeedFPTrunc = false;
5332   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5333     ArgSize = 8;
5334     NeedFPTrunc = true;
5335   }
5336 
5337   // Increment the pointer, VAList, to the next vaarg
5338   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5339                                DAG.getConstant(ArgSize, DL, PtrVT));
5340   // Store the incremented VAList to the legalized pointer
5341   SDValue APStore =
5342       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5343 
5344   // Load the actual argument out of the pointer VAList
5345   if (NeedFPTrunc) {
5346     // Load the value as an f64.
5347     SDValue WideFP =
5348         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5349     // Round the value down to an f32.
5350     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5351                                    DAG.getIntPtrConstant(1, DL));
5352     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5353     // Merge the rounded value with the chain output of the load.
5354     return DAG.getMergeValues(Ops, DL);
5355   }
5356 
5357   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5358 }
5359 
5360 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5361                                               SelectionDAG &DAG) const {
5362   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5363   MFI.setFrameAddressIsTaken(true);
5364 
5365   EVT VT = Op.getValueType();
5366   SDLoc DL(Op);
5367   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5368   SDValue FrameAddr =
5369       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5370   while (Depth--)
5371     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5372                             MachinePointerInfo());
5373   return FrameAddr;
5374 }
5375 
5376 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5377                                               SelectionDAG &DAG) const {
5378   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5379 
5380   EVT VT = getPointerTy(DAG.getDataLayout());
5381   SDLoc DL(Op);
5382   int FI = MFI.CreateFixedObject(4, 0, false);
5383   return DAG.getFrameIndex(FI, VT);
5384 }
5385 
5386 #define GET_REGISTER_MATCHER
5387 #include "AArch64GenAsmMatcher.inc"
5388 
5389 // FIXME? Maybe this could be a TableGen attribute on some registers and
5390 // this table could be generated automatically from RegInfo.
5391 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5392                                                   SelectionDAG &DAG) const {
5393   unsigned Reg = MatchRegisterName(RegName);
5394   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5395     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5396     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5397     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5398       Reg = 0;
5399   }
5400   if (Reg)
5401     return Reg;
5402   report_fatal_error(Twine("Invalid register name \""
5403                               + StringRef(RegName)  + "\"."));
5404 }
5405 
5406 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5407                                                      SelectionDAG &DAG) const {
5408   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5409 
5410   EVT VT = Op.getValueType();
5411   SDLoc DL(Op);
5412 
5413   SDValue FrameAddr =
5414       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5415   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5416 
5417   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5418 }
5419 
5420 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5421                                                SelectionDAG &DAG) const {
5422   MachineFunction &MF = DAG.getMachineFunction();
5423   MachineFrameInfo &MFI = MF.getFrameInfo();
5424   MFI.setReturnAddressIsTaken(true);
5425 
5426   EVT VT = Op.getValueType();
5427   SDLoc DL(Op);
5428   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5429   if (Depth) {
5430     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5431     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5432     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5433                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5434                        MachinePointerInfo());
5435   }
5436 
5437   // Return LR, which contains the return address. Mark it an implicit live-in.
5438   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5439   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5440 }
5441 
5442 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5443 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5444 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5445                                                     SelectionDAG &DAG) const {
5446   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5447   EVT VT = Op.getValueType();
5448   unsigned VTBits = VT.getSizeInBits();
5449   SDLoc dl(Op);
5450   SDValue ShOpLo = Op.getOperand(0);
5451   SDValue ShOpHi = Op.getOperand(1);
5452   SDValue ShAmt = Op.getOperand(2);
5453   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5454 
5455   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5456 
5457   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5458                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5459   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5460 
5461   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5462   // is "undef". We wanted 0, so CSEL it directly.
5463   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5464                                ISD::SETEQ, dl, DAG);
5465   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5466   HiBitsForLo =
5467       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5468                   HiBitsForLo, CCVal, Cmp);
5469 
5470   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5471                                    DAG.getConstant(VTBits, dl, MVT::i64));
5472 
5473   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5474   SDValue LoForNormalShift =
5475       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5476 
5477   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5478                        dl, DAG);
5479   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5480   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5481   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5482                            LoForNormalShift, CCVal, Cmp);
5483 
5484   // AArch64 shifts larger than the register width are wrapped rather than
5485   // clamped, so we can't just emit "hi >> x".
5486   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5487   SDValue HiForBigShift =
5488       Opc == ISD::SRA
5489           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5490                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5491           : DAG.getConstant(0, dl, VT);
5492   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5493                            HiForNormalShift, CCVal, Cmp);
5494 
5495   SDValue Ops[2] = { Lo, Hi };
5496   return DAG.getMergeValues(Ops, dl);
5497 }
5498 
5499 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5500 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5501 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5502                                                    SelectionDAG &DAG) const {
5503   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5504   EVT VT = Op.getValueType();
5505   unsigned VTBits = VT.getSizeInBits();
5506   SDLoc dl(Op);
5507   SDValue ShOpLo = Op.getOperand(0);
5508   SDValue ShOpHi = Op.getOperand(1);
5509   SDValue ShAmt = Op.getOperand(2);
5510 
5511   assert(Op.getOpcode() == ISD::SHL_PARTS);
5512   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5513                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5514   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5515 
5516   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5517   // is "undef". We wanted 0, so CSEL it directly.
5518   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5519                                ISD::SETEQ, dl, DAG);
5520   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5521   LoBitsForHi =
5522       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5523                   LoBitsForHi, CCVal, Cmp);
5524 
5525   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5526                                    DAG.getConstant(VTBits, dl, MVT::i64));
5527   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5528   SDValue HiForNormalShift =
5529       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5530 
5531   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5532 
5533   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5534                        dl, DAG);
5535   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5536   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5537                            HiForNormalShift, CCVal, Cmp);
5538 
5539   // AArch64 shifts of larger than register sizes are wrapped rather than
5540   // clamped, so we can't just emit "lo << a" if a is too big.
5541   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5542   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5543   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5544                            LoForNormalShift, CCVal, Cmp);
5545 
5546   SDValue Ops[2] = { Lo, Hi };
5547   return DAG.getMergeValues(Ops, dl);
5548 }
5549 
5550 bool AArch64TargetLowering::isOffsetFoldingLegal(
5551     const GlobalAddressSDNode *GA) const {
5552   // Offsets are folded in the DAG combine rather than here so that we can
5553   // intelligently choose an offset based on the uses.
5554   return false;
5555 }
5556 
5557 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5558                                          bool OptForSize) const {
5559   bool IsLegal = false;
5560   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5561   // 16-bit case when target has full fp16 support.
5562   // FIXME: We should be able to handle f128 as well with a clever lowering.
5563   const APInt ImmInt = Imm.bitcastToAPInt();
5564   if (VT == MVT::f64)
5565     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5566   else if (VT == MVT::f32)
5567     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5568   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5569     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5570   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5571   //       generate that fmov.
5572 
5573   // If we can not materialize in immediate field for fmov, check if the
5574   // value can be encoded as the immediate operand of a logical instruction.
5575   // The immediate value will be created with either MOVZ, MOVN, or ORR.
5576   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5577     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5578     // however the mov+fmov sequence is always better because of the reduced
5579     // cache pressure. The timings are still the same if you consider
5580     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5581     // movw+movk is fused). So we limit up to 2 instrdduction at most.
5582     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5583     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5584 			      Insn);
5585     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5586     IsLegal = Insn.size() <= Limit;
5587   }
5588 
5589   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5590                     << " imm value: "; Imm.dump(););
5591   return IsLegal;
5592 }
5593 
5594 //===----------------------------------------------------------------------===//
5595 //                          AArch64 Optimization Hooks
5596 //===----------------------------------------------------------------------===//
5597 
5598 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5599                            SDValue Operand, SelectionDAG &DAG,
5600                            int &ExtraSteps) {
5601   EVT VT = Operand.getValueType();
5602   if (ST->hasNEON() &&
5603       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5604        VT == MVT::f32 || VT == MVT::v1f32 ||
5605        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5606     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5607       // For the reciprocal estimates, convergence is quadratic, so the number
5608       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5609       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5610       // the result for float (23 mantissa bits) is 2 and for double (52
5611       // mantissa bits) is 3.
5612       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5613 
5614     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5615   }
5616 
5617   return SDValue();
5618 }
5619 
5620 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5621                                                SelectionDAG &DAG, int Enabled,
5622                                                int &ExtraSteps,
5623                                                bool &UseOneConst,
5624                                                bool Reciprocal) const {
5625   if (Enabled == ReciprocalEstimate::Enabled ||
5626       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5627     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5628                                        DAG, ExtraSteps)) {
5629       SDLoc DL(Operand);
5630       EVT VT = Operand.getValueType();
5631 
5632       SDNodeFlags Flags;
5633       Flags.setAllowReassociation(true);
5634 
5635       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5636       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5637       for (int i = ExtraSteps; i > 0; --i) {
5638         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5639                                    Flags);
5640         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5641         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5642       }
5643       if (!Reciprocal) {
5644         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5645                                       VT);
5646         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5647         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5648 
5649         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5650         // Correct the result if the operand is 0.0.
5651         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5652                                VT, Eq, Operand, Estimate);
5653       }
5654 
5655       ExtraSteps = 0;
5656       return Estimate;
5657     }
5658 
5659   return SDValue();
5660 }
5661 
5662 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5663                                                 SelectionDAG &DAG, int Enabled,
5664                                                 int &ExtraSteps) const {
5665   if (Enabled == ReciprocalEstimate::Enabled)
5666     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5667                                        DAG, ExtraSteps)) {
5668       SDLoc DL(Operand);
5669       EVT VT = Operand.getValueType();
5670 
5671       SDNodeFlags Flags;
5672       Flags.setAllowReassociation(true);
5673 
5674       // Newton reciprocal iteration: E * (2 - X * E)
5675       // AArch64 reciprocal iteration instruction: (2 - M * N)
5676       for (int i = ExtraSteps; i > 0; --i) {
5677         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5678                                    Estimate, Flags);
5679         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5680       }
5681 
5682       ExtraSteps = 0;
5683       return Estimate;
5684     }
5685 
5686   return SDValue();
5687 }
5688 
5689 //===----------------------------------------------------------------------===//
5690 //                          AArch64 Inline Assembly Support
5691 //===----------------------------------------------------------------------===//
5692 
5693 // Table of Constraints
5694 // TODO: This is the current set of constraints supported by ARM for the
5695 // compiler, not all of them may make sense.
5696 //
5697 // r - A general register
5698 // w - An FP/SIMD register of some size in the range v0-v31
5699 // x - An FP/SIMD register of some size in the range v0-v15
5700 // I - Constant that can be used with an ADD instruction
5701 // J - Constant that can be used with a SUB instruction
5702 // K - Constant that can be used with a 32-bit logical instruction
5703 // L - Constant that can be used with a 64-bit logical instruction
5704 // M - Constant that can be used as a 32-bit MOV immediate
5705 // N - Constant that can be used as a 64-bit MOV immediate
5706 // Q - A memory reference with base register and no offset
5707 // S - A symbolic address
5708 // Y - Floating point constant zero
5709 // Z - Integer constant zero
5710 //
5711 //   Note that general register operands will be output using their 64-bit x
5712 // register name, whatever the size of the variable, unless the asm operand
5713 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5714 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5715 // %q modifier.
5716 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5717   // At this point, we have to lower this constraint to something else, so we
5718   // lower it to an "r" or "w". However, by doing this we will force the result
5719   // to be in register, while the X constraint is much more permissive.
5720   //
5721   // Although we are correct (we are free to emit anything, without
5722   // constraints), we might break use cases that would expect us to be more
5723   // efficient and emit something else.
5724   if (!Subtarget->hasFPARMv8())
5725     return "r";
5726 
5727   if (ConstraintVT.isFloatingPoint())
5728     return "w";
5729 
5730   if (ConstraintVT.isVector() &&
5731      (ConstraintVT.getSizeInBits() == 64 ||
5732       ConstraintVT.getSizeInBits() == 128))
5733     return "w";
5734 
5735   return "r";
5736 }
5737 
5738 /// getConstraintType - Given a constraint letter, return the type of
5739 /// constraint it is for this target.
5740 AArch64TargetLowering::ConstraintType
5741 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5742   if (Constraint.size() == 1) {
5743     switch (Constraint[0]) {
5744     default:
5745       break;
5746     case 'x':
5747     case 'w':
5748       return C_RegisterClass;
5749     // An address with a single base register. Due to the way we
5750     // currently handle addresses it is the same as 'r'.
5751     case 'Q':
5752       return C_Memory;
5753     case 'I':
5754     case 'J':
5755     case 'K':
5756     case 'L':
5757     case 'M':
5758     case 'N':
5759     case 'Y':
5760     case 'Z':
5761       return C_Immediate;
5762     case 'z':
5763     case 'S': // A symbolic address
5764       return C_Other;
5765     }
5766   }
5767   return TargetLowering::getConstraintType(Constraint);
5768 }
5769 
5770 /// Examine constraint type and operand type and determine a weight value.
5771 /// This object must already have been set up with the operand type
5772 /// and the current alternative constraint selected.
5773 TargetLowering::ConstraintWeight
5774 AArch64TargetLowering::getSingleConstraintMatchWeight(
5775     AsmOperandInfo &info, const char *constraint) const {
5776   ConstraintWeight weight = CW_Invalid;
5777   Value *CallOperandVal = info.CallOperandVal;
5778   // If we don't have a value, we can't do a match,
5779   // but allow it at the lowest weight.
5780   if (!CallOperandVal)
5781     return CW_Default;
5782   Type *type = CallOperandVal->getType();
5783   // Look at the constraint type.
5784   switch (*constraint) {
5785   default:
5786     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5787     break;
5788   case 'x':
5789   case 'w':
5790     if (type->isFloatingPointTy() || type->isVectorTy())
5791       weight = CW_Register;
5792     break;
5793   case 'z':
5794     weight = CW_Constant;
5795     break;
5796   }
5797   return weight;
5798 }
5799 
5800 std::pair<unsigned, const TargetRegisterClass *>
5801 AArch64TargetLowering::getRegForInlineAsmConstraint(
5802     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5803   if (Constraint.size() == 1) {
5804     switch (Constraint[0]) {
5805     case 'r':
5806       if (VT.getSizeInBits() == 64)
5807         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5808       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5809     case 'w':
5810       if (!Subtarget->hasFPARMv8())
5811         break;
5812       if (VT.getSizeInBits() == 16)
5813         return std::make_pair(0U, &AArch64::FPR16RegClass);
5814       if (VT.getSizeInBits() == 32)
5815         return std::make_pair(0U, &AArch64::FPR32RegClass);
5816       if (VT.getSizeInBits() == 64)
5817         return std::make_pair(0U, &AArch64::FPR64RegClass);
5818       if (VT.getSizeInBits() == 128)
5819         return std::make_pair(0U, &AArch64::FPR128RegClass);
5820       break;
5821     // The instructions that this constraint is designed for can
5822     // only take 128-bit registers so just use that regclass.
5823     case 'x':
5824       if (!Subtarget->hasFPARMv8())
5825         break;
5826       if (VT.getSizeInBits() == 128)
5827         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5828       break;
5829     }
5830   }
5831   if (StringRef("{cc}").equals_lower(Constraint))
5832     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5833 
5834   // Use the default implementation in TargetLowering to convert the register
5835   // constraint into a member of a register class.
5836   std::pair<unsigned, const TargetRegisterClass *> Res;
5837   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5838 
5839   // Not found as a standard register?
5840   if (!Res.second) {
5841     unsigned Size = Constraint.size();
5842     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5843         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5844       int RegNo;
5845       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5846       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5847         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5848         // By default we'll emit v0-v31 for this unless there's a modifier where
5849         // we'll emit the correct register as well.
5850         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5851           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5852           Res.second = &AArch64::FPR64RegClass;
5853         } else {
5854           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5855           Res.second = &AArch64::FPR128RegClass;
5856         }
5857       }
5858     }
5859   }
5860 
5861   if (Res.second && !Subtarget->hasFPARMv8() &&
5862       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5863       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5864     return std::make_pair(0U, nullptr);
5865 
5866   return Res;
5867 }
5868 
5869 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5870 /// vector.  If it is invalid, don't add anything to Ops.
5871 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5872     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5873     SelectionDAG &DAG) const {
5874   SDValue Result;
5875 
5876   // Currently only support length 1 constraints.
5877   if (Constraint.length() != 1)
5878     return;
5879 
5880   char ConstraintLetter = Constraint[0];
5881   switch (ConstraintLetter) {
5882   default:
5883     break;
5884 
5885   // This set of constraints deal with valid constants for various instructions.
5886   // Validate and return a target constant for them if we can.
5887   case 'z': {
5888     // 'z' maps to xzr or wzr so it needs an input of 0.
5889     if (!isNullConstant(Op))
5890       return;
5891 
5892     if (Op.getValueType() == MVT::i64)
5893       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5894     else
5895       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5896     break;
5897   }
5898   case 'S': {
5899     // An absolute symbolic address or label reference.
5900     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5901       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5902                                           GA->getValueType(0));
5903     } else if (const BlockAddressSDNode *BA =
5904                    dyn_cast<BlockAddressSDNode>(Op)) {
5905       Result =
5906           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5907     } else if (const ExternalSymbolSDNode *ES =
5908                    dyn_cast<ExternalSymbolSDNode>(Op)) {
5909       Result =
5910           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5911     } else
5912       return;
5913     break;
5914   }
5915 
5916   case 'I':
5917   case 'J':
5918   case 'K':
5919   case 'L':
5920   case 'M':
5921   case 'N':
5922     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5923     if (!C)
5924       return;
5925 
5926     // Grab the value and do some validation.
5927     uint64_t CVal = C->getZExtValue();
5928     switch (ConstraintLetter) {
5929     // The I constraint applies only to simple ADD or SUB immediate operands:
5930     // i.e. 0 to 4095 with optional shift by 12
5931     // The J constraint applies only to ADD or SUB immediates that would be
5932     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5933     // instruction [or vice versa], in other words -1 to -4095 with optional
5934     // left shift by 12.
5935     case 'I':
5936       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5937         break;
5938       return;
5939     case 'J': {
5940       uint64_t NVal = -C->getSExtValue();
5941       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5942         CVal = C->getSExtValue();
5943         break;
5944       }
5945       return;
5946     }
5947     // The K and L constraints apply *only* to logical immediates, including
5948     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5949     // been removed and MOV should be used). So these constraints have to
5950     // distinguish between bit patterns that are valid 32-bit or 64-bit
5951     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5952     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5953     // versa.
5954     case 'K':
5955       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5956         break;
5957       return;
5958     case 'L':
5959       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5960         break;
5961       return;
5962     // The M and N constraints are a superset of K and L respectively, for use
5963     // with the MOV (immediate) alias. As well as the logical immediates they
5964     // also match 32 or 64-bit immediates that can be loaded either using a
5965     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5966     // (M) or 64-bit 0x1234000000000000 (N) etc.
5967     // As a note some of this code is liberally stolen from the asm parser.
5968     case 'M': {
5969       if (!isUInt<32>(CVal))
5970         return;
5971       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5972         break;
5973       if ((CVal & 0xFFFF) == CVal)
5974         break;
5975       if ((CVal & 0xFFFF0000ULL) == CVal)
5976         break;
5977       uint64_t NCVal = ~(uint32_t)CVal;
5978       if ((NCVal & 0xFFFFULL) == NCVal)
5979         break;
5980       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5981         break;
5982       return;
5983     }
5984     case 'N': {
5985       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5986         break;
5987       if ((CVal & 0xFFFFULL) == CVal)
5988         break;
5989       if ((CVal & 0xFFFF0000ULL) == CVal)
5990         break;
5991       if ((CVal & 0xFFFF00000000ULL) == CVal)
5992         break;
5993       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5994         break;
5995       uint64_t NCVal = ~CVal;
5996       if ((NCVal & 0xFFFFULL) == NCVal)
5997         break;
5998       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5999         break;
6000       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6001         break;
6002       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6003         break;
6004       return;
6005     }
6006     default:
6007       return;
6008     }
6009 
6010     // All assembler immediates are 64-bit integers.
6011     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6012     break;
6013   }
6014 
6015   if (Result.getNode()) {
6016     Ops.push_back(Result);
6017     return;
6018   }
6019 
6020   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6021 }
6022 
6023 //===----------------------------------------------------------------------===//
6024 //                     AArch64 Advanced SIMD Support
6025 //===----------------------------------------------------------------------===//
6026 
6027 /// WidenVector - Given a value in the V64 register class, produce the
6028 /// equivalent value in the V128 register class.
6029 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6030   EVT VT = V64Reg.getValueType();
6031   unsigned NarrowSize = VT.getVectorNumElements();
6032   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6033   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6034   SDLoc DL(V64Reg);
6035 
6036   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6037                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6038 }
6039 
6040 /// getExtFactor - Determine the adjustment factor for the position when
6041 /// generating an "extract from vector registers" instruction.
6042 static unsigned getExtFactor(SDValue &V) {
6043   EVT EltType = V.getValueType().getVectorElementType();
6044   return EltType.getSizeInBits() / 8;
6045 }
6046 
6047 /// NarrowVector - Given a value in the V128 register class, produce the
6048 /// equivalent value in the V64 register class.
6049 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6050   EVT VT = V128Reg.getValueType();
6051   unsigned WideSize = VT.getVectorNumElements();
6052   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6053   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6054   SDLoc DL(V128Reg);
6055 
6056   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6057 }
6058 
6059 // Gather data to see if the operation can be modelled as a
6060 // shuffle in combination with VEXTs.
6061 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6062                                                   SelectionDAG &DAG) const {
6063   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6064   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6065   SDLoc dl(Op);
6066   EVT VT = Op.getValueType();
6067   unsigned NumElts = VT.getVectorNumElements();
6068 
6069   struct ShuffleSourceInfo {
6070     SDValue Vec;
6071     unsigned MinElt;
6072     unsigned MaxElt;
6073 
6074     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6075     // be compatible with the shuffle we intend to construct. As a result
6076     // ShuffleVec will be some sliding window into the original Vec.
6077     SDValue ShuffleVec;
6078 
6079     // Code should guarantee that element i in Vec starts at element "WindowBase
6080     // + i * WindowScale in ShuffleVec".
6081     int WindowBase;
6082     int WindowScale;
6083 
6084     ShuffleSourceInfo(SDValue Vec)
6085       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6086           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6087 
6088     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6089   };
6090 
6091   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6092   // node.
6093   SmallVector<ShuffleSourceInfo, 2> Sources;
6094   for (unsigned i = 0; i < NumElts; ++i) {
6095     SDValue V = Op.getOperand(i);
6096     if (V.isUndef())
6097       continue;
6098     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6099              !isa<ConstantSDNode>(V.getOperand(1))) {
6100       LLVM_DEBUG(
6101           dbgs() << "Reshuffle failed: "
6102                     "a shuffle can only come from building a vector from "
6103                     "various elements of other vectors, provided their "
6104                     "indices are constant\n");
6105       return SDValue();
6106     }
6107 
6108     // Add this element source to the list if it's not already there.
6109     SDValue SourceVec = V.getOperand(0);
6110     auto Source = find(Sources, SourceVec);
6111     if (Source == Sources.end())
6112       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6113 
6114     // Update the minimum and maximum lane number seen.
6115     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6116     Source->MinElt = std::min(Source->MinElt, EltNo);
6117     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6118   }
6119 
6120   if (Sources.size() > 2) {
6121     LLVM_DEBUG(
6122         dbgs() << "Reshuffle failed: currently only do something sane when at "
6123                   "most two source vectors are involved\n");
6124     return SDValue();
6125   }
6126 
6127   // Find out the smallest element size among result and two sources, and use
6128   // it as element size to build the shuffle_vector.
6129   EVT SmallestEltTy = VT.getVectorElementType();
6130   for (auto &Source : Sources) {
6131     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6132     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6133       SmallestEltTy = SrcEltTy;
6134     }
6135   }
6136   unsigned ResMultiplier =
6137       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6138   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6139   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6140 
6141   // If the source vector is too wide or too narrow, we may nevertheless be able
6142   // to construct a compatible shuffle either by concatenating it with UNDEF or
6143   // extracting a suitable range of elements.
6144   for (auto &Src : Sources) {
6145     EVT SrcVT = Src.ShuffleVec.getValueType();
6146 
6147     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6148       continue;
6149 
6150     // This stage of the search produces a source with the same element type as
6151     // the original, but with a total width matching the BUILD_VECTOR output.
6152     EVT EltVT = SrcVT.getVectorElementType();
6153     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6154     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6155 
6156     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6157       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6158       // We can pad out the smaller vector for free, so if it's part of a
6159       // shuffle...
6160       Src.ShuffleVec =
6161           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6162                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6163       continue;
6164     }
6165 
6166     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6167 
6168     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6169       LLVM_DEBUG(
6170           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6171       return SDValue();
6172     }
6173 
6174     if (Src.MinElt >= NumSrcElts) {
6175       // The extraction can just take the second half
6176       Src.ShuffleVec =
6177           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6178                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6179       Src.WindowBase = -NumSrcElts;
6180     } else if (Src.MaxElt < NumSrcElts) {
6181       // The extraction can just take the first half
6182       Src.ShuffleVec =
6183           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6184                       DAG.getConstant(0, dl, MVT::i64));
6185     } else {
6186       // An actual VEXT is needed
6187       SDValue VEXTSrc1 =
6188           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6189                       DAG.getConstant(0, dl, MVT::i64));
6190       SDValue VEXTSrc2 =
6191           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6192                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6193       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6194 
6195       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6196                                    VEXTSrc2,
6197                                    DAG.getConstant(Imm, dl, MVT::i32));
6198       Src.WindowBase = -Src.MinElt;
6199     }
6200   }
6201 
6202   // Another possible incompatibility occurs from the vector element types. We
6203   // can fix this by bitcasting the source vectors to the same type we intend
6204   // for the shuffle.
6205   for (auto &Src : Sources) {
6206     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6207     if (SrcEltTy == SmallestEltTy)
6208       continue;
6209     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6210     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6211     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6212     Src.WindowBase *= Src.WindowScale;
6213   }
6214 
6215   // Final sanity check before we try to actually produce a shuffle.
6216   LLVM_DEBUG(for (auto Src
6217                   : Sources)
6218                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6219 
6220   // The stars all align, our next step is to produce the mask for the shuffle.
6221   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6222   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6223   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6224     SDValue Entry = Op.getOperand(i);
6225     if (Entry.isUndef())
6226       continue;
6227 
6228     auto Src = find(Sources, Entry.getOperand(0));
6229     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6230 
6231     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6232     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6233     // segment.
6234     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6235     int BitsDefined =
6236         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6237     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6238 
6239     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6240     // starting at the appropriate offset.
6241     int *LaneMask = &Mask[i * ResMultiplier];
6242 
6243     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6244     ExtractBase += NumElts * (Src - Sources.begin());
6245     for (int j = 0; j < LanesDefined; ++j)
6246       LaneMask[j] = ExtractBase + j;
6247   }
6248 
6249   // Final check before we try to produce nonsense...
6250   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6251     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6252     return SDValue();
6253   }
6254 
6255   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6256   for (unsigned i = 0; i < Sources.size(); ++i)
6257     ShuffleOps[i] = Sources[i].ShuffleVec;
6258 
6259   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6260                                          ShuffleOps[1], Mask);
6261   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6262 
6263   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6264              dbgs() << "Reshuffle, creating node: "; V.dump(););
6265 
6266   return V;
6267 }
6268 
6269 // check if an EXT instruction can handle the shuffle mask when the
6270 // vector sources of the shuffle are the same.
6271 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6272   unsigned NumElts = VT.getVectorNumElements();
6273 
6274   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6275   if (M[0] < 0)
6276     return false;
6277 
6278   Imm = M[0];
6279 
6280   // If this is a VEXT shuffle, the immediate value is the index of the first
6281   // element.  The other shuffle indices must be the successive elements after
6282   // the first one.
6283   unsigned ExpectedElt = Imm;
6284   for (unsigned i = 1; i < NumElts; ++i) {
6285     // Increment the expected index.  If it wraps around, just follow it
6286     // back to index zero and keep going.
6287     ++ExpectedElt;
6288     if (ExpectedElt == NumElts)
6289       ExpectedElt = 0;
6290 
6291     if (M[i] < 0)
6292       continue; // ignore UNDEF indices
6293     if (ExpectedElt != static_cast<unsigned>(M[i]))
6294       return false;
6295   }
6296 
6297   return true;
6298 }
6299 
6300 // check if an EXT instruction can handle the shuffle mask when the
6301 // vector sources of the shuffle are different.
6302 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6303                       unsigned &Imm) {
6304   // Look for the first non-undef element.
6305   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6306 
6307   // Benefit form APInt to handle overflow when calculating expected element.
6308   unsigned NumElts = VT.getVectorNumElements();
6309   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6310   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6311   // The following shuffle indices must be the successive elements after the
6312   // first real element.
6313   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6314       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6315   if (FirstWrongElt != M.end())
6316     return false;
6317 
6318   // The index of an EXT is the first element if it is not UNDEF.
6319   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6320   // value of the first element.  E.g.
6321   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6322   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6323   // ExpectedElt is the last mask index plus 1.
6324   Imm = ExpectedElt.getZExtValue();
6325 
6326   // There are two difference cases requiring to reverse input vectors.
6327   // For example, for vector <4 x i32> we have the following cases,
6328   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6329   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6330   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6331   // to reverse two input vectors.
6332   if (Imm < NumElts)
6333     ReverseEXT = true;
6334   else
6335     Imm -= NumElts;
6336 
6337   return true;
6338 }
6339 
6340 /// isREVMask - Check if a vector shuffle corresponds to a REV
6341 /// instruction with the specified blocksize.  (The order of the elements
6342 /// within each block of the vector is reversed.)
6343 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6344   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6345          "Only possible block sizes for REV are: 16, 32, 64");
6346 
6347   unsigned EltSz = VT.getScalarSizeInBits();
6348   if (EltSz == 64)
6349     return false;
6350 
6351   unsigned NumElts = VT.getVectorNumElements();
6352   unsigned BlockElts = M[0] + 1;
6353   // If the first shuffle index is UNDEF, be optimistic.
6354   if (M[0] < 0)
6355     BlockElts = BlockSize / EltSz;
6356 
6357   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6358     return false;
6359 
6360   for (unsigned i = 0; i < NumElts; ++i) {
6361     if (M[i] < 0)
6362       continue; // ignore UNDEF indices
6363     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6364       return false;
6365   }
6366 
6367   return true;
6368 }
6369 
6370 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6371   unsigned NumElts = VT.getVectorNumElements();
6372   if (NumElts % 2 != 0)
6373     return false;
6374   WhichResult = (M[0] == 0 ? 0 : 1);
6375   unsigned Idx = WhichResult * NumElts / 2;
6376   for (unsigned i = 0; i != NumElts; i += 2) {
6377     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6378         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6379       return false;
6380     Idx += 1;
6381   }
6382 
6383   return true;
6384 }
6385 
6386 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6387   unsigned NumElts = VT.getVectorNumElements();
6388   WhichResult = (M[0] == 0 ? 0 : 1);
6389   for (unsigned i = 0; i != NumElts; ++i) {
6390     if (M[i] < 0)
6391       continue; // ignore UNDEF indices
6392     if ((unsigned)M[i] != 2 * i + WhichResult)
6393       return false;
6394   }
6395 
6396   return true;
6397 }
6398 
6399 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6400   unsigned NumElts = VT.getVectorNumElements();
6401   if (NumElts % 2 != 0)
6402     return false;
6403   WhichResult = (M[0] == 0 ? 0 : 1);
6404   for (unsigned i = 0; i < NumElts; i += 2) {
6405     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6406         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6407       return false;
6408   }
6409   return true;
6410 }
6411 
6412 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6413 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6414 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6415 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6416   unsigned NumElts = VT.getVectorNumElements();
6417   if (NumElts % 2 != 0)
6418     return false;
6419   WhichResult = (M[0] == 0 ? 0 : 1);
6420   unsigned Idx = WhichResult * NumElts / 2;
6421   for (unsigned i = 0; i != NumElts; i += 2) {
6422     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6423         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6424       return false;
6425     Idx += 1;
6426   }
6427 
6428   return true;
6429 }
6430 
6431 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6432 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6433 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6434 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6435   unsigned Half = VT.getVectorNumElements() / 2;
6436   WhichResult = (M[0] == 0 ? 0 : 1);
6437   for (unsigned j = 0; j != 2; ++j) {
6438     unsigned Idx = WhichResult;
6439     for (unsigned i = 0; i != Half; ++i) {
6440       int MIdx = M[i + j * Half];
6441       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6442         return false;
6443       Idx += 2;
6444     }
6445   }
6446 
6447   return true;
6448 }
6449 
6450 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6451 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6452 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6453 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6454   unsigned NumElts = VT.getVectorNumElements();
6455   if (NumElts % 2 != 0)
6456     return false;
6457   WhichResult = (M[0] == 0 ? 0 : 1);
6458   for (unsigned i = 0; i < NumElts; i += 2) {
6459     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6460         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6461       return false;
6462   }
6463   return true;
6464 }
6465 
6466 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6467                       bool &DstIsLeft, int &Anomaly) {
6468   if (M.size() != static_cast<size_t>(NumInputElements))
6469     return false;
6470 
6471   int NumLHSMatch = 0, NumRHSMatch = 0;
6472   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6473 
6474   for (int i = 0; i < NumInputElements; ++i) {
6475     if (M[i] == -1) {
6476       ++NumLHSMatch;
6477       ++NumRHSMatch;
6478       continue;
6479     }
6480 
6481     if (M[i] == i)
6482       ++NumLHSMatch;
6483     else
6484       LastLHSMismatch = i;
6485 
6486     if (M[i] == i + NumInputElements)
6487       ++NumRHSMatch;
6488     else
6489       LastRHSMismatch = i;
6490   }
6491 
6492   if (NumLHSMatch == NumInputElements - 1) {
6493     DstIsLeft = true;
6494     Anomaly = LastLHSMismatch;
6495     return true;
6496   } else if (NumRHSMatch == NumInputElements - 1) {
6497     DstIsLeft = false;
6498     Anomaly = LastRHSMismatch;
6499     return true;
6500   }
6501 
6502   return false;
6503 }
6504 
6505 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6506   if (VT.getSizeInBits() != 128)
6507     return false;
6508 
6509   unsigned NumElts = VT.getVectorNumElements();
6510 
6511   for (int I = 0, E = NumElts / 2; I != E; I++) {
6512     if (Mask[I] != I)
6513       return false;
6514   }
6515 
6516   int Offset = NumElts / 2;
6517   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6518     if (Mask[I] != I + SplitLHS * Offset)
6519       return false;
6520   }
6521 
6522   return true;
6523 }
6524 
6525 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6526   SDLoc DL(Op);
6527   EVT VT = Op.getValueType();
6528   SDValue V0 = Op.getOperand(0);
6529   SDValue V1 = Op.getOperand(1);
6530   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6531 
6532   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6533       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6534     return SDValue();
6535 
6536   bool SplitV0 = V0.getValueSizeInBits() == 128;
6537 
6538   if (!isConcatMask(Mask, VT, SplitV0))
6539     return SDValue();
6540 
6541   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6542                                 VT.getVectorNumElements() / 2);
6543   if (SplitV0) {
6544     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6545                      DAG.getConstant(0, DL, MVT::i64));
6546   }
6547   if (V1.getValueSizeInBits() == 128) {
6548     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6549                      DAG.getConstant(0, DL, MVT::i64));
6550   }
6551   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6552 }
6553 
6554 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6555 /// the specified operations to build the shuffle.
6556 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6557                                       SDValue RHS, SelectionDAG &DAG,
6558                                       const SDLoc &dl) {
6559   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6560   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6561   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6562 
6563   enum {
6564     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6565     OP_VREV,
6566     OP_VDUP0,
6567     OP_VDUP1,
6568     OP_VDUP2,
6569     OP_VDUP3,
6570     OP_VEXT1,
6571     OP_VEXT2,
6572     OP_VEXT3,
6573     OP_VUZPL, // VUZP, left result
6574     OP_VUZPR, // VUZP, right result
6575     OP_VZIPL, // VZIP, left result
6576     OP_VZIPR, // VZIP, right result
6577     OP_VTRNL, // VTRN, left result
6578     OP_VTRNR  // VTRN, right result
6579   };
6580 
6581   if (OpNum == OP_COPY) {
6582     if (LHSID == (1 * 9 + 2) * 9 + 3)
6583       return LHS;
6584     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6585     return RHS;
6586   }
6587 
6588   SDValue OpLHS, OpRHS;
6589   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6590   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6591   EVT VT = OpLHS.getValueType();
6592 
6593   switch (OpNum) {
6594   default:
6595     llvm_unreachable("Unknown shuffle opcode!");
6596   case OP_VREV:
6597     // VREV divides the vector in half and swaps within the half.
6598     if (VT.getVectorElementType() == MVT::i32 ||
6599         VT.getVectorElementType() == MVT::f32)
6600       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6601     // vrev <4 x i16> -> REV32
6602     if (VT.getVectorElementType() == MVT::i16 ||
6603         VT.getVectorElementType() == MVT::f16)
6604       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6605     // vrev <4 x i8> -> REV16
6606     assert(VT.getVectorElementType() == MVT::i8);
6607     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6608   case OP_VDUP0:
6609   case OP_VDUP1:
6610   case OP_VDUP2:
6611   case OP_VDUP3: {
6612     EVT EltTy = VT.getVectorElementType();
6613     unsigned Opcode;
6614     if (EltTy == MVT::i8)
6615       Opcode = AArch64ISD::DUPLANE8;
6616     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6617       Opcode = AArch64ISD::DUPLANE16;
6618     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6619       Opcode = AArch64ISD::DUPLANE32;
6620     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6621       Opcode = AArch64ISD::DUPLANE64;
6622     else
6623       llvm_unreachable("Invalid vector element type?");
6624 
6625     if (VT.getSizeInBits() == 64)
6626       OpLHS = WidenVector(OpLHS, DAG);
6627     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6628     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6629   }
6630   case OP_VEXT1:
6631   case OP_VEXT2:
6632   case OP_VEXT3: {
6633     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6634     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6635                        DAG.getConstant(Imm, dl, MVT::i32));
6636   }
6637   case OP_VUZPL:
6638     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6639                        OpRHS);
6640   case OP_VUZPR:
6641     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6642                        OpRHS);
6643   case OP_VZIPL:
6644     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6645                        OpRHS);
6646   case OP_VZIPR:
6647     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6648                        OpRHS);
6649   case OP_VTRNL:
6650     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6651                        OpRHS);
6652   case OP_VTRNR:
6653     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6654                        OpRHS);
6655   }
6656 }
6657 
6658 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6659                            SelectionDAG &DAG) {
6660   // Check to see if we can use the TBL instruction.
6661   SDValue V1 = Op.getOperand(0);
6662   SDValue V2 = Op.getOperand(1);
6663   SDLoc DL(Op);
6664 
6665   EVT EltVT = Op.getValueType().getVectorElementType();
6666   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6667 
6668   SmallVector<SDValue, 8> TBLMask;
6669   for (int Val : ShuffleMask) {
6670     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6671       unsigned Offset = Byte + Val * BytesPerElt;
6672       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6673     }
6674   }
6675 
6676   MVT IndexVT = MVT::v8i8;
6677   unsigned IndexLen = 8;
6678   if (Op.getValueSizeInBits() == 128) {
6679     IndexVT = MVT::v16i8;
6680     IndexLen = 16;
6681   }
6682 
6683   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6684   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6685 
6686   SDValue Shuffle;
6687   if (V2.getNode()->isUndef()) {
6688     if (IndexLen == 8)
6689       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6690     Shuffle = DAG.getNode(
6691         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6692         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6693         DAG.getBuildVector(IndexVT, DL,
6694                            makeArrayRef(TBLMask.data(), IndexLen)));
6695   } else {
6696     if (IndexLen == 8) {
6697       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6698       Shuffle = DAG.getNode(
6699           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6700           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6701           DAG.getBuildVector(IndexVT, DL,
6702                              makeArrayRef(TBLMask.data(), IndexLen)));
6703     } else {
6704       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6705       // cannot currently represent the register constraints on the input
6706       // table registers.
6707       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6708       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6709       //                   IndexLen));
6710       Shuffle = DAG.getNode(
6711           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6712           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6713           V2Cst, DAG.getBuildVector(IndexVT, DL,
6714                                     makeArrayRef(TBLMask.data(), IndexLen)));
6715     }
6716   }
6717   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6718 }
6719 
6720 static unsigned getDUPLANEOp(EVT EltType) {
6721   if (EltType == MVT::i8)
6722     return AArch64ISD::DUPLANE8;
6723   if (EltType == MVT::i16 || EltType == MVT::f16)
6724     return AArch64ISD::DUPLANE16;
6725   if (EltType == MVT::i32 || EltType == MVT::f32)
6726     return AArch64ISD::DUPLANE32;
6727   if (EltType == MVT::i64 || EltType == MVT::f64)
6728     return AArch64ISD::DUPLANE64;
6729 
6730   llvm_unreachable("Invalid vector element type?");
6731 }
6732 
6733 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6734                                                    SelectionDAG &DAG) const {
6735   SDLoc dl(Op);
6736   EVT VT = Op.getValueType();
6737 
6738   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6739 
6740   // Convert shuffles that are directly supported on NEON to target-specific
6741   // DAG nodes, instead of keeping them as shuffles and matching them again
6742   // during code selection.  This is more efficient and avoids the possibility
6743   // of inconsistencies between legalization and selection.
6744   ArrayRef<int> ShuffleMask = SVN->getMask();
6745 
6746   SDValue V1 = Op.getOperand(0);
6747   SDValue V2 = Op.getOperand(1);
6748 
6749   if (SVN->isSplat()) {
6750     int Lane = SVN->getSplatIndex();
6751     // If this is undef splat, generate it via "just" vdup, if possible.
6752     if (Lane == -1)
6753       Lane = 0;
6754 
6755     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6756       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6757                          V1.getOperand(0));
6758     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6759     // constant. If so, we can just reference the lane's definition directly.
6760     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6761         !isa<ConstantSDNode>(V1.getOperand(Lane)))
6762       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6763 
6764     // Otherwise, duplicate from the lane of the input vector.
6765     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6766 
6767     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6768     // to make a vector of the same size as this SHUFFLE. We can ignore the
6769     // extract entirely, and canonicalise the concat using WidenVector.
6770     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6771       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6772       V1 = V1.getOperand(0);
6773     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6774       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6775       Lane -= Idx * VT.getVectorNumElements() / 2;
6776       V1 = WidenVector(V1.getOperand(Idx), DAG);
6777     } else if (VT.getSizeInBits() == 64)
6778       V1 = WidenVector(V1, DAG);
6779 
6780     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6781   }
6782 
6783   if (isREVMask(ShuffleMask, VT, 64))
6784     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6785   if (isREVMask(ShuffleMask, VT, 32))
6786     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6787   if (isREVMask(ShuffleMask, VT, 16))
6788     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6789 
6790   bool ReverseEXT = false;
6791   unsigned Imm;
6792   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6793     if (ReverseEXT)
6794       std::swap(V1, V2);
6795     Imm *= getExtFactor(V1);
6796     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6797                        DAG.getConstant(Imm, dl, MVT::i32));
6798   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6799     Imm *= getExtFactor(V1);
6800     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6801                        DAG.getConstant(Imm, dl, MVT::i32));
6802   }
6803 
6804   unsigned WhichResult;
6805   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6806     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6807     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6808   }
6809   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6810     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6811     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6812   }
6813   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6814     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6815     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6816   }
6817 
6818   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6819     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6820     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6821   }
6822   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6823     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6824     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6825   }
6826   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6827     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6828     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6829   }
6830 
6831   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6832     return Concat;
6833 
6834   bool DstIsLeft;
6835   int Anomaly;
6836   int NumInputElements = V1.getValueType().getVectorNumElements();
6837   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6838     SDValue DstVec = DstIsLeft ? V1 : V2;
6839     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6840 
6841     SDValue SrcVec = V1;
6842     int SrcLane = ShuffleMask[Anomaly];
6843     if (SrcLane >= NumInputElements) {
6844       SrcVec = V2;
6845       SrcLane -= VT.getVectorNumElements();
6846     }
6847     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6848 
6849     EVT ScalarVT = VT.getVectorElementType();
6850 
6851     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6852       ScalarVT = MVT::i32;
6853 
6854     return DAG.getNode(
6855         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6856         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6857         DstLaneV);
6858   }
6859 
6860   // If the shuffle is not directly supported and it has 4 elements, use
6861   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6862   unsigned NumElts = VT.getVectorNumElements();
6863   if (NumElts == 4) {
6864     unsigned PFIndexes[4];
6865     for (unsigned i = 0; i != 4; ++i) {
6866       if (ShuffleMask[i] < 0)
6867         PFIndexes[i] = 8;
6868       else
6869         PFIndexes[i] = ShuffleMask[i];
6870     }
6871 
6872     // Compute the index in the perfect shuffle table.
6873     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6874                             PFIndexes[2] * 9 + PFIndexes[3];
6875     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6876     unsigned Cost = (PFEntry >> 30);
6877 
6878     if (Cost <= 4)
6879       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6880   }
6881 
6882   return GenerateTBL(Op, ShuffleMask, DAG);
6883 }
6884 
6885 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6886                                APInt &UndefBits) {
6887   EVT VT = BVN->getValueType(0);
6888   APInt SplatBits, SplatUndef;
6889   unsigned SplatBitSize;
6890   bool HasAnyUndefs;
6891   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6892     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6893 
6894     for (unsigned i = 0; i < NumSplats; ++i) {
6895       CnstBits <<= SplatBitSize;
6896       UndefBits <<= SplatBitSize;
6897       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6898       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6899     }
6900 
6901     return true;
6902   }
6903 
6904   return false;
6905 }
6906 
6907 // Try 64-bit splatted SIMD immediate.
6908 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6909                                  const APInt &Bits) {
6910   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6911     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6912     EVT VT = Op.getValueType();
6913     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6914 
6915     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6916       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6917 
6918       SDLoc dl(Op);
6919       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6920                                 DAG.getConstant(Value, dl, MVT::i32));
6921       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6922     }
6923   }
6924 
6925   return SDValue();
6926 }
6927 
6928 // Try 32-bit splatted SIMD immediate.
6929 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6930                                   const APInt &Bits,
6931                                   const SDValue *LHS = nullptr) {
6932   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6933     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6934     EVT VT = Op.getValueType();
6935     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6936     bool isAdvSIMDModImm = false;
6937     uint64_t Shift;
6938 
6939     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6940       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6941       Shift = 0;
6942     }
6943     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6944       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6945       Shift = 8;
6946     }
6947     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6948       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6949       Shift = 16;
6950     }
6951     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6952       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6953       Shift = 24;
6954     }
6955 
6956     if (isAdvSIMDModImm) {
6957       SDLoc dl(Op);
6958       SDValue Mov;
6959 
6960       if (LHS)
6961         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6962                           DAG.getConstant(Value, dl, MVT::i32),
6963                           DAG.getConstant(Shift, dl, MVT::i32));
6964       else
6965         Mov = DAG.getNode(NewOp, dl, MovTy,
6966                           DAG.getConstant(Value, dl, MVT::i32),
6967                           DAG.getConstant(Shift, dl, MVT::i32));
6968 
6969       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6970     }
6971   }
6972 
6973   return SDValue();
6974 }
6975 
6976 // Try 16-bit splatted SIMD immediate.
6977 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6978                                   const APInt &Bits,
6979                                   const SDValue *LHS = nullptr) {
6980   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6981     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6982     EVT VT = Op.getValueType();
6983     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6984     bool isAdvSIMDModImm = false;
6985     uint64_t Shift;
6986 
6987     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6988       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6989       Shift = 0;
6990     }
6991     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6992       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6993       Shift = 8;
6994     }
6995 
6996     if (isAdvSIMDModImm) {
6997       SDLoc dl(Op);
6998       SDValue Mov;
6999 
7000       if (LHS)
7001         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7002                           DAG.getConstant(Value, dl, MVT::i32),
7003                           DAG.getConstant(Shift, dl, MVT::i32));
7004       else
7005         Mov = DAG.getNode(NewOp, dl, MovTy,
7006                           DAG.getConstant(Value, dl, MVT::i32),
7007                           DAG.getConstant(Shift, dl, MVT::i32));
7008 
7009       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7010     }
7011   }
7012 
7013   return SDValue();
7014 }
7015 
7016 // Try 32-bit splatted SIMD immediate with shifted ones.
7017 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7018                                     SelectionDAG &DAG, const APInt &Bits) {
7019   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7020     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7021     EVT VT = Op.getValueType();
7022     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7023     bool isAdvSIMDModImm = false;
7024     uint64_t Shift;
7025 
7026     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7027       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7028       Shift = 264;
7029     }
7030     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7031       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7032       Shift = 272;
7033     }
7034 
7035     if (isAdvSIMDModImm) {
7036       SDLoc dl(Op);
7037       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7038                                 DAG.getConstant(Value, dl, MVT::i32),
7039                                 DAG.getConstant(Shift, dl, MVT::i32));
7040       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7041     }
7042   }
7043 
7044   return SDValue();
7045 }
7046 
7047 // Try 8-bit splatted SIMD immediate.
7048 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7049                                  const APInt &Bits) {
7050   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7051     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7052     EVT VT = Op.getValueType();
7053     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7054 
7055     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7056       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7057 
7058       SDLoc dl(Op);
7059       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7060                                 DAG.getConstant(Value, dl, MVT::i32));
7061       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7062     }
7063   }
7064 
7065   return SDValue();
7066 }
7067 
7068 // Try FP splatted SIMD immediate.
7069 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7070                                   const APInt &Bits) {
7071   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7072     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7073     EVT VT = Op.getValueType();
7074     bool isWide = (VT.getSizeInBits() == 128);
7075     MVT MovTy;
7076     bool isAdvSIMDModImm = false;
7077 
7078     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7079       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7080       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7081     }
7082     else if (isWide &&
7083              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7084       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7085       MovTy = MVT::v2f64;
7086     }
7087 
7088     if (isAdvSIMDModImm) {
7089       SDLoc dl(Op);
7090       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7091                                 DAG.getConstant(Value, dl, MVT::i32));
7092       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7093     }
7094   }
7095 
7096   return SDValue();
7097 }
7098 
7099 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7100 // consists of only the same constant int value, returned in reference arg
7101 // ConstVal
7102 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7103                                      uint64_t &ConstVal) {
7104   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7105   if (!Bvec)
7106     return false;
7107   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7108   if (!FirstElt)
7109     return false;
7110   EVT VT = Bvec->getValueType(0);
7111   unsigned NumElts = VT.getVectorNumElements();
7112   for (unsigned i = 1; i < NumElts; ++i)
7113     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7114       return false;
7115   ConstVal = FirstElt->getZExtValue();
7116   return true;
7117 }
7118 
7119 static unsigned getIntrinsicID(const SDNode *N) {
7120   unsigned Opcode = N->getOpcode();
7121   switch (Opcode) {
7122   default:
7123     return Intrinsic::not_intrinsic;
7124   case ISD::INTRINSIC_WO_CHAIN: {
7125     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7126     if (IID < Intrinsic::num_intrinsics)
7127       return IID;
7128     return Intrinsic::not_intrinsic;
7129   }
7130   }
7131 }
7132 
7133 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7134 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7135 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7136 // Also, logical shift right -> sri, with the same structure.
7137 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7138   EVT VT = N->getValueType(0);
7139 
7140   if (!VT.isVector())
7141     return SDValue();
7142 
7143   SDLoc DL(N);
7144 
7145   // Is the first op an AND?
7146   const SDValue And = N->getOperand(0);
7147   if (And.getOpcode() != ISD::AND)
7148     return SDValue();
7149 
7150   // Is the second op an shl or lshr?
7151   SDValue Shift = N->getOperand(1);
7152   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7153   // or AArch64ISD::VLSHR vector, #shift
7154   unsigned ShiftOpc = Shift.getOpcode();
7155   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7156     return SDValue();
7157   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7158 
7159   // Is the shift amount constant?
7160   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7161   if (!C2node)
7162     return SDValue();
7163 
7164   // Is the and mask vector all constant?
7165   uint64_t C1;
7166   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7167     return SDValue();
7168 
7169   // Is C1 == ~C2, taking into account how much one can shift elements of a
7170   // particular size?
7171   uint64_t C2 = C2node->getZExtValue();
7172   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7173   if (C2 > ElemSizeInBits)
7174     return SDValue();
7175   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7176   if ((C1 & ElemMask) != (~C2 & ElemMask))
7177     return SDValue();
7178 
7179   SDValue X = And.getOperand(0);
7180   SDValue Y = Shift.getOperand(0);
7181 
7182   unsigned Intrin =
7183       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7184   SDValue ResultSLI =
7185       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7186                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7187                   Shift.getOperand(1));
7188 
7189   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7190   LLVM_DEBUG(N->dump(&DAG));
7191   LLVM_DEBUG(dbgs() << "into: \n");
7192   LLVM_DEBUG(ResultSLI->dump(&DAG));
7193 
7194   ++NumShiftInserts;
7195   return ResultSLI;
7196 }
7197 
7198 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7199                                              SelectionDAG &DAG) const {
7200   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7201   if (EnableAArch64SlrGeneration) {
7202     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7203       return Res;
7204   }
7205 
7206   EVT VT = Op.getValueType();
7207 
7208   SDValue LHS = Op.getOperand(0);
7209   BuildVectorSDNode *BVN =
7210       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7211   if (!BVN) {
7212     // OR commutes, so try swapping the operands.
7213     LHS = Op.getOperand(1);
7214     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7215   }
7216   if (!BVN)
7217     return Op;
7218 
7219   APInt DefBits(VT.getSizeInBits(), 0);
7220   APInt UndefBits(VT.getSizeInBits(), 0);
7221   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7222     SDValue NewOp;
7223 
7224     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7225                                     DefBits, &LHS)) ||
7226         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7227                                     DefBits, &LHS)))
7228       return NewOp;
7229 
7230     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7231                                     UndefBits, &LHS)) ||
7232         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7233                                     UndefBits, &LHS)))
7234       return NewOp;
7235   }
7236 
7237   // We can always fall back to a non-immediate OR.
7238   return Op;
7239 }
7240 
7241 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7242 // be truncated to fit element width.
7243 static SDValue NormalizeBuildVector(SDValue Op,
7244                                     SelectionDAG &DAG) {
7245   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7246   SDLoc dl(Op);
7247   EVT VT = Op.getValueType();
7248   EVT EltTy= VT.getVectorElementType();
7249 
7250   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7251     return Op;
7252 
7253   SmallVector<SDValue, 16> Ops;
7254   for (SDValue Lane : Op->ops()) {
7255     // For integer vectors, type legalization would have promoted the
7256     // operands already. Otherwise, if Op is a floating-point splat
7257     // (with operands cast to integers), then the only possibilities
7258     // are constants and UNDEFs.
7259     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7260       APInt LowBits(EltTy.getSizeInBits(),
7261                     CstLane->getZExtValue());
7262       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7263     } else if (Lane.getNode()->isUndef()) {
7264       Lane = DAG.getUNDEF(MVT::i32);
7265     } else {
7266       assert(Lane.getValueType() == MVT::i32 &&
7267              "Unexpected BUILD_VECTOR operand type");
7268     }
7269     Ops.push_back(Lane);
7270   }
7271   return DAG.getBuildVector(VT, dl, Ops);
7272 }
7273 
7274 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7275   EVT VT = Op.getValueType();
7276 
7277   APInt DefBits(VT.getSizeInBits(), 0);
7278   APInt UndefBits(VT.getSizeInBits(), 0);
7279   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7280   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7281     SDValue NewOp;
7282     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7283         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7284         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7285         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7286         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7287         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7288       return NewOp;
7289 
7290     DefBits = ~DefBits;
7291     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7292         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7293         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7294       return NewOp;
7295 
7296     DefBits = UndefBits;
7297     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7298         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7299         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7300         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7301         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7302         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7303       return NewOp;
7304 
7305     DefBits = ~UndefBits;
7306     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7307         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7308         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7309       return NewOp;
7310   }
7311 
7312   return SDValue();
7313 }
7314 
7315 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7316                                                  SelectionDAG &DAG) const {
7317   EVT VT = Op.getValueType();
7318 
7319   // Try to build a simple constant vector.
7320   Op = NormalizeBuildVector(Op, DAG);
7321   if (VT.isInteger()) {
7322     // Certain vector constants, used to express things like logical NOT and
7323     // arithmetic NEG, are passed through unmodified.  This allows special
7324     // patterns for these operations to match, which will lower these constants
7325     // to whatever is proven necessary.
7326     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7327     if (BVN->isConstant())
7328       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7329         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7330         APInt Val(BitSize,
7331                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7332         if (Val.isNullValue() || Val.isAllOnesValue())
7333           return Op;
7334       }
7335   }
7336 
7337   if (SDValue V = ConstantBuildVector(Op, DAG))
7338     return V;
7339 
7340   // Scan through the operands to find some interesting properties we can
7341   // exploit:
7342   //   1) If only one value is used, we can use a DUP, or
7343   //   2) if only the low element is not undef, we can just insert that, or
7344   //   3) if only one constant value is used (w/ some non-constant lanes),
7345   //      we can splat the constant value into the whole vector then fill
7346   //      in the non-constant lanes.
7347   //   4) FIXME: If different constant values are used, but we can intelligently
7348   //             select the values we'll be overwriting for the non-constant
7349   //             lanes such that we can directly materialize the vector
7350   //             some other way (MOVI, e.g.), we can be sneaky.
7351   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7352   SDLoc dl(Op);
7353   unsigned NumElts = VT.getVectorNumElements();
7354   bool isOnlyLowElement = true;
7355   bool usesOnlyOneValue = true;
7356   bool usesOnlyOneConstantValue = true;
7357   bool isConstant = true;
7358   bool AllLanesExtractElt = true;
7359   unsigned NumConstantLanes = 0;
7360   SDValue Value;
7361   SDValue ConstantValue;
7362   for (unsigned i = 0; i < NumElts; ++i) {
7363     SDValue V = Op.getOperand(i);
7364     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7365       AllLanesExtractElt = false;
7366     if (V.isUndef())
7367       continue;
7368     if (i > 0)
7369       isOnlyLowElement = false;
7370     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7371       isConstant = false;
7372 
7373     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7374       ++NumConstantLanes;
7375       if (!ConstantValue.getNode())
7376         ConstantValue = V;
7377       else if (ConstantValue != V)
7378         usesOnlyOneConstantValue = false;
7379     }
7380 
7381     if (!Value.getNode())
7382       Value = V;
7383     else if (V != Value)
7384       usesOnlyOneValue = false;
7385   }
7386 
7387   if (!Value.getNode()) {
7388     LLVM_DEBUG(
7389         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7390     return DAG.getUNDEF(VT);
7391   }
7392 
7393   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7394   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7395   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7396   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7397     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7398                          "SCALAR_TO_VECTOR node\n");
7399     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7400   }
7401 
7402   if (AllLanesExtractElt) {
7403     SDNode *Vector = nullptr;
7404     bool Even = false;
7405     bool Odd = false;
7406     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7407     // the Odd pattern <1,3,5,...>.
7408     for (unsigned i = 0; i < NumElts; ++i) {
7409       SDValue V = Op.getOperand(i);
7410       const SDNode *N = V.getNode();
7411       if (!isa<ConstantSDNode>(N->getOperand(1)))
7412         break;
7413       SDValue N0 = N->getOperand(0);
7414 
7415       // All elements are extracted from the same vector.
7416       if (!Vector) {
7417         Vector = N0.getNode();
7418         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7419         // BUILD_VECTOR.
7420         if (VT.getVectorElementType() !=
7421             N0.getValueType().getVectorElementType())
7422           break;
7423       } else if (Vector != N0.getNode()) {
7424         Odd = false;
7425         Even = false;
7426         break;
7427       }
7428 
7429       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7430       // indices <1,3,5,...>.
7431       uint64_t Val = N->getConstantOperandVal(1);
7432       if (Val == 2 * i) {
7433         Even = true;
7434         continue;
7435       }
7436       if (Val - 1 == 2 * i) {
7437         Odd = true;
7438         continue;
7439       }
7440 
7441       // Something does not match: abort.
7442       Odd = false;
7443       Even = false;
7444       break;
7445     }
7446     if (Even || Odd) {
7447       SDValue LHS =
7448           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7449                       DAG.getConstant(0, dl, MVT::i64));
7450       SDValue RHS =
7451           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7452                       DAG.getConstant(NumElts, dl, MVT::i64));
7453 
7454       if (Even && !Odd)
7455         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7456                            RHS);
7457       if (Odd && !Even)
7458         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7459                            RHS);
7460     }
7461   }
7462 
7463   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7464   // i32 and try again.
7465   if (usesOnlyOneValue) {
7466     if (!isConstant) {
7467       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7468           Value.getValueType() != VT) {
7469         LLVM_DEBUG(
7470             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7471         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7472       }
7473 
7474       // This is actually a DUPLANExx operation, which keeps everything vectory.
7475 
7476       SDValue Lane = Value.getOperand(1);
7477       Value = Value.getOperand(0);
7478       if (Value.getValueSizeInBits() == 64) {
7479         LLVM_DEBUG(
7480             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7481                       "widening it\n");
7482         Value = WidenVector(Value, DAG);
7483       }
7484 
7485       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7486       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7487     }
7488 
7489     if (VT.getVectorElementType().isFloatingPoint()) {
7490       SmallVector<SDValue, 8> Ops;
7491       EVT EltTy = VT.getVectorElementType();
7492       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7493               "Unsupported floating-point vector type");
7494       LLVM_DEBUG(
7495           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7496                     "BITCASTS, and try again\n");
7497       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7498       for (unsigned i = 0; i < NumElts; ++i)
7499         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7500       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7501       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7502       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7503                  Val.dump(););
7504       Val = LowerBUILD_VECTOR(Val, DAG);
7505       if (Val.getNode())
7506         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7507     }
7508   }
7509 
7510   // If there was only one constant value used and for more than one lane,
7511   // start by splatting that value, then replace the non-constant lanes. This
7512   // is better than the default, which will perform a separate initialization
7513   // for each lane.
7514   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7515     // Firstly, try to materialize the splat constant.
7516     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7517             Val = ConstantBuildVector(Vec, DAG);
7518     if (!Val) {
7519       // Otherwise, materialize the constant and splat it.
7520       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7521       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7522     }
7523 
7524     // Now insert the non-constant lanes.
7525     for (unsigned i = 0; i < NumElts; ++i) {
7526       SDValue V = Op.getOperand(i);
7527       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7528       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7529         // Note that type legalization likely mucked about with the VT of the
7530         // source operand, so we may have to convert it here before inserting.
7531         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7532     }
7533     return Val;
7534   }
7535 
7536   // This will generate a load from the constant pool.
7537   if (isConstant) {
7538     LLVM_DEBUG(
7539         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7540                   "expansion\n");
7541     return SDValue();
7542   }
7543 
7544   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7545   if (NumElts >= 4) {
7546     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7547       return shuffle;
7548   }
7549 
7550   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7551   // know the default expansion would otherwise fall back on something even
7552   // worse. For a vector with one or two non-undef values, that's
7553   // scalar_to_vector for the elements followed by a shuffle (provided the
7554   // shuffle is valid for the target) and materialization element by element
7555   // on the stack followed by a load for everything else.
7556   if (!isConstant && !usesOnlyOneValue) {
7557     LLVM_DEBUG(
7558         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7559                   "of INSERT_VECTOR_ELT\n");
7560 
7561     SDValue Vec = DAG.getUNDEF(VT);
7562     SDValue Op0 = Op.getOperand(0);
7563     unsigned i = 0;
7564 
7565     // Use SCALAR_TO_VECTOR for lane zero to
7566     // a) Avoid a RMW dependency on the full vector register, and
7567     // b) Allow the register coalescer to fold away the copy if the
7568     //    value is already in an S or D register, and we're forced to emit an
7569     //    INSERT_SUBREG that we can't fold anywhere.
7570     //
7571     // We also allow types like i8 and i16 which are illegal scalar but legal
7572     // vector element types. After type-legalization the inserted value is
7573     // extended (i32) and it is safe to cast them to the vector type by ignoring
7574     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7575     if (!Op0.isUndef()) {
7576       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7577       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7578       ++i;
7579     }
7580     LLVM_DEBUG(if (i < NumElts) dbgs()
7581                    << "Creating nodes for the other vector elements:\n";);
7582     for (; i < NumElts; ++i) {
7583       SDValue V = Op.getOperand(i);
7584       if (V.isUndef())
7585         continue;
7586       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7587       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7588     }
7589     return Vec;
7590   }
7591 
7592   LLVM_DEBUG(
7593       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7594                 "better alternative\n");
7595   return SDValue();
7596 }
7597 
7598 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7599                                                       SelectionDAG &DAG) const {
7600   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7601 
7602   // Check for non-constant or out of range lane.
7603   EVT VT = Op.getOperand(0).getValueType();
7604   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7605   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7606     return SDValue();
7607 
7608 
7609   // Insertion/extraction are legal for V128 types.
7610   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7611       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7612       VT == MVT::v8f16)
7613     return Op;
7614 
7615   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7616       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7617     return SDValue();
7618 
7619   // For V64 types, we perform insertion by expanding the value
7620   // to a V128 type and perform the insertion on that.
7621   SDLoc DL(Op);
7622   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7623   EVT WideTy = WideVec.getValueType();
7624 
7625   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7626                              Op.getOperand(1), Op.getOperand(2));
7627   // Re-narrow the resultant vector.
7628   return NarrowVector(Node, DAG);
7629 }
7630 
7631 SDValue
7632 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7633                                                SelectionDAG &DAG) const {
7634   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7635 
7636   // Check for non-constant or out of range lane.
7637   EVT VT = Op.getOperand(0).getValueType();
7638   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7639   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7640     return SDValue();
7641 
7642 
7643   // Insertion/extraction are legal for V128 types.
7644   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7645       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7646       VT == MVT::v8f16)
7647     return Op;
7648 
7649   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7650       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7651     return SDValue();
7652 
7653   // For V64 types, we perform extraction by expanding the value
7654   // to a V128 type and perform the extraction on that.
7655   SDLoc DL(Op);
7656   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7657   EVT WideTy = WideVec.getValueType();
7658 
7659   EVT ExtrTy = WideTy.getVectorElementType();
7660   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7661     ExtrTy = MVT::i32;
7662 
7663   // For extractions, we just return the result directly.
7664   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7665                      Op.getOperand(1));
7666 }
7667 
7668 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7669                                                       SelectionDAG &DAG) const {
7670   EVT VT = Op.getOperand(0).getValueType();
7671   SDLoc dl(Op);
7672   // Just in case...
7673   if (!VT.isVector())
7674     return SDValue();
7675 
7676   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7677   if (!Cst)
7678     return SDValue();
7679   unsigned Val = Cst->getZExtValue();
7680 
7681   unsigned Size = Op.getValueSizeInBits();
7682 
7683   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7684   if (Val == 0)
7685     return Op;
7686 
7687   // If this is extracting the upper 64-bits of a 128-bit vector, we match
7688   // that directly.
7689   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7690     return Op;
7691 
7692   return SDValue();
7693 }
7694 
7695 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7696   if (VT.getVectorNumElements() == 4 &&
7697       (VT.is128BitVector() || VT.is64BitVector())) {
7698     unsigned PFIndexes[4];
7699     for (unsigned i = 0; i != 4; ++i) {
7700       if (M[i] < 0)
7701         PFIndexes[i] = 8;
7702       else
7703         PFIndexes[i] = M[i];
7704     }
7705 
7706     // Compute the index in the perfect shuffle table.
7707     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7708                             PFIndexes[2] * 9 + PFIndexes[3];
7709     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7710     unsigned Cost = (PFEntry >> 30);
7711 
7712     if (Cost <= 4)
7713       return true;
7714   }
7715 
7716   bool DummyBool;
7717   int DummyInt;
7718   unsigned DummyUnsigned;
7719 
7720   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7721           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7722           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7723           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7724           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7725           isZIPMask(M, VT, DummyUnsigned) ||
7726           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7727           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7728           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7729           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7730           isConcatMask(M, VT, VT.getSizeInBits() == 128));
7731 }
7732 
7733 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7734 /// operand of a vector shift operation, where all the elements of the
7735 /// build_vector must have the same constant integer value.
7736 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7737   // Ignore bit_converts.
7738   while (Op.getOpcode() == ISD::BITCAST)
7739     Op = Op.getOperand(0);
7740   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7741   APInt SplatBits, SplatUndef;
7742   unsigned SplatBitSize;
7743   bool HasAnyUndefs;
7744   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7745                                     HasAnyUndefs, ElementBits) ||
7746       SplatBitSize > ElementBits)
7747     return false;
7748   Cnt = SplatBits.getSExtValue();
7749   return true;
7750 }
7751 
7752 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7753 /// operand of a vector shift left operation.  That value must be in the range:
7754 ///   0 <= Value < ElementBits for a left shift; or
7755 ///   0 <= Value <= ElementBits for a long left shift.
7756 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7757   assert(VT.isVector() && "vector shift count is not a vector type");
7758   int64_t ElementBits = VT.getScalarSizeInBits();
7759   if (!getVShiftImm(Op, ElementBits, Cnt))
7760     return false;
7761   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7762 }
7763 
7764 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7765 /// operand of a vector shift right operation. The value must be in the range:
7766 ///   1 <= Value <= ElementBits for a right shift; or
7767 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7768   assert(VT.isVector() && "vector shift count is not a vector type");
7769   int64_t ElementBits = VT.getScalarSizeInBits();
7770   if (!getVShiftImm(Op, ElementBits, Cnt))
7771     return false;
7772   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7773 }
7774 
7775 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7776                                                       SelectionDAG &DAG) const {
7777   EVT VT = Op.getValueType();
7778   SDLoc DL(Op);
7779   int64_t Cnt;
7780 
7781   if (!Op.getOperand(1).getValueType().isVector())
7782     return Op;
7783   unsigned EltSize = VT.getScalarSizeInBits();
7784 
7785   switch (Op.getOpcode()) {
7786   default:
7787     llvm_unreachable("unexpected shift opcode");
7788 
7789   case ISD::SHL:
7790     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7791       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7792                          DAG.getConstant(Cnt, DL, MVT::i32));
7793     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7794                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7795                                        MVT::i32),
7796                        Op.getOperand(0), Op.getOperand(1));
7797   case ISD::SRA:
7798   case ISD::SRL:
7799     // Right shift immediate
7800     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7801       unsigned Opc =
7802           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7803       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7804                          DAG.getConstant(Cnt, DL, MVT::i32));
7805     }
7806 
7807     // Right shift register.  Note, there is not a shift right register
7808     // instruction, but the shift left register instruction takes a signed
7809     // value, where negative numbers specify a right shift.
7810     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7811                                                 : Intrinsic::aarch64_neon_ushl;
7812     // negate the shift amount
7813     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7814     SDValue NegShiftLeft =
7815         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7816                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7817                     NegShift);
7818     return NegShiftLeft;
7819   }
7820 
7821   return SDValue();
7822 }
7823 
7824 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7825                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7826                                     const SDLoc &dl, SelectionDAG &DAG) {
7827   EVT SrcVT = LHS.getValueType();
7828   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7829          "function only supposed to emit natural comparisons");
7830 
7831   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7832   APInt CnstBits(VT.getSizeInBits(), 0);
7833   APInt UndefBits(VT.getSizeInBits(), 0);
7834   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7835   bool IsZero = IsCnst && (CnstBits == 0);
7836 
7837   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7838     switch (CC) {
7839     default:
7840       return SDValue();
7841     case AArch64CC::NE: {
7842       SDValue Fcmeq;
7843       if (IsZero)
7844         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7845       else
7846         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7847       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7848     }
7849     case AArch64CC::EQ:
7850       if (IsZero)
7851         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7852       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7853     case AArch64CC::GE:
7854       if (IsZero)
7855         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7856       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7857     case AArch64CC::GT:
7858       if (IsZero)
7859         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7860       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7861     case AArch64CC::LS:
7862       if (IsZero)
7863         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7864       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7865     case AArch64CC::LT:
7866       if (!NoNans)
7867         return SDValue();
7868       // If we ignore NaNs then we can use to the MI implementation.
7869       LLVM_FALLTHROUGH;
7870     case AArch64CC::MI:
7871       if (IsZero)
7872         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7873       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7874     }
7875   }
7876 
7877   switch (CC) {
7878   default:
7879     return SDValue();
7880   case AArch64CC::NE: {
7881     SDValue Cmeq;
7882     if (IsZero)
7883       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7884     else
7885       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7886     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7887   }
7888   case AArch64CC::EQ:
7889     if (IsZero)
7890       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7891     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7892   case AArch64CC::GE:
7893     if (IsZero)
7894       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7895     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7896   case AArch64CC::GT:
7897     if (IsZero)
7898       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7899     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7900   case AArch64CC::LE:
7901     if (IsZero)
7902       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7903     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7904   case AArch64CC::LS:
7905     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7906   case AArch64CC::LO:
7907     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7908   case AArch64CC::LT:
7909     if (IsZero)
7910       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7911     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7912   case AArch64CC::HI:
7913     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7914   case AArch64CC::HS:
7915     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7916   }
7917 }
7918 
7919 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7920                                            SelectionDAG &DAG) const {
7921   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7922   SDValue LHS = Op.getOperand(0);
7923   SDValue RHS = Op.getOperand(1);
7924   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7925   SDLoc dl(Op);
7926 
7927   if (LHS.getValueType().getVectorElementType().isInteger()) {
7928     assert(LHS.getValueType() == RHS.getValueType());
7929     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7930     SDValue Cmp =
7931         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7932     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7933   }
7934 
7935   const bool FullFP16 =
7936     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7937 
7938   // Make v4f16 (only) fcmp operations utilise vector instructions
7939   // v8f16 support will be a litle more complicated
7940   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7941     if (LHS.getValueType().getVectorNumElements() == 4) {
7942       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7943       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7944       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7945       DAG.ReplaceAllUsesWith(Op, NewSetcc);
7946       CmpVT = MVT::v4i32;
7947     } else
7948       return SDValue();
7949   }
7950 
7951   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7952           LHS.getValueType().getVectorElementType() != MVT::f128);
7953 
7954   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7955   // clean.  Some of them require two branches to implement.
7956   AArch64CC::CondCode CC1, CC2;
7957   bool ShouldInvert;
7958   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7959 
7960   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7961   SDValue Cmp =
7962       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7963   if (!Cmp.getNode())
7964     return SDValue();
7965 
7966   if (CC2 != AArch64CC::AL) {
7967     SDValue Cmp2 =
7968         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7969     if (!Cmp2.getNode())
7970       return SDValue();
7971 
7972     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7973   }
7974 
7975   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7976 
7977   if (ShouldInvert)
7978     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7979 
7980   return Cmp;
7981 }
7982 
7983 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7984                                   SelectionDAG &DAG) {
7985   SDValue VecOp = ScalarOp.getOperand(0);
7986   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7987   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7988                      DAG.getConstant(0, DL, MVT::i64));
7989 }
7990 
7991 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7992                                               SelectionDAG &DAG) const {
7993   SDLoc dl(Op);
7994   switch (Op.getOpcode()) {
7995   case ISD::VECREDUCE_ADD:
7996     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7997   case ISD::VECREDUCE_SMAX:
7998     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7999   case ISD::VECREDUCE_SMIN:
8000     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8001   case ISD::VECREDUCE_UMAX:
8002     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8003   case ISD::VECREDUCE_UMIN:
8004     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8005   case ISD::VECREDUCE_FMAX: {
8006     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8007     return DAG.getNode(
8008         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8009         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8010         Op.getOperand(0));
8011   }
8012   case ISD::VECREDUCE_FMIN: {
8013     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8014     return DAG.getNode(
8015         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8016         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8017         Op.getOperand(0));
8018   }
8019   default:
8020     llvm_unreachable("Unhandled reduction");
8021   }
8022 }
8023 
8024 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8025                                                     SelectionDAG &DAG) const {
8026   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8027   if (!Subtarget.hasLSE())
8028     return SDValue();
8029 
8030   // LSE has an atomic load-add instruction, but not a load-sub.
8031   SDLoc dl(Op);
8032   MVT VT = Op.getSimpleValueType();
8033   SDValue RHS = Op.getOperand(2);
8034   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8035   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8036   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8037                        Op.getOperand(0), Op.getOperand(1), RHS,
8038                        AN->getMemOperand());
8039 }
8040 
8041 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8042                                                     SelectionDAG &DAG) const {
8043   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8044   if (!Subtarget.hasLSE())
8045     return SDValue();
8046 
8047   // LSE has an atomic load-clear instruction, but not a load-and.
8048   SDLoc dl(Op);
8049   MVT VT = Op.getSimpleValueType();
8050   SDValue RHS = Op.getOperand(2);
8051   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8052   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8053   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8054                        Op.getOperand(0), Op.getOperand(1), RHS,
8055                        AN->getMemOperand());
8056 }
8057 
8058 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8059     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8060   SDLoc dl(Op);
8061   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8062   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8063 
8064   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8065   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8066   if (Subtarget->hasCustomCallingConv())
8067     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8068 
8069   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8070                      DAG.getConstant(4, dl, MVT::i64));
8071   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8072   Chain =
8073       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8074                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8075                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8076   // To match the actual intent better, we should read the output from X15 here
8077   // again (instead of potentially spilling it to the stack), but rereading Size
8078   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8079   // here.
8080 
8081   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8082                      DAG.getConstant(4, dl, MVT::i64));
8083   return Chain;
8084 }
8085 
8086 SDValue
8087 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8088                                                SelectionDAG &DAG) const {
8089   assert(Subtarget->isTargetWindows() &&
8090          "Only Windows alloca probing supported");
8091   SDLoc dl(Op);
8092   // Get the inputs.
8093   SDNode *Node = Op.getNode();
8094   SDValue Chain = Op.getOperand(0);
8095   SDValue Size = Op.getOperand(1);
8096   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8097   EVT VT = Node->getValueType(0);
8098 
8099   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8100           "no-stack-arg-probe")) {
8101     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8102     Chain = SP.getValue(1);
8103     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8104     if (Align)
8105       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8106                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8107     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8108     SDValue Ops[2] = {SP, Chain};
8109     return DAG.getMergeValues(Ops, dl);
8110   }
8111 
8112   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8113 
8114   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8115 
8116   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8117   Chain = SP.getValue(1);
8118   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8119   if (Align)
8120     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8121                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8122   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8123 
8124   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8125                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8126 
8127   SDValue Ops[2] = {SP, Chain};
8128   return DAG.getMergeValues(Ops, dl);
8129 }
8130 
8131 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8132 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8133 /// specified in the intrinsic calls.
8134 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8135                                                const CallInst &I,
8136                                                MachineFunction &MF,
8137                                                unsigned Intrinsic) const {
8138   auto &DL = I.getModule()->getDataLayout();
8139   switch (Intrinsic) {
8140   case Intrinsic::aarch64_neon_ld2:
8141   case Intrinsic::aarch64_neon_ld3:
8142   case Intrinsic::aarch64_neon_ld4:
8143   case Intrinsic::aarch64_neon_ld1x2:
8144   case Intrinsic::aarch64_neon_ld1x3:
8145   case Intrinsic::aarch64_neon_ld1x4:
8146   case Intrinsic::aarch64_neon_ld2lane:
8147   case Intrinsic::aarch64_neon_ld3lane:
8148   case Intrinsic::aarch64_neon_ld4lane:
8149   case Intrinsic::aarch64_neon_ld2r:
8150   case Intrinsic::aarch64_neon_ld3r:
8151   case Intrinsic::aarch64_neon_ld4r: {
8152     Info.opc = ISD::INTRINSIC_W_CHAIN;
8153     // Conservatively set memVT to the entire set of vectors loaded.
8154     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8155     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8156     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8157     Info.offset = 0;
8158     Info.align.reset();
8159     // volatile loads with NEON intrinsics not supported
8160     Info.flags = MachineMemOperand::MOLoad;
8161     return true;
8162   }
8163   case Intrinsic::aarch64_neon_st2:
8164   case Intrinsic::aarch64_neon_st3:
8165   case Intrinsic::aarch64_neon_st4:
8166   case Intrinsic::aarch64_neon_st1x2:
8167   case Intrinsic::aarch64_neon_st1x3:
8168   case Intrinsic::aarch64_neon_st1x4:
8169   case Intrinsic::aarch64_neon_st2lane:
8170   case Intrinsic::aarch64_neon_st3lane:
8171   case Intrinsic::aarch64_neon_st4lane: {
8172     Info.opc = ISD::INTRINSIC_VOID;
8173     // Conservatively set memVT to the entire set of vectors stored.
8174     unsigned NumElts = 0;
8175     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8176       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8177       if (!ArgTy->isVectorTy())
8178         break;
8179       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8180     }
8181     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8182     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8183     Info.offset = 0;
8184     Info.align.reset();
8185     // volatile stores with NEON intrinsics not supported
8186     Info.flags = MachineMemOperand::MOStore;
8187     return true;
8188   }
8189   case Intrinsic::aarch64_ldaxr:
8190   case Intrinsic::aarch64_ldxr: {
8191     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8192     Info.opc = ISD::INTRINSIC_W_CHAIN;
8193     Info.memVT = MVT::getVT(PtrTy->getElementType());
8194     Info.ptrVal = I.getArgOperand(0);
8195     Info.offset = 0;
8196     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8197     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8198     return true;
8199   }
8200   case Intrinsic::aarch64_stlxr:
8201   case Intrinsic::aarch64_stxr: {
8202     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8203     Info.opc = ISD::INTRINSIC_W_CHAIN;
8204     Info.memVT = MVT::getVT(PtrTy->getElementType());
8205     Info.ptrVal = I.getArgOperand(1);
8206     Info.offset = 0;
8207     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8208     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8209     return true;
8210   }
8211   case Intrinsic::aarch64_ldaxp:
8212   case Intrinsic::aarch64_ldxp:
8213     Info.opc = ISD::INTRINSIC_W_CHAIN;
8214     Info.memVT = MVT::i128;
8215     Info.ptrVal = I.getArgOperand(0);
8216     Info.offset = 0;
8217     Info.align = Align(16);
8218     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8219     return true;
8220   case Intrinsic::aarch64_stlxp:
8221   case Intrinsic::aarch64_stxp:
8222     Info.opc = ISD::INTRINSIC_W_CHAIN;
8223     Info.memVT = MVT::i128;
8224     Info.ptrVal = I.getArgOperand(2);
8225     Info.offset = 0;
8226     Info.align = Align(16);
8227     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8228     return true;
8229   default:
8230     break;
8231   }
8232 
8233   return false;
8234 }
8235 
8236 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8237                                                   ISD::LoadExtType ExtTy,
8238                                                   EVT NewVT) const {
8239   // TODO: This may be worth removing. Check regression tests for diffs.
8240   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8241     return false;
8242 
8243   // If we're reducing the load width in order to avoid having to use an extra
8244   // instruction to do extension then it's probably a good idea.
8245   if (ExtTy != ISD::NON_EXTLOAD)
8246     return true;
8247   // Don't reduce load width if it would prevent us from combining a shift into
8248   // the offset.
8249   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8250   assert(Mem);
8251   const SDValue &Base = Mem->getBasePtr();
8252   if (Base.getOpcode() == ISD::ADD &&
8253       Base.getOperand(1).getOpcode() == ISD::SHL &&
8254       Base.getOperand(1).hasOneUse() &&
8255       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8256     // The shift can be combined if it matches the size of the value being
8257     // loaded (and so reducing the width would make it not match).
8258     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8259     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8260     if (ShiftAmount == Log2_32(LoadBytes))
8261       return false;
8262   }
8263   // We have no reason to disallow reducing the load width, so allow it.
8264   return true;
8265 }
8266 
8267 // Truncations from 64-bit GPR to 32-bit GPR is free.
8268 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8269   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8270     return false;
8271   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8272   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8273   return NumBits1 > NumBits2;
8274 }
8275 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8276   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8277     return false;
8278   unsigned NumBits1 = VT1.getSizeInBits();
8279   unsigned NumBits2 = VT2.getSizeInBits();
8280   return NumBits1 > NumBits2;
8281 }
8282 
8283 /// Check if it is profitable to hoist instruction in then/else to if.
8284 /// Not profitable if I and it's user can form a FMA instruction
8285 /// because we prefer FMSUB/FMADD.
8286 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8287   if (I->getOpcode() != Instruction::FMul)
8288     return true;
8289 
8290   if (!I->hasOneUse())
8291     return true;
8292 
8293   Instruction *User = I->user_back();
8294 
8295   if (User &&
8296       !(User->getOpcode() == Instruction::FSub ||
8297         User->getOpcode() == Instruction::FAdd))
8298     return true;
8299 
8300   const TargetOptions &Options = getTargetMachine().Options;
8301   const DataLayout &DL = I->getModule()->getDataLayout();
8302   EVT VT = getValueType(DL, User->getOperand(0)->getType());
8303 
8304   return !(isFMAFasterThanFMulAndFAdd(VT) &&
8305            isOperationLegalOrCustom(ISD::FMA, VT) &&
8306            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8307             Options.UnsafeFPMath));
8308 }
8309 
8310 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8311 // 64-bit GPR.
8312 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8313   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8314     return false;
8315   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8316   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8317   return NumBits1 == 32 && NumBits2 == 64;
8318 }
8319 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8320   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8321     return false;
8322   unsigned NumBits1 = VT1.getSizeInBits();
8323   unsigned NumBits2 = VT2.getSizeInBits();
8324   return NumBits1 == 32 && NumBits2 == 64;
8325 }
8326 
8327 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8328   EVT VT1 = Val.getValueType();
8329   if (isZExtFree(VT1, VT2)) {
8330     return true;
8331   }
8332 
8333   if (Val.getOpcode() != ISD::LOAD)
8334     return false;
8335 
8336   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8337   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8338           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8339           VT1.getSizeInBits() <= 32);
8340 }
8341 
8342 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8343   if (isa<FPExtInst>(Ext))
8344     return false;
8345 
8346   // Vector types are not free.
8347   if (Ext->getType()->isVectorTy())
8348     return false;
8349 
8350   for (const Use &U : Ext->uses()) {
8351     // The extension is free if we can fold it with a left shift in an
8352     // addressing mode or an arithmetic operation: add, sub, and cmp.
8353 
8354     // Is there a shift?
8355     const Instruction *Instr = cast<Instruction>(U.getUser());
8356 
8357     // Is this a constant shift?
8358     switch (Instr->getOpcode()) {
8359     case Instruction::Shl:
8360       if (!isa<ConstantInt>(Instr->getOperand(1)))
8361         return false;
8362       break;
8363     case Instruction::GetElementPtr: {
8364       gep_type_iterator GTI = gep_type_begin(Instr);
8365       auto &DL = Ext->getModule()->getDataLayout();
8366       std::advance(GTI, U.getOperandNo()-1);
8367       Type *IdxTy = GTI.getIndexedType();
8368       // This extension will end up with a shift because of the scaling factor.
8369       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8370       // Get the shift amount based on the scaling factor:
8371       // log2(sizeof(IdxTy)) - log2(8).
8372       uint64_t ShiftAmt =
8373           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8374       // Is the constant foldable in the shift of the addressing mode?
8375       // I.e., shift amount is between 1 and 4 inclusive.
8376       if (ShiftAmt == 0 || ShiftAmt > 4)
8377         return false;
8378       break;
8379     }
8380     case Instruction::Trunc:
8381       // Check if this is a noop.
8382       // trunc(sext ty1 to ty2) to ty1.
8383       if (Instr->getType() == Ext->getOperand(0)->getType())
8384         continue;
8385       LLVM_FALLTHROUGH;
8386     default:
8387       return false;
8388     }
8389 
8390     // At this point we can use the bfm family, so this extension is free
8391     // for that use.
8392   }
8393   return true;
8394 }
8395 
8396 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8397 /// or upper half of the vector elements.
8398 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8399   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8400     auto *FullVT = cast<VectorType>(FullV->getType());
8401     auto *HalfVT = cast<VectorType>(HalfV->getType());
8402     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8403   };
8404 
8405   auto extractHalf = [](Value *FullV, Value *HalfV) {
8406     auto *FullVT = cast<VectorType>(FullV->getType());
8407     auto *HalfVT = cast<VectorType>(HalfV->getType());
8408     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8409   };
8410 
8411   Constant *M1, *M2;
8412   Value *S1Op1, *S2Op1;
8413   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8414       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8415     return false;
8416 
8417   // Check that the operands are half as wide as the result and we extract
8418   // half of the elements of the input vectors.
8419   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8420       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8421     return false;
8422 
8423   // Check the mask extracts either the lower or upper half of vector
8424   // elements.
8425   int M1Start = -1;
8426   int M2Start = -1;
8427   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8428   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8429       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8430       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8431     return false;
8432 
8433   return true;
8434 }
8435 
8436 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8437 /// of the vector elements.
8438 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8439   auto areExtDoubled = [](Instruction *Ext) {
8440     return Ext->getType()->getScalarSizeInBits() ==
8441            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8442   };
8443 
8444   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8445       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8446       !areExtDoubled(cast<Instruction>(Ext1)) ||
8447       !areExtDoubled(cast<Instruction>(Ext2)))
8448     return false;
8449 
8450   return true;
8451 }
8452 
8453 /// Check if sinking \p I's operands to I's basic block is profitable, because
8454 /// the operands can be folded into a target instruction, e.g.
8455 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8456 bool AArch64TargetLowering::shouldSinkOperands(
8457     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8458   if (!I->getType()->isVectorTy())
8459     return false;
8460 
8461   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8462     switch (II->getIntrinsicID()) {
8463     case Intrinsic::aarch64_neon_umull:
8464       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8465         return false;
8466       Ops.push_back(&II->getOperandUse(0));
8467       Ops.push_back(&II->getOperandUse(1));
8468       return true;
8469     default:
8470       return false;
8471     }
8472   }
8473 
8474   switch (I->getOpcode()) {
8475   case Instruction::Sub:
8476   case Instruction::Add: {
8477     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8478       return false;
8479 
8480     // If the exts' operands extract either the lower or upper elements, we
8481     // can sink them too.
8482     auto Ext1 = cast<Instruction>(I->getOperand(0));
8483     auto Ext2 = cast<Instruction>(I->getOperand(1));
8484     if (areExtractShuffleVectors(Ext1, Ext2)) {
8485       Ops.push_back(&Ext1->getOperandUse(0));
8486       Ops.push_back(&Ext2->getOperandUse(0));
8487     }
8488 
8489     Ops.push_back(&I->getOperandUse(0));
8490     Ops.push_back(&I->getOperandUse(1));
8491 
8492     return true;
8493   }
8494   default:
8495     return false;
8496   }
8497   return false;
8498 }
8499 
8500 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8501                                           unsigned &RequiredAligment) const {
8502   if (!LoadedType.isSimple() ||
8503       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8504     return false;
8505   // Cyclone supports unaligned accesses.
8506   RequiredAligment = 0;
8507   unsigned NumBits = LoadedType.getSizeInBits();
8508   return NumBits == 32 || NumBits == 64;
8509 }
8510 
8511 /// A helper function for determining the number of interleaved accesses we
8512 /// will generate when lowering accesses of the given type.
8513 unsigned
8514 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8515                                                  const DataLayout &DL) const {
8516   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8517 }
8518 
8519 MachineMemOperand::Flags
8520 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8521   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8522       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8523     return MOStridedAccess;
8524   return MachineMemOperand::MONone;
8525 }
8526 
8527 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8528     VectorType *VecTy, const DataLayout &DL) const {
8529 
8530   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8531   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8532 
8533   // Ensure the number of vector elements is greater than 1.
8534   if (VecTy->getNumElements() < 2)
8535     return false;
8536 
8537   // Ensure the element type is legal.
8538   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8539     return false;
8540 
8541   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8542   // 128 will be split into multiple interleaved accesses.
8543   return VecSize == 64 || VecSize % 128 == 0;
8544 }
8545 
8546 /// Lower an interleaved load into a ldN intrinsic.
8547 ///
8548 /// E.g. Lower an interleaved load (Factor = 2):
8549 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8550 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
8551 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
8552 ///
8553 ///      Into:
8554 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8555 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8556 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8557 bool AArch64TargetLowering::lowerInterleavedLoad(
8558     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8559     ArrayRef<unsigned> Indices, unsigned Factor) const {
8560   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8561          "Invalid interleave factor");
8562   assert(!Shuffles.empty() && "Empty shufflevector input");
8563   assert(Shuffles.size() == Indices.size() &&
8564          "Unmatched number of shufflevectors and indices");
8565 
8566   const DataLayout &DL = LI->getModule()->getDataLayout();
8567 
8568   VectorType *VecTy = Shuffles[0]->getType();
8569 
8570   // Skip if we do not have NEON and skip illegal vector types. We can
8571   // "legalize" wide vector types into multiple interleaved accesses as long as
8572   // the vector types are divisible by 128.
8573   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8574     return false;
8575 
8576   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8577 
8578   // A pointer vector can not be the return type of the ldN intrinsics. Need to
8579   // load integer vectors first and then convert to pointer vectors.
8580   Type *EltTy = VecTy->getVectorElementType();
8581   if (EltTy->isPointerTy())
8582     VecTy =
8583         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8584 
8585   IRBuilder<> Builder(LI);
8586 
8587   // The base address of the load.
8588   Value *BaseAddr = LI->getPointerOperand();
8589 
8590   if (NumLoads > 1) {
8591     // If we're going to generate more than one load, reset the sub-vector type
8592     // to something legal.
8593     VecTy = VectorType::get(VecTy->getVectorElementType(),
8594                             VecTy->getVectorNumElements() / NumLoads);
8595 
8596     // We will compute the pointer operand of each load from the original base
8597     // address using GEPs. Cast the base address to a pointer to the scalar
8598     // element type.
8599     BaseAddr = Builder.CreateBitCast(
8600         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8601                       LI->getPointerAddressSpace()));
8602   }
8603 
8604   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8605   Type *Tys[2] = {VecTy, PtrTy};
8606   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8607                                             Intrinsic::aarch64_neon_ld3,
8608                                             Intrinsic::aarch64_neon_ld4};
8609   Function *LdNFunc =
8610       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8611 
8612   // Holds sub-vectors extracted from the load intrinsic return values. The
8613   // sub-vectors are associated with the shufflevector instructions they will
8614   // replace.
8615   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8616 
8617   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8618 
8619     // If we're generating more than one load, compute the base address of
8620     // subsequent loads as an offset from the previous.
8621     if (LoadCount > 0)
8622       BaseAddr =
8623           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8624                                      VecTy->getVectorNumElements() * Factor);
8625 
8626     CallInst *LdN = Builder.CreateCall(
8627         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8628 
8629     // Extract and store the sub-vectors returned by the load intrinsic.
8630     for (unsigned i = 0; i < Shuffles.size(); i++) {
8631       ShuffleVectorInst *SVI = Shuffles[i];
8632       unsigned Index = Indices[i];
8633 
8634       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8635 
8636       // Convert the integer vector to pointer vector if the element is pointer.
8637       if (EltTy->isPointerTy())
8638         SubVec = Builder.CreateIntToPtr(
8639             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8640                                     VecTy->getVectorNumElements()));
8641       SubVecs[SVI].push_back(SubVec);
8642     }
8643   }
8644 
8645   // Replace uses of the shufflevector instructions with the sub-vectors
8646   // returned by the load intrinsic. If a shufflevector instruction is
8647   // associated with more than one sub-vector, those sub-vectors will be
8648   // concatenated into a single wide vector.
8649   for (ShuffleVectorInst *SVI : Shuffles) {
8650     auto &SubVec = SubVecs[SVI];
8651     auto *WideVec =
8652         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8653     SVI->replaceAllUsesWith(WideVec);
8654   }
8655 
8656   return true;
8657 }
8658 
8659 /// Lower an interleaved store into a stN intrinsic.
8660 ///
8661 /// E.g. Lower an interleaved store (Factor = 3):
8662 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8663 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8664 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8665 ///
8666 ///      Into:
8667 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8668 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8669 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8670 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8671 ///
8672 /// Note that the new shufflevectors will be removed and we'll only generate one
8673 /// st3 instruction in CodeGen.
8674 ///
8675 /// Example for a more general valid mask (Factor 3). Lower:
8676 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8677 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8678 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8679 ///
8680 ///      Into:
8681 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8682 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8683 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8684 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8685 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8686                                                   ShuffleVectorInst *SVI,
8687                                                   unsigned Factor) const {
8688   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8689          "Invalid interleave factor");
8690 
8691   VectorType *VecTy = SVI->getType();
8692   assert(VecTy->getVectorNumElements() % Factor == 0 &&
8693          "Invalid interleaved store");
8694 
8695   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8696   Type *EltTy = VecTy->getVectorElementType();
8697   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8698 
8699   const DataLayout &DL = SI->getModule()->getDataLayout();
8700 
8701   // Skip if we do not have NEON and skip illegal vector types. We can
8702   // "legalize" wide vector types into multiple interleaved accesses as long as
8703   // the vector types are divisible by 128.
8704   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8705     return false;
8706 
8707   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8708 
8709   Value *Op0 = SVI->getOperand(0);
8710   Value *Op1 = SVI->getOperand(1);
8711   IRBuilder<> Builder(SI);
8712 
8713   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8714   // vectors to integer vectors.
8715   if (EltTy->isPointerTy()) {
8716     Type *IntTy = DL.getIntPtrType(EltTy);
8717     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8718 
8719     // Convert to the corresponding integer vector.
8720     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8721     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8722     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8723 
8724     SubVecTy = VectorType::get(IntTy, LaneLen);
8725   }
8726 
8727   // The base address of the store.
8728   Value *BaseAddr = SI->getPointerOperand();
8729 
8730   if (NumStores > 1) {
8731     // If we're going to generate more than one store, reset the lane length
8732     // and sub-vector type to something legal.
8733     LaneLen /= NumStores;
8734     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8735 
8736     // We will compute the pointer operand of each store from the original base
8737     // address using GEPs. Cast the base address to a pointer to the scalar
8738     // element type.
8739     BaseAddr = Builder.CreateBitCast(
8740         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8741                       SI->getPointerAddressSpace()));
8742   }
8743 
8744   auto Mask = SVI->getShuffleMask();
8745 
8746   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8747   Type *Tys[2] = {SubVecTy, PtrTy};
8748   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8749                                              Intrinsic::aarch64_neon_st3,
8750                                              Intrinsic::aarch64_neon_st4};
8751   Function *StNFunc =
8752       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8753 
8754   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8755 
8756     SmallVector<Value *, 5> Ops;
8757 
8758     // Split the shufflevector operands into sub vectors for the new stN call.
8759     for (unsigned i = 0; i < Factor; i++) {
8760       unsigned IdxI = StoreCount * LaneLen * Factor + i;
8761       if (Mask[IdxI] >= 0) {
8762         Ops.push_back(Builder.CreateShuffleVector(
8763             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8764       } else {
8765         unsigned StartMask = 0;
8766         for (unsigned j = 1; j < LaneLen; j++) {
8767           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8768           if (Mask[IdxJ * Factor + IdxI] >= 0) {
8769             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8770             break;
8771           }
8772         }
8773         // Note: Filling undef gaps with random elements is ok, since
8774         // those elements were being written anyway (with undefs).
8775         // In the case of all undefs we're defaulting to using elems from 0
8776         // Note: StartMask cannot be negative, it's checked in
8777         // isReInterleaveMask
8778         Ops.push_back(Builder.CreateShuffleVector(
8779             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8780       }
8781     }
8782 
8783     // If we generating more than one store, we compute the base address of
8784     // subsequent stores as an offset from the previous.
8785     if (StoreCount > 0)
8786       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8787                                             BaseAddr, LaneLen * Factor);
8788 
8789     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8790     Builder.CreateCall(StNFunc, Ops);
8791   }
8792   return true;
8793 }
8794 
8795 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8796                        unsigned AlignCheck) {
8797   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8798           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8799 }
8800 
8801 EVT AArch64TargetLowering::getOptimalMemOpType(
8802     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8803     bool ZeroMemset, bool MemcpyStrSrc,
8804     const AttributeList &FuncAttributes) const {
8805   bool CanImplicitFloat =
8806       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8807   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8808   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8809   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8810   // taken one instruction to materialize the v2i64 zero and one store (with
8811   // restrictive addressing mode). Just do i64 stores.
8812   bool IsSmallMemset = IsMemset && Size < 32;
8813   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8814     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8815       return true;
8816     bool Fast;
8817     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8818                                           &Fast) &&
8819            Fast;
8820   };
8821 
8822   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8823       AlignmentIsAcceptable(MVT::v2i64, 16))
8824     return MVT::v2i64;
8825   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8826     return MVT::f128;
8827   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8828     return MVT::i64;
8829   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8830     return MVT::i32;
8831   return MVT::Other;
8832 }
8833 
8834 LLT AArch64TargetLowering::getOptimalMemOpLLT(
8835     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8836     bool ZeroMemset, bool MemcpyStrSrc,
8837     const AttributeList &FuncAttributes) const {
8838   bool CanImplicitFloat =
8839       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8840   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8841   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8842   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8843   // taken one instruction to materialize the v2i64 zero and one store (with
8844   // restrictive addressing mode). Just do i64 stores.
8845   bool IsSmallMemset = IsMemset && Size < 32;
8846   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8847     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8848       return true;
8849     bool Fast;
8850     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8851                                           &Fast) &&
8852            Fast;
8853   };
8854 
8855   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8856       AlignmentIsAcceptable(MVT::v2i64, 16))
8857     return LLT::vector(2, 64);
8858   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8859     return LLT::scalar(128);
8860   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8861     return LLT::scalar(64);
8862   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8863     return LLT::scalar(32);
8864   return LLT();
8865 }
8866 
8867 // 12-bit optionally shifted immediates are legal for adds.
8868 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8869   if (Immed == std::numeric_limits<int64_t>::min()) {
8870     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8871                       << ": avoid UB for INT64_MIN\n");
8872     return false;
8873   }
8874   // Same encoding for add/sub, just flip the sign.
8875   Immed = std::abs(Immed);
8876   bool IsLegal = ((Immed >> 12) == 0 ||
8877                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8878   LLVM_DEBUG(dbgs() << "Is " << Immed
8879                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8880   return IsLegal;
8881 }
8882 
8883 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8884 // immediates is the same as for an add or a sub.
8885 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8886   return isLegalAddImmediate(Immed);
8887 }
8888 
8889 /// isLegalAddressingMode - Return true if the addressing mode represented
8890 /// by AM is legal for this target, for a load/store of the specified type.
8891 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8892                                                   const AddrMode &AM, Type *Ty,
8893                                                   unsigned AS, Instruction *I) const {
8894   // AArch64 has five basic addressing modes:
8895   //  reg
8896   //  reg + 9-bit signed offset
8897   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
8898   //  reg1 + reg2
8899   //  reg + SIZE_IN_BYTES * reg
8900 
8901   // No global is ever allowed as a base.
8902   if (AM.BaseGV)
8903     return false;
8904 
8905   // No reg+reg+imm addressing.
8906   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8907     return false;
8908 
8909   // check reg + imm case:
8910   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8911   uint64_t NumBytes = 0;
8912   if (Ty->isSized()) {
8913     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8914     NumBytes = NumBits / 8;
8915     if (!isPowerOf2_64(NumBits))
8916       NumBytes = 0;
8917   }
8918 
8919   if (!AM.Scale) {
8920     int64_t Offset = AM.BaseOffs;
8921 
8922     // 9-bit signed offset
8923     if (isInt<9>(Offset))
8924       return true;
8925 
8926     // 12-bit unsigned offset
8927     unsigned shift = Log2_64(NumBytes);
8928     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8929         // Must be a multiple of NumBytes (NumBytes is a power of 2)
8930         (Offset >> shift) << shift == Offset)
8931       return true;
8932     return false;
8933   }
8934 
8935   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8936 
8937   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8938 }
8939 
8940 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8941   // Consider splitting large offset of struct or array.
8942   return true;
8943 }
8944 
8945 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8946                                                 const AddrMode &AM, Type *Ty,
8947                                                 unsigned AS) const {
8948   // Scaling factors are not free at all.
8949   // Operands                     | Rt Latency
8950   // -------------------------------------------
8951   // Rt, [Xn, Xm]                 | 4
8952   // -------------------------------------------
8953   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
8954   // Rt, [Xn, Wm, <extend> #imm]  |
8955   if (isLegalAddressingMode(DL, AM, Ty, AS))
8956     // Scale represents reg2 * scale, thus account for 1 if
8957     // it is not equal to 0 or 1.
8958     return AM.Scale != 0 && AM.Scale != 1;
8959   return -1;
8960 }
8961 
8962 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8963   VT = VT.getScalarType();
8964 
8965   if (!VT.isSimple())
8966     return false;
8967 
8968   switch (VT.getSimpleVT().SimpleTy) {
8969   case MVT::f32:
8970   case MVT::f64:
8971     return true;
8972   default:
8973     break;
8974   }
8975 
8976   return false;
8977 }
8978 
8979 const MCPhysReg *
8980 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8981   // LR is a callee-save register, but we must treat it as clobbered by any call
8982   // site. Hence we include LR in the scratch registers, which are in turn added
8983   // as implicit-defs for stackmaps and patchpoints.
8984   static const MCPhysReg ScratchRegs[] = {
8985     AArch64::X16, AArch64::X17, AArch64::LR, 0
8986   };
8987   return ScratchRegs;
8988 }
8989 
8990 bool
8991 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8992                                                      CombineLevel Level) const {
8993   N = N->getOperand(0).getNode();
8994   EVT VT = N->getValueType(0);
8995     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8996     // it with shift to let it be lowered to UBFX.
8997   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8998       isa<ConstantSDNode>(N->getOperand(1))) {
8999     uint64_t TruncMask = N->getConstantOperandVal(1);
9000     if (isMask_64(TruncMask) &&
9001       N->getOperand(0).getOpcode() == ISD::SRL &&
9002       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9003       return false;
9004   }
9005   return true;
9006 }
9007 
9008 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9009                                                               Type *Ty) const {
9010   assert(Ty->isIntegerTy());
9011 
9012   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9013   if (BitSize == 0)
9014     return false;
9015 
9016   int64_t Val = Imm.getSExtValue();
9017   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9018     return true;
9019 
9020   if ((int64_t)Val < 0)
9021     Val = ~Val;
9022   if (BitSize == 32)
9023     Val &= (1LL << 32) - 1;
9024 
9025   unsigned LZ = countLeadingZeros((uint64_t)Val);
9026   unsigned Shift = (63 - LZ) / 16;
9027   // MOVZ is free so return true for one or fewer MOVK.
9028   return Shift < 3;
9029 }
9030 
9031 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9032                                                     unsigned Index) const {
9033   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9034     return false;
9035 
9036   return (Index == 0 || Index == ResVT.getVectorNumElements());
9037 }
9038 
9039 /// Turn vector tests of the signbit in the form of:
9040 ///   xor (sra X, elt_size(X)-1), -1
9041 /// into:
9042 ///   cmge X, X, #0
9043 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9044                                          const AArch64Subtarget *Subtarget) {
9045   EVT VT = N->getValueType(0);
9046   if (!Subtarget->hasNEON() || !VT.isVector())
9047     return SDValue();
9048 
9049   // There must be a shift right algebraic before the xor, and the xor must be a
9050   // 'not' operation.
9051   SDValue Shift = N->getOperand(0);
9052   SDValue Ones = N->getOperand(1);
9053   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9054       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9055     return SDValue();
9056 
9057   // The shift should be smearing the sign bit across each vector element.
9058   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9059   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9060   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9061     return SDValue();
9062 
9063   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9064 }
9065 
9066 // Generate SUBS and CSEL for integer abs.
9067 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9068   EVT VT = N->getValueType(0);
9069 
9070   SDValue N0 = N->getOperand(0);
9071   SDValue N1 = N->getOperand(1);
9072   SDLoc DL(N);
9073 
9074   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9075   // and change it to SUB and CSEL.
9076   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9077       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9078       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9079     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9080       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9081         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9082                                   N0.getOperand(0));
9083         // Generate SUBS & CSEL.
9084         SDValue Cmp =
9085             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9086                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9087         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9088                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9089                            SDValue(Cmp.getNode(), 1));
9090       }
9091   return SDValue();
9092 }
9093 
9094 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9095                                  TargetLowering::DAGCombinerInfo &DCI,
9096                                  const AArch64Subtarget *Subtarget) {
9097   if (DCI.isBeforeLegalizeOps())
9098     return SDValue();
9099 
9100   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9101     return Cmp;
9102 
9103   return performIntegerAbsCombine(N, DAG);
9104 }
9105 
9106 SDValue
9107 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9108                                      SelectionDAG &DAG,
9109                                      SmallVectorImpl<SDNode *> &Created) const {
9110   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9111   if (isIntDivCheap(N->getValueType(0), Attr))
9112     return SDValue(N,0); // Lower SDIV as SDIV
9113 
9114   // fold (sdiv X, pow2)
9115   EVT VT = N->getValueType(0);
9116   if ((VT != MVT::i32 && VT != MVT::i64) ||
9117       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9118     return SDValue();
9119 
9120   SDLoc DL(N);
9121   SDValue N0 = N->getOperand(0);
9122   unsigned Lg2 = Divisor.countTrailingZeros();
9123   SDValue Zero = DAG.getConstant(0, DL, VT);
9124   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9125 
9126   // Add (N0 < 0) ? Pow2 - 1 : 0;
9127   SDValue CCVal;
9128   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9129   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9130   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9131 
9132   Created.push_back(Cmp.getNode());
9133   Created.push_back(Add.getNode());
9134   Created.push_back(CSel.getNode());
9135 
9136   // Divide by pow2.
9137   SDValue SRA =
9138       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9139 
9140   // If we're dividing by a positive value, we're done.  Otherwise, we must
9141   // negate the result.
9142   if (Divisor.isNonNegative())
9143     return SRA;
9144 
9145   Created.push_back(SRA.getNode());
9146   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9147 }
9148 
9149 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9150                                  TargetLowering::DAGCombinerInfo &DCI,
9151                                  const AArch64Subtarget *Subtarget) {
9152   if (DCI.isBeforeLegalizeOps())
9153     return SDValue();
9154 
9155   // The below optimizations require a constant RHS.
9156   if (!isa<ConstantSDNode>(N->getOperand(1)))
9157     return SDValue();
9158 
9159   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9160   const APInt &ConstValue = C->getAPIntValue();
9161 
9162   // Multiplication of a power of two plus/minus one can be done more
9163   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9164   // future CPUs have a cheaper MADD instruction, this may need to be
9165   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9166   // 64-bit is 5 cycles, so this is always a win.
9167   // More aggressively, some multiplications N0 * C can be lowered to
9168   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9169   // e.g. 6=3*2=(2+1)*2.
9170   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9171   // which equals to (1+2)*16-(1+2).
9172   SDValue N0 = N->getOperand(0);
9173   // TrailingZeroes is used to test if the mul can be lowered to
9174   // shift+add+shift.
9175   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9176   if (TrailingZeroes) {
9177     // Conservatively do not lower to shift+add+shift if the mul might be
9178     // folded into smul or umul.
9179     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9180                             isZeroExtended(N0.getNode(), DAG)))
9181       return SDValue();
9182     // Conservatively do not lower to shift+add+shift if the mul might be
9183     // folded into madd or msub.
9184     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9185                            N->use_begin()->getOpcode() == ISD::SUB))
9186       return SDValue();
9187   }
9188   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9189   // and shift+add+shift.
9190   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9191 
9192   unsigned ShiftAmt, AddSubOpc;
9193   // Is the shifted value the LHS operand of the add/sub?
9194   bool ShiftValUseIsN0 = true;
9195   // Do we need to negate the result?
9196   bool NegateResult = false;
9197 
9198   if (ConstValue.isNonNegative()) {
9199     // (mul x, 2^N + 1) => (add (shl x, N), x)
9200     // (mul x, 2^N - 1) => (sub (shl x, N), x)
9201     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9202     APInt SCVMinus1 = ShiftedConstValue - 1;
9203     APInt CVPlus1 = ConstValue + 1;
9204     if (SCVMinus1.isPowerOf2()) {
9205       ShiftAmt = SCVMinus1.logBase2();
9206       AddSubOpc = ISD::ADD;
9207     } else if (CVPlus1.isPowerOf2()) {
9208       ShiftAmt = CVPlus1.logBase2();
9209       AddSubOpc = ISD::SUB;
9210     } else
9211       return SDValue();
9212   } else {
9213     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9214     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9215     APInt CVNegPlus1 = -ConstValue + 1;
9216     APInt CVNegMinus1 = -ConstValue - 1;
9217     if (CVNegPlus1.isPowerOf2()) {
9218       ShiftAmt = CVNegPlus1.logBase2();
9219       AddSubOpc = ISD::SUB;
9220       ShiftValUseIsN0 = false;
9221     } else if (CVNegMinus1.isPowerOf2()) {
9222       ShiftAmt = CVNegMinus1.logBase2();
9223       AddSubOpc = ISD::ADD;
9224       NegateResult = true;
9225     } else
9226       return SDValue();
9227   }
9228 
9229   SDLoc DL(N);
9230   EVT VT = N->getValueType(0);
9231   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9232                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
9233 
9234   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9235   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9236   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9237   assert(!(NegateResult && TrailingZeroes) &&
9238          "NegateResult and TrailingZeroes cannot both be true for now.");
9239   // Negate the result.
9240   if (NegateResult)
9241     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9242   // Shift the result.
9243   if (TrailingZeroes)
9244     return DAG.getNode(ISD::SHL, DL, VT, Res,
9245                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9246   return Res;
9247 }
9248 
9249 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9250                                                          SelectionDAG &DAG) {
9251   // Take advantage of vector comparisons producing 0 or -1 in each lane to
9252   // optimize away operation when it's from a constant.
9253   //
9254   // The general transformation is:
9255   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9256   //       AND(VECTOR_CMP(x,y), constant2)
9257   //    constant2 = UNARYOP(constant)
9258 
9259   // Early exit if this isn't a vector operation, the operand of the
9260   // unary operation isn't a bitwise AND, or if the sizes of the operations
9261   // aren't the same.
9262   EVT VT = N->getValueType(0);
9263   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9264       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9265       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9266     return SDValue();
9267 
9268   // Now check that the other operand of the AND is a constant. We could
9269   // make the transformation for non-constant splats as well, but it's unclear
9270   // that would be a benefit as it would not eliminate any operations, just
9271   // perform one more step in scalar code before moving to the vector unit.
9272   if (BuildVectorSDNode *BV =
9273           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9274     // Bail out if the vector isn't a constant.
9275     if (!BV->isConstant())
9276       return SDValue();
9277 
9278     // Everything checks out. Build up the new and improved node.
9279     SDLoc DL(N);
9280     EVT IntVT = BV->getValueType(0);
9281     // Create a new constant of the appropriate type for the transformed
9282     // DAG.
9283     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9284     // The AND node needs bitcasts to/from an integer vector type around it.
9285     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9286     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9287                                  N->getOperand(0)->getOperand(0), MaskConst);
9288     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9289     return Res;
9290   }
9291 
9292   return SDValue();
9293 }
9294 
9295 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9296                                      const AArch64Subtarget *Subtarget) {
9297   // First try to optimize away the conversion when it's conditionally from
9298   // a constant. Vectors only.
9299   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9300     return Res;
9301 
9302   EVT VT = N->getValueType(0);
9303   if (VT != MVT::f32 && VT != MVT::f64)
9304     return SDValue();
9305 
9306   // Only optimize when the source and destination types have the same width.
9307   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9308     return SDValue();
9309 
9310   // If the result of an integer load is only used by an integer-to-float
9311   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9312   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9313   SDValue N0 = N->getOperand(0);
9314   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9315       // Do not change the width of a volatile load.
9316       !cast<LoadSDNode>(N0)->isVolatile()) {
9317     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9318     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9319                                LN0->getPointerInfo(), LN0->getAlignment(),
9320                                LN0->getMemOperand()->getFlags());
9321 
9322     // Make sure successors of the original load stay after it by updating them
9323     // to use the new Chain.
9324     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9325 
9326     unsigned Opcode =
9327         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9328     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9329   }
9330 
9331   return SDValue();
9332 }
9333 
9334 /// Fold a floating-point multiply by power of two into floating-point to
9335 /// fixed-point conversion.
9336 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9337                                      TargetLowering::DAGCombinerInfo &DCI,
9338                                      const AArch64Subtarget *Subtarget) {
9339   if (!Subtarget->hasNEON())
9340     return SDValue();
9341 
9342   if (!N->getValueType(0).isSimple())
9343     return SDValue();
9344 
9345   SDValue Op = N->getOperand(0);
9346   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9347       Op.getOpcode() != ISD::FMUL)
9348     return SDValue();
9349 
9350   SDValue ConstVec = Op->getOperand(1);
9351   if (!isa<BuildVectorSDNode>(ConstVec))
9352     return SDValue();
9353 
9354   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9355   uint32_t FloatBits = FloatTy.getSizeInBits();
9356   if (FloatBits != 32 && FloatBits != 64)
9357     return SDValue();
9358 
9359   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9360   uint32_t IntBits = IntTy.getSizeInBits();
9361   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9362     return SDValue();
9363 
9364   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9365   if (IntBits > FloatBits)
9366     return SDValue();
9367 
9368   BitVector UndefElements;
9369   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9370   int32_t Bits = IntBits == 64 ? 64 : 32;
9371   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9372   if (C == -1 || C == 0 || C > Bits)
9373     return SDValue();
9374 
9375   MVT ResTy;
9376   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9377   switch (NumLanes) {
9378   default:
9379     return SDValue();
9380   case 2:
9381     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9382     break;
9383   case 4:
9384     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9385     break;
9386   }
9387 
9388   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9389     return SDValue();
9390 
9391   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9392          "Illegal vector type after legalization");
9393 
9394   SDLoc DL(N);
9395   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9396   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9397                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9398   SDValue FixConv =
9399       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9400                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9401                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9402   // We can handle smaller integers by generating an extra trunc.
9403   if (IntBits < FloatBits)
9404     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9405 
9406   return FixConv;
9407 }
9408 
9409 /// Fold a floating-point divide by power of two into fixed-point to
9410 /// floating-point conversion.
9411 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9412                                   TargetLowering::DAGCombinerInfo &DCI,
9413                                   const AArch64Subtarget *Subtarget) {
9414   if (!Subtarget->hasNEON())
9415     return SDValue();
9416 
9417   SDValue Op = N->getOperand(0);
9418   unsigned Opc = Op->getOpcode();
9419   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9420       !Op.getOperand(0).getValueType().isSimple() ||
9421       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9422     return SDValue();
9423 
9424   SDValue ConstVec = N->getOperand(1);
9425   if (!isa<BuildVectorSDNode>(ConstVec))
9426     return SDValue();
9427 
9428   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9429   int32_t IntBits = IntTy.getSizeInBits();
9430   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9431     return SDValue();
9432 
9433   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9434   int32_t FloatBits = FloatTy.getSizeInBits();
9435   if (FloatBits != 32 && FloatBits != 64)
9436     return SDValue();
9437 
9438   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9439   if (IntBits > FloatBits)
9440     return SDValue();
9441 
9442   BitVector UndefElements;
9443   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9444   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9445   if (C == -1 || C == 0 || C > FloatBits)
9446     return SDValue();
9447 
9448   MVT ResTy;
9449   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9450   switch (NumLanes) {
9451   default:
9452     return SDValue();
9453   case 2:
9454     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9455     break;
9456   case 4:
9457     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9458     break;
9459   }
9460 
9461   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9462     return SDValue();
9463 
9464   SDLoc DL(N);
9465   SDValue ConvInput = Op.getOperand(0);
9466   bool IsSigned = Opc == ISD::SINT_TO_FP;
9467   if (IntBits < FloatBits)
9468     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9469                             ResTy, ConvInput);
9470 
9471   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9472                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
9473   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9474                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9475                      DAG.getConstant(C, DL, MVT::i32));
9476 }
9477 
9478 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9479 /// searches for and classifies those shifts.
9480 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9481                          bool &FromHi) {
9482   if (N.getOpcode() == ISD::SHL)
9483     FromHi = false;
9484   else if (N.getOpcode() == ISD::SRL)
9485     FromHi = true;
9486   else
9487     return false;
9488 
9489   if (!isa<ConstantSDNode>(N.getOperand(1)))
9490     return false;
9491 
9492   ShiftAmount = N->getConstantOperandVal(1);
9493   Src = N->getOperand(0);
9494   return true;
9495 }
9496 
9497 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9498 /// registers viewed as a high/low pair. This function looks for the pattern:
9499 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9500 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9501 /// aren't independent.
9502 static SDValue tryCombineToEXTR(SDNode *N,
9503                                 TargetLowering::DAGCombinerInfo &DCI) {
9504   SelectionDAG &DAG = DCI.DAG;
9505   SDLoc DL(N);
9506   EVT VT = N->getValueType(0);
9507 
9508   assert(N->getOpcode() == ISD::OR && "Unexpected root");
9509 
9510   if (VT != MVT::i32 && VT != MVT::i64)
9511     return SDValue();
9512 
9513   SDValue LHS;
9514   uint32_t ShiftLHS = 0;
9515   bool LHSFromHi = false;
9516   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9517     return SDValue();
9518 
9519   SDValue RHS;
9520   uint32_t ShiftRHS = 0;
9521   bool RHSFromHi = false;
9522   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9523     return SDValue();
9524 
9525   // If they're both trying to come from the high part of the register, they're
9526   // not really an EXTR.
9527   if (LHSFromHi == RHSFromHi)
9528     return SDValue();
9529 
9530   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9531     return SDValue();
9532 
9533   if (LHSFromHi) {
9534     std::swap(LHS, RHS);
9535     std::swap(ShiftLHS, ShiftRHS);
9536   }
9537 
9538   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9539                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
9540 }
9541 
9542 static SDValue tryCombineToBSL(SDNode *N,
9543                                 TargetLowering::DAGCombinerInfo &DCI) {
9544   EVT VT = N->getValueType(0);
9545   SelectionDAG &DAG = DCI.DAG;
9546   SDLoc DL(N);
9547 
9548   if (!VT.isVector())
9549     return SDValue();
9550 
9551   SDValue N0 = N->getOperand(0);
9552   if (N0.getOpcode() != ISD::AND)
9553     return SDValue();
9554 
9555   SDValue N1 = N->getOperand(1);
9556   if (N1.getOpcode() != ISD::AND)
9557     return SDValue();
9558 
9559   // We only have to look for constant vectors here since the general, variable
9560   // case can be handled in TableGen.
9561   unsigned Bits = VT.getScalarSizeInBits();
9562   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9563   for (int i = 1; i >= 0; --i)
9564     for (int j = 1; j >= 0; --j) {
9565       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9566       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9567       if (!BVN0 || !BVN1)
9568         continue;
9569 
9570       bool FoundMatch = true;
9571       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9572         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9573         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9574         if (!CN0 || !CN1 ||
9575             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9576           FoundMatch = false;
9577           break;
9578         }
9579       }
9580 
9581       if (FoundMatch)
9582         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9583                            N0->getOperand(1 - i), N1->getOperand(1 - j));
9584     }
9585 
9586   return SDValue();
9587 }
9588 
9589 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9590                                 const AArch64Subtarget *Subtarget) {
9591   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9592   SelectionDAG &DAG = DCI.DAG;
9593   EVT VT = N->getValueType(0);
9594 
9595   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9596     return SDValue();
9597 
9598   if (SDValue Res = tryCombineToEXTR(N, DCI))
9599     return Res;
9600 
9601   if (SDValue Res = tryCombineToBSL(N, DCI))
9602     return Res;
9603 
9604   return SDValue();
9605 }
9606 
9607 static SDValue performANDCombine(SDNode *N,
9608                                  TargetLowering::DAGCombinerInfo &DCI) {
9609   SelectionDAG &DAG = DCI.DAG;
9610   SDValue LHS = N->getOperand(0);
9611   EVT VT = N->getValueType(0);
9612   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9613     return SDValue();
9614 
9615   BuildVectorSDNode *BVN =
9616       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9617   if (!BVN)
9618     return SDValue();
9619 
9620   // AND does not accept an immediate, so check if we can use a BIC immediate
9621   // instruction instead. We do this here instead of using a (and x, (mvni imm))
9622   // pattern in isel, because some immediates may be lowered to the preferred
9623   // (and x, (movi imm)) form, even though an mvni representation also exists.
9624   APInt DefBits(VT.getSizeInBits(), 0);
9625   APInt UndefBits(VT.getSizeInBits(), 0);
9626   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9627     SDValue NewOp;
9628 
9629     DefBits = ~DefBits;
9630     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9631                                     DefBits, &LHS)) ||
9632         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9633                                     DefBits, &LHS)))
9634       return NewOp;
9635 
9636     UndefBits = ~UndefBits;
9637     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9638                                     UndefBits, &LHS)) ||
9639         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9640                                     UndefBits, &LHS)))
9641       return NewOp;
9642   }
9643 
9644   return SDValue();
9645 }
9646 
9647 static SDValue performSRLCombine(SDNode *N,
9648                                  TargetLowering::DAGCombinerInfo &DCI) {
9649   SelectionDAG &DAG = DCI.DAG;
9650   EVT VT = N->getValueType(0);
9651   if (VT != MVT::i32 && VT != MVT::i64)
9652     return SDValue();
9653 
9654   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9655   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9656   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9657   SDValue N0 = N->getOperand(0);
9658   if (N0.getOpcode() == ISD::BSWAP) {
9659     SDLoc DL(N);
9660     SDValue N1 = N->getOperand(1);
9661     SDValue N00 = N0.getOperand(0);
9662     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9663       uint64_t ShiftAmt = C->getZExtValue();
9664       if (VT == MVT::i32 && ShiftAmt == 16 &&
9665           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9666         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9667       if (VT == MVT::i64 && ShiftAmt == 32 &&
9668           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9669         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9670     }
9671   }
9672   return SDValue();
9673 }
9674 
9675 static SDValue performBitcastCombine(SDNode *N,
9676                                      TargetLowering::DAGCombinerInfo &DCI,
9677                                      SelectionDAG &DAG) {
9678   // Wait 'til after everything is legalized to try this. That way we have
9679   // legal vector types and such.
9680   if (DCI.isBeforeLegalizeOps())
9681     return SDValue();
9682 
9683   // Remove extraneous bitcasts around an extract_subvector.
9684   // For example,
9685   //    (v4i16 (bitconvert
9686   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9687   //  becomes
9688   //    (extract_subvector ((v8i16 ...), (i64 4)))
9689 
9690   // Only interested in 64-bit vectors as the ultimate result.
9691   EVT VT = N->getValueType(0);
9692   if (!VT.isVector())
9693     return SDValue();
9694   if (VT.getSimpleVT().getSizeInBits() != 64)
9695     return SDValue();
9696   // Is the operand an extract_subvector starting at the beginning or halfway
9697   // point of the vector? A low half may also come through as an
9698   // EXTRACT_SUBREG, so look for that, too.
9699   SDValue Op0 = N->getOperand(0);
9700   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9701       !(Op0->isMachineOpcode() &&
9702         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9703     return SDValue();
9704   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9705   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9706     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9707       return SDValue();
9708   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9709     if (idx != AArch64::dsub)
9710       return SDValue();
9711     // The dsub reference is equivalent to a lane zero subvector reference.
9712     idx = 0;
9713   }
9714   // Look through the bitcast of the input to the extract.
9715   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9716     return SDValue();
9717   SDValue Source = Op0->getOperand(0)->getOperand(0);
9718   // If the source type has twice the number of elements as our destination
9719   // type, we know this is an extract of the high or low half of the vector.
9720   EVT SVT = Source->getValueType(0);
9721   if (!SVT.isVector() ||
9722       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9723     return SDValue();
9724 
9725   LLVM_DEBUG(
9726       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9727 
9728   // Create the simplified form to just extract the low or high half of the
9729   // vector directly rather than bothering with the bitcasts.
9730   SDLoc dl(N);
9731   unsigned NumElements = VT.getVectorNumElements();
9732   if (idx) {
9733     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9734     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9735   } else {
9736     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9737     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9738                                       Source, SubReg),
9739                    0);
9740   }
9741 }
9742 
9743 static SDValue performConcatVectorsCombine(SDNode *N,
9744                                            TargetLowering::DAGCombinerInfo &DCI,
9745                                            SelectionDAG &DAG) {
9746   SDLoc dl(N);
9747   EVT VT = N->getValueType(0);
9748   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9749 
9750   // Optimize concat_vectors of truncated vectors, where the intermediate
9751   // type is illegal, to avoid said illegality,  e.g.,
9752   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9753   //                          (v2i16 (truncate (v2i64)))))
9754   // ->
9755   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9756   //                                    (v4i32 (bitcast (v2i64))),
9757   //                                    <0, 2, 4, 6>)))
9758   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9759   // on both input and result type, so we might generate worse code.
9760   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9761   if (N->getNumOperands() == 2 &&
9762       N0->getOpcode() == ISD::TRUNCATE &&
9763       N1->getOpcode() == ISD::TRUNCATE) {
9764     SDValue N00 = N0->getOperand(0);
9765     SDValue N10 = N1->getOperand(0);
9766     EVT N00VT = N00.getValueType();
9767 
9768     if (N00VT == N10.getValueType() &&
9769         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9770         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9771       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9772       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9773       for (size_t i = 0; i < Mask.size(); ++i)
9774         Mask[i] = i * 2;
9775       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9776                          DAG.getVectorShuffle(
9777                              MidVT, dl,
9778                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9779                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9780     }
9781   }
9782 
9783   // Wait 'til after everything is legalized to try this. That way we have
9784   // legal vector types and such.
9785   if (DCI.isBeforeLegalizeOps())
9786     return SDValue();
9787 
9788   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9789   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9790   // canonicalise to that.
9791   if (N0 == N1 && VT.getVectorNumElements() == 2) {
9792     assert(VT.getScalarSizeInBits() == 64);
9793     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9794                        DAG.getConstant(0, dl, MVT::i64));
9795   }
9796 
9797   // Canonicalise concat_vectors so that the right-hand vector has as few
9798   // bit-casts as possible before its real operation. The primary matching
9799   // destination for these operations will be the narrowing "2" instructions,
9800   // which depend on the operation being performed on this right-hand vector.
9801   // For example,
9802   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
9803   // becomes
9804   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9805 
9806   if (N1->getOpcode() != ISD::BITCAST)
9807     return SDValue();
9808   SDValue RHS = N1->getOperand(0);
9809   MVT RHSTy = RHS.getValueType().getSimpleVT();
9810   // If the RHS is not a vector, this is not the pattern we're looking for.
9811   if (!RHSTy.isVector())
9812     return SDValue();
9813 
9814   LLVM_DEBUG(
9815       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9816 
9817   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9818                                   RHSTy.getVectorNumElements() * 2);
9819   return DAG.getNode(ISD::BITCAST, dl, VT,
9820                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9821                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9822                                  RHS));
9823 }
9824 
9825 static SDValue tryCombineFixedPointConvert(SDNode *N,
9826                                            TargetLowering::DAGCombinerInfo &DCI,
9827                                            SelectionDAG &DAG) {
9828   // Wait until after everything is legalized to try this. That way we have
9829   // legal vector types and such.
9830   if (DCI.isBeforeLegalizeOps())
9831     return SDValue();
9832   // Transform a scalar conversion of a value from a lane extract into a
9833   // lane extract of a vector conversion. E.g., from foo1 to foo2:
9834   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9835   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9836   //
9837   // The second form interacts better with instruction selection and the
9838   // register allocator to avoid cross-class register copies that aren't
9839   // coalescable due to a lane reference.
9840 
9841   // Check the operand and see if it originates from a lane extract.
9842   SDValue Op1 = N->getOperand(1);
9843   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9844     // Yep, no additional predication needed. Perform the transform.
9845     SDValue IID = N->getOperand(0);
9846     SDValue Shift = N->getOperand(2);
9847     SDValue Vec = Op1.getOperand(0);
9848     SDValue Lane = Op1.getOperand(1);
9849     EVT ResTy = N->getValueType(0);
9850     EVT VecResTy;
9851     SDLoc DL(N);
9852 
9853     // The vector width should be 128 bits by the time we get here, even
9854     // if it started as 64 bits (the extract_vector handling will have
9855     // done so).
9856     assert(Vec.getValueSizeInBits() == 128 &&
9857            "unexpected vector size on extract_vector_elt!");
9858     if (Vec.getValueType() == MVT::v4i32)
9859       VecResTy = MVT::v4f32;
9860     else if (Vec.getValueType() == MVT::v2i64)
9861       VecResTy = MVT::v2f64;
9862     else
9863       llvm_unreachable("unexpected vector type!");
9864 
9865     SDValue Convert =
9866         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9867     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9868   }
9869   return SDValue();
9870 }
9871 
9872 // AArch64 high-vector "long" operations are formed by performing the non-high
9873 // version on an extract_subvector of each operand which gets the high half:
9874 //
9875 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9876 //
9877 // However, there are cases which don't have an extract_high explicitly, but
9878 // have another operation that can be made compatible with one for free. For
9879 // example:
9880 //
9881 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
9882 //
9883 // This routine does the actual conversion of such DUPs, once outer routines
9884 // have determined that everything else is in order.
9885 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9886 // similarly here.
9887 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9888   switch (N.getOpcode()) {
9889   case AArch64ISD::DUP:
9890   case AArch64ISD::DUPLANE8:
9891   case AArch64ISD::DUPLANE16:
9892   case AArch64ISD::DUPLANE32:
9893   case AArch64ISD::DUPLANE64:
9894   case AArch64ISD::MOVI:
9895   case AArch64ISD::MOVIshift:
9896   case AArch64ISD::MOVIedit:
9897   case AArch64ISD::MOVImsl:
9898   case AArch64ISD::MVNIshift:
9899   case AArch64ISD::MVNImsl:
9900     break;
9901   default:
9902     // FMOV could be supported, but isn't very useful, as it would only occur
9903     // if you passed a bitcast' floating point immediate to an eligible long
9904     // integer op (addl, smull, ...).
9905     return SDValue();
9906   }
9907 
9908   MVT NarrowTy = N.getSimpleValueType();
9909   if (!NarrowTy.is64BitVector())
9910     return SDValue();
9911 
9912   MVT ElementTy = NarrowTy.getVectorElementType();
9913   unsigned NumElems = NarrowTy.getVectorNumElements();
9914   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9915 
9916   SDLoc dl(N);
9917   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9918                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9919                      DAG.getConstant(NumElems, dl, MVT::i64));
9920 }
9921 
9922 static bool isEssentiallyExtractHighSubvector(SDValue N) {
9923   if (N.getOpcode() == ISD::BITCAST)
9924     N = N.getOperand(0);
9925   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9926     return false;
9927   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9928          N.getOperand(0).getValueType().getVectorNumElements() / 2;
9929 }
9930 
9931 /// Helper structure to keep track of ISD::SET_CC operands.
9932 struct GenericSetCCInfo {
9933   const SDValue *Opnd0;
9934   const SDValue *Opnd1;
9935   ISD::CondCode CC;
9936 };
9937 
9938 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9939 struct AArch64SetCCInfo {
9940   const SDValue *Cmp;
9941   AArch64CC::CondCode CC;
9942 };
9943 
9944 /// Helper structure to keep track of SetCC information.
9945 union SetCCInfo {
9946   GenericSetCCInfo Generic;
9947   AArch64SetCCInfo AArch64;
9948 };
9949 
9950 /// Helper structure to be able to read SetCC information.  If set to
9951 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9952 /// GenericSetCCInfo.
9953 struct SetCCInfoAndKind {
9954   SetCCInfo Info;
9955   bool IsAArch64;
9956 };
9957 
9958 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9959 /// an
9960 /// AArch64 lowered one.
9961 /// \p SetCCInfo is filled accordingly.
9962 /// \post SetCCInfo is meanginfull only when this function returns true.
9963 /// \return True when Op is a kind of SET_CC operation.
9964 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9965   // If this is a setcc, this is straight forward.
9966   if (Op.getOpcode() == ISD::SETCC) {
9967     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9968     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9969     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9970     SetCCInfo.IsAArch64 = false;
9971     return true;
9972   }
9973   // Otherwise, check if this is a matching csel instruction.
9974   // In other words:
9975   // - csel 1, 0, cc
9976   // - csel 0, 1, !cc
9977   if (Op.getOpcode() != AArch64ISD::CSEL)
9978     return false;
9979   // Set the information about the operands.
9980   // TODO: we want the operands of the Cmp not the csel
9981   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9982   SetCCInfo.IsAArch64 = true;
9983   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9984       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9985 
9986   // Check that the operands matches the constraints:
9987   // (1) Both operands must be constants.
9988   // (2) One must be 1 and the other must be 0.
9989   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9990   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9991 
9992   // Check (1).
9993   if (!TValue || !FValue)
9994     return false;
9995 
9996   // Check (2).
9997   if (!TValue->isOne()) {
9998     // Update the comparison when we are interested in !cc.
9999     std::swap(TValue, FValue);
10000     SetCCInfo.Info.AArch64.CC =
10001         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10002   }
10003   return TValue->isOne() && FValue->isNullValue();
10004 }
10005 
10006 // Returns true if Op is setcc or zext of setcc.
10007 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10008   if (isSetCC(Op, Info))
10009     return true;
10010   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10011     isSetCC(Op->getOperand(0), Info));
10012 }
10013 
10014 // The folding we want to perform is:
10015 // (add x, [zext] (setcc cc ...) )
10016 //   -->
10017 // (csel x, (add x, 1), !cc ...)
10018 //
10019 // The latter will get matched to a CSINC instruction.
10020 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10021   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10022   SDValue LHS = Op->getOperand(0);
10023   SDValue RHS = Op->getOperand(1);
10024   SetCCInfoAndKind InfoAndKind;
10025 
10026   // If neither operand is a SET_CC, give up.
10027   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10028     std::swap(LHS, RHS);
10029     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10030       return SDValue();
10031   }
10032 
10033   // FIXME: This could be generatized to work for FP comparisons.
10034   EVT CmpVT = InfoAndKind.IsAArch64
10035                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10036                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10037   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10038     return SDValue();
10039 
10040   SDValue CCVal;
10041   SDValue Cmp;
10042   SDLoc dl(Op);
10043   if (InfoAndKind.IsAArch64) {
10044     CCVal = DAG.getConstant(
10045         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10046         MVT::i32);
10047     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10048   } else
10049     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10050                       *InfoAndKind.Info.Generic.Opnd1,
10051                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10052                       CCVal, DAG, dl);
10053 
10054   EVT VT = Op->getValueType(0);
10055   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10056   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10057 }
10058 
10059 // The basic add/sub long vector instructions have variants with "2" on the end
10060 // which act on the high-half of their inputs. They are normally matched by
10061 // patterns like:
10062 //
10063 // (add (zeroext (extract_high LHS)),
10064 //      (zeroext (extract_high RHS)))
10065 // -> uaddl2 vD, vN, vM
10066 //
10067 // However, if one of the extracts is something like a duplicate, this
10068 // instruction can still be used profitably. This function puts the DAG into a
10069 // more appropriate form for those patterns to trigger.
10070 static SDValue performAddSubLongCombine(SDNode *N,
10071                                         TargetLowering::DAGCombinerInfo &DCI,
10072                                         SelectionDAG &DAG) {
10073   if (DCI.isBeforeLegalizeOps())
10074     return SDValue();
10075 
10076   MVT VT = N->getSimpleValueType(0);
10077   if (!VT.is128BitVector()) {
10078     if (N->getOpcode() == ISD::ADD)
10079       return performSetccAddFolding(N, DAG);
10080     return SDValue();
10081   }
10082 
10083   // Make sure both branches are extended in the same way.
10084   SDValue LHS = N->getOperand(0);
10085   SDValue RHS = N->getOperand(1);
10086   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10087        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10088       LHS.getOpcode() != RHS.getOpcode())
10089     return SDValue();
10090 
10091   unsigned ExtType = LHS.getOpcode();
10092 
10093   // It's not worth doing if at least one of the inputs isn't already an
10094   // extract, but we don't know which it'll be so we have to try both.
10095   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10096     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10097     if (!RHS.getNode())
10098       return SDValue();
10099 
10100     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10101   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10102     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10103     if (!LHS.getNode())
10104       return SDValue();
10105 
10106     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10107   }
10108 
10109   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10110 }
10111 
10112 // Massage DAGs which we can use the high-half "long" operations on into
10113 // something isel will recognize better. E.g.
10114 //
10115 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10116 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10117 //                     (extract_high (v2i64 (dup128 scalar)))))
10118 //
10119 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10120                                        TargetLowering::DAGCombinerInfo &DCI,
10121                                        SelectionDAG &DAG) {
10122   if (DCI.isBeforeLegalizeOps())
10123     return SDValue();
10124 
10125   SDValue LHS = N->getOperand(1);
10126   SDValue RHS = N->getOperand(2);
10127   assert(LHS.getValueType().is64BitVector() &&
10128          RHS.getValueType().is64BitVector() &&
10129          "unexpected shape for long operation");
10130 
10131   // Either node could be a DUP, but it's not worth doing both of them (you'd
10132   // just as well use the non-high version) so look for a corresponding extract
10133   // operation on the other "wing".
10134   if (isEssentiallyExtractHighSubvector(LHS)) {
10135     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10136     if (!RHS.getNode())
10137       return SDValue();
10138   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10139     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10140     if (!LHS.getNode())
10141       return SDValue();
10142   }
10143 
10144   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10145                      N->getOperand(0), LHS, RHS);
10146 }
10147 
10148 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10149   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10150   unsigned ElemBits = ElemTy.getSizeInBits();
10151 
10152   int64_t ShiftAmount;
10153   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10154     APInt SplatValue, SplatUndef;
10155     unsigned SplatBitSize;
10156     bool HasAnyUndefs;
10157     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10158                               HasAnyUndefs, ElemBits) ||
10159         SplatBitSize != ElemBits)
10160       return SDValue();
10161 
10162     ShiftAmount = SplatValue.getSExtValue();
10163   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10164     ShiftAmount = CVN->getSExtValue();
10165   } else
10166     return SDValue();
10167 
10168   unsigned Opcode;
10169   bool IsRightShift;
10170   switch (IID) {
10171   default:
10172     llvm_unreachable("Unknown shift intrinsic");
10173   case Intrinsic::aarch64_neon_sqshl:
10174     Opcode = AArch64ISD::SQSHL_I;
10175     IsRightShift = false;
10176     break;
10177   case Intrinsic::aarch64_neon_uqshl:
10178     Opcode = AArch64ISD::UQSHL_I;
10179     IsRightShift = false;
10180     break;
10181   case Intrinsic::aarch64_neon_srshl:
10182     Opcode = AArch64ISD::SRSHR_I;
10183     IsRightShift = true;
10184     break;
10185   case Intrinsic::aarch64_neon_urshl:
10186     Opcode = AArch64ISD::URSHR_I;
10187     IsRightShift = true;
10188     break;
10189   case Intrinsic::aarch64_neon_sqshlu:
10190     Opcode = AArch64ISD::SQSHLU_I;
10191     IsRightShift = false;
10192     break;
10193   }
10194 
10195   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10196     SDLoc dl(N);
10197     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10198                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10199   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10200     SDLoc dl(N);
10201     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10202                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
10203   }
10204 
10205   return SDValue();
10206 }
10207 
10208 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10209 // the intrinsics must be legal and take an i32, this means there's almost
10210 // certainly going to be a zext in the DAG which we can eliminate.
10211 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10212   SDValue AndN = N->getOperand(2);
10213   if (AndN.getOpcode() != ISD::AND)
10214     return SDValue();
10215 
10216   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10217   if (!CMask || CMask->getZExtValue() != Mask)
10218     return SDValue();
10219 
10220   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10221                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10222 }
10223 
10224 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10225                                            SelectionDAG &DAG) {
10226   SDLoc dl(N);
10227   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10228                      DAG.getNode(Opc, dl,
10229                                  N->getOperand(1).getSimpleValueType(),
10230                                  N->getOperand(1)),
10231                      DAG.getConstant(0, dl, MVT::i64));
10232 }
10233 
10234 static SDValue performIntrinsicCombine(SDNode *N,
10235                                        TargetLowering::DAGCombinerInfo &DCI,
10236                                        const AArch64Subtarget *Subtarget) {
10237   SelectionDAG &DAG = DCI.DAG;
10238   unsigned IID = getIntrinsicID(N);
10239   switch (IID) {
10240   default:
10241     break;
10242   case Intrinsic::aarch64_neon_vcvtfxs2fp:
10243   case Intrinsic::aarch64_neon_vcvtfxu2fp:
10244     return tryCombineFixedPointConvert(N, DCI, DAG);
10245   case Intrinsic::aarch64_neon_saddv:
10246     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10247   case Intrinsic::aarch64_neon_uaddv:
10248     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10249   case Intrinsic::aarch64_neon_sminv:
10250     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10251   case Intrinsic::aarch64_neon_uminv:
10252     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10253   case Intrinsic::aarch64_neon_smaxv:
10254     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10255   case Intrinsic::aarch64_neon_umaxv:
10256     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10257   case Intrinsic::aarch64_neon_fmax:
10258     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10259                        N->getOperand(1), N->getOperand(2));
10260   case Intrinsic::aarch64_neon_fmin:
10261     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10262                        N->getOperand(1), N->getOperand(2));
10263   case Intrinsic::aarch64_neon_fmaxnm:
10264     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10265                        N->getOperand(1), N->getOperand(2));
10266   case Intrinsic::aarch64_neon_fminnm:
10267     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10268                        N->getOperand(1), N->getOperand(2));
10269   case Intrinsic::aarch64_neon_smull:
10270   case Intrinsic::aarch64_neon_umull:
10271   case Intrinsic::aarch64_neon_pmull:
10272   case Intrinsic::aarch64_neon_sqdmull:
10273     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10274   case Intrinsic::aarch64_neon_sqshl:
10275   case Intrinsic::aarch64_neon_uqshl:
10276   case Intrinsic::aarch64_neon_sqshlu:
10277   case Intrinsic::aarch64_neon_srshl:
10278   case Intrinsic::aarch64_neon_urshl:
10279     return tryCombineShiftImm(IID, N, DAG);
10280   case Intrinsic::aarch64_crc32b:
10281   case Intrinsic::aarch64_crc32cb:
10282     return tryCombineCRC32(0xff, N, DAG);
10283   case Intrinsic::aarch64_crc32h:
10284   case Intrinsic::aarch64_crc32ch:
10285     return tryCombineCRC32(0xffff, N, DAG);
10286   }
10287   return SDValue();
10288 }
10289 
10290 static SDValue performExtendCombine(SDNode *N,
10291                                     TargetLowering::DAGCombinerInfo &DCI,
10292                                     SelectionDAG &DAG) {
10293   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10294   // we can convert that DUP into another extract_high (of a bigger DUP), which
10295   // helps the backend to decide that an sabdl2 would be useful, saving a real
10296   // extract_high operation.
10297   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10298       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10299     SDNode *ABDNode = N->getOperand(0).getNode();
10300     unsigned IID = getIntrinsicID(ABDNode);
10301     if (IID == Intrinsic::aarch64_neon_sabd ||
10302         IID == Intrinsic::aarch64_neon_uabd) {
10303       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10304       if (!NewABD.getNode())
10305         return SDValue();
10306 
10307       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10308                          NewABD);
10309     }
10310   }
10311 
10312   // This is effectively a custom type legalization for AArch64.
10313   //
10314   // Type legalization will split an extend of a small, legal, type to a larger
10315   // illegal type by first splitting the destination type, often creating
10316   // illegal source types, which then get legalized in isel-confusing ways,
10317   // leading to really terrible codegen. E.g.,
10318   //   %result = v8i32 sext v8i8 %value
10319   // becomes
10320   //   %losrc = extract_subreg %value, ...
10321   //   %hisrc = extract_subreg %value, ...
10322   //   %lo = v4i32 sext v4i8 %losrc
10323   //   %hi = v4i32 sext v4i8 %hisrc
10324   // Things go rapidly downhill from there.
10325   //
10326   // For AArch64, the [sz]ext vector instructions can only go up one element
10327   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10328   // take two instructions.
10329   //
10330   // This implies that the most efficient way to do the extend from v8i8
10331   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10332   // the normal splitting to happen for the v8i16->v8i32.
10333 
10334   // This is pre-legalization to catch some cases where the default
10335   // type legalization will create ill-tempered code.
10336   if (!DCI.isBeforeLegalizeOps())
10337     return SDValue();
10338 
10339   // We're only interested in cleaning things up for non-legal vector types
10340   // here. If both the source and destination are legal, things will just
10341   // work naturally without any fiddling.
10342   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10343   EVT ResVT = N->getValueType(0);
10344   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10345     return SDValue();
10346   // If the vector type isn't a simple VT, it's beyond the scope of what
10347   // we're  worried about here. Let legalization do its thing and hope for
10348   // the best.
10349   SDValue Src = N->getOperand(0);
10350   EVT SrcVT = Src->getValueType(0);
10351   if (!ResVT.isSimple() || !SrcVT.isSimple())
10352     return SDValue();
10353 
10354   // If the source VT is a 64-bit vector, we can play games and get the
10355   // better results we want.
10356   if (SrcVT.getSizeInBits() != 64)
10357     return SDValue();
10358 
10359   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10360   unsigned ElementCount = SrcVT.getVectorNumElements();
10361   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10362   SDLoc DL(N);
10363   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10364 
10365   // Now split the rest of the operation into two halves, each with a 64
10366   // bit source.
10367   EVT LoVT, HiVT;
10368   SDValue Lo, Hi;
10369   unsigned NumElements = ResVT.getVectorNumElements();
10370   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10371   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10372                                  ResVT.getVectorElementType(), NumElements / 2);
10373 
10374   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10375                                LoVT.getVectorNumElements());
10376   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10377                    DAG.getConstant(0, DL, MVT::i64));
10378   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10379                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10380   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10381   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10382 
10383   // Now combine the parts back together so we still have a single result
10384   // like the combiner expects.
10385   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10386 }
10387 
10388 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10389                                SDValue SplatVal, unsigned NumVecElts) {
10390   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10391   unsigned OrigAlignment = St.getAlignment();
10392   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10393 
10394   // Create scalar stores. This is at least as good as the code sequence for a
10395   // split unaligned store which is a dup.s, ext.b, and two stores.
10396   // Most of the time the three stores should be replaced by store pair
10397   // instructions (stp).
10398   SDLoc DL(&St);
10399   SDValue BasePtr = St.getBasePtr();
10400   uint64_t BaseOffset = 0;
10401 
10402   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10403   SDValue NewST1 =
10404       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10405                    OrigAlignment, St.getMemOperand()->getFlags());
10406 
10407   // As this in ISel, we will not merge this add which may degrade results.
10408   if (BasePtr->getOpcode() == ISD::ADD &&
10409       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10410     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10411     BasePtr = BasePtr->getOperand(0);
10412   }
10413 
10414   unsigned Offset = EltOffset;
10415   while (--NumVecElts) {
10416     unsigned Alignment = MinAlign(OrigAlignment, Offset);
10417     SDValue OffsetPtr =
10418         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10419                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10420     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10421                           PtrInfo.getWithOffset(Offset), Alignment,
10422                           St.getMemOperand()->getFlags());
10423     Offset += EltOffset;
10424   }
10425   return NewST1;
10426 }
10427 
10428 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
10429 /// load store optimizer pass will merge them to store pair stores.  This should
10430 /// be better than a movi to create the vector zero followed by a vector store
10431 /// if the zero constant is not re-used, since one instructions and one register
10432 /// live range will be removed.
10433 ///
10434 /// For example, the final generated code should be:
10435 ///
10436 ///   stp xzr, xzr, [x0]
10437 ///
10438 /// instead of:
10439 ///
10440 ///   movi v0.2d, #0
10441 ///   str q0, [x0]
10442 ///
10443 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10444   SDValue StVal = St.getValue();
10445   EVT VT = StVal.getValueType();
10446 
10447   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10448   // 2, 3 or 4 i32 elements.
10449   int NumVecElts = VT.getVectorNumElements();
10450   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10451          VT.getVectorElementType().getSizeInBits() == 64) ||
10452         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10453          VT.getVectorElementType().getSizeInBits() == 32)))
10454     return SDValue();
10455 
10456   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10457     return SDValue();
10458 
10459   // If the zero constant has more than one use then the vector store could be
10460   // better since the constant mov will be amortized and stp q instructions
10461   // should be able to be formed.
10462   if (!StVal.hasOneUse())
10463     return SDValue();
10464 
10465   // If the store is truncating then it's going down to i16 or smaller, which
10466   // means it can be implemented in a single store anyway.
10467   if (St.isTruncatingStore())
10468     return SDValue();
10469 
10470   // If the immediate offset of the address operand is too large for the stp
10471   // instruction, then bail out.
10472   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10473     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10474     if (Offset < -512 || Offset > 504)
10475       return SDValue();
10476   }
10477 
10478   for (int I = 0; I < NumVecElts; ++I) {
10479     SDValue EltVal = StVal.getOperand(I);
10480     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10481       return SDValue();
10482   }
10483 
10484   // Use a CopyFromReg WZR/XZR here to prevent
10485   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10486   SDLoc DL(&St);
10487   unsigned ZeroReg;
10488   EVT ZeroVT;
10489   if (VT.getVectorElementType().getSizeInBits() == 32) {
10490     ZeroReg = AArch64::WZR;
10491     ZeroVT = MVT::i32;
10492   } else {
10493     ZeroReg = AArch64::XZR;
10494     ZeroVT = MVT::i64;
10495   }
10496   SDValue SplatVal =
10497       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10498   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10499 }
10500 
10501 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10502 /// value. The load store optimizer pass will merge them to store pair stores.
10503 /// This has better performance than a splat of the scalar followed by a split
10504 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10505 /// followed by an ext.b and two stores.
10506 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10507   SDValue StVal = St.getValue();
10508   EVT VT = StVal.getValueType();
10509 
10510   // Don't replace floating point stores, they possibly won't be transformed to
10511   // stp because of the store pair suppress pass.
10512   if (VT.isFloatingPoint())
10513     return SDValue();
10514 
10515   // We can express a splat as store pair(s) for 2 or 4 elements.
10516   unsigned NumVecElts = VT.getVectorNumElements();
10517   if (NumVecElts != 4 && NumVecElts != 2)
10518     return SDValue();
10519 
10520   // If the store is truncating then it's going down to i16 or smaller, which
10521   // means it can be implemented in a single store anyway.
10522   if (St.isTruncatingStore())
10523     return SDValue();
10524 
10525   // Check that this is a splat.
10526   // Make sure that each of the relevant vector element locations are inserted
10527   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10528   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10529   SDValue SplatVal;
10530   for (unsigned I = 0; I < NumVecElts; ++I) {
10531     // Check for insert vector elements.
10532     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10533       return SDValue();
10534 
10535     // Check that same value is inserted at each vector element.
10536     if (I == 0)
10537       SplatVal = StVal.getOperand(1);
10538     else if (StVal.getOperand(1) != SplatVal)
10539       return SDValue();
10540 
10541     // Check insert element index.
10542     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10543     if (!CIndex)
10544       return SDValue();
10545     uint64_t IndexVal = CIndex->getZExtValue();
10546     if (IndexVal >= NumVecElts)
10547       return SDValue();
10548     IndexNotInserted.reset(IndexVal);
10549 
10550     StVal = StVal.getOperand(0);
10551   }
10552   // Check that all vector element locations were inserted to.
10553   if (IndexNotInserted.any())
10554       return SDValue();
10555 
10556   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10557 }
10558 
10559 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10560                            SelectionDAG &DAG,
10561                            const AArch64Subtarget *Subtarget) {
10562 
10563   StoreSDNode *S = cast<StoreSDNode>(N);
10564   if (S->isVolatile() || S->isIndexed())
10565     return SDValue();
10566 
10567   SDValue StVal = S->getValue();
10568   EVT VT = StVal.getValueType();
10569   if (!VT.isVector())
10570     return SDValue();
10571 
10572   // If we get a splat of zeros, convert this vector store to a store of
10573   // scalars. They will be merged into store pairs of xzr thereby removing one
10574   // instruction and one register.
10575   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10576     return ReplacedZeroSplat;
10577 
10578   // FIXME: The logic for deciding if an unaligned store should be split should
10579   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10580   // a call to that function here.
10581 
10582   if (!Subtarget->isMisaligned128StoreSlow())
10583     return SDValue();
10584 
10585   // Don't split at -Oz.
10586   if (DAG.getMachineFunction().getFunction().hasMinSize())
10587     return SDValue();
10588 
10589   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10590   // those up regresses performance on micro-benchmarks and olden/bh.
10591   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10592     return SDValue();
10593 
10594   // Split unaligned 16B stores. They are terrible for performance.
10595   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10596   // extensions can use this to mark that it does not want splitting to happen
10597   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10598   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10599   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10600       S->getAlignment() <= 2)
10601     return SDValue();
10602 
10603   // If we get a splat of a scalar convert this vector store to a store of
10604   // scalars. They will be merged into store pairs thereby removing two
10605   // instructions.
10606   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10607     return ReplacedSplat;
10608 
10609   SDLoc DL(S);
10610   unsigned NumElts = VT.getVectorNumElements() / 2;
10611   // Split VT into two.
10612   EVT HalfVT =
10613       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10614   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10615                                    DAG.getConstant(0, DL, MVT::i64));
10616   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10617                                    DAG.getConstant(NumElts, DL, MVT::i64));
10618   SDValue BasePtr = S->getBasePtr();
10619   SDValue NewST1 =
10620       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10621                    S->getAlignment(), S->getMemOperand()->getFlags());
10622   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10623                                   DAG.getConstant(8, DL, MVT::i64));
10624   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10625                       S->getPointerInfo(), S->getAlignment(),
10626                       S->getMemOperand()->getFlags());
10627 }
10628 
10629 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10630 /// post-increment LD1R.
10631 static SDValue performPostLD1Combine(SDNode *N,
10632                                      TargetLowering::DAGCombinerInfo &DCI,
10633                                      bool IsLaneOp) {
10634   if (DCI.isBeforeLegalizeOps())
10635     return SDValue();
10636 
10637   SelectionDAG &DAG = DCI.DAG;
10638   EVT VT = N->getValueType(0);
10639 
10640   unsigned LoadIdx = IsLaneOp ? 1 : 0;
10641   SDNode *LD = N->getOperand(LoadIdx).getNode();
10642   // If it is not LOAD, can not do such combine.
10643   if (LD->getOpcode() != ISD::LOAD)
10644     return SDValue();
10645 
10646   // The vector lane must be a constant in the LD1LANE opcode.
10647   SDValue Lane;
10648   if (IsLaneOp) {
10649     Lane = N->getOperand(2);
10650     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10651     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10652       return SDValue();
10653   }
10654 
10655   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10656   EVT MemVT = LoadSDN->getMemoryVT();
10657   // Check if memory operand is the same type as the vector element.
10658   if (MemVT != VT.getVectorElementType())
10659     return SDValue();
10660 
10661   // Check if there are other uses. If so, do not combine as it will introduce
10662   // an extra load.
10663   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10664        ++UI) {
10665     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10666       continue;
10667     if (*UI != N)
10668       return SDValue();
10669   }
10670 
10671   SDValue Addr = LD->getOperand(1);
10672   SDValue Vector = N->getOperand(0);
10673   // Search for a use of the address operand that is an increment.
10674   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10675        Addr.getNode()->use_end(); UI != UE; ++UI) {
10676     SDNode *User = *UI;
10677     if (User->getOpcode() != ISD::ADD
10678         || UI.getUse().getResNo() != Addr.getResNo())
10679       continue;
10680 
10681     // If the increment is a constant, it must match the memory ref size.
10682     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10683     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10684       uint32_t IncVal = CInc->getZExtValue();
10685       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10686       if (IncVal != NumBytes)
10687         continue;
10688       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10689     }
10690 
10691     // To avoid cycle construction make sure that neither the load nor the add
10692     // are predecessors to each other or the Vector.
10693     SmallPtrSet<const SDNode *, 32> Visited;
10694     SmallVector<const SDNode *, 16> Worklist;
10695     Visited.insert(N);
10696     Worklist.push_back(User);
10697     Worklist.push_back(LD);
10698     Worklist.push_back(Vector.getNode());
10699     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10700         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10701       continue;
10702 
10703     SmallVector<SDValue, 8> Ops;
10704     Ops.push_back(LD->getOperand(0));  // Chain
10705     if (IsLaneOp) {
10706       Ops.push_back(Vector);           // The vector to be inserted
10707       Ops.push_back(Lane);             // The lane to be inserted in the vector
10708     }
10709     Ops.push_back(Addr);
10710     Ops.push_back(Inc);
10711 
10712     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10713     SDVTList SDTys = DAG.getVTList(Tys);
10714     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10715     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10716                                            MemVT,
10717                                            LoadSDN->getMemOperand());
10718 
10719     // Update the uses.
10720     SDValue NewResults[] = {
10721         SDValue(LD, 0),            // The result of load
10722         SDValue(UpdN.getNode(), 2) // Chain
10723     };
10724     DCI.CombineTo(LD, NewResults);
10725     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
10726     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
10727 
10728     break;
10729   }
10730   return SDValue();
10731 }
10732 
10733 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10734 /// address translation.
10735 static bool performTBISimplification(SDValue Addr,
10736                                      TargetLowering::DAGCombinerInfo &DCI,
10737                                      SelectionDAG &DAG) {
10738   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10739   KnownBits Known;
10740   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10741                                         !DCI.isBeforeLegalizeOps());
10742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10743   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10744     DCI.CommitTargetLoweringOpt(TLO);
10745     return true;
10746   }
10747   return false;
10748 }
10749 
10750 static SDValue performSTORECombine(SDNode *N,
10751                                    TargetLowering::DAGCombinerInfo &DCI,
10752                                    SelectionDAG &DAG,
10753                                    const AArch64Subtarget *Subtarget) {
10754   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10755     return Split;
10756 
10757   if (Subtarget->supportsAddressTopByteIgnored() &&
10758       performTBISimplification(N->getOperand(2), DCI, DAG))
10759     return SDValue(N, 0);
10760 
10761   return SDValue();
10762 }
10763 
10764 
10765 /// Target-specific DAG combine function for NEON load/store intrinsics
10766 /// to merge base address updates.
10767 static SDValue performNEONPostLDSTCombine(SDNode *N,
10768                                           TargetLowering::DAGCombinerInfo &DCI,
10769                                           SelectionDAG &DAG) {
10770   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10771     return SDValue();
10772 
10773   unsigned AddrOpIdx = N->getNumOperands() - 1;
10774   SDValue Addr = N->getOperand(AddrOpIdx);
10775 
10776   // Search for a use of the address operand that is an increment.
10777   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10778        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10779     SDNode *User = *UI;
10780     if (User->getOpcode() != ISD::ADD ||
10781         UI.getUse().getResNo() != Addr.getResNo())
10782       continue;
10783 
10784     // Check that the add is independent of the load/store.  Otherwise, folding
10785     // it would create a cycle.
10786     SmallPtrSet<const SDNode *, 32> Visited;
10787     SmallVector<const SDNode *, 16> Worklist;
10788     Visited.insert(Addr.getNode());
10789     Worklist.push_back(N);
10790     Worklist.push_back(User);
10791     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10792         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10793       continue;
10794 
10795     // Find the new opcode for the updating load/store.
10796     bool IsStore = false;
10797     bool IsLaneOp = false;
10798     bool IsDupOp = false;
10799     unsigned NewOpc = 0;
10800     unsigned NumVecs = 0;
10801     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10802     switch (IntNo) {
10803     default: llvm_unreachable("unexpected intrinsic for Neon base update");
10804     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
10805       NumVecs = 2; break;
10806     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
10807       NumVecs = 3; break;
10808     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
10809       NumVecs = 4; break;
10810     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
10811       NumVecs = 2; IsStore = true; break;
10812     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
10813       NumVecs = 3; IsStore = true; break;
10814     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
10815       NumVecs = 4; IsStore = true; break;
10816     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
10817       NumVecs = 2; break;
10818     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
10819       NumVecs = 3; break;
10820     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
10821       NumVecs = 4; break;
10822     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
10823       NumVecs = 2; IsStore = true; break;
10824     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
10825       NumVecs = 3; IsStore = true; break;
10826     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
10827       NumVecs = 4; IsStore = true; break;
10828     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
10829       NumVecs = 2; IsDupOp = true; break;
10830     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
10831       NumVecs = 3; IsDupOp = true; break;
10832     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
10833       NumVecs = 4; IsDupOp = true; break;
10834     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
10835       NumVecs = 2; IsLaneOp = true; break;
10836     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
10837       NumVecs = 3; IsLaneOp = true; break;
10838     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
10839       NumVecs = 4; IsLaneOp = true; break;
10840     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
10841       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10842     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
10843       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10844     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
10845       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10846     }
10847 
10848     EVT VecTy;
10849     if (IsStore)
10850       VecTy = N->getOperand(2).getValueType();
10851     else
10852       VecTy = N->getValueType(0);
10853 
10854     // If the increment is a constant, it must match the memory ref size.
10855     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10856     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10857       uint32_t IncVal = CInc->getZExtValue();
10858       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10859       if (IsLaneOp || IsDupOp)
10860         NumBytes /= VecTy.getVectorNumElements();
10861       if (IncVal != NumBytes)
10862         continue;
10863       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10864     }
10865     SmallVector<SDValue, 8> Ops;
10866     Ops.push_back(N->getOperand(0)); // Incoming chain
10867     // Load lane and store have vector list as input.
10868     if (IsLaneOp || IsStore)
10869       for (unsigned i = 2; i < AddrOpIdx; ++i)
10870         Ops.push_back(N->getOperand(i));
10871     Ops.push_back(Addr); // Base register
10872     Ops.push_back(Inc);
10873 
10874     // Return Types.
10875     EVT Tys[6];
10876     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10877     unsigned n;
10878     for (n = 0; n < NumResultVecs; ++n)
10879       Tys[n] = VecTy;
10880     Tys[n++] = MVT::i64;  // Type of write back register
10881     Tys[n] = MVT::Other;  // Type of the chain
10882     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10883 
10884     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10885     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10886                                            MemInt->getMemoryVT(),
10887                                            MemInt->getMemOperand());
10888 
10889     // Update the uses.
10890     std::vector<SDValue> NewResults;
10891     for (unsigned i = 0; i < NumResultVecs; ++i) {
10892       NewResults.push_back(SDValue(UpdN.getNode(), i));
10893     }
10894     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10895     DCI.CombineTo(N, NewResults);
10896     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10897 
10898     break;
10899   }
10900   return SDValue();
10901 }
10902 
10903 // Checks to see if the value is the prescribed width and returns information
10904 // about its extension mode.
10905 static
10906 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10907   ExtType = ISD::NON_EXTLOAD;
10908   switch(V.getNode()->getOpcode()) {
10909   default:
10910     return false;
10911   case ISD::LOAD: {
10912     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10913     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10914        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10915       ExtType = LoadNode->getExtensionType();
10916       return true;
10917     }
10918     return false;
10919   }
10920   case ISD::AssertSext: {
10921     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10922     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10923        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10924       ExtType = ISD::SEXTLOAD;
10925       return true;
10926     }
10927     return false;
10928   }
10929   case ISD::AssertZext: {
10930     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10931     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10932        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10933       ExtType = ISD::ZEXTLOAD;
10934       return true;
10935     }
10936     return false;
10937   }
10938   case ISD::Constant:
10939   case ISD::TargetConstant: {
10940     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10941            1LL << (width - 1);
10942   }
10943   }
10944 
10945   return true;
10946 }
10947 
10948 // This function does a whole lot of voodoo to determine if the tests are
10949 // equivalent without and with a mask. Essentially what happens is that given a
10950 // DAG resembling:
10951 //
10952 //  +-------------+ +-------------+ +-------------+ +-------------+
10953 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
10954 //  +-------------+ +-------------+ +-------------+ +-------------+
10955 //           |           |           |               |
10956 //           V           V           |    +----------+
10957 //          +-------------+  +----+  |    |
10958 //          |     ADD     |  |0xff|  |    |
10959 //          +-------------+  +----+  |    |
10960 //                  |           |    |    |
10961 //                  V           V    |    |
10962 //                 +-------------+   |    |
10963 //                 |     AND     |   |    |
10964 //                 +-------------+   |    |
10965 //                      |            |    |
10966 //                      +-----+      |    |
10967 //                            |      |    |
10968 //                            V      V    V
10969 //                           +-------------+
10970 //                           |     CMP     |
10971 //                           +-------------+
10972 //
10973 // The AND node may be safely removed for some combinations of inputs. In
10974 // particular we need to take into account the extension type of the Input,
10975 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10976 // width of the input (this can work for any width inputs, the above graph is
10977 // specific to 8 bits.
10978 //
10979 // The specific equations were worked out by generating output tables for each
10980 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10981 // problem was simplified by working with 4 bit inputs, which means we only
10982 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10983 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10984 // patterns present in both extensions (0,7). For every distinct set of
10985 // AddConstant and CompConstants bit patterns we can consider the masked and
10986 // unmasked versions to be equivalent if the result of this function is true for
10987 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10988 //
10989 //   sub      w8, w0, w1
10990 //   and      w10, w8, #0x0f
10991 //   cmp      w8, w2
10992 //   cset     w9, AArch64CC
10993 //   cmp      w10, w2
10994 //   cset     w11, AArch64CC
10995 //   cmp      w9, w11
10996 //   cset     w0, eq
10997 //   ret
10998 //
10999 // Since the above function shows when the outputs are equivalent it defines
11000 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11001 // would be expensive to run during compiles. The equations below were written
11002 // in a test harness that confirmed they gave equivalent outputs to the above
11003 // for all inputs function, so they can be used determine if the removal is
11004 // legal instead.
11005 //
11006 // isEquivalentMaskless() is the code for testing if the AND can be removed
11007 // factored out of the DAG recognition as the DAG can take several forms.
11008 
11009 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11010                                  ISD::LoadExtType ExtType, int AddConstant,
11011                                  int CompConstant) {
11012   // By being careful about our equations and only writing the in term
11013   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11014   // make them generally applicable to all bit widths.
11015   int MaxUInt = (1 << width);
11016 
11017   // For the purposes of these comparisons sign extending the type is
11018   // equivalent to zero extending the add and displacing it by half the integer
11019   // width. Provided we are careful and make sure our equations are valid over
11020   // the whole range we can just adjust the input and avoid writing equations
11021   // for sign extended inputs.
11022   if (ExtType == ISD::SEXTLOAD)
11023     AddConstant -= (1 << (width-1));
11024 
11025   switch(CC) {
11026   case AArch64CC::LE:
11027   case AArch64CC::GT:
11028     if ((AddConstant == 0) ||
11029         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11030         (AddConstant >= 0 && CompConstant < 0) ||
11031         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11032       return true;
11033     break;
11034   case AArch64CC::LT:
11035   case AArch64CC::GE:
11036     if ((AddConstant == 0) ||
11037         (AddConstant >= 0 && CompConstant <= 0) ||
11038         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11039       return true;
11040     break;
11041   case AArch64CC::HI:
11042   case AArch64CC::LS:
11043     if ((AddConstant >= 0 && CompConstant < 0) ||
11044        (AddConstant <= 0 && CompConstant >= -1 &&
11045         CompConstant < AddConstant + MaxUInt))
11046       return true;
11047    break;
11048   case AArch64CC::PL:
11049   case AArch64CC::MI:
11050     if ((AddConstant == 0) ||
11051         (AddConstant > 0 && CompConstant <= 0) ||
11052         (AddConstant < 0 && CompConstant <= AddConstant))
11053       return true;
11054     break;
11055   case AArch64CC::LO:
11056   case AArch64CC::HS:
11057     if ((AddConstant >= 0 && CompConstant <= 0) ||
11058         (AddConstant <= 0 && CompConstant >= 0 &&
11059          CompConstant <= AddConstant + MaxUInt))
11060       return true;
11061     break;
11062   case AArch64CC::EQ:
11063   case AArch64CC::NE:
11064     if ((AddConstant > 0 && CompConstant < 0) ||
11065         (AddConstant < 0 && CompConstant >= 0 &&
11066          CompConstant < AddConstant + MaxUInt) ||
11067         (AddConstant >= 0 && CompConstant >= 0 &&
11068          CompConstant >= AddConstant) ||
11069         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11070       return true;
11071     break;
11072   case AArch64CC::VS:
11073   case AArch64CC::VC:
11074   case AArch64CC::AL:
11075   case AArch64CC::NV:
11076     return true;
11077   case AArch64CC::Invalid:
11078     break;
11079   }
11080 
11081   return false;
11082 }
11083 
11084 static
11085 SDValue performCONDCombine(SDNode *N,
11086                            TargetLowering::DAGCombinerInfo &DCI,
11087                            SelectionDAG &DAG, unsigned CCIndex,
11088                            unsigned CmpIndex) {
11089   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11090   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11091   unsigned CondOpcode = SubsNode->getOpcode();
11092 
11093   if (CondOpcode != AArch64ISD::SUBS)
11094     return SDValue();
11095 
11096   // There is a SUBS feeding this condition. Is it fed by a mask we can
11097   // use?
11098 
11099   SDNode *AndNode = SubsNode->getOperand(0).getNode();
11100   unsigned MaskBits = 0;
11101 
11102   if (AndNode->getOpcode() != ISD::AND)
11103     return SDValue();
11104 
11105   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11106     uint32_t CNV = CN->getZExtValue();
11107     if (CNV == 255)
11108       MaskBits = 8;
11109     else if (CNV == 65535)
11110       MaskBits = 16;
11111   }
11112 
11113   if (!MaskBits)
11114     return SDValue();
11115 
11116   SDValue AddValue = AndNode->getOperand(0);
11117 
11118   if (AddValue.getOpcode() != ISD::ADD)
11119     return SDValue();
11120 
11121   // The basic dag structure is correct, grab the inputs and validate them.
11122 
11123   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11124   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11125   SDValue SubsInputValue = SubsNode->getOperand(1);
11126 
11127   // The mask is present and the provenance of all the values is a smaller type,
11128   // lets see if the mask is superfluous.
11129 
11130   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11131       !isa<ConstantSDNode>(SubsInputValue.getNode()))
11132     return SDValue();
11133 
11134   ISD::LoadExtType ExtType;
11135 
11136   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11137       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11138       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11139     return SDValue();
11140 
11141   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11142                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11143                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11144     return SDValue();
11145 
11146   // The AND is not necessary, remove it.
11147 
11148   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11149                                SubsNode->getValueType(1));
11150   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11151 
11152   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11153   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11154 
11155   return SDValue(N, 0);
11156 }
11157 
11158 // Optimize compare with zero and branch.
11159 static SDValue performBRCONDCombine(SDNode *N,
11160                                     TargetLowering::DAGCombinerInfo &DCI,
11161                                     SelectionDAG &DAG) {
11162   MachineFunction &MF = DAG.getMachineFunction();
11163   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11164   // will not be produced, as they are conditional branch instructions that do
11165   // not set flags.
11166   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11167     return SDValue();
11168 
11169   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11170     N = NV.getNode();
11171   SDValue Chain = N->getOperand(0);
11172   SDValue Dest = N->getOperand(1);
11173   SDValue CCVal = N->getOperand(2);
11174   SDValue Cmp = N->getOperand(3);
11175 
11176   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11177   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11178   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11179     return SDValue();
11180 
11181   unsigned CmpOpc = Cmp.getOpcode();
11182   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11183     return SDValue();
11184 
11185   // Only attempt folding if there is only one use of the flag and no use of the
11186   // value.
11187   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11188     return SDValue();
11189 
11190   SDValue LHS = Cmp.getOperand(0);
11191   SDValue RHS = Cmp.getOperand(1);
11192 
11193   assert(LHS.getValueType() == RHS.getValueType() &&
11194          "Expected the value type to be the same for both operands!");
11195   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11196     return SDValue();
11197 
11198   if (isNullConstant(LHS))
11199     std::swap(LHS, RHS);
11200 
11201   if (!isNullConstant(RHS))
11202     return SDValue();
11203 
11204   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11205       LHS.getOpcode() == ISD::SRL)
11206     return SDValue();
11207 
11208   // Fold the compare into the branch instruction.
11209   SDValue BR;
11210   if (CC == AArch64CC::EQ)
11211     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11212   else
11213     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11214 
11215   // Do not add new nodes to DAG combiner worklist.
11216   DCI.CombineTo(N, BR, false);
11217 
11218   return SDValue();
11219 }
11220 
11221 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
11222 // as well as whether the test should be inverted.  This code is required to
11223 // catch these cases (as opposed to standard dag combines) because
11224 // AArch64ISD::TBZ is matched during legalization.
11225 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11226                                  SelectionDAG &DAG) {
11227 
11228   if (!Op->hasOneUse())
11229     return Op;
11230 
11231   // We don't handle undef/constant-fold cases below, as they should have
11232   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11233   // etc.)
11234 
11235   // (tbz (trunc x), b) -> (tbz x, b)
11236   // This case is just here to enable more of the below cases to be caught.
11237   if (Op->getOpcode() == ISD::TRUNCATE &&
11238       Bit < Op->getValueType(0).getSizeInBits()) {
11239     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11240   }
11241 
11242   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11243   if (Op->getOpcode() == ISD::ANY_EXTEND &&
11244       Bit < Op->getOperand(0).getValueSizeInBits()) {
11245     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11246   }
11247 
11248   if (Op->getNumOperands() != 2)
11249     return Op;
11250 
11251   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11252   if (!C)
11253     return Op;
11254 
11255   switch (Op->getOpcode()) {
11256   default:
11257     return Op;
11258 
11259   // (tbz (and x, m), b) -> (tbz x, b)
11260   case ISD::AND:
11261     if ((C->getZExtValue() >> Bit) & 1)
11262       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11263     return Op;
11264 
11265   // (tbz (shl x, c), b) -> (tbz x, b-c)
11266   case ISD::SHL:
11267     if (C->getZExtValue() <= Bit &&
11268         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11269       Bit = Bit - C->getZExtValue();
11270       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11271     }
11272     return Op;
11273 
11274   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11275   case ISD::SRA:
11276     Bit = Bit + C->getZExtValue();
11277     if (Bit >= Op->getValueType(0).getSizeInBits())
11278       Bit = Op->getValueType(0).getSizeInBits() - 1;
11279     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11280 
11281   // (tbz (srl x, c), b) -> (tbz x, b+c)
11282   case ISD::SRL:
11283     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11284       Bit = Bit + C->getZExtValue();
11285       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11286     }
11287     return Op;
11288 
11289   // (tbz (xor x, -1), b) -> (tbnz x, b)
11290   case ISD::XOR:
11291     if ((C->getZExtValue() >> Bit) & 1)
11292       Invert = !Invert;
11293     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11294   }
11295 }
11296 
11297 // Optimize test single bit zero/non-zero and branch.
11298 static SDValue performTBZCombine(SDNode *N,
11299                                  TargetLowering::DAGCombinerInfo &DCI,
11300                                  SelectionDAG &DAG) {
11301   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11302   bool Invert = false;
11303   SDValue TestSrc = N->getOperand(1);
11304   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11305 
11306   if (TestSrc == NewTestSrc)
11307     return SDValue();
11308 
11309   unsigned NewOpc = N->getOpcode();
11310   if (Invert) {
11311     if (NewOpc == AArch64ISD::TBZ)
11312       NewOpc = AArch64ISD::TBNZ;
11313     else {
11314       assert(NewOpc == AArch64ISD::TBNZ);
11315       NewOpc = AArch64ISD::TBZ;
11316     }
11317   }
11318 
11319   SDLoc DL(N);
11320   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11321                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11322 }
11323 
11324 // vselect (v1i1 setcc) ->
11325 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
11326 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11327 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11328 // such VSELECT.
11329 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11330   SDValue N0 = N->getOperand(0);
11331   EVT CCVT = N0.getValueType();
11332 
11333   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11334       CCVT.getVectorElementType() != MVT::i1)
11335     return SDValue();
11336 
11337   EVT ResVT = N->getValueType(0);
11338   EVT CmpVT = N0.getOperand(0).getValueType();
11339   // Only combine when the result type is of the same size as the compared
11340   // operands.
11341   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11342     return SDValue();
11343 
11344   SDValue IfTrue = N->getOperand(1);
11345   SDValue IfFalse = N->getOperand(2);
11346   SDValue SetCC =
11347       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11348                    N0.getOperand(0), N0.getOperand(1),
11349                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
11350   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11351                      IfTrue, IfFalse);
11352 }
11353 
11354 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11355 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11356 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11357 /// with a vector one followed by a DUP shuffle on the result.
11358 static SDValue performSelectCombine(SDNode *N,
11359                                     TargetLowering::DAGCombinerInfo &DCI) {
11360   SelectionDAG &DAG = DCI.DAG;
11361   SDValue N0 = N->getOperand(0);
11362   EVT ResVT = N->getValueType(0);
11363 
11364   if (N0.getOpcode() != ISD::SETCC)
11365     return SDValue();
11366 
11367   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11368   // scalar SetCCResultType. We also don't expect vectors, because we assume
11369   // that selects fed by vector SETCCs are canonicalized to VSELECT.
11370   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11371          "Scalar-SETCC feeding SELECT has unexpected result type!");
11372 
11373   // If NumMaskElts == 0, the comparison is larger than select result. The
11374   // largest real NEON comparison is 64-bits per lane, which means the result is
11375   // at most 32-bits and an illegal vector. Just bail out for now.
11376   EVT SrcVT = N0.getOperand(0).getValueType();
11377 
11378   // Don't try to do this optimization when the setcc itself has i1 operands.
11379   // There are no legal vectors of i1, so this would be pointless.
11380   if (SrcVT == MVT::i1)
11381     return SDValue();
11382 
11383   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11384   if (!ResVT.isVector() || NumMaskElts == 0)
11385     return SDValue();
11386 
11387   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11388   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11389 
11390   // Also bail out if the vector CCVT isn't the same size as ResVT.
11391   // This can happen if the SETCC operand size doesn't divide the ResVT size
11392   // (e.g., f64 vs v3f32).
11393   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11394     return SDValue();
11395 
11396   // Make sure we didn't create illegal types, if we're not supposed to.
11397   assert(DCI.isBeforeLegalize() ||
11398          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11399 
11400   // First perform a vector comparison, where lane 0 is the one we're interested
11401   // in.
11402   SDLoc DL(N0);
11403   SDValue LHS =
11404       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11405   SDValue RHS =
11406       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11407   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11408 
11409   // Now duplicate the comparison mask we want across all other lanes.
11410   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11411   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11412   Mask = DAG.getNode(ISD::BITCAST, DL,
11413                      ResVT.changeVectorElementTypeToInteger(), Mask);
11414 
11415   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11416 }
11417 
11418 /// Get rid of unnecessary NVCASTs (that don't change the type).
11419 static SDValue performNVCASTCombine(SDNode *N) {
11420   if (N->getValueType(0) == N->getOperand(0).getValueType())
11421     return N->getOperand(0);
11422 
11423   return SDValue();
11424 }
11425 
11426 // If all users of the globaladdr are of the form (globaladdr + constant), find
11427 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11428 // globaladdr as (globaladdr + constant) - constant.
11429 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11430                                            const AArch64Subtarget *Subtarget,
11431                                            const TargetMachine &TM) {
11432   auto *GN = cast<GlobalAddressSDNode>(N);
11433   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11434       AArch64II::MO_NO_FLAG)
11435     return SDValue();
11436 
11437   uint64_t MinOffset = -1ull;
11438   for (SDNode *N : GN->uses()) {
11439     if (N->getOpcode() != ISD::ADD)
11440       return SDValue();
11441     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11442     if (!C)
11443       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11444     if (!C)
11445       return SDValue();
11446     MinOffset = std::min(MinOffset, C->getZExtValue());
11447   }
11448   uint64_t Offset = MinOffset + GN->getOffset();
11449 
11450   // Require that the new offset is larger than the existing one. Otherwise, we
11451   // can end up oscillating between two possible DAGs, for example,
11452   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11453   if (Offset <= uint64_t(GN->getOffset()))
11454     return SDValue();
11455 
11456   // Check whether folding this offset is legal. It must not go out of bounds of
11457   // the referenced object to avoid violating the code model, and must be
11458   // smaller than 2^21 because this is the largest offset expressible in all
11459   // object formats.
11460   //
11461   // This check also prevents us from folding negative offsets, which will end
11462   // up being treated in the same way as large positive ones. They could also
11463   // cause code model violations, and aren't really common enough to matter.
11464   if (Offset >= (1 << 21))
11465     return SDValue();
11466 
11467   const GlobalValue *GV = GN->getGlobal();
11468   Type *T = GV->getValueType();
11469   if (!T->isSized() ||
11470       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11471     return SDValue();
11472 
11473   SDLoc DL(GN);
11474   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11475   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11476                      DAG.getConstant(MinOffset, DL, MVT::i64));
11477 }
11478 
11479 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11480                                                  DAGCombinerInfo &DCI) const {
11481   SelectionDAG &DAG = DCI.DAG;
11482   switch (N->getOpcode()) {
11483   default:
11484     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11485     break;
11486   case ISD::ADD:
11487   case ISD::SUB:
11488     return performAddSubLongCombine(N, DCI, DAG);
11489   case ISD::XOR:
11490     return performXorCombine(N, DAG, DCI, Subtarget);
11491   case ISD::MUL:
11492     return performMulCombine(N, DAG, DCI, Subtarget);
11493   case ISD::SINT_TO_FP:
11494   case ISD::UINT_TO_FP:
11495     return performIntToFpCombine(N, DAG, Subtarget);
11496   case ISD::FP_TO_SINT:
11497   case ISD::FP_TO_UINT:
11498     return performFpToIntCombine(N, DAG, DCI, Subtarget);
11499   case ISD::FDIV:
11500     return performFDivCombine(N, DAG, DCI, Subtarget);
11501   case ISD::OR:
11502     return performORCombine(N, DCI, Subtarget);
11503   case ISD::AND:
11504     return performANDCombine(N, DCI);
11505   case ISD::SRL:
11506     return performSRLCombine(N, DCI);
11507   case ISD::INTRINSIC_WO_CHAIN:
11508     return performIntrinsicCombine(N, DCI, Subtarget);
11509   case ISD::ANY_EXTEND:
11510   case ISD::ZERO_EXTEND:
11511   case ISD::SIGN_EXTEND:
11512     return performExtendCombine(N, DCI, DAG);
11513   case ISD::BITCAST:
11514     return performBitcastCombine(N, DCI, DAG);
11515   case ISD::CONCAT_VECTORS:
11516     return performConcatVectorsCombine(N, DCI, DAG);
11517   case ISD::SELECT:
11518     return performSelectCombine(N, DCI);
11519   case ISD::VSELECT:
11520     return performVSelectCombine(N, DCI.DAG);
11521   case ISD::LOAD:
11522     if (performTBISimplification(N->getOperand(1), DCI, DAG))
11523       return SDValue(N, 0);
11524     break;
11525   case ISD::STORE:
11526     return performSTORECombine(N, DCI, DAG, Subtarget);
11527   case AArch64ISD::BRCOND:
11528     return performBRCONDCombine(N, DCI, DAG);
11529   case AArch64ISD::TBNZ:
11530   case AArch64ISD::TBZ:
11531     return performTBZCombine(N, DCI, DAG);
11532   case AArch64ISD::CSEL:
11533     return performCONDCombine(N, DCI, DAG, 2, 3);
11534   case AArch64ISD::DUP:
11535     return performPostLD1Combine(N, DCI, false);
11536   case AArch64ISD::NVCAST:
11537     return performNVCASTCombine(N);
11538   case ISD::INSERT_VECTOR_ELT:
11539     return performPostLD1Combine(N, DCI, true);
11540   case ISD::INTRINSIC_VOID:
11541   case ISD::INTRINSIC_W_CHAIN:
11542     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11543     case Intrinsic::aarch64_neon_ld2:
11544     case Intrinsic::aarch64_neon_ld3:
11545     case Intrinsic::aarch64_neon_ld4:
11546     case Intrinsic::aarch64_neon_ld1x2:
11547     case Intrinsic::aarch64_neon_ld1x3:
11548     case Intrinsic::aarch64_neon_ld1x4:
11549     case Intrinsic::aarch64_neon_ld2lane:
11550     case Intrinsic::aarch64_neon_ld3lane:
11551     case Intrinsic::aarch64_neon_ld4lane:
11552     case Intrinsic::aarch64_neon_ld2r:
11553     case Intrinsic::aarch64_neon_ld3r:
11554     case Intrinsic::aarch64_neon_ld4r:
11555     case Intrinsic::aarch64_neon_st2:
11556     case Intrinsic::aarch64_neon_st3:
11557     case Intrinsic::aarch64_neon_st4:
11558     case Intrinsic::aarch64_neon_st1x2:
11559     case Intrinsic::aarch64_neon_st1x3:
11560     case Intrinsic::aarch64_neon_st1x4:
11561     case Intrinsic::aarch64_neon_st2lane:
11562     case Intrinsic::aarch64_neon_st3lane:
11563     case Intrinsic::aarch64_neon_st4lane:
11564       return performNEONPostLDSTCombine(N, DCI, DAG);
11565     default:
11566       break;
11567     }
11568     break;
11569   case ISD::GlobalAddress:
11570     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11571   }
11572   return SDValue();
11573 }
11574 
11575 // Check if the return value is used as only a return value, as otherwise
11576 // we can't perform a tail-call. In particular, we need to check for
11577 // target ISD nodes that are returns and any other "odd" constructs
11578 // that the generic analysis code won't necessarily catch.
11579 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11580                                                SDValue &Chain) const {
11581   if (N->getNumValues() != 1)
11582     return false;
11583   if (!N->hasNUsesOfValue(1, 0))
11584     return false;
11585 
11586   SDValue TCChain = Chain;
11587   SDNode *Copy = *N->use_begin();
11588   if (Copy->getOpcode() == ISD::CopyToReg) {
11589     // If the copy has a glue operand, we conservatively assume it isn't safe to
11590     // perform a tail call.
11591     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11592         MVT::Glue)
11593       return false;
11594     TCChain = Copy->getOperand(0);
11595   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11596     return false;
11597 
11598   bool HasRet = false;
11599   for (SDNode *Node : Copy->uses()) {
11600     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11601       return false;
11602     HasRet = true;
11603   }
11604 
11605   if (!HasRet)
11606     return false;
11607 
11608   Chain = TCChain;
11609   return true;
11610 }
11611 
11612 // Return whether the an instruction can potentially be optimized to a tail
11613 // call. This will cause the optimizers to attempt to move, or duplicate,
11614 // return instructions to help enable tail call optimizations for this
11615 // instruction.
11616 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11617   return CI->isTailCall();
11618 }
11619 
11620 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11621                                                    SDValue &Offset,
11622                                                    ISD::MemIndexedMode &AM,
11623                                                    bool &IsInc,
11624                                                    SelectionDAG &DAG) const {
11625   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11626     return false;
11627 
11628   Base = Op->getOperand(0);
11629   // All of the indexed addressing mode instructions take a signed
11630   // 9 bit immediate offset.
11631   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11632     int64_t RHSC = RHS->getSExtValue();
11633     if (Op->getOpcode() == ISD::SUB)
11634       RHSC = -(uint64_t)RHSC;
11635     if (!isInt<9>(RHSC))
11636       return false;
11637     IsInc = (Op->getOpcode() == ISD::ADD);
11638     Offset = Op->getOperand(1);
11639     return true;
11640   }
11641   return false;
11642 }
11643 
11644 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11645                                                       SDValue &Offset,
11646                                                       ISD::MemIndexedMode &AM,
11647                                                       SelectionDAG &DAG) const {
11648   EVT VT;
11649   SDValue Ptr;
11650   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11651     VT = LD->getMemoryVT();
11652     Ptr = LD->getBasePtr();
11653   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11654     VT = ST->getMemoryVT();
11655     Ptr = ST->getBasePtr();
11656   } else
11657     return false;
11658 
11659   bool IsInc;
11660   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11661     return false;
11662   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11663   return true;
11664 }
11665 
11666 bool AArch64TargetLowering::getPostIndexedAddressParts(
11667     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11668     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11669   EVT VT;
11670   SDValue Ptr;
11671   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11672     VT = LD->getMemoryVT();
11673     Ptr = LD->getBasePtr();
11674   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11675     VT = ST->getMemoryVT();
11676     Ptr = ST->getBasePtr();
11677   } else
11678     return false;
11679 
11680   bool IsInc;
11681   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11682     return false;
11683   // Post-indexing updates the base, so it's not a valid transform
11684   // if that's not the same as the load's pointer.
11685   if (Ptr != Base)
11686     return false;
11687   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11688   return true;
11689 }
11690 
11691 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11692                                   SelectionDAG &DAG) {
11693   SDLoc DL(N);
11694   SDValue Op = N->getOperand(0);
11695 
11696   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11697     return;
11698 
11699   Op = SDValue(
11700       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11701                          DAG.getUNDEF(MVT::i32), Op,
11702                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11703       0);
11704   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11705   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11706 }
11707 
11708 static void ReplaceReductionResults(SDNode *N,
11709                                     SmallVectorImpl<SDValue> &Results,
11710                                     SelectionDAG &DAG, unsigned InterOp,
11711                                     unsigned AcrossOp) {
11712   EVT LoVT, HiVT;
11713   SDValue Lo, Hi;
11714   SDLoc dl(N);
11715   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11716   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11717   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11718   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11719   Results.push_back(SplitVal);
11720 }
11721 
11722 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11723   SDLoc DL(N);
11724   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11725   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11726                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11727                                        DAG.getConstant(64, DL, MVT::i64)));
11728   return std::make_pair(Lo, Hi);
11729 }
11730 
11731 // Create an even/odd pair of X registers holding integer value V.
11732 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11733   SDLoc dl(V.getNode());
11734   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11735   SDValue VHi = DAG.getAnyExtOrTrunc(
11736       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11737       dl, MVT::i64);
11738   if (DAG.getDataLayout().isBigEndian())
11739     std::swap (VLo, VHi);
11740   SDValue RegClass =
11741       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11742   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11743   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11744   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11745   return SDValue(
11746       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11747 }
11748 
11749 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11750                                        SmallVectorImpl<SDValue> &Results,
11751                                        SelectionDAG &DAG,
11752                                        const AArch64Subtarget *Subtarget) {
11753   assert(N->getValueType(0) == MVT::i128 &&
11754          "AtomicCmpSwap on types less than 128 should be legal");
11755 
11756   if (Subtarget->hasLSE()) {
11757     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11758     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11759     SDValue Ops[] = {
11760         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11761         createGPRPairNode(DAG, N->getOperand(3)), // Store value
11762         N->getOperand(1), // Ptr
11763         N->getOperand(0), // Chain in
11764     };
11765 
11766     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11767 
11768     unsigned Opcode;
11769     switch (MemOp->getOrdering()) {
11770     case AtomicOrdering::Monotonic:
11771       Opcode = AArch64::CASPX;
11772       break;
11773     case AtomicOrdering::Acquire:
11774       Opcode = AArch64::CASPAX;
11775       break;
11776     case AtomicOrdering::Release:
11777       Opcode = AArch64::CASPLX;
11778       break;
11779     case AtomicOrdering::AcquireRelease:
11780     case AtomicOrdering::SequentiallyConsistent:
11781       Opcode = AArch64::CASPALX;
11782       break;
11783     default:
11784       llvm_unreachable("Unexpected ordering!");
11785     }
11786 
11787     MachineSDNode *CmpSwap = DAG.getMachineNode(
11788         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11789     DAG.setNodeMemRefs(CmpSwap, {MemOp});
11790 
11791     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11792     if (DAG.getDataLayout().isBigEndian())
11793       std::swap(SubReg1, SubReg2);
11794     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11795                                                  SDValue(CmpSwap, 0)));
11796     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11797                                                  SDValue(CmpSwap, 0)));
11798     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11799     return;
11800   }
11801 
11802   auto Desired = splitInt128(N->getOperand(2), DAG);
11803   auto New = splitInt128(N->getOperand(3), DAG);
11804   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11805                    New.first,        New.second,    N->getOperand(0)};
11806   SDNode *CmpSwap = DAG.getMachineNode(
11807       AArch64::CMP_SWAP_128, SDLoc(N),
11808       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11809 
11810   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11811   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11812 
11813   Results.push_back(SDValue(CmpSwap, 0));
11814   Results.push_back(SDValue(CmpSwap, 1));
11815   Results.push_back(SDValue(CmpSwap, 3));
11816 }
11817 
11818 void AArch64TargetLowering::ReplaceNodeResults(
11819     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11820   switch (N->getOpcode()) {
11821   default:
11822     llvm_unreachable("Don't know how to custom expand this");
11823   case ISD::BITCAST:
11824     ReplaceBITCASTResults(N, Results, DAG);
11825     return;
11826   case ISD::VECREDUCE_ADD:
11827   case ISD::VECREDUCE_SMAX:
11828   case ISD::VECREDUCE_SMIN:
11829   case ISD::VECREDUCE_UMAX:
11830   case ISD::VECREDUCE_UMIN:
11831     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11832     return;
11833 
11834   case AArch64ISD::SADDV:
11835     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11836     return;
11837   case AArch64ISD::UADDV:
11838     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11839     return;
11840   case AArch64ISD::SMINV:
11841     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11842     return;
11843   case AArch64ISD::UMINV:
11844     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11845     return;
11846   case AArch64ISD::SMAXV:
11847     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11848     return;
11849   case AArch64ISD::UMAXV:
11850     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11851     return;
11852   case ISD::FP_TO_UINT:
11853   case ISD::FP_TO_SINT:
11854     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11855     // Let normal code take care of it by not adding anything to Results.
11856     return;
11857   case ISD::ATOMIC_CMP_SWAP:
11858     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11859     return;
11860   }
11861 }
11862 
11863 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11864   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11865     return TargetLowering::useLoadStackGuardNode();
11866   return true;
11867 }
11868 
11869 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11870   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11871   // reciprocal if there are three or more FDIVs.
11872   return 3;
11873 }
11874 
11875 TargetLoweringBase::LegalizeTypeAction
11876 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
11877   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
11878   // v4i16, v2i32 instead of to promote.
11879   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11880       VT == MVT::v1f32)
11881     return TypeWidenVector;
11882 
11883   return TargetLoweringBase::getPreferredVectorAction(VT);
11884 }
11885 
11886 // Loads and stores less than 128-bits are already atomic; ones above that
11887 // are doomed anyway, so defer to the default libcall and blame the OS when
11888 // things go wrong.
11889 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11890   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11891   return Size == 128;
11892 }
11893 
11894 // Loads and stores less than 128-bits are already atomic; ones above that
11895 // are doomed anyway, so defer to the default libcall and blame the OS when
11896 // things go wrong.
11897 TargetLowering::AtomicExpansionKind
11898 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11899   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11900   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11901 }
11902 
11903 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11904 TargetLowering::AtomicExpansionKind
11905 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11906   if (AI->isFloatingPointOperation())
11907     return AtomicExpansionKind::CmpXChg;
11908 
11909   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11910   if (Size > 128) return AtomicExpansionKind::None;
11911   // Nand not supported in LSE.
11912   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11913   // Leave 128 bits to LLSC.
11914   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11915 }
11916 
11917 TargetLowering::AtomicExpansionKind
11918 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11919     AtomicCmpXchgInst *AI) const {
11920   // If subtarget has LSE, leave cmpxchg intact for codegen.
11921   if (Subtarget->hasLSE())
11922     return AtomicExpansionKind::None;
11923   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11924   // implement cmpxchg without spilling. If the address being exchanged is also
11925   // on the stack and close enough to the spill slot, this can lead to a
11926   // situation where the monitor always gets cleared and the atomic operation
11927   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11928   if (getTargetMachine().getOptLevel() == 0)
11929     return AtomicExpansionKind::None;
11930   return AtomicExpansionKind::LLSC;
11931 }
11932 
11933 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11934                                              AtomicOrdering Ord) const {
11935   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11936   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11937   bool IsAcquire = isAcquireOrStronger(Ord);
11938 
11939   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11940   // intrinsic must return {i64, i64} and we have to recombine them into a
11941   // single i128 here.
11942   if (ValTy->getPrimitiveSizeInBits() == 128) {
11943     Intrinsic::ID Int =
11944         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11945     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11946 
11947     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11948     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11949 
11950     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11951     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11952     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11953     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11954     return Builder.CreateOr(
11955         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11956   }
11957 
11958   Type *Tys[] = { Addr->getType() };
11959   Intrinsic::ID Int =
11960       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11961   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11962 
11963   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11964 
11965   const DataLayout &DL = M->getDataLayout();
11966   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11967   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11968 
11969   return Builder.CreateBitCast(Trunc, EltTy);
11970 }
11971 
11972 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11973     IRBuilder<> &Builder) const {
11974   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11975   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11976 }
11977 
11978 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11979                                                    Value *Val, Value *Addr,
11980                                                    AtomicOrdering Ord) const {
11981   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11982   bool IsRelease = isReleaseOrStronger(Ord);
11983 
11984   // Since the intrinsics must have legal type, the i128 intrinsics take two
11985   // parameters: "i64, i64". We must marshal Val into the appropriate form
11986   // before the call.
11987   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11988     Intrinsic::ID Int =
11989         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11990     Function *Stxr = Intrinsic::getDeclaration(M, Int);
11991     Type *Int64Ty = Type::getInt64Ty(M->getContext());
11992 
11993     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11994     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11995     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11996     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
11997   }
11998 
11999   Intrinsic::ID Int =
12000       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12001   Type *Tys[] = { Addr->getType() };
12002   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12003 
12004   const DataLayout &DL = M->getDataLayout();
12005   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12006   Val = Builder.CreateBitCast(Val, IntValTy);
12007 
12008   return Builder.CreateCall(Stxr,
12009                             {Builder.CreateZExtOrBitCast(
12010                                  Val, Stxr->getFunctionType()->getParamType(0)),
12011                              Addr});
12012 }
12013 
12014 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12015     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12016   return Ty->isArrayTy();
12017 }
12018 
12019 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12020                                                             EVT) const {
12021   return false;
12022 }
12023 
12024 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
12025   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12026   Function *ThreadPointerFunc =
12027       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
12028   return IRB.CreatePointerCast(
12029       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12030                              Offset),
12031       IRB.getInt8PtrTy()->getPointerTo(0));
12032 }
12033 
12034 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12035   // Android provides a fixed TLS slot for the stack cookie. See the definition
12036   // of TLS_SLOT_STACK_GUARD in
12037   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12038   if (Subtarget->isTargetAndroid())
12039     return UseTlsOffset(IRB, 0x28);
12040 
12041   // Fuchsia is similar.
12042   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12043   if (Subtarget->isTargetFuchsia())
12044     return UseTlsOffset(IRB, -0x10);
12045 
12046   return TargetLowering::getIRStackGuard(IRB);
12047 }
12048 
12049 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12050   // MSVC CRT provides functionalities for stack protection.
12051   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12052     // MSVC CRT has a global variable holding security cookie.
12053     M.getOrInsertGlobal("__security_cookie",
12054                         Type::getInt8PtrTy(M.getContext()));
12055 
12056     // MSVC CRT has a function to validate security cookie.
12057     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12058         "__security_check_cookie", Type::getVoidTy(M.getContext()),
12059         Type::getInt8PtrTy(M.getContext()));
12060     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12061       F->setCallingConv(CallingConv::Win64);
12062       F->addAttribute(1, Attribute::AttrKind::InReg);
12063     }
12064     return;
12065   }
12066   TargetLowering::insertSSPDeclarations(M);
12067 }
12068 
12069 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12070   // MSVC CRT has a global variable holding security cookie.
12071   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12072     return M.getGlobalVariable("__security_cookie");
12073   return TargetLowering::getSDagStackGuard(M);
12074 }
12075 
12076 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
12077   // MSVC CRT has a function to validate security cookie.
12078   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12079     return M.getFunction("__security_check_cookie");
12080   return TargetLowering::getSSPStackGuardCheck(M);
12081 }
12082 
12083 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
12084   // Android provides a fixed TLS slot for the SafeStack pointer. See the
12085   // definition of TLS_SLOT_SAFESTACK in
12086   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12087   if (Subtarget->isTargetAndroid())
12088     return UseTlsOffset(IRB, 0x48);
12089 
12090   // Fuchsia is similar.
12091   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12092   if (Subtarget->isTargetFuchsia())
12093     return UseTlsOffset(IRB, -0x8);
12094 
12095   return TargetLowering::getSafeStackPointerLocation(IRB);
12096 }
12097 
12098 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12099     const Instruction &AndI) const {
12100   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12101   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
12102   // may be beneficial to sink in other cases, but we would have to check that
12103   // the cmp would not get folded into the br to form a cbz for these to be
12104   // beneficial.
12105   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12106   if (!Mask)
12107     return false;
12108   return Mask->getValue().isPowerOf2();
12109 }
12110 
12111 bool AArch64TargetLowering::
12112     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12113         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12114         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12115         SelectionDAG &DAG) const {
12116   // Does baseline recommend not to perform the fold by default?
12117   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12118           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12119     return false;
12120   // Else, if this is a vector shift, prefer 'shl'.
12121   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12122 }
12123 
12124 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12125   // Update IsSplitCSR in AArch64unctionInfo.
12126   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12127   AFI->setIsSplitCSR(true);
12128 }
12129 
12130 void AArch64TargetLowering::insertCopiesSplitCSR(
12131     MachineBasicBlock *Entry,
12132     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12133   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12134   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12135   if (!IStart)
12136     return;
12137 
12138   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12139   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12140   MachineBasicBlock::iterator MBBI = Entry->begin();
12141   for (const MCPhysReg *I = IStart; *I; ++I) {
12142     const TargetRegisterClass *RC = nullptr;
12143     if (AArch64::GPR64RegClass.contains(*I))
12144       RC = &AArch64::GPR64RegClass;
12145     else if (AArch64::FPR64RegClass.contains(*I))
12146       RC = &AArch64::FPR64RegClass;
12147     else
12148       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12149 
12150     Register NewVR = MRI->createVirtualRegister(RC);
12151     // Create copy from CSR to a virtual register.
12152     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12153     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12154     // nounwind. If we want to generalize this later, we may need to emit
12155     // CFI pseudo-instructions.
12156     assert(Entry->getParent()->getFunction().hasFnAttribute(
12157                Attribute::NoUnwind) &&
12158            "Function should be nounwind in insertCopiesSplitCSR!");
12159     Entry->addLiveIn(*I);
12160     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12161         .addReg(*I);
12162 
12163     // Insert the copy-back instructions right before the terminator.
12164     for (auto *Exit : Exits)
12165       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12166               TII->get(TargetOpcode::COPY), *I)
12167           .addReg(NewVR);
12168   }
12169 }
12170 
12171 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12172   // Integer division on AArch64 is expensive. However, when aggressively
12173   // optimizing for code size, we prefer to use a div instruction, as it is
12174   // usually smaller than the alternative sequence.
12175   // The exception to this is vector division. Since AArch64 doesn't have vector
12176   // integer division, leaving the division as-is is a loss even in terms of
12177   // size, because it will have to be scalarized, while the alternative code
12178   // sequence can be performed in vector form.
12179   bool OptSize =
12180       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12181   return OptSize && !VT.isVector();
12182 }
12183 
12184 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12185   // We want inc-of-add for scalars and sub-of-not for vectors.
12186   return VT.isScalarInteger();
12187 }
12188 
12189 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12190   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12191 }
12192 
12193 unsigned
12194 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
12195   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12196     return getPointerTy(DL).getSizeInBits();
12197 
12198   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12199 }
12200 
12201 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12202   MF.getFrameInfo().computeMaxCallFrameSize(MF);
12203   TargetLoweringBase::finalizeLowering(MF);
12204 }
12205 
12206 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12207 bool AArch64TargetLowering::needsFixedCatchObjects() const {
12208   return false;
12209 }
12210