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   unsigned DestReg = MI.getOperand(0).getReg();
1320   unsigned IfTrueReg = MI.getOperand(1).getReg();
1321   unsigned 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         unsigned 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::MONonTemporal | MachineMemOperand::MOInvariant |
4304           MachineMemOperand::MODereferenceable);
4305   Chain = FuncTLVGet.getValue(1);
4306 
4307   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4308   MFI.setAdjustsStack(true);
4309 
4310   // TLS calls preserve all registers except those that absolutely must be
4311   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4312   // silly).
4313   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4314   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4315   if (Subtarget->hasCustomCallingConv())
4316     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4317 
4318   // Finally, we can make the call. This is just a degenerate version of a
4319   // normal AArch64 call node: x0 takes the address of the descriptor, and
4320   // returns the address of the variable in this thread.
4321   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4322   Chain =
4323       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4324                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4325                   DAG.getRegisterMask(Mask), Chain.getValue(1));
4326   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4327 }
4328 
4329 /// When accessing thread-local variables under either the general-dynamic or
4330 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4331 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4332 /// is a function pointer to carry out the resolution.
4333 ///
4334 /// The sequence is:
4335 ///    adrp  x0, :tlsdesc:var
4336 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
4337 ///    add   x0, x0, #:tlsdesc_lo12:var
4338 ///    .tlsdesccall var
4339 ///    blr   x1
4340 ///    (TPIDR_EL0 offset now in x0)
4341 ///
4342 ///  The above sequence must be produced unscheduled, to enable the linker to
4343 ///  optimize/relax this sequence.
4344 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4345 ///  above sequence, and expanded really late in the compilation flow, to ensure
4346 ///  the sequence is produced as per above.
4347 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4348                                                       const SDLoc &DL,
4349                                                       SelectionDAG &DAG) const {
4350   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4351 
4352   SDValue Chain = DAG.getEntryNode();
4353   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4354 
4355   Chain =
4356       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4357   SDValue Glue = Chain.getValue(1);
4358 
4359   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4360 }
4361 
4362 SDValue
4363 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4364                                                 SelectionDAG &DAG) const {
4365   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4366   if (getTargetMachine().getCodeModel() == CodeModel::Large)
4367     report_fatal_error("ELF TLS only supported in small memory model");
4368   // Different choices can be made for the maximum size of the TLS area for a
4369   // module. For the small address model, the default TLS size is 16MiB and the
4370   // maximum TLS size is 4GiB.
4371   // FIXME: add -mtls-size command line option and make it control the 16MiB
4372   // vs. 4GiB code sequence generation.
4373   // FIXME: add tiny codemodel support. We currently generate the same code as
4374   // small, which may be larger than needed.
4375   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4376 
4377   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4378 
4379   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4380     if (Model == TLSModel::LocalDynamic)
4381       Model = TLSModel::GeneralDynamic;
4382   }
4383 
4384   SDValue TPOff;
4385   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4386   SDLoc DL(Op);
4387   const GlobalValue *GV = GA->getGlobal();
4388 
4389   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4390 
4391   if (Model == TLSModel::LocalExec) {
4392     SDValue HiVar = DAG.getTargetGlobalAddress(
4393         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4394     SDValue LoVar = DAG.getTargetGlobalAddress(
4395         GV, DL, PtrVT, 0,
4396         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4397 
4398     SDValue TPWithOff_lo =
4399         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4400                                    HiVar,
4401                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4402                 0);
4403     SDValue TPWithOff =
4404         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4405                                    LoVar,
4406                                    DAG.getTargetConstant(0, DL, MVT::i32)),
4407                 0);
4408     return TPWithOff;
4409   } else if (Model == TLSModel::InitialExec) {
4410     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4411     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4412   } else if (Model == TLSModel::LocalDynamic) {
4413     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4414     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4415     // the beginning of the module's TLS region, followed by a DTPREL offset
4416     // calculation.
4417 
4418     // These accesses will need deduplicating if there's more than one.
4419     AArch64FunctionInfo *MFI =
4420         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4421     MFI->incNumLocalDynamicTLSAccesses();
4422 
4423     // The call needs a relocation too for linker relaxation. It doesn't make
4424     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4425     // the address.
4426     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4427                                                   AArch64II::MO_TLS);
4428 
4429     // Now we can calculate the offset from TPIDR_EL0 to this module's
4430     // thread-local area.
4431     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4432 
4433     // Now use :dtprel_whatever: operations to calculate this variable's offset
4434     // in its thread-storage area.
4435     SDValue HiVar = DAG.getTargetGlobalAddress(
4436         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4437     SDValue LoVar = DAG.getTargetGlobalAddress(
4438         GV, DL, MVT::i64, 0,
4439         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4440 
4441     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4442                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4443                     0);
4444     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4445                                        DAG.getTargetConstant(0, DL, MVT::i32)),
4446                     0);
4447   } else if (Model == TLSModel::GeneralDynamic) {
4448     // The call needs a relocation too for linker relaxation. It doesn't make
4449     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4450     // the address.
4451     SDValue SymAddr =
4452         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4453 
4454     // Finally we can make a call to calculate the offset from tpidr_el0.
4455     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4456   } else
4457     llvm_unreachable("Unsupported ELF TLS access model");
4458 
4459   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4460 }
4461 
4462 SDValue
4463 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4464                                                     SelectionDAG &DAG) const {
4465   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4466 
4467   SDValue Chain = DAG.getEntryNode();
4468   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4469   SDLoc DL(Op);
4470 
4471   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4472 
4473   // Load the ThreadLocalStoragePointer from the TEB
4474   // A pointer to the TLS array is located at offset 0x58 from the TEB.
4475   SDValue TLSArray =
4476       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4477   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4478   Chain = TLSArray.getValue(1);
4479 
4480   // Load the TLS index from the C runtime;
4481   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4482   // This also does the same as LOADgot, but using a generic i32 load,
4483   // while LOADgot only loads i64.
4484   SDValue TLSIndexHi =
4485       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4486   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4487       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4488   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4489   SDValue TLSIndex =
4490       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4491   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4492   Chain = TLSIndex.getValue(1);
4493 
4494   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4495   // offset into the TLSArray.
4496   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4497   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4498                              DAG.getConstant(3, DL, PtrVT));
4499   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4500                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4501                             MachinePointerInfo());
4502   Chain = TLS.getValue(1);
4503 
4504   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4505   const GlobalValue *GV = GA->getGlobal();
4506   SDValue TGAHi = DAG.getTargetGlobalAddress(
4507       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4508   SDValue TGALo = DAG.getTargetGlobalAddress(
4509       GV, DL, PtrVT, 0,
4510       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4511 
4512   // Add the offset from the start of the .tls section (section base).
4513   SDValue Addr =
4514       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4515                                  DAG.getTargetConstant(0, DL, MVT::i32)),
4516               0);
4517   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4518   return Addr;
4519 }
4520 
4521 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4522                                                      SelectionDAG &DAG) const {
4523   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4524   if (DAG.getTarget().useEmulatedTLS())
4525     return LowerToTLSEmulatedModel(GA, DAG);
4526 
4527   if (Subtarget->isTargetDarwin())
4528     return LowerDarwinGlobalTLSAddress(Op, DAG);
4529   if (Subtarget->isTargetELF())
4530     return LowerELFGlobalTLSAddress(Op, DAG);
4531   if (Subtarget->isTargetWindows())
4532     return LowerWindowsGlobalTLSAddress(Op, DAG);
4533 
4534   llvm_unreachable("Unexpected platform trying to use TLS");
4535 }
4536 
4537 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4538   SDValue Chain = Op.getOperand(0);
4539   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4540   SDValue LHS = Op.getOperand(2);
4541   SDValue RHS = Op.getOperand(3);
4542   SDValue Dest = Op.getOperand(4);
4543   SDLoc dl(Op);
4544 
4545   MachineFunction &MF = DAG.getMachineFunction();
4546   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4547   // will not be produced, as they are conditional branch instructions that do
4548   // not set flags.
4549   bool ProduceNonFlagSettingCondBr =
4550       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4551 
4552   // Handle f128 first, since lowering it will result in comparing the return
4553   // value of a libcall against zero, which is just what the rest of LowerBR_CC
4554   // is expecting to deal with.
4555   if (LHS.getValueType() == MVT::f128) {
4556     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4557 
4558     // If softenSetCCOperands returned a scalar, we need to compare the result
4559     // against zero to select between true and false values.
4560     if (!RHS.getNode()) {
4561       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4562       CC = ISD::SETNE;
4563     }
4564   }
4565 
4566   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4567   // instruction.
4568   if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4569       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4570     // Only lower legal XALUO ops.
4571     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4572       return SDValue();
4573 
4574     // The actual operation with overflow check.
4575     AArch64CC::CondCode OFCC;
4576     SDValue Value, Overflow;
4577     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4578 
4579     if (CC == ISD::SETNE)
4580       OFCC = getInvertedCondCode(OFCC);
4581     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4582 
4583     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4584                        Overflow);
4585   }
4586 
4587   if (LHS.getValueType().isInteger()) {
4588     assert((LHS.getValueType() == RHS.getValueType()) &&
4589            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4590 
4591     // If the RHS of the comparison is zero, we can potentially fold this
4592     // to a specialized branch.
4593     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4594     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4595       if (CC == ISD::SETEQ) {
4596         // See if we can use a TBZ to fold in an AND as well.
4597         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4598         // out of bounds, a late MI-layer pass rewrites branches.
4599         // 403.gcc is an example that hits this case.
4600         if (LHS.getOpcode() == ISD::AND &&
4601             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4602             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4603           SDValue Test = LHS.getOperand(0);
4604           uint64_t Mask = LHS.getConstantOperandVal(1);
4605           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4606                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4607                              Dest);
4608         }
4609 
4610         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4611       } else if (CC == ISD::SETNE) {
4612         // See if we can use a TBZ to fold in an AND as well.
4613         // TBZ has a smaller branch displacement than CBZ.  If the offset is
4614         // out of bounds, a late MI-layer pass rewrites branches.
4615         // 403.gcc is an example that hits this case.
4616         if (LHS.getOpcode() == ISD::AND &&
4617             isa<ConstantSDNode>(LHS.getOperand(1)) &&
4618             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4619           SDValue Test = LHS.getOperand(0);
4620           uint64_t Mask = LHS.getConstantOperandVal(1);
4621           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4622                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4623                              Dest);
4624         }
4625 
4626         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4627       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4628         // Don't combine AND since emitComparison converts the AND to an ANDS
4629         // (a.k.a. TST) and the test in the test bit and branch instruction
4630         // becomes redundant.  This would also increase register pressure.
4631         uint64_t Mask = LHS.getValueSizeInBits() - 1;
4632         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4633                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
4634       }
4635     }
4636     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4637         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4638       // Don't combine AND since emitComparison converts the AND to an ANDS
4639       // (a.k.a. TST) and the test in the test bit and branch instruction
4640       // becomes redundant.  This would also increase register pressure.
4641       uint64_t Mask = LHS.getValueSizeInBits() - 1;
4642       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4643                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
4644     }
4645 
4646     SDValue CCVal;
4647     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4648     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4649                        Cmp);
4650   }
4651 
4652   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4653          LHS.getValueType() == MVT::f64);
4654 
4655   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4656   // clean.  Some of them require two branches to implement.
4657   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4658   AArch64CC::CondCode CC1, CC2;
4659   changeFPCCToAArch64CC(CC, CC1, CC2);
4660   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4661   SDValue BR1 =
4662       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4663   if (CC2 != AArch64CC::AL) {
4664     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4665     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4666                        Cmp);
4667   }
4668 
4669   return BR1;
4670 }
4671 
4672 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4673                                               SelectionDAG &DAG) const {
4674   EVT VT = Op.getValueType();
4675   SDLoc DL(Op);
4676 
4677   SDValue In1 = Op.getOperand(0);
4678   SDValue In2 = Op.getOperand(1);
4679   EVT SrcVT = In2.getValueType();
4680 
4681   if (SrcVT.bitsLT(VT))
4682     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4683   else if (SrcVT.bitsGT(VT))
4684     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4685 
4686   EVT VecVT;
4687   uint64_t EltMask;
4688   SDValue VecVal1, VecVal2;
4689 
4690   auto setVecVal = [&] (int Idx) {
4691     if (!VT.isVector()) {
4692       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4693                                           DAG.getUNDEF(VecVT), In1);
4694       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4695                                           DAG.getUNDEF(VecVT), In2);
4696     } else {
4697       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4698       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4699     }
4700   };
4701 
4702   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4703     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4704     EltMask = 0x80000000ULL;
4705     setVecVal(AArch64::ssub);
4706   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4707     VecVT = MVT::v2i64;
4708 
4709     // We want to materialize a mask with the high bit set, but the AdvSIMD
4710     // immediate moves cannot materialize that in a single instruction for
4711     // 64-bit elements. Instead, materialize zero and then negate it.
4712     EltMask = 0;
4713 
4714     setVecVal(AArch64::dsub);
4715   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4716     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4717     EltMask = 0x8000ULL;
4718     setVecVal(AArch64::hsub);
4719   } else {
4720     llvm_unreachable("Invalid type for copysign!");
4721   }
4722 
4723   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4724 
4725   // If we couldn't materialize the mask above, then the mask vector will be
4726   // the zero vector, and we need to negate it here.
4727   if (VT == MVT::f64 || VT == MVT::v2f64) {
4728     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4729     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4730     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4731   }
4732 
4733   SDValue Sel =
4734       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4735 
4736   if (VT == MVT::f16)
4737     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4738   if (VT == MVT::f32)
4739     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4740   else if (VT == MVT::f64)
4741     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4742   else
4743     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4744 }
4745 
4746 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4747   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4748           Attribute::NoImplicitFloat))
4749     return SDValue();
4750 
4751   if (!Subtarget->hasNEON())
4752     return SDValue();
4753 
4754   // While there is no integer popcount instruction, it can
4755   // be more efficiently lowered to the following sequence that uses
4756   // AdvSIMD registers/instructions as long as the copies to/from
4757   // the AdvSIMD registers are cheap.
4758   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4759   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4760   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4761   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4762   SDValue Val = Op.getOperand(0);
4763   SDLoc DL(Op);
4764   EVT VT = Op.getValueType();
4765 
4766   if (VT == MVT::i32 || VT == MVT::i64) {
4767     if (VT == MVT::i32)
4768       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4769     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4770 
4771     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4772     SDValue UaddLV = DAG.getNode(
4773         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4774         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4775 
4776     if (VT == MVT::i64)
4777       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4778     return UaddLV;
4779   }
4780 
4781   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4782           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4783          "Unexpected type for custom ctpop lowering");
4784 
4785   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4786   Val = DAG.getBitcast(VT8Bit, Val);
4787   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4788 
4789   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4790   unsigned EltSize = 8;
4791   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4792   while (EltSize != VT.getScalarSizeInBits()) {
4793     EltSize *= 2;
4794     NumElts /= 2;
4795     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4796     Val = DAG.getNode(
4797         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4798         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4799   }
4800 
4801   return Val;
4802 }
4803 
4804 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4805 
4806   if (Op.getValueType().isVector())
4807     return LowerVSETCC(Op, DAG);
4808 
4809   SDValue LHS = Op.getOperand(0);
4810   SDValue RHS = Op.getOperand(1);
4811   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4812   SDLoc dl(Op);
4813 
4814   // We chose ZeroOrOneBooleanContents, so use zero and one.
4815   EVT VT = Op.getValueType();
4816   SDValue TVal = DAG.getConstant(1, dl, VT);
4817   SDValue FVal = DAG.getConstant(0, dl, VT);
4818 
4819   // Handle f128 first, since one possible outcome is a normal integer
4820   // comparison which gets picked up by the next if statement.
4821   if (LHS.getValueType() == MVT::f128) {
4822     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4823 
4824     // If softenSetCCOperands returned a scalar, use it.
4825     if (!RHS.getNode()) {
4826       assert(LHS.getValueType() == Op.getValueType() &&
4827              "Unexpected setcc expansion!");
4828       return LHS;
4829     }
4830   }
4831 
4832   if (LHS.getValueType().isInteger()) {
4833     SDValue CCVal;
4834     SDValue Cmp =
4835         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4836 
4837     // Note that we inverted the condition above, so we reverse the order of
4838     // the true and false operands here.  This will allow the setcc to be
4839     // matched to a single CSINC instruction.
4840     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4841   }
4842 
4843   // Now we know we're dealing with FP values.
4844   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4845          LHS.getValueType() == MVT::f64);
4846 
4847   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4848   // and do the comparison.
4849   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4850 
4851   AArch64CC::CondCode CC1, CC2;
4852   changeFPCCToAArch64CC(CC, CC1, CC2);
4853   if (CC2 == AArch64CC::AL) {
4854     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4855     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4856 
4857     // Note that we inverted the condition above, so we reverse the order of
4858     // the true and false operands here.  This will allow the setcc to be
4859     // matched to a single CSINC instruction.
4860     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4861   } else {
4862     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4863     // totally clean.  Some of them require two CSELs to implement.  As is in
4864     // this case, we emit the first CSEL and then emit a second using the output
4865     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4866 
4867     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4868     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4869     SDValue CS1 =
4870         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4871 
4872     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4873     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4874   }
4875 }
4876 
4877 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4878                                               SDValue RHS, SDValue TVal,
4879                                               SDValue FVal, const SDLoc &dl,
4880                                               SelectionDAG &DAG) const {
4881   // Handle f128 first, because it will result in a comparison of some RTLIB
4882   // call result against zero.
4883   if (LHS.getValueType() == MVT::f128) {
4884     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4885 
4886     // If softenSetCCOperands returned a scalar, we need to compare the result
4887     // against zero to select between true and false values.
4888     if (!RHS.getNode()) {
4889       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4890       CC = ISD::SETNE;
4891     }
4892   }
4893 
4894   // Also handle f16, for which we need to do a f32 comparison.
4895   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4896     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4897     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4898   }
4899 
4900   // Next, handle integers.
4901   if (LHS.getValueType().isInteger()) {
4902     assert((LHS.getValueType() == RHS.getValueType()) &&
4903            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4904 
4905     unsigned Opcode = AArch64ISD::CSEL;
4906 
4907     // If both the TVal and the FVal are constants, see if we can swap them in
4908     // order to for a CSINV or CSINC out of them.
4909     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4910     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4911 
4912     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4913       std::swap(TVal, FVal);
4914       std::swap(CTVal, CFVal);
4915       CC = ISD::getSetCCInverse(CC, true);
4916     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4917       std::swap(TVal, FVal);
4918       std::swap(CTVal, CFVal);
4919       CC = ISD::getSetCCInverse(CC, true);
4920     } else if (TVal.getOpcode() == ISD::XOR) {
4921       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4922       // with a CSINV rather than a CSEL.
4923       if (isAllOnesConstant(TVal.getOperand(1))) {
4924         std::swap(TVal, FVal);
4925         std::swap(CTVal, CFVal);
4926         CC = ISD::getSetCCInverse(CC, true);
4927       }
4928     } else if (TVal.getOpcode() == ISD::SUB) {
4929       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4930       // that we can match with a CSNEG rather than a CSEL.
4931       if (isNullConstant(TVal.getOperand(0))) {
4932         std::swap(TVal, FVal);
4933         std::swap(CTVal, CFVal);
4934         CC = ISD::getSetCCInverse(CC, true);
4935       }
4936     } else if (CTVal && CFVal) {
4937       const int64_t TrueVal = CTVal->getSExtValue();
4938       const int64_t FalseVal = CFVal->getSExtValue();
4939       bool Swap = false;
4940 
4941       // If both TVal and FVal are constants, see if FVal is the
4942       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4943       // instead of a CSEL in that case.
4944       if (TrueVal == ~FalseVal) {
4945         Opcode = AArch64ISD::CSINV;
4946       } else if (TrueVal == -FalseVal) {
4947         Opcode = AArch64ISD::CSNEG;
4948       } else if (TVal.getValueType() == MVT::i32) {
4949         // If our operands are only 32-bit wide, make sure we use 32-bit
4950         // arithmetic for the check whether we can use CSINC. This ensures that
4951         // the addition in the check will wrap around properly in case there is
4952         // an overflow (which would not be the case if we do the check with
4953         // 64-bit arithmetic).
4954         const uint32_t TrueVal32 = CTVal->getZExtValue();
4955         const uint32_t FalseVal32 = CFVal->getZExtValue();
4956 
4957         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4958           Opcode = AArch64ISD::CSINC;
4959 
4960           if (TrueVal32 > FalseVal32) {
4961             Swap = true;
4962           }
4963         }
4964         // 64-bit check whether we can use CSINC.
4965       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4966         Opcode = AArch64ISD::CSINC;
4967 
4968         if (TrueVal > FalseVal) {
4969           Swap = true;
4970         }
4971       }
4972 
4973       // Swap TVal and FVal if necessary.
4974       if (Swap) {
4975         std::swap(TVal, FVal);
4976         std::swap(CTVal, CFVal);
4977         CC = ISD::getSetCCInverse(CC, true);
4978       }
4979 
4980       if (Opcode != AArch64ISD::CSEL) {
4981         // Drop FVal since we can get its value by simply inverting/negating
4982         // TVal.
4983         FVal = TVal;
4984       }
4985     }
4986 
4987     // Avoid materializing a constant when possible by reusing a known value in
4988     // a register.  However, don't perform this optimization if the known value
4989     // is one, zero or negative one in the case of a CSEL.  We can always
4990     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4991     // FVal, respectively.
4992     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4993     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4994         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4995       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4996       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4997       // "a != C ? x : a" to avoid materializing C.
4998       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4999         TVal = LHS;
5000       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5001         FVal = LHS;
5002     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5003       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5004       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5005       // avoid materializing C.
5006       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5007       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5008         Opcode = AArch64ISD::CSINV;
5009         TVal = LHS;
5010         FVal = DAG.getConstant(0, dl, FVal.getValueType());
5011       }
5012     }
5013 
5014     SDValue CCVal;
5015     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5016     EVT VT = TVal.getValueType();
5017     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5018   }
5019 
5020   // Now we know we're dealing with FP values.
5021   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5022          LHS.getValueType() == MVT::f64);
5023   assert(LHS.getValueType() == RHS.getValueType());
5024   EVT VT = TVal.getValueType();
5025   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5026 
5027   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5028   // clean.  Some of them require two CSELs to implement.
5029   AArch64CC::CondCode CC1, CC2;
5030   changeFPCCToAArch64CC(CC, CC1, CC2);
5031 
5032   if (DAG.getTarget().Options.UnsafeFPMath) {
5033     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5034     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5035     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5036     if (RHSVal && RHSVal->isZero()) {
5037       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5038       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5039 
5040       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5041           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5042         TVal = LHS;
5043       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5044                CFVal && CFVal->isZero() &&
5045                FVal.getValueType() == LHS.getValueType())
5046         FVal = LHS;
5047     }
5048   }
5049 
5050   // Emit first, and possibly only, CSEL.
5051   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5052   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5053 
5054   // If we need a second CSEL, emit it, using the output of the first as the
5055   // RHS.  We're effectively OR'ing the two CC's together.
5056   if (CC2 != AArch64CC::AL) {
5057     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5058     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5059   }
5060 
5061   // Otherwise, return the output of the first CSEL.
5062   return CS1;
5063 }
5064 
5065 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5066                                               SelectionDAG &DAG) const {
5067   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5068   SDValue LHS = Op.getOperand(0);
5069   SDValue RHS = Op.getOperand(1);
5070   SDValue TVal = Op.getOperand(2);
5071   SDValue FVal = Op.getOperand(3);
5072   SDLoc DL(Op);
5073   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5074 }
5075 
5076 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5077                                            SelectionDAG &DAG) const {
5078   SDValue CCVal = Op->getOperand(0);
5079   SDValue TVal = Op->getOperand(1);
5080   SDValue FVal = Op->getOperand(2);
5081   SDLoc DL(Op);
5082 
5083   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5084   // instruction.
5085   if (isOverflowIntrOpRes(CCVal)) {
5086     // Only lower legal XALUO ops.
5087     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5088       return SDValue();
5089 
5090     AArch64CC::CondCode OFCC;
5091     SDValue Value, Overflow;
5092     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5093     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5094 
5095     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5096                        CCVal, Overflow);
5097   }
5098 
5099   // Lower it the same way as we would lower a SELECT_CC node.
5100   ISD::CondCode CC;
5101   SDValue LHS, RHS;
5102   if (CCVal.getOpcode() == ISD::SETCC) {
5103     LHS = CCVal.getOperand(0);
5104     RHS = CCVal.getOperand(1);
5105     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5106   } else {
5107     LHS = CCVal;
5108     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5109     CC = ISD::SETNE;
5110   }
5111   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5112 }
5113 
5114 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5115                                               SelectionDAG &DAG) const {
5116   // Jump table entries as PC relative offsets. No additional tweaking
5117   // is necessary here. Just get the address of the jump table.
5118   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5119 
5120   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5121       !Subtarget->isTargetMachO()) {
5122     return getAddrLarge(JT, DAG);
5123   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5124     return getAddrTiny(JT, DAG);
5125   }
5126   return getAddr(JT, DAG);
5127 }
5128 
5129 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5130                                           SelectionDAG &DAG) const {
5131   // Jump table entries as PC relative offsets. No additional tweaking
5132   // is necessary here. Just get the address of the jump table.
5133   SDLoc DL(Op);
5134   SDValue JT = Op.getOperand(1);
5135   SDValue Entry = Op.getOperand(2);
5136   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5137 
5138   SDNode *Dest =
5139       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5140                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5141   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5142                      SDValue(Dest, 0));
5143 }
5144 
5145 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5146                                                  SelectionDAG &DAG) const {
5147   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5148 
5149   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5150     // Use the GOT for the large code model on iOS.
5151     if (Subtarget->isTargetMachO()) {
5152       return getGOT(CP, DAG);
5153     }
5154     return getAddrLarge(CP, DAG);
5155   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5156     return getAddrTiny(CP, DAG);
5157   } else {
5158     return getAddr(CP, DAG);
5159   }
5160 }
5161 
5162 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5163                                                SelectionDAG &DAG) const {
5164   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5165   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5166       !Subtarget->isTargetMachO()) {
5167     return getAddrLarge(BA, DAG);
5168   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5169     return getAddrTiny(BA, DAG);
5170   }
5171   return getAddr(BA, DAG);
5172 }
5173 
5174 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5175                                                  SelectionDAG &DAG) const {
5176   AArch64FunctionInfo *FuncInfo =
5177       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5178 
5179   SDLoc DL(Op);
5180   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5181                                  getPointerTy(DAG.getDataLayout()));
5182   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5183   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5184                       MachinePointerInfo(SV));
5185 }
5186 
5187 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5188                                                   SelectionDAG &DAG) const {
5189   AArch64FunctionInfo *FuncInfo =
5190       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5191 
5192   SDLoc DL(Op);
5193   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5194                                      ? FuncInfo->getVarArgsGPRIndex()
5195                                      : FuncInfo->getVarArgsStackIndex(),
5196                                  getPointerTy(DAG.getDataLayout()));
5197   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5198   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5199                       MachinePointerInfo(SV));
5200 }
5201 
5202 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5203                                                 SelectionDAG &DAG) const {
5204   // The layout of the va_list struct is specified in the AArch64 Procedure Call
5205   // Standard, section B.3.
5206   MachineFunction &MF = DAG.getMachineFunction();
5207   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5208   auto PtrVT = getPointerTy(DAG.getDataLayout());
5209   SDLoc DL(Op);
5210 
5211   SDValue Chain = Op.getOperand(0);
5212   SDValue VAList = Op.getOperand(1);
5213   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5214   SmallVector<SDValue, 4> MemOps;
5215 
5216   // void *__stack at offset 0
5217   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5218   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5219                                 MachinePointerInfo(SV), /* Alignment = */ 8));
5220 
5221   // void *__gr_top at offset 8
5222   int GPRSize = FuncInfo->getVarArgsGPRSize();
5223   if (GPRSize > 0) {
5224     SDValue GRTop, GRTopAddr;
5225 
5226     GRTopAddr =
5227         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5228 
5229     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5230     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5231                         DAG.getConstant(GPRSize, DL, PtrVT));
5232 
5233     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5234                                   MachinePointerInfo(SV, 8),
5235                                   /* Alignment = */ 8));
5236   }
5237 
5238   // void *__vr_top at offset 16
5239   int FPRSize = FuncInfo->getVarArgsFPRSize();
5240   if (FPRSize > 0) {
5241     SDValue VRTop, VRTopAddr;
5242     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5243                             DAG.getConstant(16, DL, PtrVT));
5244 
5245     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5246     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5247                         DAG.getConstant(FPRSize, DL, PtrVT));
5248 
5249     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5250                                   MachinePointerInfo(SV, 16),
5251                                   /* Alignment = */ 8));
5252   }
5253 
5254   // int __gr_offs at offset 24
5255   SDValue GROffsAddr =
5256       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5257   MemOps.push_back(DAG.getStore(
5258       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5259       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5260 
5261   // int __vr_offs at offset 28
5262   SDValue VROffsAddr =
5263       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5264   MemOps.push_back(DAG.getStore(
5265       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5266       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5267 
5268   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5269 }
5270 
5271 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5272                                             SelectionDAG &DAG) const {
5273   MachineFunction &MF = DAG.getMachineFunction();
5274 
5275   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5276     return LowerWin64_VASTART(Op, DAG);
5277   else if (Subtarget->isTargetDarwin())
5278     return LowerDarwin_VASTART(Op, DAG);
5279   else
5280     return LowerAAPCS_VASTART(Op, DAG);
5281 }
5282 
5283 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5284                                            SelectionDAG &DAG) const {
5285   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5286   // pointer.
5287   SDLoc DL(Op);
5288   unsigned VaListSize =
5289       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5290   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5291   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5292 
5293   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5294                        Op.getOperand(2),
5295                        DAG.getConstant(VaListSize, DL, MVT::i32),
5296                        8, false, false, false, MachinePointerInfo(DestSV),
5297                        MachinePointerInfo(SrcSV));
5298 }
5299 
5300 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5301   assert(Subtarget->isTargetDarwin() &&
5302          "automatic va_arg instruction only works on Darwin");
5303 
5304   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5305   EVT VT = Op.getValueType();
5306   SDLoc DL(Op);
5307   SDValue Chain = Op.getOperand(0);
5308   SDValue Addr = Op.getOperand(1);
5309   unsigned Align = Op.getConstantOperandVal(3);
5310   auto PtrVT = getPointerTy(DAG.getDataLayout());
5311 
5312   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5313   Chain = VAList.getValue(1);
5314 
5315   if (Align > 8) {
5316     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5317     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5318                          DAG.getConstant(Align - 1, DL, PtrVT));
5319     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5320                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5321   }
5322 
5323   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5324   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5325 
5326   // Scalar integer and FP values smaller than 64 bits are implicitly extended
5327   // up to 64 bits.  At the very least, we have to increase the striding of the
5328   // vaargs list to match this, and for FP values we need to introduce
5329   // FP_ROUND nodes as well.
5330   if (VT.isInteger() && !VT.isVector())
5331     ArgSize = 8;
5332   bool NeedFPTrunc = false;
5333   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5334     ArgSize = 8;
5335     NeedFPTrunc = true;
5336   }
5337 
5338   // Increment the pointer, VAList, to the next vaarg
5339   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5340                                DAG.getConstant(ArgSize, DL, PtrVT));
5341   // Store the incremented VAList to the legalized pointer
5342   SDValue APStore =
5343       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5344 
5345   // Load the actual argument out of the pointer VAList
5346   if (NeedFPTrunc) {
5347     // Load the value as an f64.
5348     SDValue WideFP =
5349         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5350     // Round the value down to an f32.
5351     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5352                                    DAG.getIntPtrConstant(1, DL));
5353     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5354     // Merge the rounded value with the chain output of the load.
5355     return DAG.getMergeValues(Ops, DL);
5356   }
5357 
5358   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5359 }
5360 
5361 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5362                                               SelectionDAG &DAG) const {
5363   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5364   MFI.setFrameAddressIsTaken(true);
5365 
5366   EVT VT = Op.getValueType();
5367   SDLoc DL(Op);
5368   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5369   SDValue FrameAddr =
5370       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5371   while (Depth--)
5372     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5373                             MachinePointerInfo());
5374   return FrameAddr;
5375 }
5376 
5377 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5378                                               SelectionDAG &DAG) const {
5379   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5380 
5381   EVT VT = getPointerTy(DAG.getDataLayout());
5382   SDLoc DL(Op);
5383   int FI = MFI.CreateFixedObject(4, 0, false);
5384   return DAG.getFrameIndex(FI, VT);
5385 }
5386 
5387 #define GET_REGISTER_MATCHER
5388 #include "AArch64GenAsmMatcher.inc"
5389 
5390 // FIXME? Maybe this could be a TableGen attribute on some registers and
5391 // this table could be generated automatically from RegInfo.
5392 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5393                                                   SelectionDAG &DAG) const {
5394   unsigned Reg = MatchRegisterName(RegName);
5395   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5396     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5397     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5398     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5399       Reg = 0;
5400   }
5401   if (Reg)
5402     return Reg;
5403   report_fatal_error(Twine("Invalid register name \""
5404                               + StringRef(RegName)  + "\"."));
5405 }
5406 
5407 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5408                                                      SelectionDAG &DAG) const {
5409   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5410 
5411   EVT VT = Op.getValueType();
5412   SDLoc DL(Op);
5413 
5414   SDValue FrameAddr =
5415       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5416   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5417 
5418   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5419 }
5420 
5421 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5422                                                SelectionDAG &DAG) const {
5423   MachineFunction &MF = DAG.getMachineFunction();
5424   MachineFrameInfo &MFI = MF.getFrameInfo();
5425   MFI.setReturnAddressIsTaken(true);
5426 
5427   EVT VT = Op.getValueType();
5428   SDLoc DL(Op);
5429   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5430   if (Depth) {
5431     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5432     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5433     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5434                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5435                        MachinePointerInfo());
5436   }
5437 
5438   // Return LR, which contains the return address. Mark it an implicit live-in.
5439   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5440   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5441 }
5442 
5443 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5444 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5445 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5446                                                     SelectionDAG &DAG) const {
5447   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5448   EVT VT = Op.getValueType();
5449   unsigned VTBits = VT.getSizeInBits();
5450   SDLoc dl(Op);
5451   SDValue ShOpLo = Op.getOperand(0);
5452   SDValue ShOpHi = Op.getOperand(1);
5453   SDValue ShAmt = Op.getOperand(2);
5454   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5455 
5456   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5457 
5458   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5459                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5460   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5461 
5462   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5463   // is "undef". We wanted 0, so CSEL it directly.
5464   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5465                                ISD::SETEQ, dl, DAG);
5466   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5467   HiBitsForLo =
5468       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5469                   HiBitsForLo, CCVal, Cmp);
5470 
5471   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5472                                    DAG.getConstant(VTBits, dl, MVT::i64));
5473 
5474   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5475   SDValue LoForNormalShift =
5476       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5477 
5478   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5479                        dl, DAG);
5480   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5481   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5482   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5483                            LoForNormalShift, CCVal, Cmp);
5484 
5485   // AArch64 shifts larger than the register width are wrapped rather than
5486   // clamped, so we can't just emit "hi >> x".
5487   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5488   SDValue HiForBigShift =
5489       Opc == ISD::SRA
5490           ? DAG.getNode(Opc, dl, VT, ShOpHi,
5491                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
5492           : DAG.getConstant(0, dl, VT);
5493   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5494                            HiForNormalShift, CCVal, Cmp);
5495 
5496   SDValue Ops[2] = { Lo, Hi };
5497   return DAG.getMergeValues(Ops, dl);
5498 }
5499 
5500 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5501 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5502 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5503                                                    SelectionDAG &DAG) const {
5504   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5505   EVT VT = Op.getValueType();
5506   unsigned VTBits = VT.getSizeInBits();
5507   SDLoc dl(Op);
5508   SDValue ShOpLo = Op.getOperand(0);
5509   SDValue ShOpHi = Op.getOperand(1);
5510   SDValue ShAmt = Op.getOperand(2);
5511 
5512   assert(Op.getOpcode() == ISD::SHL_PARTS);
5513   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5514                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5515   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5516 
5517   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5518   // is "undef". We wanted 0, so CSEL it directly.
5519   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5520                                ISD::SETEQ, dl, DAG);
5521   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5522   LoBitsForHi =
5523       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5524                   LoBitsForHi, CCVal, Cmp);
5525 
5526   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5527                                    DAG.getConstant(VTBits, dl, MVT::i64));
5528   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5529   SDValue HiForNormalShift =
5530       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5531 
5532   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5533 
5534   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5535                        dl, DAG);
5536   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5537   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5538                            HiForNormalShift, CCVal, Cmp);
5539 
5540   // AArch64 shifts of larger than register sizes are wrapped rather than
5541   // clamped, so we can't just emit "lo << a" if a is too big.
5542   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5543   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5544   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5545                            LoForNormalShift, CCVal, Cmp);
5546 
5547   SDValue Ops[2] = { Lo, Hi };
5548   return DAG.getMergeValues(Ops, dl);
5549 }
5550 
5551 bool AArch64TargetLowering::isOffsetFoldingLegal(
5552     const GlobalAddressSDNode *GA) const {
5553   // Offsets are folded in the DAG combine rather than here so that we can
5554   // intelligently choose an offset based on the uses.
5555   return false;
5556 }
5557 
5558 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5559                                          bool OptForSize) const {
5560   bool IsLegal = false;
5561   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5562   // 16-bit case when target has full fp16 support.
5563   // FIXME: We should be able to handle f128 as well with a clever lowering.
5564   const APInt ImmInt = Imm.bitcastToAPInt();
5565   if (VT == MVT::f64)
5566     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5567   else if (VT == MVT::f32)
5568     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5569   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5570     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5571   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5572   //       generate that fmov.
5573 
5574   // If we can not materialize in immediate field for fmov, check if the
5575   // value can be encoded as the immediate operand of a logical instruction.
5576   // The immediate value will be created with either MOVZ, MOVN, or ORR.
5577   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5578     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5579     // however the mov+fmov sequence is always better because of the reduced
5580     // cache pressure. The timings are still the same if you consider
5581     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5582     // movw+movk is fused). So we limit up to 2 instrdduction at most.
5583     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5584     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5585 			      Insn);
5586     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5587     IsLegal = Insn.size() <= Limit;
5588   }
5589 
5590   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5591                     << " imm value: "; Imm.dump(););
5592   return IsLegal;
5593 }
5594 
5595 //===----------------------------------------------------------------------===//
5596 //                          AArch64 Optimization Hooks
5597 //===----------------------------------------------------------------------===//
5598 
5599 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5600                            SDValue Operand, SelectionDAG &DAG,
5601                            int &ExtraSteps) {
5602   EVT VT = Operand.getValueType();
5603   if (ST->hasNEON() &&
5604       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5605        VT == MVT::f32 || VT == MVT::v1f32 ||
5606        VT == MVT::v2f32 || VT == MVT::v4f32)) {
5607     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5608       // For the reciprocal estimates, convergence is quadratic, so the number
5609       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
5610       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
5611       // the result for float (23 mantissa bits) is 2 and for double (52
5612       // mantissa bits) is 3.
5613       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5614 
5615     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5616   }
5617 
5618   return SDValue();
5619 }
5620 
5621 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5622                                                SelectionDAG &DAG, int Enabled,
5623                                                int &ExtraSteps,
5624                                                bool &UseOneConst,
5625                                                bool Reciprocal) const {
5626   if (Enabled == ReciprocalEstimate::Enabled ||
5627       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5628     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5629                                        DAG, ExtraSteps)) {
5630       SDLoc DL(Operand);
5631       EVT VT = Operand.getValueType();
5632 
5633       SDNodeFlags Flags;
5634       Flags.setAllowReassociation(true);
5635 
5636       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5637       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5638       for (int i = ExtraSteps; i > 0; --i) {
5639         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5640                                    Flags);
5641         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5642         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5643       }
5644       if (!Reciprocal) {
5645         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5646                                       VT);
5647         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5648         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5649 
5650         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5651         // Correct the result if the operand is 0.0.
5652         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5653                                VT, Eq, Operand, Estimate);
5654       }
5655 
5656       ExtraSteps = 0;
5657       return Estimate;
5658     }
5659 
5660   return SDValue();
5661 }
5662 
5663 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5664                                                 SelectionDAG &DAG, int Enabled,
5665                                                 int &ExtraSteps) const {
5666   if (Enabled == ReciprocalEstimate::Enabled)
5667     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5668                                        DAG, ExtraSteps)) {
5669       SDLoc DL(Operand);
5670       EVT VT = Operand.getValueType();
5671 
5672       SDNodeFlags Flags;
5673       Flags.setAllowReassociation(true);
5674 
5675       // Newton reciprocal iteration: E * (2 - X * E)
5676       // AArch64 reciprocal iteration instruction: (2 - M * N)
5677       for (int i = ExtraSteps; i > 0; --i) {
5678         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5679                                    Estimate, Flags);
5680         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5681       }
5682 
5683       ExtraSteps = 0;
5684       return Estimate;
5685     }
5686 
5687   return SDValue();
5688 }
5689 
5690 //===----------------------------------------------------------------------===//
5691 //                          AArch64 Inline Assembly Support
5692 //===----------------------------------------------------------------------===//
5693 
5694 // Table of Constraints
5695 // TODO: This is the current set of constraints supported by ARM for the
5696 // compiler, not all of them may make sense.
5697 //
5698 // r - A general register
5699 // w - An FP/SIMD register of some size in the range v0-v31
5700 // x - An FP/SIMD register of some size in the range v0-v15
5701 // I - Constant that can be used with an ADD instruction
5702 // J - Constant that can be used with a SUB instruction
5703 // K - Constant that can be used with a 32-bit logical instruction
5704 // L - Constant that can be used with a 64-bit logical instruction
5705 // M - Constant that can be used as a 32-bit MOV immediate
5706 // N - Constant that can be used as a 64-bit MOV immediate
5707 // Q - A memory reference with base register and no offset
5708 // S - A symbolic address
5709 // Y - Floating point constant zero
5710 // Z - Integer constant zero
5711 //
5712 //   Note that general register operands will be output using their 64-bit x
5713 // register name, whatever the size of the variable, unless the asm operand
5714 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5715 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5716 // %q modifier.
5717 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5718   // At this point, we have to lower this constraint to something else, so we
5719   // lower it to an "r" or "w". However, by doing this we will force the result
5720   // to be in register, while the X constraint is much more permissive.
5721   //
5722   // Although we are correct (we are free to emit anything, without
5723   // constraints), we might break use cases that would expect us to be more
5724   // efficient and emit something else.
5725   if (!Subtarget->hasFPARMv8())
5726     return "r";
5727 
5728   if (ConstraintVT.isFloatingPoint())
5729     return "w";
5730 
5731   if (ConstraintVT.isVector() &&
5732      (ConstraintVT.getSizeInBits() == 64 ||
5733       ConstraintVT.getSizeInBits() == 128))
5734     return "w";
5735 
5736   return "r";
5737 }
5738 
5739 /// getConstraintType - Given a constraint letter, return the type of
5740 /// constraint it is for this target.
5741 AArch64TargetLowering::ConstraintType
5742 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5743   if (Constraint.size() == 1) {
5744     switch (Constraint[0]) {
5745     default:
5746       break;
5747     case 'x':
5748     case 'w':
5749       return C_RegisterClass;
5750     // An address with a single base register. Due to the way we
5751     // currently handle addresses it is the same as 'r'.
5752     case 'Q':
5753       return C_Memory;
5754     case 'I':
5755     case 'J':
5756     case 'K':
5757     case 'L':
5758     case 'M':
5759     case 'N':
5760     case 'Y':
5761     case 'Z':
5762       return C_Immediate;
5763     case 'z':
5764     case 'S': // A symbolic address
5765       return C_Other;
5766     }
5767   }
5768   return TargetLowering::getConstraintType(Constraint);
5769 }
5770 
5771 /// Examine constraint type and operand type and determine a weight value.
5772 /// This object must already have been set up with the operand type
5773 /// and the current alternative constraint selected.
5774 TargetLowering::ConstraintWeight
5775 AArch64TargetLowering::getSingleConstraintMatchWeight(
5776     AsmOperandInfo &info, const char *constraint) const {
5777   ConstraintWeight weight = CW_Invalid;
5778   Value *CallOperandVal = info.CallOperandVal;
5779   // If we don't have a value, we can't do a match,
5780   // but allow it at the lowest weight.
5781   if (!CallOperandVal)
5782     return CW_Default;
5783   Type *type = CallOperandVal->getType();
5784   // Look at the constraint type.
5785   switch (*constraint) {
5786   default:
5787     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5788     break;
5789   case 'x':
5790   case 'w':
5791     if (type->isFloatingPointTy() || type->isVectorTy())
5792       weight = CW_Register;
5793     break;
5794   case 'z':
5795     weight = CW_Constant;
5796     break;
5797   }
5798   return weight;
5799 }
5800 
5801 std::pair<unsigned, const TargetRegisterClass *>
5802 AArch64TargetLowering::getRegForInlineAsmConstraint(
5803     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5804   if (Constraint.size() == 1) {
5805     switch (Constraint[0]) {
5806     case 'r':
5807       if (VT.getSizeInBits() == 64)
5808         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5809       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5810     case 'w':
5811       if (!Subtarget->hasFPARMv8())
5812         break;
5813       if (VT.getSizeInBits() == 16)
5814         return std::make_pair(0U, &AArch64::FPR16RegClass);
5815       if (VT.getSizeInBits() == 32)
5816         return std::make_pair(0U, &AArch64::FPR32RegClass);
5817       if (VT.getSizeInBits() == 64)
5818         return std::make_pair(0U, &AArch64::FPR64RegClass);
5819       if (VT.getSizeInBits() == 128)
5820         return std::make_pair(0U, &AArch64::FPR128RegClass);
5821       break;
5822     // The instructions that this constraint is designed for can
5823     // only take 128-bit registers so just use that regclass.
5824     case 'x':
5825       if (!Subtarget->hasFPARMv8())
5826         break;
5827       if (VT.getSizeInBits() == 128)
5828         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5829       break;
5830     }
5831   }
5832   if (StringRef("{cc}").equals_lower(Constraint))
5833     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5834 
5835   // Use the default implementation in TargetLowering to convert the register
5836   // constraint into a member of a register class.
5837   std::pair<unsigned, const TargetRegisterClass *> Res;
5838   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5839 
5840   // Not found as a standard register?
5841   if (!Res.second) {
5842     unsigned Size = Constraint.size();
5843     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5844         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5845       int RegNo;
5846       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5847       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5848         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5849         // By default we'll emit v0-v31 for this unless there's a modifier where
5850         // we'll emit the correct register as well.
5851         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5852           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5853           Res.second = &AArch64::FPR64RegClass;
5854         } else {
5855           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5856           Res.second = &AArch64::FPR128RegClass;
5857         }
5858       }
5859     }
5860   }
5861 
5862   if (Res.second && !Subtarget->hasFPARMv8() &&
5863       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5864       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5865     return std::make_pair(0U, nullptr);
5866 
5867   return Res;
5868 }
5869 
5870 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5871 /// vector.  If it is invalid, don't add anything to Ops.
5872 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5873     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5874     SelectionDAG &DAG) const {
5875   SDValue Result;
5876 
5877   // Currently only support length 1 constraints.
5878   if (Constraint.length() != 1)
5879     return;
5880 
5881   char ConstraintLetter = Constraint[0];
5882   switch (ConstraintLetter) {
5883   default:
5884     break;
5885 
5886   // This set of constraints deal with valid constants for various instructions.
5887   // Validate and return a target constant for them if we can.
5888   case 'z': {
5889     // 'z' maps to xzr or wzr so it needs an input of 0.
5890     if (!isNullConstant(Op))
5891       return;
5892 
5893     if (Op.getValueType() == MVT::i64)
5894       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5895     else
5896       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5897     break;
5898   }
5899   case 'S': {
5900     // An absolute symbolic address or label reference.
5901     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5902       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5903                                           GA->getValueType(0));
5904     } else if (const BlockAddressSDNode *BA =
5905                    dyn_cast<BlockAddressSDNode>(Op)) {
5906       Result =
5907           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5908     } else if (const ExternalSymbolSDNode *ES =
5909                    dyn_cast<ExternalSymbolSDNode>(Op)) {
5910       Result =
5911           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5912     } else
5913       return;
5914     break;
5915   }
5916 
5917   case 'I':
5918   case 'J':
5919   case 'K':
5920   case 'L':
5921   case 'M':
5922   case 'N':
5923     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5924     if (!C)
5925       return;
5926 
5927     // Grab the value and do some validation.
5928     uint64_t CVal = C->getZExtValue();
5929     switch (ConstraintLetter) {
5930     // The I constraint applies only to simple ADD or SUB immediate operands:
5931     // i.e. 0 to 4095 with optional shift by 12
5932     // The J constraint applies only to ADD or SUB immediates that would be
5933     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5934     // instruction [or vice versa], in other words -1 to -4095 with optional
5935     // left shift by 12.
5936     case 'I':
5937       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5938         break;
5939       return;
5940     case 'J': {
5941       uint64_t NVal = -C->getSExtValue();
5942       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5943         CVal = C->getSExtValue();
5944         break;
5945       }
5946       return;
5947     }
5948     // The K and L constraints apply *only* to logical immediates, including
5949     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5950     // been removed and MOV should be used). So these constraints have to
5951     // distinguish between bit patterns that are valid 32-bit or 64-bit
5952     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5953     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5954     // versa.
5955     case 'K':
5956       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5957         break;
5958       return;
5959     case 'L':
5960       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5961         break;
5962       return;
5963     // The M and N constraints are a superset of K and L respectively, for use
5964     // with the MOV (immediate) alias. As well as the logical immediates they
5965     // also match 32 or 64-bit immediates that can be loaded either using a
5966     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5967     // (M) or 64-bit 0x1234000000000000 (N) etc.
5968     // As a note some of this code is liberally stolen from the asm parser.
5969     case 'M': {
5970       if (!isUInt<32>(CVal))
5971         return;
5972       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5973         break;
5974       if ((CVal & 0xFFFF) == CVal)
5975         break;
5976       if ((CVal & 0xFFFF0000ULL) == CVal)
5977         break;
5978       uint64_t NCVal = ~(uint32_t)CVal;
5979       if ((NCVal & 0xFFFFULL) == NCVal)
5980         break;
5981       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5982         break;
5983       return;
5984     }
5985     case 'N': {
5986       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5987         break;
5988       if ((CVal & 0xFFFFULL) == CVal)
5989         break;
5990       if ((CVal & 0xFFFF0000ULL) == CVal)
5991         break;
5992       if ((CVal & 0xFFFF00000000ULL) == CVal)
5993         break;
5994       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5995         break;
5996       uint64_t NCVal = ~CVal;
5997       if ((NCVal & 0xFFFFULL) == NCVal)
5998         break;
5999       if ((NCVal & 0xFFFF0000ULL) == NCVal)
6000         break;
6001       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6002         break;
6003       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6004         break;
6005       return;
6006     }
6007     default:
6008       return;
6009     }
6010 
6011     // All assembler immediates are 64-bit integers.
6012     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6013     break;
6014   }
6015 
6016   if (Result.getNode()) {
6017     Ops.push_back(Result);
6018     return;
6019   }
6020 
6021   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6022 }
6023 
6024 //===----------------------------------------------------------------------===//
6025 //                     AArch64 Advanced SIMD Support
6026 //===----------------------------------------------------------------------===//
6027 
6028 /// WidenVector - Given a value in the V64 register class, produce the
6029 /// equivalent value in the V128 register class.
6030 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6031   EVT VT = V64Reg.getValueType();
6032   unsigned NarrowSize = VT.getVectorNumElements();
6033   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6034   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6035   SDLoc DL(V64Reg);
6036 
6037   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6038                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
6039 }
6040 
6041 /// getExtFactor - Determine the adjustment factor for the position when
6042 /// generating an "extract from vector registers" instruction.
6043 static unsigned getExtFactor(SDValue &V) {
6044   EVT EltType = V.getValueType().getVectorElementType();
6045   return EltType.getSizeInBits() / 8;
6046 }
6047 
6048 /// NarrowVector - Given a value in the V128 register class, produce the
6049 /// equivalent value in the V64 register class.
6050 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6051   EVT VT = V128Reg.getValueType();
6052   unsigned WideSize = VT.getVectorNumElements();
6053   MVT EltTy = VT.getVectorElementType().getSimpleVT();
6054   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6055   SDLoc DL(V128Reg);
6056 
6057   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6058 }
6059 
6060 // Gather data to see if the operation can be modelled as a
6061 // shuffle in combination with VEXTs.
6062 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6063                                                   SelectionDAG &DAG) const {
6064   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6065   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6066   SDLoc dl(Op);
6067   EVT VT = Op.getValueType();
6068   unsigned NumElts = VT.getVectorNumElements();
6069 
6070   struct ShuffleSourceInfo {
6071     SDValue Vec;
6072     unsigned MinElt;
6073     unsigned MaxElt;
6074 
6075     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6076     // be compatible with the shuffle we intend to construct. As a result
6077     // ShuffleVec will be some sliding window into the original Vec.
6078     SDValue ShuffleVec;
6079 
6080     // Code should guarantee that element i in Vec starts at element "WindowBase
6081     // + i * WindowScale in ShuffleVec".
6082     int WindowBase;
6083     int WindowScale;
6084 
6085     ShuffleSourceInfo(SDValue Vec)
6086       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6087           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6088 
6089     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6090   };
6091 
6092   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6093   // node.
6094   SmallVector<ShuffleSourceInfo, 2> Sources;
6095   for (unsigned i = 0; i < NumElts; ++i) {
6096     SDValue V = Op.getOperand(i);
6097     if (V.isUndef())
6098       continue;
6099     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6100              !isa<ConstantSDNode>(V.getOperand(1))) {
6101       LLVM_DEBUG(
6102           dbgs() << "Reshuffle failed: "
6103                     "a shuffle can only come from building a vector from "
6104                     "various elements of other vectors, provided their "
6105                     "indices are constant\n");
6106       return SDValue();
6107     }
6108 
6109     // Add this element source to the list if it's not already there.
6110     SDValue SourceVec = V.getOperand(0);
6111     auto Source = find(Sources, SourceVec);
6112     if (Source == Sources.end())
6113       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6114 
6115     // Update the minimum and maximum lane number seen.
6116     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6117     Source->MinElt = std::min(Source->MinElt, EltNo);
6118     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6119   }
6120 
6121   if (Sources.size() > 2) {
6122     LLVM_DEBUG(
6123         dbgs() << "Reshuffle failed: currently only do something sane when at "
6124                   "most two source vectors are involved\n");
6125     return SDValue();
6126   }
6127 
6128   // Find out the smallest element size among result and two sources, and use
6129   // it as element size to build the shuffle_vector.
6130   EVT SmallestEltTy = VT.getVectorElementType();
6131   for (auto &Source : Sources) {
6132     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6133     if (SrcEltTy.bitsLT(SmallestEltTy)) {
6134       SmallestEltTy = SrcEltTy;
6135     }
6136   }
6137   unsigned ResMultiplier =
6138       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6139   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6140   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6141 
6142   // If the source vector is too wide or too narrow, we may nevertheless be able
6143   // to construct a compatible shuffle either by concatenating it with UNDEF or
6144   // extracting a suitable range of elements.
6145   for (auto &Src : Sources) {
6146     EVT SrcVT = Src.ShuffleVec.getValueType();
6147 
6148     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6149       continue;
6150 
6151     // This stage of the search produces a source with the same element type as
6152     // the original, but with a total width matching the BUILD_VECTOR output.
6153     EVT EltVT = SrcVT.getVectorElementType();
6154     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6155     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6156 
6157     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6158       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6159       // We can pad out the smaller vector for free, so if it's part of a
6160       // shuffle...
6161       Src.ShuffleVec =
6162           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6163                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6164       continue;
6165     }
6166 
6167     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6168 
6169     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6170       LLVM_DEBUG(
6171           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6172       return SDValue();
6173     }
6174 
6175     if (Src.MinElt >= NumSrcElts) {
6176       // The extraction can just take the second half
6177       Src.ShuffleVec =
6178           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6179                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6180       Src.WindowBase = -NumSrcElts;
6181     } else if (Src.MaxElt < NumSrcElts) {
6182       // The extraction can just take the first half
6183       Src.ShuffleVec =
6184           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6185                       DAG.getConstant(0, dl, MVT::i64));
6186     } else {
6187       // An actual VEXT is needed
6188       SDValue VEXTSrc1 =
6189           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6190                       DAG.getConstant(0, dl, MVT::i64));
6191       SDValue VEXTSrc2 =
6192           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6193                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
6194       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6195 
6196       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6197                                    VEXTSrc2,
6198                                    DAG.getConstant(Imm, dl, MVT::i32));
6199       Src.WindowBase = -Src.MinElt;
6200     }
6201   }
6202 
6203   // Another possible incompatibility occurs from the vector element types. We
6204   // can fix this by bitcasting the source vectors to the same type we intend
6205   // for the shuffle.
6206   for (auto &Src : Sources) {
6207     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6208     if (SrcEltTy == SmallestEltTy)
6209       continue;
6210     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6211     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6212     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6213     Src.WindowBase *= Src.WindowScale;
6214   }
6215 
6216   // Final sanity check before we try to actually produce a shuffle.
6217   LLVM_DEBUG(for (auto Src
6218                   : Sources)
6219                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6220 
6221   // The stars all align, our next step is to produce the mask for the shuffle.
6222   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6223   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6224   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6225     SDValue Entry = Op.getOperand(i);
6226     if (Entry.isUndef())
6227       continue;
6228 
6229     auto Src = find(Sources, Entry.getOperand(0));
6230     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6231 
6232     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6233     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6234     // segment.
6235     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6236     int BitsDefined =
6237         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6238     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6239 
6240     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6241     // starting at the appropriate offset.
6242     int *LaneMask = &Mask[i * ResMultiplier];
6243 
6244     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6245     ExtractBase += NumElts * (Src - Sources.begin());
6246     for (int j = 0; j < LanesDefined; ++j)
6247       LaneMask[j] = ExtractBase + j;
6248   }
6249 
6250   // Final check before we try to produce nonsense...
6251   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6252     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6253     return SDValue();
6254   }
6255 
6256   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6257   for (unsigned i = 0; i < Sources.size(); ++i)
6258     ShuffleOps[i] = Sources[i].ShuffleVec;
6259 
6260   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6261                                          ShuffleOps[1], Mask);
6262   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6263 
6264   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6265              dbgs() << "Reshuffle, creating node: "; V.dump(););
6266 
6267   return V;
6268 }
6269 
6270 // check if an EXT instruction can handle the shuffle mask when the
6271 // vector sources of the shuffle are the same.
6272 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6273   unsigned NumElts = VT.getVectorNumElements();
6274 
6275   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6276   if (M[0] < 0)
6277     return false;
6278 
6279   Imm = M[0];
6280 
6281   // If this is a VEXT shuffle, the immediate value is the index of the first
6282   // element.  The other shuffle indices must be the successive elements after
6283   // the first one.
6284   unsigned ExpectedElt = Imm;
6285   for (unsigned i = 1; i < NumElts; ++i) {
6286     // Increment the expected index.  If it wraps around, just follow it
6287     // back to index zero and keep going.
6288     ++ExpectedElt;
6289     if (ExpectedElt == NumElts)
6290       ExpectedElt = 0;
6291 
6292     if (M[i] < 0)
6293       continue; // ignore UNDEF indices
6294     if (ExpectedElt != static_cast<unsigned>(M[i]))
6295       return false;
6296   }
6297 
6298   return true;
6299 }
6300 
6301 // check if an EXT instruction can handle the shuffle mask when the
6302 // vector sources of the shuffle are different.
6303 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6304                       unsigned &Imm) {
6305   // Look for the first non-undef element.
6306   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6307 
6308   // Benefit form APInt to handle overflow when calculating expected element.
6309   unsigned NumElts = VT.getVectorNumElements();
6310   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6311   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6312   // The following shuffle indices must be the successive elements after the
6313   // first real element.
6314   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6315       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6316   if (FirstWrongElt != M.end())
6317     return false;
6318 
6319   // The index of an EXT is the first element if it is not UNDEF.
6320   // Watch out for the beginning UNDEFs. The EXT index should be the expected
6321   // value of the first element.  E.g.
6322   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6323   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6324   // ExpectedElt is the last mask index plus 1.
6325   Imm = ExpectedElt.getZExtValue();
6326 
6327   // There are two difference cases requiring to reverse input vectors.
6328   // For example, for vector <4 x i32> we have the following cases,
6329   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6330   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6331   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6332   // to reverse two input vectors.
6333   if (Imm < NumElts)
6334     ReverseEXT = true;
6335   else
6336     Imm -= NumElts;
6337 
6338   return true;
6339 }
6340 
6341 /// isREVMask - Check if a vector shuffle corresponds to a REV
6342 /// instruction with the specified blocksize.  (The order of the elements
6343 /// within each block of the vector is reversed.)
6344 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6345   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6346          "Only possible block sizes for REV are: 16, 32, 64");
6347 
6348   unsigned EltSz = VT.getScalarSizeInBits();
6349   if (EltSz == 64)
6350     return false;
6351 
6352   unsigned NumElts = VT.getVectorNumElements();
6353   unsigned BlockElts = M[0] + 1;
6354   // If the first shuffle index is UNDEF, be optimistic.
6355   if (M[0] < 0)
6356     BlockElts = BlockSize / EltSz;
6357 
6358   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6359     return false;
6360 
6361   for (unsigned i = 0; i < NumElts; ++i) {
6362     if (M[i] < 0)
6363       continue; // ignore UNDEF indices
6364     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6365       return false;
6366   }
6367 
6368   return true;
6369 }
6370 
6371 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6372   unsigned NumElts = VT.getVectorNumElements();
6373   if (NumElts % 2 != 0)
6374     return false;
6375   WhichResult = (M[0] == 0 ? 0 : 1);
6376   unsigned Idx = WhichResult * NumElts / 2;
6377   for (unsigned i = 0; i != NumElts; i += 2) {
6378     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6379         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6380       return false;
6381     Idx += 1;
6382   }
6383 
6384   return true;
6385 }
6386 
6387 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6388   unsigned NumElts = VT.getVectorNumElements();
6389   WhichResult = (M[0] == 0 ? 0 : 1);
6390   for (unsigned i = 0; i != NumElts; ++i) {
6391     if (M[i] < 0)
6392       continue; // ignore UNDEF indices
6393     if ((unsigned)M[i] != 2 * i + WhichResult)
6394       return false;
6395   }
6396 
6397   return true;
6398 }
6399 
6400 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6401   unsigned NumElts = VT.getVectorNumElements();
6402   if (NumElts % 2 != 0)
6403     return false;
6404   WhichResult = (M[0] == 0 ? 0 : 1);
6405   for (unsigned i = 0; i < NumElts; i += 2) {
6406     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6407         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6408       return false;
6409   }
6410   return true;
6411 }
6412 
6413 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6414 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6415 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6416 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6417   unsigned NumElts = VT.getVectorNumElements();
6418   if (NumElts % 2 != 0)
6419     return false;
6420   WhichResult = (M[0] == 0 ? 0 : 1);
6421   unsigned Idx = WhichResult * NumElts / 2;
6422   for (unsigned i = 0; i != NumElts; i += 2) {
6423     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6424         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6425       return false;
6426     Idx += 1;
6427   }
6428 
6429   return true;
6430 }
6431 
6432 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6433 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6434 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6435 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6436   unsigned Half = VT.getVectorNumElements() / 2;
6437   WhichResult = (M[0] == 0 ? 0 : 1);
6438   for (unsigned j = 0; j != 2; ++j) {
6439     unsigned Idx = WhichResult;
6440     for (unsigned i = 0; i != Half; ++i) {
6441       int MIdx = M[i + j * Half];
6442       if (MIdx >= 0 && (unsigned)MIdx != Idx)
6443         return false;
6444       Idx += 2;
6445     }
6446   }
6447 
6448   return true;
6449 }
6450 
6451 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6452 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6453 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6454 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6455   unsigned NumElts = VT.getVectorNumElements();
6456   if (NumElts % 2 != 0)
6457     return false;
6458   WhichResult = (M[0] == 0 ? 0 : 1);
6459   for (unsigned i = 0; i < NumElts; i += 2) {
6460     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6461         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6462       return false;
6463   }
6464   return true;
6465 }
6466 
6467 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6468                       bool &DstIsLeft, int &Anomaly) {
6469   if (M.size() != static_cast<size_t>(NumInputElements))
6470     return false;
6471 
6472   int NumLHSMatch = 0, NumRHSMatch = 0;
6473   int LastLHSMismatch = -1, LastRHSMismatch = -1;
6474 
6475   for (int i = 0; i < NumInputElements; ++i) {
6476     if (M[i] == -1) {
6477       ++NumLHSMatch;
6478       ++NumRHSMatch;
6479       continue;
6480     }
6481 
6482     if (M[i] == i)
6483       ++NumLHSMatch;
6484     else
6485       LastLHSMismatch = i;
6486 
6487     if (M[i] == i + NumInputElements)
6488       ++NumRHSMatch;
6489     else
6490       LastRHSMismatch = i;
6491   }
6492 
6493   if (NumLHSMatch == NumInputElements - 1) {
6494     DstIsLeft = true;
6495     Anomaly = LastLHSMismatch;
6496     return true;
6497   } else if (NumRHSMatch == NumInputElements - 1) {
6498     DstIsLeft = false;
6499     Anomaly = LastRHSMismatch;
6500     return true;
6501   }
6502 
6503   return false;
6504 }
6505 
6506 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6507   if (VT.getSizeInBits() != 128)
6508     return false;
6509 
6510   unsigned NumElts = VT.getVectorNumElements();
6511 
6512   for (int I = 0, E = NumElts / 2; I != E; I++) {
6513     if (Mask[I] != I)
6514       return false;
6515   }
6516 
6517   int Offset = NumElts / 2;
6518   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6519     if (Mask[I] != I + SplitLHS * Offset)
6520       return false;
6521   }
6522 
6523   return true;
6524 }
6525 
6526 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6527   SDLoc DL(Op);
6528   EVT VT = Op.getValueType();
6529   SDValue V0 = Op.getOperand(0);
6530   SDValue V1 = Op.getOperand(1);
6531   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6532 
6533   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6534       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6535     return SDValue();
6536 
6537   bool SplitV0 = V0.getValueSizeInBits() == 128;
6538 
6539   if (!isConcatMask(Mask, VT, SplitV0))
6540     return SDValue();
6541 
6542   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
6543                                 VT.getVectorNumElements() / 2);
6544   if (SplitV0) {
6545     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6546                      DAG.getConstant(0, DL, MVT::i64));
6547   }
6548   if (V1.getValueSizeInBits() == 128) {
6549     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6550                      DAG.getConstant(0, DL, MVT::i64));
6551   }
6552   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6553 }
6554 
6555 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6556 /// the specified operations to build the shuffle.
6557 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6558                                       SDValue RHS, SelectionDAG &DAG,
6559                                       const SDLoc &dl) {
6560   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6561   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6562   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6563 
6564   enum {
6565     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6566     OP_VREV,
6567     OP_VDUP0,
6568     OP_VDUP1,
6569     OP_VDUP2,
6570     OP_VDUP3,
6571     OP_VEXT1,
6572     OP_VEXT2,
6573     OP_VEXT3,
6574     OP_VUZPL, // VUZP, left result
6575     OP_VUZPR, // VUZP, right result
6576     OP_VZIPL, // VZIP, left result
6577     OP_VZIPR, // VZIP, right result
6578     OP_VTRNL, // VTRN, left result
6579     OP_VTRNR  // VTRN, right result
6580   };
6581 
6582   if (OpNum == OP_COPY) {
6583     if (LHSID == (1 * 9 + 2) * 9 + 3)
6584       return LHS;
6585     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6586     return RHS;
6587   }
6588 
6589   SDValue OpLHS, OpRHS;
6590   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6591   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6592   EVT VT = OpLHS.getValueType();
6593 
6594   switch (OpNum) {
6595   default:
6596     llvm_unreachable("Unknown shuffle opcode!");
6597   case OP_VREV:
6598     // VREV divides the vector in half and swaps within the half.
6599     if (VT.getVectorElementType() == MVT::i32 ||
6600         VT.getVectorElementType() == MVT::f32)
6601       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6602     // vrev <4 x i16> -> REV32
6603     if (VT.getVectorElementType() == MVT::i16 ||
6604         VT.getVectorElementType() == MVT::f16)
6605       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6606     // vrev <4 x i8> -> REV16
6607     assert(VT.getVectorElementType() == MVT::i8);
6608     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6609   case OP_VDUP0:
6610   case OP_VDUP1:
6611   case OP_VDUP2:
6612   case OP_VDUP3: {
6613     EVT EltTy = VT.getVectorElementType();
6614     unsigned Opcode;
6615     if (EltTy == MVT::i8)
6616       Opcode = AArch64ISD::DUPLANE8;
6617     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6618       Opcode = AArch64ISD::DUPLANE16;
6619     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6620       Opcode = AArch64ISD::DUPLANE32;
6621     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6622       Opcode = AArch64ISD::DUPLANE64;
6623     else
6624       llvm_unreachable("Invalid vector element type?");
6625 
6626     if (VT.getSizeInBits() == 64)
6627       OpLHS = WidenVector(OpLHS, DAG);
6628     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6629     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6630   }
6631   case OP_VEXT1:
6632   case OP_VEXT2:
6633   case OP_VEXT3: {
6634     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6635     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6636                        DAG.getConstant(Imm, dl, MVT::i32));
6637   }
6638   case OP_VUZPL:
6639     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6640                        OpRHS);
6641   case OP_VUZPR:
6642     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6643                        OpRHS);
6644   case OP_VZIPL:
6645     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6646                        OpRHS);
6647   case OP_VZIPR:
6648     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6649                        OpRHS);
6650   case OP_VTRNL:
6651     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6652                        OpRHS);
6653   case OP_VTRNR:
6654     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6655                        OpRHS);
6656   }
6657 }
6658 
6659 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6660                            SelectionDAG &DAG) {
6661   // Check to see if we can use the TBL instruction.
6662   SDValue V1 = Op.getOperand(0);
6663   SDValue V2 = Op.getOperand(1);
6664   SDLoc DL(Op);
6665 
6666   EVT EltVT = Op.getValueType().getVectorElementType();
6667   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6668 
6669   SmallVector<SDValue, 8> TBLMask;
6670   for (int Val : ShuffleMask) {
6671     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6672       unsigned Offset = Byte + Val * BytesPerElt;
6673       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6674     }
6675   }
6676 
6677   MVT IndexVT = MVT::v8i8;
6678   unsigned IndexLen = 8;
6679   if (Op.getValueSizeInBits() == 128) {
6680     IndexVT = MVT::v16i8;
6681     IndexLen = 16;
6682   }
6683 
6684   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6685   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6686 
6687   SDValue Shuffle;
6688   if (V2.getNode()->isUndef()) {
6689     if (IndexLen == 8)
6690       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6691     Shuffle = DAG.getNode(
6692         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6693         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6694         DAG.getBuildVector(IndexVT, DL,
6695                            makeArrayRef(TBLMask.data(), IndexLen)));
6696   } else {
6697     if (IndexLen == 8) {
6698       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6699       Shuffle = DAG.getNode(
6700           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6701           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6702           DAG.getBuildVector(IndexVT, DL,
6703                              makeArrayRef(TBLMask.data(), IndexLen)));
6704     } else {
6705       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6706       // cannot currently represent the register constraints on the input
6707       // table registers.
6708       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6709       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6710       //                   IndexLen));
6711       Shuffle = DAG.getNode(
6712           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6713           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6714           V2Cst, DAG.getBuildVector(IndexVT, DL,
6715                                     makeArrayRef(TBLMask.data(), IndexLen)));
6716     }
6717   }
6718   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6719 }
6720 
6721 static unsigned getDUPLANEOp(EVT EltType) {
6722   if (EltType == MVT::i8)
6723     return AArch64ISD::DUPLANE8;
6724   if (EltType == MVT::i16 || EltType == MVT::f16)
6725     return AArch64ISD::DUPLANE16;
6726   if (EltType == MVT::i32 || EltType == MVT::f32)
6727     return AArch64ISD::DUPLANE32;
6728   if (EltType == MVT::i64 || EltType == MVT::f64)
6729     return AArch64ISD::DUPLANE64;
6730 
6731   llvm_unreachable("Invalid vector element type?");
6732 }
6733 
6734 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6735                                                    SelectionDAG &DAG) const {
6736   SDLoc dl(Op);
6737   EVT VT = Op.getValueType();
6738 
6739   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6740 
6741   // Convert shuffles that are directly supported on NEON to target-specific
6742   // DAG nodes, instead of keeping them as shuffles and matching them again
6743   // during code selection.  This is more efficient and avoids the possibility
6744   // of inconsistencies between legalization and selection.
6745   ArrayRef<int> ShuffleMask = SVN->getMask();
6746 
6747   SDValue V1 = Op.getOperand(0);
6748   SDValue V2 = Op.getOperand(1);
6749 
6750   if (SVN->isSplat()) {
6751     int Lane = SVN->getSplatIndex();
6752     // If this is undef splat, generate it via "just" vdup, if possible.
6753     if (Lane == -1)
6754       Lane = 0;
6755 
6756     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6757       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6758                          V1.getOperand(0));
6759     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6760     // constant. If so, we can just reference the lane's definition directly.
6761     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6762         !isa<ConstantSDNode>(V1.getOperand(Lane)))
6763       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6764 
6765     // Otherwise, duplicate from the lane of the input vector.
6766     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6767 
6768     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6769     // to make a vector of the same size as this SHUFFLE. We can ignore the
6770     // extract entirely, and canonicalise the concat using WidenVector.
6771     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6772       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6773       V1 = V1.getOperand(0);
6774     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6775       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6776       Lane -= Idx * VT.getVectorNumElements() / 2;
6777       V1 = WidenVector(V1.getOperand(Idx), DAG);
6778     } else if (VT.getSizeInBits() == 64)
6779       V1 = WidenVector(V1, DAG);
6780 
6781     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6782   }
6783 
6784   if (isREVMask(ShuffleMask, VT, 64))
6785     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6786   if (isREVMask(ShuffleMask, VT, 32))
6787     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6788   if (isREVMask(ShuffleMask, VT, 16))
6789     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6790 
6791   bool ReverseEXT = false;
6792   unsigned Imm;
6793   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6794     if (ReverseEXT)
6795       std::swap(V1, V2);
6796     Imm *= getExtFactor(V1);
6797     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6798                        DAG.getConstant(Imm, dl, MVT::i32));
6799   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6800     Imm *= getExtFactor(V1);
6801     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6802                        DAG.getConstant(Imm, dl, MVT::i32));
6803   }
6804 
6805   unsigned WhichResult;
6806   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6807     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6808     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6809   }
6810   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6811     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6812     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6813   }
6814   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6815     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6816     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6817   }
6818 
6819   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6820     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6821     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6822   }
6823   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6824     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6825     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6826   }
6827   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6828     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6829     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6830   }
6831 
6832   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6833     return Concat;
6834 
6835   bool DstIsLeft;
6836   int Anomaly;
6837   int NumInputElements = V1.getValueType().getVectorNumElements();
6838   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6839     SDValue DstVec = DstIsLeft ? V1 : V2;
6840     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6841 
6842     SDValue SrcVec = V1;
6843     int SrcLane = ShuffleMask[Anomaly];
6844     if (SrcLane >= NumInputElements) {
6845       SrcVec = V2;
6846       SrcLane -= VT.getVectorNumElements();
6847     }
6848     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6849 
6850     EVT ScalarVT = VT.getVectorElementType();
6851 
6852     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6853       ScalarVT = MVT::i32;
6854 
6855     return DAG.getNode(
6856         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6857         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6858         DstLaneV);
6859   }
6860 
6861   // If the shuffle is not directly supported and it has 4 elements, use
6862   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6863   unsigned NumElts = VT.getVectorNumElements();
6864   if (NumElts == 4) {
6865     unsigned PFIndexes[4];
6866     for (unsigned i = 0; i != 4; ++i) {
6867       if (ShuffleMask[i] < 0)
6868         PFIndexes[i] = 8;
6869       else
6870         PFIndexes[i] = ShuffleMask[i];
6871     }
6872 
6873     // Compute the index in the perfect shuffle table.
6874     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6875                             PFIndexes[2] * 9 + PFIndexes[3];
6876     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6877     unsigned Cost = (PFEntry >> 30);
6878 
6879     if (Cost <= 4)
6880       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6881   }
6882 
6883   return GenerateTBL(Op, ShuffleMask, DAG);
6884 }
6885 
6886 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6887                                APInt &UndefBits) {
6888   EVT VT = BVN->getValueType(0);
6889   APInt SplatBits, SplatUndef;
6890   unsigned SplatBitSize;
6891   bool HasAnyUndefs;
6892   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6893     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6894 
6895     for (unsigned i = 0; i < NumSplats; ++i) {
6896       CnstBits <<= SplatBitSize;
6897       UndefBits <<= SplatBitSize;
6898       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6899       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6900     }
6901 
6902     return true;
6903   }
6904 
6905   return false;
6906 }
6907 
6908 // Try 64-bit splatted SIMD immediate.
6909 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6910                                  const APInt &Bits) {
6911   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6912     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6913     EVT VT = Op.getValueType();
6914     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6915 
6916     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6917       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6918 
6919       SDLoc dl(Op);
6920       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6921                                 DAG.getConstant(Value, dl, MVT::i32));
6922       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6923     }
6924   }
6925 
6926   return SDValue();
6927 }
6928 
6929 // Try 32-bit splatted SIMD immediate.
6930 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6931                                   const APInt &Bits,
6932                                   const SDValue *LHS = nullptr) {
6933   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6934     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6935     EVT VT = Op.getValueType();
6936     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6937     bool isAdvSIMDModImm = false;
6938     uint64_t Shift;
6939 
6940     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6941       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6942       Shift = 0;
6943     }
6944     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6945       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6946       Shift = 8;
6947     }
6948     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6949       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6950       Shift = 16;
6951     }
6952     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6953       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6954       Shift = 24;
6955     }
6956 
6957     if (isAdvSIMDModImm) {
6958       SDLoc dl(Op);
6959       SDValue Mov;
6960 
6961       if (LHS)
6962         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6963                           DAG.getConstant(Value, dl, MVT::i32),
6964                           DAG.getConstant(Shift, dl, MVT::i32));
6965       else
6966         Mov = DAG.getNode(NewOp, dl, MovTy,
6967                           DAG.getConstant(Value, dl, MVT::i32),
6968                           DAG.getConstant(Shift, dl, MVT::i32));
6969 
6970       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6971     }
6972   }
6973 
6974   return SDValue();
6975 }
6976 
6977 // Try 16-bit splatted SIMD immediate.
6978 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6979                                   const APInt &Bits,
6980                                   const SDValue *LHS = nullptr) {
6981   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6982     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6983     EVT VT = Op.getValueType();
6984     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6985     bool isAdvSIMDModImm = false;
6986     uint64_t Shift;
6987 
6988     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
6989       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
6990       Shift = 0;
6991     }
6992     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
6993       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
6994       Shift = 8;
6995     }
6996 
6997     if (isAdvSIMDModImm) {
6998       SDLoc dl(Op);
6999       SDValue Mov;
7000 
7001       if (LHS)
7002         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7003                           DAG.getConstant(Value, dl, MVT::i32),
7004                           DAG.getConstant(Shift, dl, MVT::i32));
7005       else
7006         Mov = DAG.getNode(NewOp, dl, MovTy,
7007                           DAG.getConstant(Value, dl, MVT::i32),
7008                           DAG.getConstant(Shift, dl, MVT::i32));
7009 
7010       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7011     }
7012   }
7013 
7014   return SDValue();
7015 }
7016 
7017 // Try 32-bit splatted SIMD immediate with shifted ones.
7018 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7019                                     SelectionDAG &DAG, const APInt &Bits) {
7020   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7021     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7022     EVT VT = Op.getValueType();
7023     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7024     bool isAdvSIMDModImm = false;
7025     uint64_t Shift;
7026 
7027     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7028       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7029       Shift = 264;
7030     }
7031     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7032       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7033       Shift = 272;
7034     }
7035 
7036     if (isAdvSIMDModImm) {
7037       SDLoc dl(Op);
7038       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7039                                 DAG.getConstant(Value, dl, MVT::i32),
7040                                 DAG.getConstant(Shift, dl, MVT::i32));
7041       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7042     }
7043   }
7044 
7045   return SDValue();
7046 }
7047 
7048 // Try 8-bit splatted SIMD immediate.
7049 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7050                                  const APInt &Bits) {
7051   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7052     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7053     EVT VT = Op.getValueType();
7054     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7055 
7056     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7057       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7058 
7059       SDLoc dl(Op);
7060       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7061                                 DAG.getConstant(Value, dl, MVT::i32));
7062       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7063     }
7064   }
7065 
7066   return SDValue();
7067 }
7068 
7069 // Try FP splatted SIMD immediate.
7070 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7071                                   const APInt &Bits) {
7072   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7073     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7074     EVT VT = Op.getValueType();
7075     bool isWide = (VT.getSizeInBits() == 128);
7076     MVT MovTy;
7077     bool isAdvSIMDModImm = false;
7078 
7079     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7080       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7081       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7082     }
7083     else if (isWide &&
7084              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7085       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7086       MovTy = MVT::v2f64;
7087     }
7088 
7089     if (isAdvSIMDModImm) {
7090       SDLoc dl(Op);
7091       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7092                                 DAG.getConstant(Value, dl, MVT::i32));
7093       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7094     }
7095   }
7096 
7097   return SDValue();
7098 }
7099 
7100 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7101 // consists of only the same constant int value, returned in reference arg
7102 // ConstVal
7103 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7104                                      uint64_t &ConstVal) {
7105   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7106   if (!Bvec)
7107     return false;
7108   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7109   if (!FirstElt)
7110     return false;
7111   EVT VT = Bvec->getValueType(0);
7112   unsigned NumElts = VT.getVectorNumElements();
7113   for (unsigned i = 1; i < NumElts; ++i)
7114     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7115       return false;
7116   ConstVal = FirstElt->getZExtValue();
7117   return true;
7118 }
7119 
7120 static unsigned getIntrinsicID(const SDNode *N) {
7121   unsigned Opcode = N->getOpcode();
7122   switch (Opcode) {
7123   default:
7124     return Intrinsic::not_intrinsic;
7125   case ISD::INTRINSIC_WO_CHAIN: {
7126     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7127     if (IID < Intrinsic::num_intrinsics)
7128       return IID;
7129     return Intrinsic::not_intrinsic;
7130   }
7131   }
7132 }
7133 
7134 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7135 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7136 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7137 // Also, logical shift right -> sri, with the same structure.
7138 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7139   EVT VT = N->getValueType(0);
7140 
7141   if (!VT.isVector())
7142     return SDValue();
7143 
7144   SDLoc DL(N);
7145 
7146   // Is the first op an AND?
7147   const SDValue And = N->getOperand(0);
7148   if (And.getOpcode() != ISD::AND)
7149     return SDValue();
7150 
7151   // Is the second op an shl or lshr?
7152   SDValue Shift = N->getOperand(1);
7153   // This will have been turned into: AArch64ISD::VSHL vector, #shift
7154   // or AArch64ISD::VLSHR vector, #shift
7155   unsigned ShiftOpc = Shift.getOpcode();
7156   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7157     return SDValue();
7158   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7159 
7160   // Is the shift amount constant?
7161   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7162   if (!C2node)
7163     return SDValue();
7164 
7165   // Is the and mask vector all constant?
7166   uint64_t C1;
7167   if (!isAllConstantBuildVector(And.getOperand(1), C1))
7168     return SDValue();
7169 
7170   // Is C1 == ~C2, taking into account how much one can shift elements of a
7171   // particular size?
7172   uint64_t C2 = C2node->getZExtValue();
7173   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7174   if (C2 > ElemSizeInBits)
7175     return SDValue();
7176   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7177   if ((C1 & ElemMask) != (~C2 & ElemMask))
7178     return SDValue();
7179 
7180   SDValue X = And.getOperand(0);
7181   SDValue Y = Shift.getOperand(0);
7182 
7183   unsigned Intrin =
7184       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7185   SDValue ResultSLI =
7186       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7187                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7188                   Shift.getOperand(1));
7189 
7190   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7191   LLVM_DEBUG(N->dump(&DAG));
7192   LLVM_DEBUG(dbgs() << "into: \n");
7193   LLVM_DEBUG(ResultSLI->dump(&DAG));
7194 
7195   ++NumShiftInserts;
7196   return ResultSLI;
7197 }
7198 
7199 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7200                                              SelectionDAG &DAG) const {
7201   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7202   if (EnableAArch64SlrGeneration) {
7203     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7204       return Res;
7205   }
7206 
7207   EVT VT = Op.getValueType();
7208 
7209   SDValue LHS = Op.getOperand(0);
7210   BuildVectorSDNode *BVN =
7211       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7212   if (!BVN) {
7213     // OR commutes, so try swapping the operands.
7214     LHS = Op.getOperand(1);
7215     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7216   }
7217   if (!BVN)
7218     return Op;
7219 
7220   APInt DefBits(VT.getSizeInBits(), 0);
7221   APInt UndefBits(VT.getSizeInBits(), 0);
7222   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7223     SDValue NewOp;
7224 
7225     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7226                                     DefBits, &LHS)) ||
7227         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7228                                     DefBits, &LHS)))
7229       return NewOp;
7230 
7231     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7232                                     UndefBits, &LHS)) ||
7233         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7234                                     UndefBits, &LHS)))
7235       return NewOp;
7236   }
7237 
7238   // We can always fall back to a non-immediate OR.
7239   return Op;
7240 }
7241 
7242 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7243 // be truncated to fit element width.
7244 static SDValue NormalizeBuildVector(SDValue Op,
7245                                     SelectionDAG &DAG) {
7246   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7247   SDLoc dl(Op);
7248   EVT VT = Op.getValueType();
7249   EVT EltTy= VT.getVectorElementType();
7250 
7251   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7252     return Op;
7253 
7254   SmallVector<SDValue, 16> Ops;
7255   for (SDValue Lane : Op->ops()) {
7256     // For integer vectors, type legalization would have promoted the
7257     // operands already. Otherwise, if Op is a floating-point splat
7258     // (with operands cast to integers), then the only possibilities
7259     // are constants and UNDEFs.
7260     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7261       APInt LowBits(EltTy.getSizeInBits(),
7262                     CstLane->getZExtValue());
7263       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7264     } else if (Lane.getNode()->isUndef()) {
7265       Lane = DAG.getUNDEF(MVT::i32);
7266     } else {
7267       assert(Lane.getValueType() == MVT::i32 &&
7268              "Unexpected BUILD_VECTOR operand type");
7269     }
7270     Ops.push_back(Lane);
7271   }
7272   return DAG.getBuildVector(VT, dl, Ops);
7273 }
7274 
7275 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7276   EVT VT = Op.getValueType();
7277 
7278   APInt DefBits(VT.getSizeInBits(), 0);
7279   APInt UndefBits(VT.getSizeInBits(), 0);
7280   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7281   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7282     SDValue NewOp;
7283     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7284         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7285         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7286         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7287         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7288         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7289       return NewOp;
7290 
7291     DefBits = ~DefBits;
7292     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7293         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7294         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7295       return NewOp;
7296 
7297     DefBits = UndefBits;
7298     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7299         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7300         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7301         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7302         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7303         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7304       return NewOp;
7305 
7306     DefBits = ~UndefBits;
7307     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7308         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7309         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7310       return NewOp;
7311   }
7312 
7313   return SDValue();
7314 }
7315 
7316 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7317                                                  SelectionDAG &DAG) const {
7318   EVT VT = Op.getValueType();
7319 
7320   // Try to build a simple constant vector.
7321   Op = NormalizeBuildVector(Op, DAG);
7322   if (VT.isInteger()) {
7323     // Certain vector constants, used to express things like logical NOT and
7324     // arithmetic NEG, are passed through unmodified.  This allows special
7325     // patterns for these operations to match, which will lower these constants
7326     // to whatever is proven necessary.
7327     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7328     if (BVN->isConstant())
7329       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7330         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7331         APInt Val(BitSize,
7332                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7333         if (Val.isNullValue() || Val.isAllOnesValue())
7334           return Op;
7335       }
7336   }
7337 
7338   if (SDValue V = ConstantBuildVector(Op, DAG))
7339     return V;
7340 
7341   // Scan through the operands to find some interesting properties we can
7342   // exploit:
7343   //   1) If only one value is used, we can use a DUP, or
7344   //   2) if only the low element is not undef, we can just insert that, or
7345   //   3) if only one constant value is used (w/ some non-constant lanes),
7346   //      we can splat the constant value into the whole vector then fill
7347   //      in the non-constant lanes.
7348   //   4) FIXME: If different constant values are used, but we can intelligently
7349   //             select the values we'll be overwriting for the non-constant
7350   //             lanes such that we can directly materialize the vector
7351   //             some other way (MOVI, e.g.), we can be sneaky.
7352   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7353   SDLoc dl(Op);
7354   unsigned NumElts = VT.getVectorNumElements();
7355   bool isOnlyLowElement = true;
7356   bool usesOnlyOneValue = true;
7357   bool usesOnlyOneConstantValue = true;
7358   bool isConstant = true;
7359   bool AllLanesExtractElt = true;
7360   unsigned NumConstantLanes = 0;
7361   SDValue Value;
7362   SDValue ConstantValue;
7363   for (unsigned i = 0; i < NumElts; ++i) {
7364     SDValue V = Op.getOperand(i);
7365     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7366       AllLanesExtractElt = false;
7367     if (V.isUndef())
7368       continue;
7369     if (i > 0)
7370       isOnlyLowElement = false;
7371     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7372       isConstant = false;
7373 
7374     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7375       ++NumConstantLanes;
7376       if (!ConstantValue.getNode())
7377         ConstantValue = V;
7378       else if (ConstantValue != V)
7379         usesOnlyOneConstantValue = false;
7380     }
7381 
7382     if (!Value.getNode())
7383       Value = V;
7384     else if (V != Value)
7385       usesOnlyOneValue = false;
7386   }
7387 
7388   if (!Value.getNode()) {
7389     LLVM_DEBUG(
7390         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7391     return DAG.getUNDEF(VT);
7392   }
7393 
7394   // Convert BUILD_VECTOR where all elements but the lowest are undef into
7395   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7396   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7397   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7398     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7399                          "SCALAR_TO_VECTOR node\n");
7400     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7401   }
7402 
7403   if (AllLanesExtractElt) {
7404     SDNode *Vector = nullptr;
7405     bool Even = false;
7406     bool Odd = false;
7407     // Check whether the extract elements match the Even pattern <0,2,4,...> or
7408     // the Odd pattern <1,3,5,...>.
7409     for (unsigned i = 0; i < NumElts; ++i) {
7410       SDValue V = Op.getOperand(i);
7411       const SDNode *N = V.getNode();
7412       if (!isa<ConstantSDNode>(N->getOperand(1)))
7413         break;
7414       SDValue N0 = N->getOperand(0);
7415 
7416       // All elements are extracted from the same vector.
7417       if (!Vector) {
7418         Vector = N0.getNode();
7419         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7420         // BUILD_VECTOR.
7421         if (VT.getVectorElementType() !=
7422             N0.getValueType().getVectorElementType())
7423           break;
7424       } else if (Vector != N0.getNode()) {
7425         Odd = false;
7426         Even = false;
7427         break;
7428       }
7429 
7430       // Extracted values are either at Even indices <0,2,4,...> or at Odd
7431       // indices <1,3,5,...>.
7432       uint64_t Val = N->getConstantOperandVal(1);
7433       if (Val == 2 * i) {
7434         Even = true;
7435         continue;
7436       }
7437       if (Val - 1 == 2 * i) {
7438         Odd = true;
7439         continue;
7440       }
7441 
7442       // Something does not match: abort.
7443       Odd = false;
7444       Even = false;
7445       break;
7446     }
7447     if (Even || Odd) {
7448       SDValue LHS =
7449           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7450                       DAG.getConstant(0, dl, MVT::i64));
7451       SDValue RHS =
7452           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7453                       DAG.getConstant(NumElts, dl, MVT::i64));
7454 
7455       if (Even && !Odd)
7456         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7457                            RHS);
7458       if (Odd && !Even)
7459         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7460                            RHS);
7461     }
7462   }
7463 
7464   // Use DUP for non-constant splats. For f32 constant splats, reduce to
7465   // i32 and try again.
7466   if (usesOnlyOneValue) {
7467     if (!isConstant) {
7468       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7469           Value.getValueType() != VT) {
7470         LLVM_DEBUG(
7471             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7472         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7473       }
7474 
7475       // This is actually a DUPLANExx operation, which keeps everything vectory.
7476 
7477       SDValue Lane = Value.getOperand(1);
7478       Value = Value.getOperand(0);
7479       if (Value.getValueSizeInBits() == 64) {
7480         LLVM_DEBUG(
7481             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7482                       "widening it\n");
7483         Value = WidenVector(Value, DAG);
7484       }
7485 
7486       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7487       return DAG.getNode(Opcode, dl, VT, Value, Lane);
7488     }
7489 
7490     if (VT.getVectorElementType().isFloatingPoint()) {
7491       SmallVector<SDValue, 8> Ops;
7492       EVT EltTy = VT.getVectorElementType();
7493       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7494               "Unsupported floating-point vector type");
7495       LLVM_DEBUG(
7496           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7497                     "BITCASTS, and try again\n");
7498       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7499       for (unsigned i = 0; i < NumElts; ++i)
7500         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7501       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7502       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7503       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7504                  Val.dump(););
7505       Val = LowerBUILD_VECTOR(Val, DAG);
7506       if (Val.getNode())
7507         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7508     }
7509   }
7510 
7511   // If there was only one constant value used and for more than one lane,
7512   // start by splatting that value, then replace the non-constant lanes. This
7513   // is better than the default, which will perform a separate initialization
7514   // for each lane.
7515   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7516     // Firstly, try to materialize the splat constant.
7517     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7518             Val = ConstantBuildVector(Vec, DAG);
7519     if (!Val) {
7520       // Otherwise, materialize the constant and splat it.
7521       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7522       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7523     }
7524 
7525     // Now insert the non-constant lanes.
7526     for (unsigned i = 0; i < NumElts; ++i) {
7527       SDValue V = Op.getOperand(i);
7528       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7529       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7530         // Note that type legalization likely mucked about with the VT of the
7531         // source operand, so we may have to convert it here before inserting.
7532         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7533     }
7534     return Val;
7535   }
7536 
7537   // This will generate a load from the constant pool.
7538   if (isConstant) {
7539     LLVM_DEBUG(
7540         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7541                   "expansion\n");
7542     return SDValue();
7543   }
7544 
7545   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7546   if (NumElts >= 4) {
7547     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7548       return shuffle;
7549   }
7550 
7551   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7552   // know the default expansion would otherwise fall back on something even
7553   // worse. For a vector with one or two non-undef values, that's
7554   // scalar_to_vector for the elements followed by a shuffle (provided the
7555   // shuffle is valid for the target) and materialization element by element
7556   // on the stack followed by a load for everything else.
7557   if (!isConstant && !usesOnlyOneValue) {
7558     LLVM_DEBUG(
7559         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7560                   "of INSERT_VECTOR_ELT\n");
7561 
7562     SDValue Vec = DAG.getUNDEF(VT);
7563     SDValue Op0 = Op.getOperand(0);
7564     unsigned i = 0;
7565 
7566     // Use SCALAR_TO_VECTOR for lane zero to
7567     // a) Avoid a RMW dependency on the full vector register, and
7568     // b) Allow the register coalescer to fold away the copy if the
7569     //    value is already in an S or D register, and we're forced to emit an
7570     //    INSERT_SUBREG that we can't fold anywhere.
7571     //
7572     // We also allow types like i8 and i16 which are illegal scalar but legal
7573     // vector element types. After type-legalization the inserted value is
7574     // extended (i32) and it is safe to cast them to the vector type by ignoring
7575     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7576     if (!Op0.isUndef()) {
7577       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7578       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7579       ++i;
7580     }
7581     LLVM_DEBUG(if (i < NumElts) dbgs()
7582                    << "Creating nodes for the other vector elements:\n";);
7583     for (; i < NumElts; ++i) {
7584       SDValue V = Op.getOperand(i);
7585       if (V.isUndef())
7586         continue;
7587       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7588       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7589     }
7590     return Vec;
7591   }
7592 
7593   LLVM_DEBUG(
7594       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7595                 "better alternative\n");
7596   return SDValue();
7597 }
7598 
7599 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7600                                                       SelectionDAG &DAG) const {
7601   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7602 
7603   // Check for non-constant or out of range lane.
7604   EVT VT = Op.getOperand(0).getValueType();
7605   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7606   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7607     return SDValue();
7608 
7609 
7610   // Insertion/extraction are legal for V128 types.
7611   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7612       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7613       VT == MVT::v8f16)
7614     return Op;
7615 
7616   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7617       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7618     return SDValue();
7619 
7620   // For V64 types, we perform insertion by expanding the value
7621   // to a V128 type and perform the insertion on that.
7622   SDLoc DL(Op);
7623   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7624   EVT WideTy = WideVec.getValueType();
7625 
7626   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7627                              Op.getOperand(1), Op.getOperand(2));
7628   // Re-narrow the resultant vector.
7629   return NarrowVector(Node, DAG);
7630 }
7631 
7632 SDValue
7633 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7634                                                SelectionDAG &DAG) const {
7635   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7636 
7637   // Check for non-constant or out of range lane.
7638   EVT VT = Op.getOperand(0).getValueType();
7639   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7640   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7641     return SDValue();
7642 
7643 
7644   // Insertion/extraction are legal for V128 types.
7645   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7646       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7647       VT == MVT::v8f16)
7648     return Op;
7649 
7650   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7651       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7652     return SDValue();
7653 
7654   // For V64 types, we perform extraction by expanding the value
7655   // to a V128 type and perform the extraction on that.
7656   SDLoc DL(Op);
7657   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7658   EVT WideTy = WideVec.getValueType();
7659 
7660   EVT ExtrTy = WideTy.getVectorElementType();
7661   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7662     ExtrTy = MVT::i32;
7663 
7664   // For extractions, we just return the result directly.
7665   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7666                      Op.getOperand(1));
7667 }
7668 
7669 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7670                                                       SelectionDAG &DAG) const {
7671   EVT VT = Op.getOperand(0).getValueType();
7672   SDLoc dl(Op);
7673   // Just in case...
7674   if (!VT.isVector())
7675     return SDValue();
7676 
7677   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7678   if (!Cst)
7679     return SDValue();
7680   unsigned Val = Cst->getZExtValue();
7681 
7682   unsigned Size = Op.getValueSizeInBits();
7683 
7684   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7685   if (Val == 0)
7686     return Op;
7687 
7688   // If this is extracting the upper 64-bits of a 128-bit vector, we match
7689   // that directly.
7690   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7691     return Op;
7692 
7693   return SDValue();
7694 }
7695 
7696 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7697   if (VT.getVectorNumElements() == 4 &&
7698       (VT.is128BitVector() || VT.is64BitVector())) {
7699     unsigned PFIndexes[4];
7700     for (unsigned i = 0; i != 4; ++i) {
7701       if (M[i] < 0)
7702         PFIndexes[i] = 8;
7703       else
7704         PFIndexes[i] = M[i];
7705     }
7706 
7707     // Compute the index in the perfect shuffle table.
7708     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7709                             PFIndexes[2] * 9 + PFIndexes[3];
7710     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7711     unsigned Cost = (PFEntry >> 30);
7712 
7713     if (Cost <= 4)
7714       return true;
7715   }
7716 
7717   bool DummyBool;
7718   int DummyInt;
7719   unsigned DummyUnsigned;
7720 
7721   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7722           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7723           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7724           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7725           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7726           isZIPMask(M, VT, DummyUnsigned) ||
7727           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7728           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7729           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7730           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7731           isConcatMask(M, VT, VT.getSizeInBits() == 128));
7732 }
7733 
7734 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7735 /// operand of a vector shift operation, where all the elements of the
7736 /// build_vector must have the same constant integer value.
7737 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7738   // Ignore bit_converts.
7739   while (Op.getOpcode() == ISD::BITCAST)
7740     Op = Op.getOperand(0);
7741   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7742   APInt SplatBits, SplatUndef;
7743   unsigned SplatBitSize;
7744   bool HasAnyUndefs;
7745   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7746                                     HasAnyUndefs, ElementBits) ||
7747       SplatBitSize > ElementBits)
7748     return false;
7749   Cnt = SplatBits.getSExtValue();
7750   return true;
7751 }
7752 
7753 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7754 /// operand of a vector shift left operation.  That value must be in the range:
7755 ///   0 <= Value < ElementBits for a left shift; or
7756 ///   0 <= Value <= ElementBits for a long left shift.
7757 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7758   assert(VT.isVector() && "vector shift count is not a vector type");
7759   int64_t ElementBits = VT.getScalarSizeInBits();
7760   if (!getVShiftImm(Op, ElementBits, Cnt))
7761     return false;
7762   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7763 }
7764 
7765 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7766 /// operand of a vector shift right operation. The value must be in the range:
7767 ///   1 <= Value <= ElementBits for a right shift; or
7768 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7769   assert(VT.isVector() && "vector shift count is not a vector type");
7770   int64_t ElementBits = VT.getScalarSizeInBits();
7771   if (!getVShiftImm(Op, ElementBits, Cnt))
7772     return false;
7773   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7774 }
7775 
7776 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7777                                                       SelectionDAG &DAG) const {
7778   EVT VT = Op.getValueType();
7779   SDLoc DL(Op);
7780   int64_t Cnt;
7781 
7782   if (!Op.getOperand(1).getValueType().isVector())
7783     return Op;
7784   unsigned EltSize = VT.getScalarSizeInBits();
7785 
7786   switch (Op.getOpcode()) {
7787   default:
7788     llvm_unreachable("unexpected shift opcode");
7789 
7790   case ISD::SHL:
7791     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7792       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7793                          DAG.getConstant(Cnt, DL, MVT::i32));
7794     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7795                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7796                                        MVT::i32),
7797                        Op.getOperand(0), Op.getOperand(1));
7798   case ISD::SRA:
7799   case ISD::SRL:
7800     // Right shift immediate
7801     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7802       unsigned Opc =
7803           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7804       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7805                          DAG.getConstant(Cnt, DL, MVT::i32));
7806     }
7807 
7808     // Right shift register.  Note, there is not a shift right register
7809     // instruction, but the shift left register instruction takes a signed
7810     // value, where negative numbers specify a right shift.
7811     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7812                                                 : Intrinsic::aarch64_neon_ushl;
7813     // negate the shift amount
7814     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7815     SDValue NegShiftLeft =
7816         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7817                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7818                     NegShift);
7819     return NegShiftLeft;
7820   }
7821 
7822   return SDValue();
7823 }
7824 
7825 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7826                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7827                                     const SDLoc &dl, SelectionDAG &DAG) {
7828   EVT SrcVT = LHS.getValueType();
7829   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7830          "function only supposed to emit natural comparisons");
7831 
7832   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7833   APInt CnstBits(VT.getSizeInBits(), 0);
7834   APInt UndefBits(VT.getSizeInBits(), 0);
7835   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7836   bool IsZero = IsCnst && (CnstBits == 0);
7837 
7838   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7839     switch (CC) {
7840     default:
7841       return SDValue();
7842     case AArch64CC::NE: {
7843       SDValue Fcmeq;
7844       if (IsZero)
7845         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7846       else
7847         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7848       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7849     }
7850     case AArch64CC::EQ:
7851       if (IsZero)
7852         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7853       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7854     case AArch64CC::GE:
7855       if (IsZero)
7856         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7857       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7858     case AArch64CC::GT:
7859       if (IsZero)
7860         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7861       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7862     case AArch64CC::LS:
7863       if (IsZero)
7864         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7865       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7866     case AArch64CC::LT:
7867       if (!NoNans)
7868         return SDValue();
7869       // If we ignore NaNs then we can use to the MI implementation.
7870       LLVM_FALLTHROUGH;
7871     case AArch64CC::MI:
7872       if (IsZero)
7873         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7874       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7875     }
7876   }
7877 
7878   switch (CC) {
7879   default:
7880     return SDValue();
7881   case AArch64CC::NE: {
7882     SDValue Cmeq;
7883     if (IsZero)
7884       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7885     else
7886       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7887     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7888   }
7889   case AArch64CC::EQ:
7890     if (IsZero)
7891       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7892     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7893   case AArch64CC::GE:
7894     if (IsZero)
7895       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7896     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7897   case AArch64CC::GT:
7898     if (IsZero)
7899       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7900     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7901   case AArch64CC::LE:
7902     if (IsZero)
7903       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7904     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7905   case AArch64CC::LS:
7906     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7907   case AArch64CC::LO:
7908     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7909   case AArch64CC::LT:
7910     if (IsZero)
7911       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7912     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7913   case AArch64CC::HI:
7914     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7915   case AArch64CC::HS:
7916     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7917   }
7918 }
7919 
7920 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7921                                            SelectionDAG &DAG) const {
7922   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7923   SDValue LHS = Op.getOperand(0);
7924   SDValue RHS = Op.getOperand(1);
7925   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7926   SDLoc dl(Op);
7927 
7928   if (LHS.getValueType().getVectorElementType().isInteger()) {
7929     assert(LHS.getValueType() == RHS.getValueType());
7930     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7931     SDValue Cmp =
7932         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7933     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7934   }
7935 
7936   const bool FullFP16 =
7937     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7938 
7939   // Make v4f16 (only) fcmp operations utilise vector instructions
7940   // v8f16 support will be a litle more complicated
7941   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7942     if (LHS.getValueType().getVectorNumElements() == 4) {
7943       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7944       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7945       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7946       DAG.ReplaceAllUsesWith(Op, NewSetcc);
7947       CmpVT = MVT::v4i32;
7948     } else
7949       return SDValue();
7950   }
7951 
7952   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7953           LHS.getValueType().getVectorElementType() != MVT::f128);
7954 
7955   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7956   // clean.  Some of them require two branches to implement.
7957   AArch64CC::CondCode CC1, CC2;
7958   bool ShouldInvert;
7959   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7960 
7961   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7962   SDValue Cmp =
7963       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7964   if (!Cmp.getNode())
7965     return SDValue();
7966 
7967   if (CC2 != AArch64CC::AL) {
7968     SDValue Cmp2 =
7969         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7970     if (!Cmp2.getNode())
7971       return SDValue();
7972 
7973     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7974   }
7975 
7976   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7977 
7978   if (ShouldInvert)
7979     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7980 
7981   return Cmp;
7982 }
7983 
7984 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7985                                   SelectionDAG &DAG) {
7986   SDValue VecOp = ScalarOp.getOperand(0);
7987   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7988   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7989                      DAG.getConstant(0, DL, MVT::i64));
7990 }
7991 
7992 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7993                                               SelectionDAG &DAG) const {
7994   SDLoc dl(Op);
7995   switch (Op.getOpcode()) {
7996   case ISD::VECREDUCE_ADD:
7997     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7998   case ISD::VECREDUCE_SMAX:
7999     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8000   case ISD::VECREDUCE_SMIN:
8001     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8002   case ISD::VECREDUCE_UMAX:
8003     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8004   case ISD::VECREDUCE_UMIN:
8005     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8006   case ISD::VECREDUCE_FMAX: {
8007     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8008     return DAG.getNode(
8009         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8010         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8011         Op.getOperand(0));
8012   }
8013   case ISD::VECREDUCE_FMIN: {
8014     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8015     return DAG.getNode(
8016         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8017         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8018         Op.getOperand(0));
8019   }
8020   default:
8021     llvm_unreachable("Unhandled reduction");
8022   }
8023 }
8024 
8025 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8026                                                     SelectionDAG &DAG) const {
8027   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8028   if (!Subtarget.hasLSE())
8029     return SDValue();
8030 
8031   // LSE has an atomic load-add instruction, but not a load-sub.
8032   SDLoc dl(Op);
8033   MVT VT = Op.getSimpleValueType();
8034   SDValue RHS = Op.getOperand(2);
8035   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8036   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8037   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8038                        Op.getOperand(0), Op.getOperand(1), RHS,
8039                        AN->getMemOperand());
8040 }
8041 
8042 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8043                                                     SelectionDAG &DAG) const {
8044   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8045   if (!Subtarget.hasLSE())
8046     return SDValue();
8047 
8048   // LSE has an atomic load-clear instruction, but not a load-and.
8049   SDLoc dl(Op);
8050   MVT VT = Op.getSimpleValueType();
8051   SDValue RHS = Op.getOperand(2);
8052   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8053   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8054   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8055                        Op.getOperand(0), Op.getOperand(1), RHS,
8056                        AN->getMemOperand());
8057 }
8058 
8059 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8060     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8061   SDLoc dl(Op);
8062   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8063   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8064 
8065   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8066   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8067   if (Subtarget->hasCustomCallingConv())
8068     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8069 
8070   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8071                      DAG.getConstant(4, dl, MVT::i64));
8072   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8073   Chain =
8074       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8075                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8076                   DAG.getRegisterMask(Mask), Chain.getValue(1));
8077   // To match the actual intent better, we should read the output from X15 here
8078   // again (instead of potentially spilling it to the stack), but rereading Size
8079   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8080   // here.
8081 
8082   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8083                      DAG.getConstant(4, dl, MVT::i64));
8084   return Chain;
8085 }
8086 
8087 SDValue
8088 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8089                                                SelectionDAG &DAG) const {
8090   assert(Subtarget->isTargetWindows() &&
8091          "Only Windows alloca probing supported");
8092   SDLoc dl(Op);
8093   // Get the inputs.
8094   SDNode *Node = Op.getNode();
8095   SDValue Chain = Op.getOperand(0);
8096   SDValue Size = Op.getOperand(1);
8097   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8098   EVT VT = Node->getValueType(0);
8099 
8100   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8101           "no-stack-arg-probe")) {
8102     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8103     Chain = SP.getValue(1);
8104     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8105     if (Align)
8106       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8107                        DAG.getConstant(-(uint64_t)Align, dl, VT));
8108     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8109     SDValue Ops[2] = {SP, Chain};
8110     return DAG.getMergeValues(Ops, dl);
8111   }
8112 
8113   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8114 
8115   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8116 
8117   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8118   Chain = SP.getValue(1);
8119   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8120   if (Align)
8121     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8122                      DAG.getConstant(-(uint64_t)Align, dl, VT));
8123   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8124 
8125   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8126                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8127 
8128   SDValue Ops[2] = {SP, Chain};
8129   return DAG.getMergeValues(Ops, dl);
8130 }
8131 
8132 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8133 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
8134 /// specified in the intrinsic calls.
8135 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8136                                                const CallInst &I,
8137                                                MachineFunction &MF,
8138                                                unsigned Intrinsic) const {
8139   auto &DL = I.getModule()->getDataLayout();
8140   switch (Intrinsic) {
8141   case Intrinsic::aarch64_neon_ld2:
8142   case Intrinsic::aarch64_neon_ld3:
8143   case Intrinsic::aarch64_neon_ld4:
8144   case Intrinsic::aarch64_neon_ld1x2:
8145   case Intrinsic::aarch64_neon_ld1x3:
8146   case Intrinsic::aarch64_neon_ld1x4:
8147   case Intrinsic::aarch64_neon_ld2lane:
8148   case Intrinsic::aarch64_neon_ld3lane:
8149   case Intrinsic::aarch64_neon_ld4lane:
8150   case Intrinsic::aarch64_neon_ld2r:
8151   case Intrinsic::aarch64_neon_ld3r:
8152   case Intrinsic::aarch64_neon_ld4r: {
8153     Info.opc = ISD::INTRINSIC_W_CHAIN;
8154     // Conservatively set memVT to the entire set of vectors loaded.
8155     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8156     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8157     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8158     Info.offset = 0;
8159     Info.align.reset();
8160     // volatile loads with NEON intrinsics not supported
8161     Info.flags = MachineMemOperand::MOLoad;
8162     return true;
8163   }
8164   case Intrinsic::aarch64_neon_st2:
8165   case Intrinsic::aarch64_neon_st3:
8166   case Intrinsic::aarch64_neon_st4:
8167   case Intrinsic::aarch64_neon_st1x2:
8168   case Intrinsic::aarch64_neon_st1x3:
8169   case Intrinsic::aarch64_neon_st1x4:
8170   case Intrinsic::aarch64_neon_st2lane:
8171   case Intrinsic::aarch64_neon_st3lane:
8172   case Intrinsic::aarch64_neon_st4lane: {
8173     Info.opc = ISD::INTRINSIC_VOID;
8174     // Conservatively set memVT to the entire set of vectors stored.
8175     unsigned NumElts = 0;
8176     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8177       Type *ArgTy = I.getArgOperand(ArgI)->getType();
8178       if (!ArgTy->isVectorTy())
8179         break;
8180       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8181     }
8182     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8183     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8184     Info.offset = 0;
8185     Info.align.reset();
8186     // volatile stores with NEON intrinsics not supported
8187     Info.flags = MachineMemOperand::MOStore;
8188     return true;
8189   }
8190   case Intrinsic::aarch64_ldaxr:
8191   case Intrinsic::aarch64_ldxr: {
8192     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8193     Info.opc = ISD::INTRINSIC_W_CHAIN;
8194     Info.memVT = MVT::getVT(PtrTy->getElementType());
8195     Info.ptrVal = I.getArgOperand(0);
8196     Info.offset = 0;
8197     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8198     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8199     return true;
8200   }
8201   case Intrinsic::aarch64_stlxr:
8202   case Intrinsic::aarch64_stxr: {
8203     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8204     Info.opc = ISD::INTRINSIC_W_CHAIN;
8205     Info.memVT = MVT::getVT(PtrTy->getElementType());
8206     Info.ptrVal = I.getArgOperand(1);
8207     Info.offset = 0;
8208     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8209     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8210     return true;
8211   }
8212   case Intrinsic::aarch64_ldaxp:
8213   case Intrinsic::aarch64_ldxp:
8214     Info.opc = ISD::INTRINSIC_W_CHAIN;
8215     Info.memVT = MVT::i128;
8216     Info.ptrVal = I.getArgOperand(0);
8217     Info.offset = 0;
8218     Info.align = Align(16);
8219     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8220     return true;
8221   case Intrinsic::aarch64_stlxp:
8222   case Intrinsic::aarch64_stxp:
8223     Info.opc = ISD::INTRINSIC_W_CHAIN;
8224     Info.memVT = MVT::i128;
8225     Info.ptrVal = I.getArgOperand(2);
8226     Info.offset = 0;
8227     Info.align = Align(16);
8228     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8229     return true;
8230   default:
8231     break;
8232   }
8233 
8234   return false;
8235 }
8236 
8237 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8238                                                   ISD::LoadExtType ExtTy,
8239                                                   EVT NewVT) const {
8240   // TODO: This may be worth removing. Check regression tests for diffs.
8241   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8242     return false;
8243 
8244   // If we're reducing the load width in order to avoid having to use an extra
8245   // instruction to do extension then it's probably a good idea.
8246   if (ExtTy != ISD::NON_EXTLOAD)
8247     return true;
8248   // Don't reduce load width if it would prevent us from combining a shift into
8249   // the offset.
8250   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8251   assert(Mem);
8252   const SDValue &Base = Mem->getBasePtr();
8253   if (Base.getOpcode() == ISD::ADD &&
8254       Base.getOperand(1).getOpcode() == ISD::SHL &&
8255       Base.getOperand(1).hasOneUse() &&
8256       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8257     // The shift can be combined if it matches the size of the value being
8258     // loaded (and so reducing the width would make it not match).
8259     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8260     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8261     if (ShiftAmount == Log2_32(LoadBytes))
8262       return false;
8263   }
8264   // We have no reason to disallow reducing the load width, so allow it.
8265   return true;
8266 }
8267 
8268 // Truncations from 64-bit GPR to 32-bit GPR is free.
8269 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8270   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8271     return false;
8272   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8273   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8274   return NumBits1 > NumBits2;
8275 }
8276 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8277   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8278     return false;
8279   unsigned NumBits1 = VT1.getSizeInBits();
8280   unsigned NumBits2 = VT2.getSizeInBits();
8281   return NumBits1 > NumBits2;
8282 }
8283 
8284 /// Check if it is profitable to hoist instruction in then/else to if.
8285 /// Not profitable if I and it's user can form a FMA instruction
8286 /// because we prefer FMSUB/FMADD.
8287 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8288   if (I->getOpcode() != Instruction::FMul)
8289     return true;
8290 
8291   if (!I->hasOneUse())
8292     return true;
8293 
8294   Instruction *User = I->user_back();
8295 
8296   if (User &&
8297       !(User->getOpcode() == Instruction::FSub ||
8298         User->getOpcode() == Instruction::FAdd))
8299     return true;
8300 
8301   const TargetOptions &Options = getTargetMachine().Options;
8302   const DataLayout &DL = I->getModule()->getDataLayout();
8303   EVT VT = getValueType(DL, User->getOperand(0)->getType());
8304 
8305   return !(isFMAFasterThanFMulAndFAdd(VT) &&
8306            isOperationLegalOrCustom(ISD::FMA, VT) &&
8307            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8308             Options.UnsafeFPMath));
8309 }
8310 
8311 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8312 // 64-bit GPR.
8313 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8314   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8315     return false;
8316   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8317   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8318   return NumBits1 == 32 && NumBits2 == 64;
8319 }
8320 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8321   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8322     return false;
8323   unsigned NumBits1 = VT1.getSizeInBits();
8324   unsigned NumBits2 = VT2.getSizeInBits();
8325   return NumBits1 == 32 && NumBits2 == 64;
8326 }
8327 
8328 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8329   EVT VT1 = Val.getValueType();
8330   if (isZExtFree(VT1, VT2)) {
8331     return true;
8332   }
8333 
8334   if (Val.getOpcode() != ISD::LOAD)
8335     return false;
8336 
8337   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8338   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8339           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8340           VT1.getSizeInBits() <= 32);
8341 }
8342 
8343 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8344   if (isa<FPExtInst>(Ext))
8345     return false;
8346 
8347   // Vector types are not free.
8348   if (Ext->getType()->isVectorTy())
8349     return false;
8350 
8351   for (const Use &U : Ext->uses()) {
8352     // The extension is free if we can fold it with a left shift in an
8353     // addressing mode or an arithmetic operation: add, sub, and cmp.
8354 
8355     // Is there a shift?
8356     const Instruction *Instr = cast<Instruction>(U.getUser());
8357 
8358     // Is this a constant shift?
8359     switch (Instr->getOpcode()) {
8360     case Instruction::Shl:
8361       if (!isa<ConstantInt>(Instr->getOperand(1)))
8362         return false;
8363       break;
8364     case Instruction::GetElementPtr: {
8365       gep_type_iterator GTI = gep_type_begin(Instr);
8366       auto &DL = Ext->getModule()->getDataLayout();
8367       std::advance(GTI, U.getOperandNo()-1);
8368       Type *IdxTy = GTI.getIndexedType();
8369       // This extension will end up with a shift because of the scaling factor.
8370       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8371       // Get the shift amount based on the scaling factor:
8372       // log2(sizeof(IdxTy)) - log2(8).
8373       uint64_t ShiftAmt =
8374           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8375       // Is the constant foldable in the shift of the addressing mode?
8376       // I.e., shift amount is between 1 and 4 inclusive.
8377       if (ShiftAmt == 0 || ShiftAmt > 4)
8378         return false;
8379       break;
8380     }
8381     case Instruction::Trunc:
8382       // Check if this is a noop.
8383       // trunc(sext ty1 to ty2) to ty1.
8384       if (Instr->getType() == Ext->getOperand(0)->getType())
8385         continue;
8386       LLVM_FALLTHROUGH;
8387     default:
8388       return false;
8389     }
8390 
8391     // At this point we can use the bfm family, so this extension is free
8392     // for that use.
8393   }
8394   return true;
8395 }
8396 
8397 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8398 /// or upper half of the vector elements.
8399 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8400   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8401     auto *FullVT = cast<VectorType>(FullV->getType());
8402     auto *HalfVT = cast<VectorType>(HalfV->getType());
8403     return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8404   };
8405 
8406   auto extractHalf = [](Value *FullV, Value *HalfV) {
8407     auto *FullVT = cast<VectorType>(FullV->getType());
8408     auto *HalfVT = cast<VectorType>(HalfV->getType());
8409     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8410   };
8411 
8412   Constant *M1, *M2;
8413   Value *S1Op1, *S2Op1;
8414   if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8415       !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8416     return false;
8417 
8418   // Check that the operands are half as wide as the result and we extract
8419   // half of the elements of the input vectors.
8420   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8421       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8422     return false;
8423 
8424   // Check the mask extracts either the lower or upper half of vector
8425   // elements.
8426   int M1Start = -1;
8427   int M2Start = -1;
8428   int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8429   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8430       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8431       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8432     return false;
8433 
8434   return true;
8435 }
8436 
8437 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8438 /// of the vector elements.
8439 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8440   auto areExtDoubled = [](Instruction *Ext) {
8441     return Ext->getType()->getScalarSizeInBits() ==
8442            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8443   };
8444 
8445   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8446       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8447       !areExtDoubled(cast<Instruction>(Ext1)) ||
8448       !areExtDoubled(cast<Instruction>(Ext2)))
8449     return false;
8450 
8451   return true;
8452 }
8453 
8454 /// Check if sinking \p I's operands to I's basic block is profitable, because
8455 /// the operands can be folded into a target instruction, e.g.
8456 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8457 bool AArch64TargetLowering::shouldSinkOperands(
8458     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8459   if (!I->getType()->isVectorTy())
8460     return false;
8461 
8462   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8463     switch (II->getIntrinsicID()) {
8464     case Intrinsic::aarch64_neon_umull:
8465       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8466         return false;
8467       Ops.push_back(&II->getOperandUse(0));
8468       Ops.push_back(&II->getOperandUse(1));
8469       return true;
8470     default:
8471       return false;
8472     }
8473   }
8474 
8475   switch (I->getOpcode()) {
8476   case Instruction::Sub:
8477   case Instruction::Add: {
8478     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8479       return false;
8480 
8481     // If the exts' operands extract either the lower or upper elements, we
8482     // can sink them too.
8483     auto Ext1 = cast<Instruction>(I->getOperand(0));
8484     auto Ext2 = cast<Instruction>(I->getOperand(1));
8485     if (areExtractShuffleVectors(Ext1, Ext2)) {
8486       Ops.push_back(&Ext1->getOperandUse(0));
8487       Ops.push_back(&Ext2->getOperandUse(0));
8488     }
8489 
8490     Ops.push_back(&I->getOperandUse(0));
8491     Ops.push_back(&I->getOperandUse(1));
8492 
8493     return true;
8494   }
8495   default:
8496     return false;
8497   }
8498   return false;
8499 }
8500 
8501 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8502                                           unsigned &RequiredAligment) const {
8503   if (!LoadedType.isSimple() ||
8504       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8505     return false;
8506   // Cyclone supports unaligned accesses.
8507   RequiredAligment = 0;
8508   unsigned NumBits = LoadedType.getSizeInBits();
8509   return NumBits == 32 || NumBits == 64;
8510 }
8511 
8512 /// A helper function for determining the number of interleaved accesses we
8513 /// will generate when lowering accesses of the given type.
8514 unsigned
8515 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8516                                                  const DataLayout &DL) const {
8517   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8518 }
8519 
8520 MachineMemOperand::Flags
8521 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8522   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8523       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8524     return MOStridedAccess;
8525   return MachineMemOperand::MONone;
8526 }
8527 
8528 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8529     VectorType *VecTy, const DataLayout &DL) const {
8530 
8531   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8532   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8533 
8534   // Ensure the number of vector elements is greater than 1.
8535   if (VecTy->getNumElements() < 2)
8536     return false;
8537 
8538   // Ensure the element type is legal.
8539   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8540     return false;
8541 
8542   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8543   // 128 will be split into multiple interleaved accesses.
8544   return VecSize == 64 || VecSize % 128 == 0;
8545 }
8546 
8547 /// Lower an interleaved load into a ldN intrinsic.
8548 ///
8549 /// E.g. Lower an interleaved load (Factor = 2):
8550 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8551 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
8552 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
8553 ///
8554 ///      Into:
8555 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8556 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8557 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8558 bool AArch64TargetLowering::lowerInterleavedLoad(
8559     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8560     ArrayRef<unsigned> Indices, unsigned Factor) const {
8561   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8562          "Invalid interleave factor");
8563   assert(!Shuffles.empty() && "Empty shufflevector input");
8564   assert(Shuffles.size() == Indices.size() &&
8565          "Unmatched number of shufflevectors and indices");
8566 
8567   const DataLayout &DL = LI->getModule()->getDataLayout();
8568 
8569   VectorType *VecTy = Shuffles[0]->getType();
8570 
8571   // Skip if we do not have NEON and skip illegal vector types. We can
8572   // "legalize" wide vector types into multiple interleaved accesses as long as
8573   // the vector types are divisible by 128.
8574   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8575     return false;
8576 
8577   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8578 
8579   // A pointer vector can not be the return type of the ldN intrinsics. Need to
8580   // load integer vectors first and then convert to pointer vectors.
8581   Type *EltTy = VecTy->getVectorElementType();
8582   if (EltTy->isPointerTy())
8583     VecTy =
8584         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8585 
8586   IRBuilder<> Builder(LI);
8587 
8588   // The base address of the load.
8589   Value *BaseAddr = LI->getPointerOperand();
8590 
8591   if (NumLoads > 1) {
8592     // If we're going to generate more than one load, reset the sub-vector type
8593     // to something legal.
8594     VecTy = VectorType::get(VecTy->getVectorElementType(),
8595                             VecTy->getVectorNumElements() / NumLoads);
8596 
8597     // We will compute the pointer operand of each load from the original base
8598     // address using GEPs. Cast the base address to a pointer to the scalar
8599     // element type.
8600     BaseAddr = Builder.CreateBitCast(
8601         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8602                       LI->getPointerAddressSpace()));
8603   }
8604 
8605   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8606   Type *Tys[2] = {VecTy, PtrTy};
8607   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8608                                             Intrinsic::aarch64_neon_ld3,
8609                                             Intrinsic::aarch64_neon_ld4};
8610   Function *LdNFunc =
8611       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8612 
8613   // Holds sub-vectors extracted from the load intrinsic return values. The
8614   // sub-vectors are associated with the shufflevector instructions they will
8615   // replace.
8616   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8617 
8618   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8619 
8620     // If we're generating more than one load, compute the base address of
8621     // subsequent loads as an offset from the previous.
8622     if (LoadCount > 0)
8623       BaseAddr =
8624           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8625                                      VecTy->getVectorNumElements() * Factor);
8626 
8627     CallInst *LdN = Builder.CreateCall(
8628         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8629 
8630     // Extract and store the sub-vectors returned by the load intrinsic.
8631     for (unsigned i = 0; i < Shuffles.size(); i++) {
8632       ShuffleVectorInst *SVI = Shuffles[i];
8633       unsigned Index = Indices[i];
8634 
8635       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8636 
8637       // Convert the integer vector to pointer vector if the element is pointer.
8638       if (EltTy->isPointerTy())
8639         SubVec = Builder.CreateIntToPtr(
8640             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8641                                     VecTy->getVectorNumElements()));
8642       SubVecs[SVI].push_back(SubVec);
8643     }
8644   }
8645 
8646   // Replace uses of the shufflevector instructions with the sub-vectors
8647   // returned by the load intrinsic. If a shufflevector instruction is
8648   // associated with more than one sub-vector, those sub-vectors will be
8649   // concatenated into a single wide vector.
8650   for (ShuffleVectorInst *SVI : Shuffles) {
8651     auto &SubVec = SubVecs[SVI];
8652     auto *WideVec =
8653         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8654     SVI->replaceAllUsesWith(WideVec);
8655   }
8656 
8657   return true;
8658 }
8659 
8660 /// Lower an interleaved store into a stN intrinsic.
8661 ///
8662 /// E.g. Lower an interleaved store (Factor = 3):
8663 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8664 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8665 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8666 ///
8667 ///      Into:
8668 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8669 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8670 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8671 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8672 ///
8673 /// Note that the new shufflevectors will be removed and we'll only generate one
8674 /// st3 instruction in CodeGen.
8675 ///
8676 /// Example for a more general valid mask (Factor 3). Lower:
8677 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8678 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8679 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
8680 ///
8681 ///      Into:
8682 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8683 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8684 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8685 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8686 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8687                                                   ShuffleVectorInst *SVI,
8688                                                   unsigned Factor) const {
8689   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8690          "Invalid interleave factor");
8691 
8692   VectorType *VecTy = SVI->getType();
8693   assert(VecTy->getVectorNumElements() % Factor == 0 &&
8694          "Invalid interleaved store");
8695 
8696   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8697   Type *EltTy = VecTy->getVectorElementType();
8698   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8699 
8700   const DataLayout &DL = SI->getModule()->getDataLayout();
8701 
8702   // Skip if we do not have NEON and skip illegal vector types. We can
8703   // "legalize" wide vector types into multiple interleaved accesses as long as
8704   // the vector types are divisible by 128.
8705   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8706     return false;
8707 
8708   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8709 
8710   Value *Op0 = SVI->getOperand(0);
8711   Value *Op1 = SVI->getOperand(1);
8712   IRBuilder<> Builder(SI);
8713 
8714   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8715   // vectors to integer vectors.
8716   if (EltTy->isPointerTy()) {
8717     Type *IntTy = DL.getIntPtrType(EltTy);
8718     unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8719 
8720     // Convert to the corresponding integer vector.
8721     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8722     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8723     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8724 
8725     SubVecTy = VectorType::get(IntTy, LaneLen);
8726   }
8727 
8728   // The base address of the store.
8729   Value *BaseAddr = SI->getPointerOperand();
8730 
8731   if (NumStores > 1) {
8732     // If we're going to generate more than one store, reset the lane length
8733     // and sub-vector type to something legal.
8734     LaneLen /= NumStores;
8735     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8736 
8737     // We will compute the pointer operand of each store from the original base
8738     // address using GEPs. Cast the base address to a pointer to the scalar
8739     // element type.
8740     BaseAddr = Builder.CreateBitCast(
8741         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8742                       SI->getPointerAddressSpace()));
8743   }
8744 
8745   auto Mask = SVI->getShuffleMask();
8746 
8747   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8748   Type *Tys[2] = {SubVecTy, PtrTy};
8749   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8750                                              Intrinsic::aarch64_neon_st3,
8751                                              Intrinsic::aarch64_neon_st4};
8752   Function *StNFunc =
8753       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8754 
8755   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8756 
8757     SmallVector<Value *, 5> Ops;
8758 
8759     // Split the shufflevector operands into sub vectors for the new stN call.
8760     for (unsigned i = 0; i < Factor; i++) {
8761       unsigned IdxI = StoreCount * LaneLen * Factor + i;
8762       if (Mask[IdxI] >= 0) {
8763         Ops.push_back(Builder.CreateShuffleVector(
8764             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8765       } else {
8766         unsigned StartMask = 0;
8767         for (unsigned j = 1; j < LaneLen; j++) {
8768           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8769           if (Mask[IdxJ * Factor + IdxI] >= 0) {
8770             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8771             break;
8772           }
8773         }
8774         // Note: Filling undef gaps with random elements is ok, since
8775         // those elements were being written anyway (with undefs).
8776         // In the case of all undefs we're defaulting to using elems from 0
8777         // Note: StartMask cannot be negative, it's checked in
8778         // isReInterleaveMask
8779         Ops.push_back(Builder.CreateShuffleVector(
8780             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8781       }
8782     }
8783 
8784     // If we generating more than one store, we compute the base address of
8785     // subsequent stores as an offset from the previous.
8786     if (StoreCount > 0)
8787       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8788                                             BaseAddr, LaneLen * Factor);
8789 
8790     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8791     Builder.CreateCall(StNFunc, Ops);
8792   }
8793   return true;
8794 }
8795 
8796 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8797                        unsigned AlignCheck) {
8798   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8799           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8800 }
8801 
8802 EVT AArch64TargetLowering::getOptimalMemOpType(
8803     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8804     bool ZeroMemset, bool MemcpyStrSrc,
8805     const AttributeList &FuncAttributes) const {
8806   bool CanImplicitFloat =
8807       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8808   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8809   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8810   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8811   // taken one instruction to materialize the v2i64 zero and one store (with
8812   // restrictive addressing mode). Just do i64 stores.
8813   bool IsSmallMemset = IsMemset && Size < 32;
8814   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8815     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8816       return true;
8817     bool Fast;
8818     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8819                                           &Fast) &&
8820            Fast;
8821   };
8822 
8823   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8824       AlignmentIsAcceptable(MVT::v2i64, 16))
8825     return MVT::v2i64;
8826   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8827     return MVT::f128;
8828   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8829     return MVT::i64;
8830   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8831     return MVT::i32;
8832   return MVT::Other;
8833 }
8834 
8835 LLT AArch64TargetLowering::getOptimalMemOpLLT(
8836     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8837     bool ZeroMemset, bool MemcpyStrSrc,
8838     const AttributeList &FuncAttributes) const {
8839   bool CanImplicitFloat =
8840       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8841   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8842   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8843   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8844   // taken one instruction to materialize the v2i64 zero and one store (with
8845   // restrictive addressing mode). Just do i64 stores.
8846   bool IsSmallMemset = IsMemset && Size < 32;
8847   auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8848     if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8849       return true;
8850     bool Fast;
8851     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8852                                           &Fast) &&
8853            Fast;
8854   };
8855 
8856   if (CanUseNEON && IsMemset && !IsSmallMemset &&
8857       AlignmentIsAcceptable(MVT::v2i64, 16))
8858     return LLT::vector(2, 64);
8859   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8860     return LLT::scalar(128);
8861   if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8862     return LLT::scalar(64);
8863   if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8864     return LLT::scalar(32);
8865   return LLT();
8866 }
8867 
8868 // 12-bit optionally shifted immediates are legal for adds.
8869 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8870   if (Immed == std::numeric_limits<int64_t>::min()) {
8871     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8872                       << ": avoid UB for INT64_MIN\n");
8873     return false;
8874   }
8875   // Same encoding for add/sub, just flip the sign.
8876   Immed = std::abs(Immed);
8877   bool IsLegal = ((Immed >> 12) == 0 ||
8878                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8879   LLVM_DEBUG(dbgs() << "Is " << Immed
8880                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8881   return IsLegal;
8882 }
8883 
8884 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8885 // immediates is the same as for an add or a sub.
8886 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8887   return isLegalAddImmediate(Immed);
8888 }
8889 
8890 /// isLegalAddressingMode - Return true if the addressing mode represented
8891 /// by AM is legal for this target, for a load/store of the specified type.
8892 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8893                                                   const AddrMode &AM, Type *Ty,
8894                                                   unsigned AS, Instruction *I) const {
8895   // AArch64 has five basic addressing modes:
8896   //  reg
8897   //  reg + 9-bit signed offset
8898   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
8899   //  reg1 + reg2
8900   //  reg + SIZE_IN_BYTES * reg
8901 
8902   // No global is ever allowed as a base.
8903   if (AM.BaseGV)
8904     return false;
8905 
8906   // No reg+reg+imm addressing.
8907   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8908     return false;
8909 
8910   // check reg + imm case:
8911   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8912   uint64_t NumBytes = 0;
8913   if (Ty->isSized()) {
8914     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8915     NumBytes = NumBits / 8;
8916     if (!isPowerOf2_64(NumBits))
8917       NumBytes = 0;
8918   }
8919 
8920   if (!AM.Scale) {
8921     int64_t Offset = AM.BaseOffs;
8922 
8923     // 9-bit signed offset
8924     if (isInt<9>(Offset))
8925       return true;
8926 
8927     // 12-bit unsigned offset
8928     unsigned shift = Log2_64(NumBytes);
8929     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8930         // Must be a multiple of NumBytes (NumBytes is a power of 2)
8931         (Offset >> shift) << shift == Offset)
8932       return true;
8933     return false;
8934   }
8935 
8936   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8937 
8938   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8939 }
8940 
8941 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8942   // Consider splitting large offset of struct or array.
8943   return true;
8944 }
8945 
8946 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8947                                                 const AddrMode &AM, Type *Ty,
8948                                                 unsigned AS) const {
8949   // Scaling factors are not free at all.
8950   // Operands                     | Rt Latency
8951   // -------------------------------------------
8952   // Rt, [Xn, Xm]                 | 4
8953   // -------------------------------------------
8954   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
8955   // Rt, [Xn, Wm, <extend> #imm]  |
8956   if (isLegalAddressingMode(DL, AM, Ty, AS))
8957     // Scale represents reg2 * scale, thus account for 1 if
8958     // it is not equal to 0 or 1.
8959     return AM.Scale != 0 && AM.Scale != 1;
8960   return -1;
8961 }
8962 
8963 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8964   VT = VT.getScalarType();
8965 
8966   if (!VT.isSimple())
8967     return false;
8968 
8969   switch (VT.getSimpleVT().SimpleTy) {
8970   case MVT::f32:
8971   case MVT::f64:
8972     return true;
8973   default:
8974     break;
8975   }
8976 
8977   return false;
8978 }
8979 
8980 const MCPhysReg *
8981 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8982   // LR is a callee-save register, but we must treat it as clobbered by any call
8983   // site. Hence we include LR in the scratch registers, which are in turn added
8984   // as implicit-defs for stackmaps and patchpoints.
8985   static const MCPhysReg ScratchRegs[] = {
8986     AArch64::X16, AArch64::X17, AArch64::LR, 0
8987   };
8988   return ScratchRegs;
8989 }
8990 
8991 bool
8992 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
8993                                                      CombineLevel Level) const {
8994   N = N->getOperand(0).getNode();
8995   EVT VT = N->getValueType(0);
8996     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8997     // it with shift to let it be lowered to UBFX.
8998   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8999       isa<ConstantSDNode>(N->getOperand(1))) {
9000     uint64_t TruncMask = N->getConstantOperandVal(1);
9001     if (isMask_64(TruncMask) &&
9002       N->getOperand(0).getOpcode() == ISD::SRL &&
9003       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9004       return false;
9005   }
9006   return true;
9007 }
9008 
9009 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9010                                                               Type *Ty) const {
9011   assert(Ty->isIntegerTy());
9012 
9013   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9014   if (BitSize == 0)
9015     return false;
9016 
9017   int64_t Val = Imm.getSExtValue();
9018   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9019     return true;
9020 
9021   if ((int64_t)Val < 0)
9022     Val = ~Val;
9023   if (BitSize == 32)
9024     Val &= (1LL << 32) - 1;
9025 
9026   unsigned LZ = countLeadingZeros((uint64_t)Val);
9027   unsigned Shift = (63 - LZ) / 16;
9028   // MOVZ is free so return true for one or fewer MOVK.
9029   return Shift < 3;
9030 }
9031 
9032 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9033                                                     unsigned Index) const {
9034   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9035     return false;
9036 
9037   return (Index == 0 || Index == ResVT.getVectorNumElements());
9038 }
9039 
9040 /// Turn vector tests of the signbit in the form of:
9041 ///   xor (sra X, elt_size(X)-1), -1
9042 /// into:
9043 ///   cmge X, X, #0
9044 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9045                                          const AArch64Subtarget *Subtarget) {
9046   EVT VT = N->getValueType(0);
9047   if (!Subtarget->hasNEON() || !VT.isVector())
9048     return SDValue();
9049 
9050   // There must be a shift right algebraic before the xor, and the xor must be a
9051   // 'not' operation.
9052   SDValue Shift = N->getOperand(0);
9053   SDValue Ones = N->getOperand(1);
9054   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9055       !ISD::isBuildVectorAllOnes(Ones.getNode()))
9056     return SDValue();
9057 
9058   // The shift should be smearing the sign bit across each vector element.
9059   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9060   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9061   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9062     return SDValue();
9063 
9064   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9065 }
9066 
9067 // Generate SUBS and CSEL for integer abs.
9068 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9069   EVT VT = N->getValueType(0);
9070 
9071   SDValue N0 = N->getOperand(0);
9072   SDValue N1 = N->getOperand(1);
9073   SDLoc DL(N);
9074 
9075   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9076   // and change it to SUB and CSEL.
9077   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9078       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9079       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9080     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9081       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9082         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9083                                   N0.getOperand(0));
9084         // Generate SUBS & CSEL.
9085         SDValue Cmp =
9086             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9087                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
9088         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9089                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9090                            SDValue(Cmp.getNode(), 1));
9091       }
9092   return SDValue();
9093 }
9094 
9095 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9096                                  TargetLowering::DAGCombinerInfo &DCI,
9097                                  const AArch64Subtarget *Subtarget) {
9098   if (DCI.isBeforeLegalizeOps())
9099     return SDValue();
9100 
9101   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9102     return Cmp;
9103 
9104   return performIntegerAbsCombine(N, DAG);
9105 }
9106 
9107 SDValue
9108 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9109                                      SelectionDAG &DAG,
9110                                      SmallVectorImpl<SDNode *> &Created) const {
9111   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9112   if (isIntDivCheap(N->getValueType(0), Attr))
9113     return SDValue(N,0); // Lower SDIV as SDIV
9114 
9115   // fold (sdiv X, pow2)
9116   EVT VT = N->getValueType(0);
9117   if ((VT != MVT::i32 && VT != MVT::i64) ||
9118       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9119     return SDValue();
9120 
9121   SDLoc DL(N);
9122   SDValue N0 = N->getOperand(0);
9123   unsigned Lg2 = Divisor.countTrailingZeros();
9124   SDValue Zero = DAG.getConstant(0, DL, VT);
9125   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9126 
9127   // Add (N0 < 0) ? Pow2 - 1 : 0;
9128   SDValue CCVal;
9129   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9130   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9131   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9132 
9133   Created.push_back(Cmp.getNode());
9134   Created.push_back(Add.getNode());
9135   Created.push_back(CSel.getNode());
9136 
9137   // Divide by pow2.
9138   SDValue SRA =
9139       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9140 
9141   // If we're dividing by a positive value, we're done.  Otherwise, we must
9142   // negate the result.
9143   if (Divisor.isNonNegative())
9144     return SRA;
9145 
9146   Created.push_back(SRA.getNode());
9147   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9148 }
9149 
9150 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9151                                  TargetLowering::DAGCombinerInfo &DCI,
9152                                  const AArch64Subtarget *Subtarget) {
9153   if (DCI.isBeforeLegalizeOps())
9154     return SDValue();
9155 
9156   // The below optimizations require a constant RHS.
9157   if (!isa<ConstantSDNode>(N->getOperand(1)))
9158     return SDValue();
9159 
9160   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9161   const APInt &ConstValue = C->getAPIntValue();
9162 
9163   // Multiplication of a power of two plus/minus one can be done more
9164   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9165   // future CPUs have a cheaper MADD instruction, this may need to be
9166   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9167   // 64-bit is 5 cycles, so this is always a win.
9168   // More aggressively, some multiplications N0 * C can be lowered to
9169   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9170   // e.g. 6=3*2=(2+1)*2.
9171   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9172   // which equals to (1+2)*16-(1+2).
9173   SDValue N0 = N->getOperand(0);
9174   // TrailingZeroes is used to test if the mul can be lowered to
9175   // shift+add+shift.
9176   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9177   if (TrailingZeroes) {
9178     // Conservatively do not lower to shift+add+shift if the mul might be
9179     // folded into smul or umul.
9180     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9181                             isZeroExtended(N0.getNode(), DAG)))
9182       return SDValue();
9183     // Conservatively do not lower to shift+add+shift if the mul might be
9184     // folded into madd or msub.
9185     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9186                            N->use_begin()->getOpcode() == ISD::SUB))
9187       return SDValue();
9188   }
9189   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9190   // and shift+add+shift.
9191   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9192 
9193   unsigned ShiftAmt, AddSubOpc;
9194   // Is the shifted value the LHS operand of the add/sub?
9195   bool ShiftValUseIsN0 = true;
9196   // Do we need to negate the result?
9197   bool NegateResult = false;
9198 
9199   if (ConstValue.isNonNegative()) {
9200     // (mul x, 2^N + 1) => (add (shl x, N), x)
9201     // (mul x, 2^N - 1) => (sub (shl x, N), x)
9202     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9203     APInt SCVMinus1 = ShiftedConstValue - 1;
9204     APInt CVPlus1 = ConstValue + 1;
9205     if (SCVMinus1.isPowerOf2()) {
9206       ShiftAmt = SCVMinus1.logBase2();
9207       AddSubOpc = ISD::ADD;
9208     } else if (CVPlus1.isPowerOf2()) {
9209       ShiftAmt = CVPlus1.logBase2();
9210       AddSubOpc = ISD::SUB;
9211     } else
9212       return SDValue();
9213   } else {
9214     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9215     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9216     APInt CVNegPlus1 = -ConstValue + 1;
9217     APInt CVNegMinus1 = -ConstValue - 1;
9218     if (CVNegPlus1.isPowerOf2()) {
9219       ShiftAmt = CVNegPlus1.logBase2();
9220       AddSubOpc = ISD::SUB;
9221       ShiftValUseIsN0 = false;
9222     } else if (CVNegMinus1.isPowerOf2()) {
9223       ShiftAmt = CVNegMinus1.logBase2();
9224       AddSubOpc = ISD::ADD;
9225       NegateResult = true;
9226     } else
9227       return SDValue();
9228   }
9229 
9230   SDLoc DL(N);
9231   EVT VT = N->getValueType(0);
9232   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9233                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
9234 
9235   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9236   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9237   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9238   assert(!(NegateResult && TrailingZeroes) &&
9239          "NegateResult and TrailingZeroes cannot both be true for now.");
9240   // Negate the result.
9241   if (NegateResult)
9242     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9243   // Shift the result.
9244   if (TrailingZeroes)
9245     return DAG.getNode(ISD::SHL, DL, VT, Res,
9246                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9247   return Res;
9248 }
9249 
9250 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9251                                                          SelectionDAG &DAG) {
9252   // Take advantage of vector comparisons producing 0 or -1 in each lane to
9253   // optimize away operation when it's from a constant.
9254   //
9255   // The general transformation is:
9256   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9257   //       AND(VECTOR_CMP(x,y), constant2)
9258   //    constant2 = UNARYOP(constant)
9259 
9260   // Early exit if this isn't a vector operation, the operand of the
9261   // unary operation isn't a bitwise AND, or if the sizes of the operations
9262   // aren't the same.
9263   EVT VT = N->getValueType(0);
9264   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9265       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9266       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9267     return SDValue();
9268 
9269   // Now check that the other operand of the AND is a constant. We could
9270   // make the transformation for non-constant splats as well, but it's unclear
9271   // that would be a benefit as it would not eliminate any operations, just
9272   // perform one more step in scalar code before moving to the vector unit.
9273   if (BuildVectorSDNode *BV =
9274           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9275     // Bail out if the vector isn't a constant.
9276     if (!BV->isConstant())
9277       return SDValue();
9278 
9279     // Everything checks out. Build up the new and improved node.
9280     SDLoc DL(N);
9281     EVT IntVT = BV->getValueType(0);
9282     // Create a new constant of the appropriate type for the transformed
9283     // DAG.
9284     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9285     // The AND node needs bitcasts to/from an integer vector type around it.
9286     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9287     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9288                                  N->getOperand(0)->getOperand(0), MaskConst);
9289     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9290     return Res;
9291   }
9292 
9293   return SDValue();
9294 }
9295 
9296 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9297                                      const AArch64Subtarget *Subtarget) {
9298   // First try to optimize away the conversion when it's conditionally from
9299   // a constant. Vectors only.
9300   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9301     return Res;
9302 
9303   EVT VT = N->getValueType(0);
9304   if (VT != MVT::f32 && VT != MVT::f64)
9305     return SDValue();
9306 
9307   // Only optimize when the source and destination types have the same width.
9308   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9309     return SDValue();
9310 
9311   // If the result of an integer load is only used by an integer-to-float
9312   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9313   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9314   SDValue N0 = N->getOperand(0);
9315   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9316       // Do not change the width of a volatile load.
9317       !cast<LoadSDNode>(N0)->isVolatile()) {
9318     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9319     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9320                                LN0->getPointerInfo(), LN0->getAlignment(),
9321                                LN0->getMemOperand()->getFlags());
9322 
9323     // Make sure successors of the original load stay after it by updating them
9324     // to use the new Chain.
9325     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9326 
9327     unsigned Opcode =
9328         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9329     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9330   }
9331 
9332   return SDValue();
9333 }
9334 
9335 /// Fold a floating-point multiply by power of two into floating-point to
9336 /// fixed-point conversion.
9337 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9338                                      TargetLowering::DAGCombinerInfo &DCI,
9339                                      const AArch64Subtarget *Subtarget) {
9340   if (!Subtarget->hasNEON())
9341     return SDValue();
9342 
9343   if (!N->getValueType(0).isSimple())
9344     return SDValue();
9345 
9346   SDValue Op = N->getOperand(0);
9347   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9348       Op.getOpcode() != ISD::FMUL)
9349     return SDValue();
9350 
9351   SDValue ConstVec = Op->getOperand(1);
9352   if (!isa<BuildVectorSDNode>(ConstVec))
9353     return SDValue();
9354 
9355   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9356   uint32_t FloatBits = FloatTy.getSizeInBits();
9357   if (FloatBits != 32 && FloatBits != 64)
9358     return SDValue();
9359 
9360   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9361   uint32_t IntBits = IntTy.getSizeInBits();
9362   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9363     return SDValue();
9364 
9365   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9366   if (IntBits > FloatBits)
9367     return SDValue();
9368 
9369   BitVector UndefElements;
9370   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9371   int32_t Bits = IntBits == 64 ? 64 : 32;
9372   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9373   if (C == -1 || C == 0 || C > Bits)
9374     return SDValue();
9375 
9376   MVT ResTy;
9377   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9378   switch (NumLanes) {
9379   default:
9380     return SDValue();
9381   case 2:
9382     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9383     break;
9384   case 4:
9385     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9386     break;
9387   }
9388 
9389   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9390     return SDValue();
9391 
9392   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9393          "Illegal vector type after legalization");
9394 
9395   SDLoc DL(N);
9396   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9397   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9398                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
9399   SDValue FixConv =
9400       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9401                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9402                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9403   // We can handle smaller integers by generating an extra trunc.
9404   if (IntBits < FloatBits)
9405     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9406 
9407   return FixConv;
9408 }
9409 
9410 /// Fold a floating-point divide by power of two into fixed-point to
9411 /// floating-point conversion.
9412 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9413                                   TargetLowering::DAGCombinerInfo &DCI,
9414                                   const AArch64Subtarget *Subtarget) {
9415   if (!Subtarget->hasNEON())
9416     return SDValue();
9417 
9418   SDValue Op = N->getOperand(0);
9419   unsigned Opc = Op->getOpcode();
9420   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9421       !Op.getOperand(0).getValueType().isSimple() ||
9422       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9423     return SDValue();
9424 
9425   SDValue ConstVec = N->getOperand(1);
9426   if (!isa<BuildVectorSDNode>(ConstVec))
9427     return SDValue();
9428 
9429   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9430   int32_t IntBits = IntTy.getSizeInBits();
9431   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9432     return SDValue();
9433 
9434   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9435   int32_t FloatBits = FloatTy.getSizeInBits();
9436   if (FloatBits != 32 && FloatBits != 64)
9437     return SDValue();
9438 
9439   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9440   if (IntBits > FloatBits)
9441     return SDValue();
9442 
9443   BitVector UndefElements;
9444   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9445   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9446   if (C == -1 || C == 0 || C > FloatBits)
9447     return SDValue();
9448 
9449   MVT ResTy;
9450   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9451   switch (NumLanes) {
9452   default:
9453     return SDValue();
9454   case 2:
9455     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9456     break;
9457   case 4:
9458     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9459     break;
9460   }
9461 
9462   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9463     return SDValue();
9464 
9465   SDLoc DL(N);
9466   SDValue ConvInput = Op.getOperand(0);
9467   bool IsSigned = Opc == ISD::SINT_TO_FP;
9468   if (IntBits < FloatBits)
9469     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9470                             ResTy, ConvInput);
9471 
9472   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9473                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
9474   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9475                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9476                      DAG.getConstant(C, DL, MVT::i32));
9477 }
9478 
9479 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9480 /// searches for and classifies those shifts.
9481 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9482                          bool &FromHi) {
9483   if (N.getOpcode() == ISD::SHL)
9484     FromHi = false;
9485   else if (N.getOpcode() == ISD::SRL)
9486     FromHi = true;
9487   else
9488     return false;
9489 
9490   if (!isa<ConstantSDNode>(N.getOperand(1)))
9491     return false;
9492 
9493   ShiftAmount = N->getConstantOperandVal(1);
9494   Src = N->getOperand(0);
9495   return true;
9496 }
9497 
9498 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9499 /// registers viewed as a high/low pair. This function looks for the pattern:
9500 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9501 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9502 /// aren't independent.
9503 static SDValue tryCombineToEXTR(SDNode *N,
9504                                 TargetLowering::DAGCombinerInfo &DCI) {
9505   SelectionDAG &DAG = DCI.DAG;
9506   SDLoc DL(N);
9507   EVT VT = N->getValueType(0);
9508 
9509   assert(N->getOpcode() == ISD::OR && "Unexpected root");
9510 
9511   if (VT != MVT::i32 && VT != MVT::i64)
9512     return SDValue();
9513 
9514   SDValue LHS;
9515   uint32_t ShiftLHS = 0;
9516   bool LHSFromHi = false;
9517   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9518     return SDValue();
9519 
9520   SDValue RHS;
9521   uint32_t ShiftRHS = 0;
9522   bool RHSFromHi = false;
9523   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9524     return SDValue();
9525 
9526   // If they're both trying to come from the high part of the register, they're
9527   // not really an EXTR.
9528   if (LHSFromHi == RHSFromHi)
9529     return SDValue();
9530 
9531   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9532     return SDValue();
9533 
9534   if (LHSFromHi) {
9535     std::swap(LHS, RHS);
9536     std::swap(ShiftLHS, ShiftRHS);
9537   }
9538 
9539   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9540                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
9541 }
9542 
9543 static SDValue tryCombineToBSL(SDNode *N,
9544                                 TargetLowering::DAGCombinerInfo &DCI) {
9545   EVT VT = N->getValueType(0);
9546   SelectionDAG &DAG = DCI.DAG;
9547   SDLoc DL(N);
9548 
9549   if (!VT.isVector())
9550     return SDValue();
9551 
9552   SDValue N0 = N->getOperand(0);
9553   if (N0.getOpcode() != ISD::AND)
9554     return SDValue();
9555 
9556   SDValue N1 = N->getOperand(1);
9557   if (N1.getOpcode() != ISD::AND)
9558     return SDValue();
9559 
9560   // We only have to look for constant vectors here since the general, variable
9561   // case can be handled in TableGen.
9562   unsigned Bits = VT.getScalarSizeInBits();
9563   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9564   for (int i = 1; i >= 0; --i)
9565     for (int j = 1; j >= 0; --j) {
9566       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9567       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9568       if (!BVN0 || !BVN1)
9569         continue;
9570 
9571       bool FoundMatch = true;
9572       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9573         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9574         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9575         if (!CN0 || !CN1 ||
9576             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9577           FoundMatch = false;
9578           break;
9579         }
9580       }
9581 
9582       if (FoundMatch)
9583         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9584                            N0->getOperand(1 - i), N1->getOperand(1 - j));
9585     }
9586 
9587   return SDValue();
9588 }
9589 
9590 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9591                                 const AArch64Subtarget *Subtarget) {
9592   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9593   SelectionDAG &DAG = DCI.DAG;
9594   EVT VT = N->getValueType(0);
9595 
9596   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9597     return SDValue();
9598 
9599   if (SDValue Res = tryCombineToEXTR(N, DCI))
9600     return Res;
9601 
9602   if (SDValue Res = tryCombineToBSL(N, DCI))
9603     return Res;
9604 
9605   return SDValue();
9606 }
9607 
9608 static SDValue performANDCombine(SDNode *N,
9609                                  TargetLowering::DAGCombinerInfo &DCI) {
9610   SelectionDAG &DAG = DCI.DAG;
9611   SDValue LHS = N->getOperand(0);
9612   EVT VT = N->getValueType(0);
9613   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9614     return SDValue();
9615 
9616   BuildVectorSDNode *BVN =
9617       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9618   if (!BVN)
9619     return SDValue();
9620 
9621   // AND does not accept an immediate, so check if we can use a BIC immediate
9622   // instruction instead. We do this here instead of using a (and x, (mvni imm))
9623   // pattern in isel, because some immediates may be lowered to the preferred
9624   // (and x, (movi imm)) form, even though an mvni representation also exists.
9625   APInt DefBits(VT.getSizeInBits(), 0);
9626   APInt UndefBits(VT.getSizeInBits(), 0);
9627   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9628     SDValue NewOp;
9629 
9630     DefBits = ~DefBits;
9631     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9632                                     DefBits, &LHS)) ||
9633         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9634                                     DefBits, &LHS)))
9635       return NewOp;
9636 
9637     UndefBits = ~UndefBits;
9638     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9639                                     UndefBits, &LHS)) ||
9640         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9641                                     UndefBits, &LHS)))
9642       return NewOp;
9643   }
9644 
9645   return SDValue();
9646 }
9647 
9648 static SDValue performSRLCombine(SDNode *N,
9649                                  TargetLowering::DAGCombinerInfo &DCI) {
9650   SelectionDAG &DAG = DCI.DAG;
9651   EVT VT = N->getValueType(0);
9652   if (VT != MVT::i32 && VT != MVT::i64)
9653     return SDValue();
9654 
9655   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9656   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9657   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9658   SDValue N0 = N->getOperand(0);
9659   if (N0.getOpcode() == ISD::BSWAP) {
9660     SDLoc DL(N);
9661     SDValue N1 = N->getOperand(1);
9662     SDValue N00 = N0.getOperand(0);
9663     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9664       uint64_t ShiftAmt = C->getZExtValue();
9665       if (VT == MVT::i32 && ShiftAmt == 16 &&
9666           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9667         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9668       if (VT == MVT::i64 && ShiftAmt == 32 &&
9669           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9670         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9671     }
9672   }
9673   return SDValue();
9674 }
9675 
9676 static SDValue performBitcastCombine(SDNode *N,
9677                                      TargetLowering::DAGCombinerInfo &DCI,
9678                                      SelectionDAG &DAG) {
9679   // Wait 'til after everything is legalized to try this. That way we have
9680   // legal vector types and such.
9681   if (DCI.isBeforeLegalizeOps())
9682     return SDValue();
9683 
9684   // Remove extraneous bitcasts around an extract_subvector.
9685   // For example,
9686   //    (v4i16 (bitconvert
9687   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9688   //  becomes
9689   //    (extract_subvector ((v8i16 ...), (i64 4)))
9690 
9691   // Only interested in 64-bit vectors as the ultimate result.
9692   EVT VT = N->getValueType(0);
9693   if (!VT.isVector())
9694     return SDValue();
9695   if (VT.getSimpleVT().getSizeInBits() != 64)
9696     return SDValue();
9697   // Is the operand an extract_subvector starting at the beginning or halfway
9698   // point of the vector? A low half may also come through as an
9699   // EXTRACT_SUBREG, so look for that, too.
9700   SDValue Op0 = N->getOperand(0);
9701   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9702       !(Op0->isMachineOpcode() &&
9703         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9704     return SDValue();
9705   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9706   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9707     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9708       return SDValue();
9709   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9710     if (idx != AArch64::dsub)
9711       return SDValue();
9712     // The dsub reference is equivalent to a lane zero subvector reference.
9713     idx = 0;
9714   }
9715   // Look through the bitcast of the input to the extract.
9716   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9717     return SDValue();
9718   SDValue Source = Op0->getOperand(0)->getOperand(0);
9719   // If the source type has twice the number of elements as our destination
9720   // type, we know this is an extract of the high or low half of the vector.
9721   EVT SVT = Source->getValueType(0);
9722   if (!SVT.isVector() ||
9723       SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9724     return SDValue();
9725 
9726   LLVM_DEBUG(
9727       dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9728 
9729   // Create the simplified form to just extract the low or high half of the
9730   // vector directly rather than bothering with the bitcasts.
9731   SDLoc dl(N);
9732   unsigned NumElements = VT.getVectorNumElements();
9733   if (idx) {
9734     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9735     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9736   } else {
9737     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9738     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9739                                       Source, SubReg),
9740                    0);
9741   }
9742 }
9743 
9744 static SDValue performConcatVectorsCombine(SDNode *N,
9745                                            TargetLowering::DAGCombinerInfo &DCI,
9746                                            SelectionDAG &DAG) {
9747   SDLoc dl(N);
9748   EVT VT = N->getValueType(0);
9749   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9750 
9751   // Optimize concat_vectors of truncated vectors, where the intermediate
9752   // type is illegal, to avoid said illegality,  e.g.,
9753   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9754   //                          (v2i16 (truncate (v2i64)))))
9755   // ->
9756   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9757   //                                    (v4i32 (bitcast (v2i64))),
9758   //                                    <0, 2, 4, 6>)))
9759   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9760   // on both input and result type, so we might generate worse code.
9761   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9762   if (N->getNumOperands() == 2 &&
9763       N0->getOpcode() == ISD::TRUNCATE &&
9764       N1->getOpcode() == ISD::TRUNCATE) {
9765     SDValue N00 = N0->getOperand(0);
9766     SDValue N10 = N1->getOperand(0);
9767     EVT N00VT = N00.getValueType();
9768 
9769     if (N00VT == N10.getValueType() &&
9770         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9771         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9772       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9773       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9774       for (size_t i = 0; i < Mask.size(); ++i)
9775         Mask[i] = i * 2;
9776       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9777                          DAG.getVectorShuffle(
9778                              MidVT, dl,
9779                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9780                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9781     }
9782   }
9783 
9784   // Wait 'til after everything is legalized to try this. That way we have
9785   // legal vector types and such.
9786   if (DCI.isBeforeLegalizeOps())
9787     return SDValue();
9788 
9789   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9790   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9791   // canonicalise to that.
9792   if (N0 == N1 && VT.getVectorNumElements() == 2) {
9793     assert(VT.getScalarSizeInBits() == 64);
9794     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9795                        DAG.getConstant(0, dl, MVT::i64));
9796   }
9797 
9798   // Canonicalise concat_vectors so that the right-hand vector has as few
9799   // bit-casts as possible before its real operation. The primary matching
9800   // destination for these operations will be the narrowing "2" instructions,
9801   // which depend on the operation being performed on this right-hand vector.
9802   // For example,
9803   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
9804   // becomes
9805   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9806 
9807   if (N1->getOpcode() != ISD::BITCAST)
9808     return SDValue();
9809   SDValue RHS = N1->getOperand(0);
9810   MVT RHSTy = RHS.getValueType().getSimpleVT();
9811   // If the RHS is not a vector, this is not the pattern we're looking for.
9812   if (!RHSTy.isVector())
9813     return SDValue();
9814 
9815   LLVM_DEBUG(
9816       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9817 
9818   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9819                                   RHSTy.getVectorNumElements() * 2);
9820   return DAG.getNode(ISD::BITCAST, dl, VT,
9821                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9822                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9823                                  RHS));
9824 }
9825 
9826 static SDValue tryCombineFixedPointConvert(SDNode *N,
9827                                            TargetLowering::DAGCombinerInfo &DCI,
9828                                            SelectionDAG &DAG) {
9829   // Wait until after everything is legalized to try this. That way we have
9830   // legal vector types and such.
9831   if (DCI.isBeforeLegalizeOps())
9832     return SDValue();
9833   // Transform a scalar conversion of a value from a lane extract into a
9834   // lane extract of a vector conversion. E.g., from foo1 to foo2:
9835   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9836   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9837   //
9838   // The second form interacts better with instruction selection and the
9839   // register allocator to avoid cross-class register copies that aren't
9840   // coalescable due to a lane reference.
9841 
9842   // Check the operand and see if it originates from a lane extract.
9843   SDValue Op1 = N->getOperand(1);
9844   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9845     // Yep, no additional predication needed. Perform the transform.
9846     SDValue IID = N->getOperand(0);
9847     SDValue Shift = N->getOperand(2);
9848     SDValue Vec = Op1.getOperand(0);
9849     SDValue Lane = Op1.getOperand(1);
9850     EVT ResTy = N->getValueType(0);
9851     EVT VecResTy;
9852     SDLoc DL(N);
9853 
9854     // The vector width should be 128 bits by the time we get here, even
9855     // if it started as 64 bits (the extract_vector handling will have
9856     // done so).
9857     assert(Vec.getValueSizeInBits() == 128 &&
9858            "unexpected vector size on extract_vector_elt!");
9859     if (Vec.getValueType() == MVT::v4i32)
9860       VecResTy = MVT::v4f32;
9861     else if (Vec.getValueType() == MVT::v2i64)
9862       VecResTy = MVT::v2f64;
9863     else
9864       llvm_unreachable("unexpected vector type!");
9865 
9866     SDValue Convert =
9867         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9868     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9869   }
9870   return SDValue();
9871 }
9872 
9873 // AArch64 high-vector "long" operations are formed by performing the non-high
9874 // version on an extract_subvector of each operand which gets the high half:
9875 //
9876 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9877 //
9878 // However, there are cases which don't have an extract_high explicitly, but
9879 // have another operation that can be made compatible with one for free. For
9880 // example:
9881 //
9882 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
9883 //
9884 // This routine does the actual conversion of such DUPs, once outer routines
9885 // have determined that everything else is in order.
9886 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9887 // similarly here.
9888 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9889   switch (N.getOpcode()) {
9890   case AArch64ISD::DUP:
9891   case AArch64ISD::DUPLANE8:
9892   case AArch64ISD::DUPLANE16:
9893   case AArch64ISD::DUPLANE32:
9894   case AArch64ISD::DUPLANE64:
9895   case AArch64ISD::MOVI:
9896   case AArch64ISD::MOVIshift:
9897   case AArch64ISD::MOVIedit:
9898   case AArch64ISD::MOVImsl:
9899   case AArch64ISD::MVNIshift:
9900   case AArch64ISD::MVNImsl:
9901     break;
9902   default:
9903     // FMOV could be supported, but isn't very useful, as it would only occur
9904     // if you passed a bitcast' floating point immediate to an eligible long
9905     // integer op (addl, smull, ...).
9906     return SDValue();
9907   }
9908 
9909   MVT NarrowTy = N.getSimpleValueType();
9910   if (!NarrowTy.is64BitVector())
9911     return SDValue();
9912 
9913   MVT ElementTy = NarrowTy.getVectorElementType();
9914   unsigned NumElems = NarrowTy.getVectorNumElements();
9915   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9916 
9917   SDLoc dl(N);
9918   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9919                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9920                      DAG.getConstant(NumElems, dl, MVT::i64));
9921 }
9922 
9923 static bool isEssentiallyExtractHighSubvector(SDValue N) {
9924   if (N.getOpcode() == ISD::BITCAST)
9925     N = N.getOperand(0);
9926   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9927     return false;
9928   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9929          N.getOperand(0).getValueType().getVectorNumElements() / 2;
9930 }
9931 
9932 /// Helper structure to keep track of ISD::SET_CC operands.
9933 struct GenericSetCCInfo {
9934   const SDValue *Opnd0;
9935   const SDValue *Opnd1;
9936   ISD::CondCode CC;
9937 };
9938 
9939 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9940 struct AArch64SetCCInfo {
9941   const SDValue *Cmp;
9942   AArch64CC::CondCode CC;
9943 };
9944 
9945 /// Helper structure to keep track of SetCC information.
9946 union SetCCInfo {
9947   GenericSetCCInfo Generic;
9948   AArch64SetCCInfo AArch64;
9949 };
9950 
9951 /// Helper structure to be able to read SetCC information.  If set to
9952 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9953 /// GenericSetCCInfo.
9954 struct SetCCInfoAndKind {
9955   SetCCInfo Info;
9956   bool IsAArch64;
9957 };
9958 
9959 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9960 /// an
9961 /// AArch64 lowered one.
9962 /// \p SetCCInfo is filled accordingly.
9963 /// \post SetCCInfo is meanginfull only when this function returns true.
9964 /// \return True when Op is a kind of SET_CC operation.
9965 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9966   // If this is a setcc, this is straight forward.
9967   if (Op.getOpcode() == ISD::SETCC) {
9968     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9969     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9970     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9971     SetCCInfo.IsAArch64 = false;
9972     return true;
9973   }
9974   // Otherwise, check if this is a matching csel instruction.
9975   // In other words:
9976   // - csel 1, 0, cc
9977   // - csel 0, 1, !cc
9978   if (Op.getOpcode() != AArch64ISD::CSEL)
9979     return false;
9980   // Set the information about the operands.
9981   // TODO: we want the operands of the Cmp not the csel
9982   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9983   SetCCInfo.IsAArch64 = true;
9984   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9985       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9986 
9987   // Check that the operands matches the constraints:
9988   // (1) Both operands must be constants.
9989   // (2) One must be 1 and the other must be 0.
9990   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9991   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9992 
9993   // Check (1).
9994   if (!TValue || !FValue)
9995     return false;
9996 
9997   // Check (2).
9998   if (!TValue->isOne()) {
9999     // Update the comparison when we are interested in !cc.
10000     std::swap(TValue, FValue);
10001     SetCCInfo.Info.AArch64.CC =
10002         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10003   }
10004   return TValue->isOne() && FValue->isNullValue();
10005 }
10006 
10007 // Returns true if Op is setcc or zext of setcc.
10008 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10009   if (isSetCC(Op, Info))
10010     return true;
10011   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10012     isSetCC(Op->getOperand(0), Info));
10013 }
10014 
10015 // The folding we want to perform is:
10016 // (add x, [zext] (setcc cc ...) )
10017 //   -->
10018 // (csel x, (add x, 1), !cc ...)
10019 //
10020 // The latter will get matched to a CSINC instruction.
10021 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10022   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10023   SDValue LHS = Op->getOperand(0);
10024   SDValue RHS = Op->getOperand(1);
10025   SetCCInfoAndKind InfoAndKind;
10026 
10027   // If neither operand is a SET_CC, give up.
10028   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10029     std::swap(LHS, RHS);
10030     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10031       return SDValue();
10032   }
10033 
10034   // FIXME: This could be generatized to work for FP comparisons.
10035   EVT CmpVT = InfoAndKind.IsAArch64
10036                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10037                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
10038   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10039     return SDValue();
10040 
10041   SDValue CCVal;
10042   SDValue Cmp;
10043   SDLoc dl(Op);
10044   if (InfoAndKind.IsAArch64) {
10045     CCVal = DAG.getConstant(
10046         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10047         MVT::i32);
10048     Cmp = *InfoAndKind.Info.AArch64.Cmp;
10049   } else
10050     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10051                       *InfoAndKind.Info.Generic.Opnd1,
10052                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10053                       CCVal, DAG, dl);
10054 
10055   EVT VT = Op->getValueType(0);
10056   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10057   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10058 }
10059 
10060 // The basic add/sub long vector instructions have variants with "2" on the end
10061 // which act on the high-half of their inputs. They are normally matched by
10062 // patterns like:
10063 //
10064 // (add (zeroext (extract_high LHS)),
10065 //      (zeroext (extract_high RHS)))
10066 // -> uaddl2 vD, vN, vM
10067 //
10068 // However, if one of the extracts is something like a duplicate, this
10069 // instruction can still be used profitably. This function puts the DAG into a
10070 // more appropriate form for those patterns to trigger.
10071 static SDValue performAddSubLongCombine(SDNode *N,
10072                                         TargetLowering::DAGCombinerInfo &DCI,
10073                                         SelectionDAG &DAG) {
10074   if (DCI.isBeforeLegalizeOps())
10075     return SDValue();
10076 
10077   MVT VT = N->getSimpleValueType(0);
10078   if (!VT.is128BitVector()) {
10079     if (N->getOpcode() == ISD::ADD)
10080       return performSetccAddFolding(N, DAG);
10081     return SDValue();
10082   }
10083 
10084   // Make sure both branches are extended in the same way.
10085   SDValue LHS = N->getOperand(0);
10086   SDValue RHS = N->getOperand(1);
10087   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10088        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10089       LHS.getOpcode() != RHS.getOpcode())
10090     return SDValue();
10091 
10092   unsigned ExtType = LHS.getOpcode();
10093 
10094   // It's not worth doing if at least one of the inputs isn't already an
10095   // extract, but we don't know which it'll be so we have to try both.
10096   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10097     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10098     if (!RHS.getNode())
10099       return SDValue();
10100 
10101     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10102   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10103     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10104     if (!LHS.getNode())
10105       return SDValue();
10106 
10107     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10108   }
10109 
10110   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10111 }
10112 
10113 // Massage DAGs which we can use the high-half "long" operations on into
10114 // something isel will recognize better. E.g.
10115 //
10116 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10117 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
10118 //                     (extract_high (v2i64 (dup128 scalar)))))
10119 //
10120 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10121                                        TargetLowering::DAGCombinerInfo &DCI,
10122                                        SelectionDAG &DAG) {
10123   if (DCI.isBeforeLegalizeOps())
10124     return SDValue();
10125 
10126   SDValue LHS = N->getOperand(1);
10127   SDValue RHS = N->getOperand(2);
10128   assert(LHS.getValueType().is64BitVector() &&
10129          RHS.getValueType().is64BitVector() &&
10130          "unexpected shape for long operation");
10131 
10132   // Either node could be a DUP, but it's not worth doing both of them (you'd
10133   // just as well use the non-high version) so look for a corresponding extract
10134   // operation on the other "wing".
10135   if (isEssentiallyExtractHighSubvector(LHS)) {
10136     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10137     if (!RHS.getNode())
10138       return SDValue();
10139   } else if (isEssentiallyExtractHighSubvector(RHS)) {
10140     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10141     if (!LHS.getNode())
10142       return SDValue();
10143   }
10144 
10145   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10146                      N->getOperand(0), LHS, RHS);
10147 }
10148 
10149 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10150   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10151   unsigned ElemBits = ElemTy.getSizeInBits();
10152 
10153   int64_t ShiftAmount;
10154   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10155     APInt SplatValue, SplatUndef;
10156     unsigned SplatBitSize;
10157     bool HasAnyUndefs;
10158     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10159                               HasAnyUndefs, ElemBits) ||
10160         SplatBitSize != ElemBits)
10161       return SDValue();
10162 
10163     ShiftAmount = SplatValue.getSExtValue();
10164   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10165     ShiftAmount = CVN->getSExtValue();
10166   } else
10167     return SDValue();
10168 
10169   unsigned Opcode;
10170   bool IsRightShift;
10171   switch (IID) {
10172   default:
10173     llvm_unreachable("Unknown shift intrinsic");
10174   case Intrinsic::aarch64_neon_sqshl:
10175     Opcode = AArch64ISD::SQSHL_I;
10176     IsRightShift = false;
10177     break;
10178   case Intrinsic::aarch64_neon_uqshl:
10179     Opcode = AArch64ISD::UQSHL_I;
10180     IsRightShift = false;
10181     break;
10182   case Intrinsic::aarch64_neon_srshl:
10183     Opcode = AArch64ISD::SRSHR_I;
10184     IsRightShift = true;
10185     break;
10186   case Intrinsic::aarch64_neon_urshl:
10187     Opcode = AArch64ISD::URSHR_I;
10188     IsRightShift = true;
10189     break;
10190   case Intrinsic::aarch64_neon_sqshlu:
10191     Opcode = AArch64ISD::SQSHLU_I;
10192     IsRightShift = false;
10193     break;
10194   }
10195 
10196   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10197     SDLoc dl(N);
10198     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10199                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10200   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10201     SDLoc dl(N);
10202     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10203                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
10204   }
10205 
10206   return SDValue();
10207 }
10208 
10209 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10210 // the intrinsics must be legal and take an i32, this means there's almost
10211 // certainly going to be a zext in the DAG which we can eliminate.
10212 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10213   SDValue AndN = N->getOperand(2);
10214   if (AndN.getOpcode() != ISD::AND)
10215     return SDValue();
10216 
10217   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10218   if (!CMask || CMask->getZExtValue() != Mask)
10219     return SDValue();
10220 
10221   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10222                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10223 }
10224 
10225 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10226                                            SelectionDAG &DAG) {
10227   SDLoc dl(N);
10228   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10229                      DAG.getNode(Opc, dl,
10230                                  N->getOperand(1).getSimpleValueType(),
10231                                  N->getOperand(1)),
10232                      DAG.getConstant(0, dl, MVT::i64));
10233 }
10234 
10235 static SDValue performIntrinsicCombine(SDNode *N,
10236                                        TargetLowering::DAGCombinerInfo &DCI,
10237                                        const AArch64Subtarget *Subtarget) {
10238   SelectionDAG &DAG = DCI.DAG;
10239   unsigned IID = getIntrinsicID(N);
10240   switch (IID) {
10241   default:
10242     break;
10243   case Intrinsic::aarch64_neon_vcvtfxs2fp:
10244   case Intrinsic::aarch64_neon_vcvtfxu2fp:
10245     return tryCombineFixedPointConvert(N, DCI, DAG);
10246   case Intrinsic::aarch64_neon_saddv:
10247     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10248   case Intrinsic::aarch64_neon_uaddv:
10249     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10250   case Intrinsic::aarch64_neon_sminv:
10251     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10252   case Intrinsic::aarch64_neon_uminv:
10253     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10254   case Intrinsic::aarch64_neon_smaxv:
10255     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10256   case Intrinsic::aarch64_neon_umaxv:
10257     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10258   case Intrinsic::aarch64_neon_fmax:
10259     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10260                        N->getOperand(1), N->getOperand(2));
10261   case Intrinsic::aarch64_neon_fmin:
10262     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10263                        N->getOperand(1), N->getOperand(2));
10264   case Intrinsic::aarch64_neon_fmaxnm:
10265     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10266                        N->getOperand(1), N->getOperand(2));
10267   case Intrinsic::aarch64_neon_fminnm:
10268     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10269                        N->getOperand(1), N->getOperand(2));
10270   case Intrinsic::aarch64_neon_smull:
10271   case Intrinsic::aarch64_neon_umull:
10272   case Intrinsic::aarch64_neon_pmull:
10273   case Intrinsic::aarch64_neon_sqdmull:
10274     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10275   case Intrinsic::aarch64_neon_sqshl:
10276   case Intrinsic::aarch64_neon_uqshl:
10277   case Intrinsic::aarch64_neon_sqshlu:
10278   case Intrinsic::aarch64_neon_srshl:
10279   case Intrinsic::aarch64_neon_urshl:
10280     return tryCombineShiftImm(IID, N, DAG);
10281   case Intrinsic::aarch64_crc32b:
10282   case Intrinsic::aarch64_crc32cb:
10283     return tryCombineCRC32(0xff, N, DAG);
10284   case Intrinsic::aarch64_crc32h:
10285   case Intrinsic::aarch64_crc32ch:
10286     return tryCombineCRC32(0xffff, N, DAG);
10287   }
10288   return SDValue();
10289 }
10290 
10291 static SDValue performExtendCombine(SDNode *N,
10292                                     TargetLowering::DAGCombinerInfo &DCI,
10293                                     SelectionDAG &DAG) {
10294   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10295   // we can convert that DUP into another extract_high (of a bigger DUP), which
10296   // helps the backend to decide that an sabdl2 would be useful, saving a real
10297   // extract_high operation.
10298   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10299       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10300     SDNode *ABDNode = N->getOperand(0).getNode();
10301     unsigned IID = getIntrinsicID(ABDNode);
10302     if (IID == Intrinsic::aarch64_neon_sabd ||
10303         IID == Intrinsic::aarch64_neon_uabd) {
10304       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10305       if (!NewABD.getNode())
10306         return SDValue();
10307 
10308       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10309                          NewABD);
10310     }
10311   }
10312 
10313   // This is effectively a custom type legalization for AArch64.
10314   //
10315   // Type legalization will split an extend of a small, legal, type to a larger
10316   // illegal type by first splitting the destination type, often creating
10317   // illegal source types, which then get legalized in isel-confusing ways,
10318   // leading to really terrible codegen. E.g.,
10319   //   %result = v8i32 sext v8i8 %value
10320   // becomes
10321   //   %losrc = extract_subreg %value, ...
10322   //   %hisrc = extract_subreg %value, ...
10323   //   %lo = v4i32 sext v4i8 %losrc
10324   //   %hi = v4i32 sext v4i8 %hisrc
10325   // Things go rapidly downhill from there.
10326   //
10327   // For AArch64, the [sz]ext vector instructions can only go up one element
10328   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10329   // take two instructions.
10330   //
10331   // This implies that the most efficient way to do the extend from v8i8
10332   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10333   // the normal splitting to happen for the v8i16->v8i32.
10334 
10335   // This is pre-legalization to catch some cases where the default
10336   // type legalization will create ill-tempered code.
10337   if (!DCI.isBeforeLegalizeOps())
10338     return SDValue();
10339 
10340   // We're only interested in cleaning things up for non-legal vector types
10341   // here. If both the source and destination are legal, things will just
10342   // work naturally without any fiddling.
10343   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10344   EVT ResVT = N->getValueType(0);
10345   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10346     return SDValue();
10347   // If the vector type isn't a simple VT, it's beyond the scope of what
10348   // we're  worried about here. Let legalization do its thing and hope for
10349   // the best.
10350   SDValue Src = N->getOperand(0);
10351   EVT SrcVT = Src->getValueType(0);
10352   if (!ResVT.isSimple() || !SrcVT.isSimple())
10353     return SDValue();
10354 
10355   // If the source VT is a 64-bit vector, we can play games and get the
10356   // better results we want.
10357   if (SrcVT.getSizeInBits() != 64)
10358     return SDValue();
10359 
10360   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10361   unsigned ElementCount = SrcVT.getVectorNumElements();
10362   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10363   SDLoc DL(N);
10364   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10365 
10366   // Now split the rest of the operation into two halves, each with a 64
10367   // bit source.
10368   EVT LoVT, HiVT;
10369   SDValue Lo, Hi;
10370   unsigned NumElements = ResVT.getVectorNumElements();
10371   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10372   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10373                                  ResVT.getVectorElementType(), NumElements / 2);
10374 
10375   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10376                                LoVT.getVectorNumElements());
10377   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10378                    DAG.getConstant(0, DL, MVT::i64));
10379   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10380                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10381   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10382   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10383 
10384   // Now combine the parts back together so we still have a single result
10385   // like the combiner expects.
10386   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10387 }
10388 
10389 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10390                                SDValue SplatVal, unsigned NumVecElts) {
10391   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10392   unsigned OrigAlignment = St.getAlignment();
10393   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10394 
10395   // Create scalar stores. This is at least as good as the code sequence for a
10396   // split unaligned store which is a dup.s, ext.b, and two stores.
10397   // Most of the time the three stores should be replaced by store pair
10398   // instructions (stp).
10399   SDLoc DL(&St);
10400   SDValue BasePtr = St.getBasePtr();
10401   uint64_t BaseOffset = 0;
10402 
10403   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10404   SDValue NewST1 =
10405       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10406                    OrigAlignment, St.getMemOperand()->getFlags());
10407 
10408   // As this in ISel, we will not merge this add which may degrade results.
10409   if (BasePtr->getOpcode() == ISD::ADD &&
10410       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10411     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10412     BasePtr = BasePtr->getOperand(0);
10413   }
10414 
10415   unsigned Offset = EltOffset;
10416   while (--NumVecElts) {
10417     unsigned Alignment = MinAlign(OrigAlignment, Offset);
10418     SDValue OffsetPtr =
10419         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10420                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10421     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10422                           PtrInfo.getWithOffset(Offset), Alignment,
10423                           St.getMemOperand()->getFlags());
10424     Offset += EltOffset;
10425   }
10426   return NewST1;
10427 }
10428 
10429 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
10430 /// load store optimizer pass will merge them to store pair stores.  This should
10431 /// be better than a movi to create the vector zero followed by a vector store
10432 /// if the zero constant is not re-used, since one instructions and one register
10433 /// live range will be removed.
10434 ///
10435 /// For example, the final generated code should be:
10436 ///
10437 ///   stp xzr, xzr, [x0]
10438 ///
10439 /// instead of:
10440 ///
10441 ///   movi v0.2d, #0
10442 ///   str q0, [x0]
10443 ///
10444 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10445   SDValue StVal = St.getValue();
10446   EVT VT = StVal.getValueType();
10447 
10448   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10449   // 2, 3 or 4 i32 elements.
10450   int NumVecElts = VT.getVectorNumElements();
10451   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10452          VT.getVectorElementType().getSizeInBits() == 64) ||
10453         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10454          VT.getVectorElementType().getSizeInBits() == 32)))
10455     return SDValue();
10456 
10457   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10458     return SDValue();
10459 
10460   // If the zero constant has more than one use then the vector store could be
10461   // better since the constant mov will be amortized and stp q instructions
10462   // should be able to be formed.
10463   if (!StVal.hasOneUse())
10464     return SDValue();
10465 
10466   // If the store is truncating then it's going down to i16 or smaller, which
10467   // means it can be implemented in a single store anyway.
10468   if (St.isTruncatingStore())
10469     return SDValue();
10470 
10471   // If the immediate offset of the address operand is too large for the stp
10472   // instruction, then bail out.
10473   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10474     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10475     if (Offset < -512 || Offset > 504)
10476       return SDValue();
10477   }
10478 
10479   for (int I = 0; I < NumVecElts; ++I) {
10480     SDValue EltVal = StVal.getOperand(I);
10481     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10482       return SDValue();
10483   }
10484 
10485   // Use a CopyFromReg WZR/XZR here to prevent
10486   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10487   SDLoc DL(&St);
10488   unsigned ZeroReg;
10489   EVT ZeroVT;
10490   if (VT.getVectorElementType().getSizeInBits() == 32) {
10491     ZeroReg = AArch64::WZR;
10492     ZeroVT = MVT::i32;
10493   } else {
10494     ZeroReg = AArch64::XZR;
10495     ZeroVT = MVT::i64;
10496   }
10497   SDValue SplatVal =
10498       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10499   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10500 }
10501 
10502 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10503 /// value. The load store optimizer pass will merge them to store pair stores.
10504 /// This has better performance than a splat of the scalar followed by a split
10505 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10506 /// followed by an ext.b and two stores.
10507 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10508   SDValue StVal = St.getValue();
10509   EVT VT = StVal.getValueType();
10510 
10511   // Don't replace floating point stores, they possibly won't be transformed to
10512   // stp because of the store pair suppress pass.
10513   if (VT.isFloatingPoint())
10514     return SDValue();
10515 
10516   // We can express a splat as store pair(s) for 2 or 4 elements.
10517   unsigned NumVecElts = VT.getVectorNumElements();
10518   if (NumVecElts != 4 && NumVecElts != 2)
10519     return SDValue();
10520 
10521   // If the store is truncating then it's going down to i16 or smaller, which
10522   // means it can be implemented in a single store anyway.
10523   if (St.isTruncatingStore())
10524     return SDValue();
10525 
10526   // Check that this is a splat.
10527   // Make sure that each of the relevant vector element locations are inserted
10528   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10529   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10530   SDValue SplatVal;
10531   for (unsigned I = 0; I < NumVecElts; ++I) {
10532     // Check for insert vector elements.
10533     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10534       return SDValue();
10535 
10536     // Check that same value is inserted at each vector element.
10537     if (I == 0)
10538       SplatVal = StVal.getOperand(1);
10539     else if (StVal.getOperand(1) != SplatVal)
10540       return SDValue();
10541 
10542     // Check insert element index.
10543     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10544     if (!CIndex)
10545       return SDValue();
10546     uint64_t IndexVal = CIndex->getZExtValue();
10547     if (IndexVal >= NumVecElts)
10548       return SDValue();
10549     IndexNotInserted.reset(IndexVal);
10550 
10551     StVal = StVal.getOperand(0);
10552   }
10553   // Check that all vector element locations were inserted to.
10554   if (IndexNotInserted.any())
10555       return SDValue();
10556 
10557   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10558 }
10559 
10560 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10561                            SelectionDAG &DAG,
10562                            const AArch64Subtarget *Subtarget) {
10563 
10564   StoreSDNode *S = cast<StoreSDNode>(N);
10565   if (S->isVolatile() || S->isIndexed())
10566     return SDValue();
10567 
10568   SDValue StVal = S->getValue();
10569   EVT VT = StVal.getValueType();
10570   if (!VT.isVector())
10571     return SDValue();
10572 
10573   // If we get a splat of zeros, convert this vector store to a store of
10574   // scalars. They will be merged into store pairs of xzr thereby removing one
10575   // instruction and one register.
10576   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10577     return ReplacedZeroSplat;
10578 
10579   // FIXME: The logic for deciding if an unaligned store should be split should
10580   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10581   // a call to that function here.
10582 
10583   if (!Subtarget->isMisaligned128StoreSlow())
10584     return SDValue();
10585 
10586   // Don't split at -Oz.
10587   if (DAG.getMachineFunction().getFunction().hasMinSize())
10588     return SDValue();
10589 
10590   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10591   // those up regresses performance on micro-benchmarks and olden/bh.
10592   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10593     return SDValue();
10594 
10595   // Split unaligned 16B stores. They are terrible for performance.
10596   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10597   // extensions can use this to mark that it does not want splitting to happen
10598   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10599   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10600   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10601       S->getAlignment() <= 2)
10602     return SDValue();
10603 
10604   // If we get a splat of a scalar convert this vector store to a store of
10605   // scalars. They will be merged into store pairs thereby removing two
10606   // instructions.
10607   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10608     return ReplacedSplat;
10609 
10610   SDLoc DL(S);
10611   unsigned NumElts = VT.getVectorNumElements() / 2;
10612   // Split VT into two.
10613   EVT HalfVT =
10614       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
10615   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10616                                    DAG.getConstant(0, DL, MVT::i64));
10617   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10618                                    DAG.getConstant(NumElts, DL, MVT::i64));
10619   SDValue BasePtr = S->getBasePtr();
10620   SDValue NewST1 =
10621       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10622                    S->getAlignment(), S->getMemOperand()->getFlags());
10623   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10624                                   DAG.getConstant(8, DL, MVT::i64));
10625   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10626                       S->getPointerInfo(), S->getAlignment(),
10627                       S->getMemOperand()->getFlags());
10628 }
10629 
10630 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10631 /// post-increment LD1R.
10632 static SDValue performPostLD1Combine(SDNode *N,
10633                                      TargetLowering::DAGCombinerInfo &DCI,
10634                                      bool IsLaneOp) {
10635   if (DCI.isBeforeLegalizeOps())
10636     return SDValue();
10637 
10638   SelectionDAG &DAG = DCI.DAG;
10639   EVT VT = N->getValueType(0);
10640 
10641   unsigned LoadIdx = IsLaneOp ? 1 : 0;
10642   SDNode *LD = N->getOperand(LoadIdx).getNode();
10643   // If it is not LOAD, can not do such combine.
10644   if (LD->getOpcode() != ISD::LOAD)
10645     return SDValue();
10646 
10647   // The vector lane must be a constant in the LD1LANE opcode.
10648   SDValue Lane;
10649   if (IsLaneOp) {
10650     Lane = N->getOperand(2);
10651     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10652     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10653       return SDValue();
10654   }
10655 
10656   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10657   EVT MemVT = LoadSDN->getMemoryVT();
10658   // Check if memory operand is the same type as the vector element.
10659   if (MemVT != VT.getVectorElementType())
10660     return SDValue();
10661 
10662   // Check if there are other uses. If so, do not combine as it will introduce
10663   // an extra load.
10664   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10665        ++UI) {
10666     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10667       continue;
10668     if (*UI != N)
10669       return SDValue();
10670   }
10671 
10672   SDValue Addr = LD->getOperand(1);
10673   SDValue Vector = N->getOperand(0);
10674   // Search for a use of the address operand that is an increment.
10675   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10676        Addr.getNode()->use_end(); UI != UE; ++UI) {
10677     SDNode *User = *UI;
10678     if (User->getOpcode() != ISD::ADD
10679         || UI.getUse().getResNo() != Addr.getResNo())
10680       continue;
10681 
10682     // If the increment is a constant, it must match the memory ref size.
10683     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10684     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10685       uint32_t IncVal = CInc->getZExtValue();
10686       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10687       if (IncVal != NumBytes)
10688         continue;
10689       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10690     }
10691 
10692     // To avoid cycle construction make sure that neither the load nor the add
10693     // are predecessors to each other or the Vector.
10694     SmallPtrSet<const SDNode *, 32> Visited;
10695     SmallVector<const SDNode *, 16> Worklist;
10696     Visited.insert(N);
10697     Worklist.push_back(User);
10698     Worklist.push_back(LD);
10699     Worklist.push_back(Vector.getNode());
10700     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10701         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10702       continue;
10703 
10704     SmallVector<SDValue, 8> Ops;
10705     Ops.push_back(LD->getOperand(0));  // Chain
10706     if (IsLaneOp) {
10707       Ops.push_back(Vector);           // The vector to be inserted
10708       Ops.push_back(Lane);             // The lane to be inserted in the vector
10709     }
10710     Ops.push_back(Addr);
10711     Ops.push_back(Inc);
10712 
10713     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10714     SDVTList SDTys = DAG.getVTList(Tys);
10715     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10716     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10717                                            MemVT,
10718                                            LoadSDN->getMemOperand());
10719 
10720     // Update the uses.
10721     SDValue NewResults[] = {
10722         SDValue(LD, 0),            // The result of load
10723         SDValue(UpdN.getNode(), 2) // Chain
10724     };
10725     DCI.CombineTo(LD, NewResults);
10726     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
10727     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
10728 
10729     break;
10730   }
10731   return SDValue();
10732 }
10733 
10734 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10735 /// address translation.
10736 static bool performTBISimplification(SDValue Addr,
10737                                      TargetLowering::DAGCombinerInfo &DCI,
10738                                      SelectionDAG &DAG) {
10739   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10740   KnownBits Known;
10741   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10742                                         !DCI.isBeforeLegalizeOps());
10743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10744   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10745     DCI.CommitTargetLoweringOpt(TLO);
10746     return true;
10747   }
10748   return false;
10749 }
10750 
10751 static SDValue performSTORECombine(SDNode *N,
10752                                    TargetLowering::DAGCombinerInfo &DCI,
10753                                    SelectionDAG &DAG,
10754                                    const AArch64Subtarget *Subtarget) {
10755   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10756     return Split;
10757 
10758   if (Subtarget->supportsAddressTopByteIgnored() &&
10759       performTBISimplification(N->getOperand(2), DCI, DAG))
10760     return SDValue(N, 0);
10761 
10762   return SDValue();
10763 }
10764 
10765 
10766 /// Target-specific DAG combine function for NEON load/store intrinsics
10767 /// to merge base address updates.
10768 static SDValue performNEONPostLDSTCombine(SDNode *N,
10769                                           TargetLowering::DAGCombinerInfo &DCI,
10770                                           SelectionDAG &DAG) {
10771   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10772     return SDValue();
10773 
10774   unsigned AddrOpIdx = N->getNumOperands() - 1;
10775   SDValue Addr = N->getOperand(AddrOpIdx);
10776 
10777   // Search for a use of the address operand that is an increment.
10778   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10779        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10780     SDNode *User = *UI;
10781     if (User->getOpcode() != ISD::ADD ||
10782         UI.getUse().getResNo() != Addr.getResNo())
10783       continue;
10784 
10785     // Check that the add is independent of the load/store.  Otherwise, folding
10786     // it would create a cycle.
10787     SmallPtrSet<const SDNode *, 32> Visited;
10788     SmallVector<const SDNode *, 16> Worklist;
10789     Visited.insert(Addr.getNode());
10790     Worklist.push_back(N);
10791     Worklist.push_back(User);
10792     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10793         SDNode::hasPredecessorHelper(User, Visited, Worklist))
10794       continue;
10795 
10796     // Find the new opcode for the updating load/store.
10797     bool IsStore = false;
10798     bool IsLaneOp = false;
10799     bool IsDupOp = false;
10800     unsigned NewOpc = 0;
10801     unsigned NumVecs = 0;
10802     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10803     switch (IntNo) {
10804     default: llvm_unreachable("unexpected intrinsic for Neon base update");
10805     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
10806       NumVecs = 2; break;
10807     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
10808       NumVecs = 3; break;
10809     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
10810       NumVecs = 4; break;
10811     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
10812       NumVecs = 2; IsStore = true; break;
10813     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
10814       NumVecs = 3; IsStore = true; break;
10815     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
10816       NumVecs = 4; IsStore = true; break;
10817     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
10818       NumVecs = 2; break;
10819     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
10820       NumVecs = 3; break;
10821     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
10822       NumVecs = 4; break;
10823     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
10824       NumVecs = 2; IsStore = true; break;
10825     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
10826       NumVecs = 3; IsStore = true; break;
10827     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
10828       NumVecs = 4; IsStore = true; break;
10829     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
10830       NumVecs = 2; IsDupOp = true; break;
10831     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
10832       NumVecs = 3; IsDupOp = true; break;
10833     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
10834       NumVecs = 4; IsDupOp = true; break;
10835     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
10836       NumVecs = 2; IsLaneOp = true; break;
10837     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
10838       NumVecs = 3; IsLaneOp = true; break;
10839     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
10840       NumVecs = 4; IsLaneOp = true; break;
10841     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
10842       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10843     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
10844       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10845     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
10846       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10847     }
10848 
10849     EVT VecTy;
10850     if (IsStore)
10851       VecTy = N->getOperand(2).getValueType();
10852     else
10853       VecTy = N->getValueType(0);
10854 
10855     // If the increment is a constant, it must match the memory ref size.
10856     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10857     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10858       uint32_t IncVal = CInc->getZExtValue();
10859       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10860       if (IsLaneOp || IsDupOp)
10861         NumBytes /= VecTy.getVectorNumElements();
10862       if (IncVal != NumBytes)
10863         continue;
10864       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10865     }
10866     SmallVector<SDValue, 8> Ops;
10867     Ops.push_back(N->getOperand(0)); // Incoming chain
10868     // Load lane and store have vector list as input.
10869     if (IsLaneOp || IsStore)
10870       for (unsigned i = 2; i < AddrOpIdx; ++i)
10871         Ops.push_back(N->getOperand(i));
10872     Ops.push_back(Addr); // Base register
10873     Ops.push_back(Inc);
10874 
10875     // Return Types.
10876     EVT Tys[6];
10877     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10878     unsigned n;
10879     for (n = 0; n < NumResultVecs; ++n)
10880       Tys[n] = VecTy;
10881     Tys[n++] = MVT::i64;  // Type of write back register
10882     Tys[n] = MVT::Other;  // Type of the chain
10883     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10884 
10885     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10886     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10887                                            MemInt->getMemoryVT(),
10888                                            MemInt->getMemOperand());
10889 
10890     // Update the uses.
10891     std::vector<SDValue> NewResults;
10892     for (unsigned i = 0; i < NumResultVecs; ++i) {
10893       NewResults.push_back(SDValue(UpdN.getNode(), i));
10894     }
10895     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10896     DCI.CombineTo(N, NewResults);
10897     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10898 
10899     break;
10900   }
10901   return SDValue();
10902 }
10903 
10904 // Checks to see if the value is the prescribed width and returns information
10905 // about its extension mode.
10906 static
10907 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10908   ExtType = ISD::NON_EXTLOAD;
10909   switch(V.getNode()->getOpcode()) {
10910   default:
10911     return false;
10912   case ISD::LOAD: {
10913     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10914     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10915        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10916       ExtType = LoadNode->getExtensionType();
10917       return true;
10918     }
10919     return false;
10920   }
10921   case ISD::AssertSext: {
10922     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10923     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10924        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10925       ExtType = ISD::SEXTLOAD;
10926       return true;
10927     }
10928     return false;
10929   }
10930   case ISD::AssertZext: {
10931     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10932     if ((TypeNode->getVT() == MVT::i8 && width == 8)
10933        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10934       ExtType = ISD::ZEXTLOAD;
10935       return true;
10936     }
10937     return false;
10938   }
10939   case ISD::Constant:
10940   case ISD::TargetConstant: {
10941     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10942            1LL << (width - 1);
10943   }
10944   }
10945 
10946   return true;
10947 }
10948 
10949 // This function does a whole lot of voodoo to determine if the tests are
10950 // equivalent without and with a mask. Essentially what happens is that given a
10951 // DAG resembling:
10952 //
10953 //  +-------------+ +-------------+ +-------------+ +-------------+
10954 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
10955 //  +-------------+ +-------------+ +-------------+ +-------------+
10956 //           |           |           |               |
10957 //           V           V           |    +----------+
10958 //          +-------------+  +----+  |    |
10959 //          |     ADD     |  |0xff|  |    |
10960 //          +-------------+  +----+  |    |
10961 //                  |           |    |    |
10962 //                  V           V    |    |
10963 //                 +-------------+   |    |
10964 //                 |     AND     |   |    |
10965 //                 +-------------+   |    |
10966 //                      |            |    |
10967 //                      +-----+      |    |
10968 //                            |      |    |
10969 //                            V      V    V
10970 //                           +-------------+
10971 //                           |     CMP     |
10972 //                           +-------------+
10973 //
10974 // The AND node may be safely removed for some combinations of inputs. In
10975 // particular we need to take into account the extension type of the Input,
10976 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10977 // width of the input (this can work for any width inputs, the above graph is
10978 // specific to 8 bits.
10979 //
10980 // The specific equations were worked out by generating output tables for each
10981 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10982 // problem was simplified by working with 4 bit inputs, which means we only
10983 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10984 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10985 // patterns present in both extensions (0,7). For every distinct set of
10986 // AddConstant and CompConstants bit patterns we can consider the masked and
10987 // unmasked versions to be equivalent if the result of this function is true for
10988 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10989 //
10990 //   sub      w8, w0, w1
10991 //   and      w10, w8, #0x0f
10992 //   cmp      w8, w2
10993 //   cset     w9, AArch64CC
10994 //   cmp      w10, w2
10995 //   cset     w11, AArch64CC
10996 //   cmp      w9, w11
10997 //   cset     w0, eq
10998 //   ret
10999 //
11000 // Since the above function shows when the outputs are equivalent it defines
11001 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11002 // would be expensive to run during compiles. The equations below were written
11003 // in a test harness that confirmed they gave equivalent outputs to the above
11004 // for all inputs function, so they can be used determine if the removal is
11005 // legal instead.
11006 //
11007 // isEquivalentMaskless() is the code for testing if the AND can be removed
11008 // factored out of the DAG recognition as the DAG can take several forms.
11009 
11010 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11011                                  ISD::LoadExtType ExtType, int AddConstant,
11012                                  int CompConstant) {
11013   // By being careful about our equations and only writing the in term
11014   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11015   // make them generally applicable to all bit widths.
11016   int MaxUInt = (1 << width);
11017 
11018   // For the purposes of these comparisons sign extending the type is
11019   // equivalent to zero extending the add and displacing it by half the integer
11020   // width. Provided we are careful and make sure our equations are valid over
11021   // the whole range we can just adjust the input and avoid writing equations
11022   // for sign extended inputs.
11023   if (ExtType == ISD::SEXTLOAD)
11024     AddConstant -= (1 << (width-1));
11025 
11026   switch(CC) {
11027   case AArch64CC::LE:
11028   case AArch64CC::GT:
11029     if ((AddConstant == 0) ||
11030         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11031         (AddConstant >= 0 && CompConstant < 0) ||
11032         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11033       return true;
11034     break;
11035   case AArch64CC::LT:
11036   case AArch64CC::GE:
11037     if ((AddConstant == 0) ||
11038         (AddConstant >= 0 && CompConstant <= 0) ||
11039         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11040       return true;
11041     break;
11042   case AArch64CC::HI:
11043   case AArch64CC::LS:
11044     if ((AddConstant >= 0 && CompConstant < 0) ||
11045        (AddConstant <= 0 && CompConstant >= -1 &&
11046         CompConstant < AddConstant + MaxUInt))
11047       return true;
11048    break;
11049   case AArch64CC::PL:
11050   case AArch64CC::MI:
11051     if ((AddConstant == 0) ||
11052         (AddConstant > 0 && CompConstant <= 0) ||
11053         (AddConstant < 0 && CompConstant <= AddConstant))
11054       return true;
11055     break;
11056   case AArch64CC::LO:
11057   case AArch64CC::HS:
11058     if ((AddConstant >= 0 && CompConstant <= 0) ||
11059         (AddConstant <= 0 && CompConstant >= 0 &&
11060          CompConstant <= AddConstant + MaxUInt))
11061       return true;
11062     break;
11063   case AArch64CC::EQ:
11064   case AArch64CC::NE:
11065     if ((AddConstant > 0 && CompConstant < 0) ||
11066         (AddConstant < 0 && CompConstant >= 0 &&
11067          CompConstant < AddConstant + MaxUInt) ||
11068         (AddConstant >= 0 && CompConstant >= 0 &&
11069          CompConstant >= AddConstant) ||
11070         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11071       return true;
11072     break;
11073   case AArch64CC::VS:
11074   case AArch64CC::VC:
11075   case AArch64CC::AL:
11076   case AArch64CC::NV:
11077     return true;
11078   case AArch64CC::Invalid:
11079     break;
11080   }
11081 
11082   return false;
11083 }
11084 
11085 static
11086 SDValue performCONDCombine(SDNode *N,
11087                            TargetLowering::DAGCombinerInfo &DCI,
11088                            SelectionDAG &DAG, unsigned CCIndex,
11089                            unsigned CmpIndex) {
11090   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11091   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11092   unsigned CondOpcode = SubsNode->getOpcode();
11093 
11094   if (CondOpcode != AArch64ISD::SUBS)
11095     return SDValue();
11096 
11097   // There is a SUBS feeding this condition. Is it fed by a mask we can
11098   // use?
11099 
11100   SDNode *AndNode = SubsNode->getOperand(0).getNode();
11101   unsigned MaskBits = 0;
11102 
11103   if (AndNode->getOpcode() != ISD::AND)
11104     return SDValue();
11105 
11106   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11107     uint32_t CNV = CN->getZExtValue();
11108     if (CNV == 255)
11109       MaskBits = 8;
11110     else if (CNV == 65535)
11111       MaskBits = 16;
11112   }
11113 
11114   if (!MaskBits)
11115     return SDValue();
11116 
11117   SDValue AddValue = AndNode->getOperand(0);
11118 
11119   if (AddValue.getOpcode() != ISD::ADD)
11120     return SDValue();
11121 
11122   // The basic dag structure is correct, grab the inputs and validate them.
11123 
11124   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11125   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11126   SDValue SubsInputValue = SubsNode->getOperand(1);
11127 
11128   // The mask is present and the provenance of all the values is a smaller type,
11129   // lets see if the mask is superfluous.
11130 
11131   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11132       !isa<ConstantSDNode>(SubsInputValue.getNode()))
11133     return SDValue();
11134 
11135   ISD::LoadExtType ExtType;
11136 
11137   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11138       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11139       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11140     return SDValue();
11141 
11142   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11143                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11144                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11145     return SDValue();
11146 
11147   // The AND is not necessary, remove it.
11148 
11149   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11150                                SubsNode->getValueType(1));
11151   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11152 
11153   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11154   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11155 
11156   return SDValue(N, 0);
11157 }
11158 
11159 // Optimize compare with zero and branch.
11160 static SDValue performBRCONDCombine(SDNode *N,
11161                                     TargetLowering::DAGCombinerInfo &DCI,
11162                                     SelectionDAG &DAG) {
11163   MachineFunction &MF = DAG.getMachineFunction();
11164   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11165   // will not be produced, as they are conditional branch instructions that do
11166   // not set flags.
11167   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11168     return SDValue();
11169 
11170   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11171     N = NV.getNode();
11172   SDValue Chain = N->getOperand(0);
11173   SDValue Dest = N->getOperand(1);
11174   SDValue CCVal = N->getOperand(2);
11175   SDValue Cmp = N->getOperand(3);
11176 
11177   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11178   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11179   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11180     return SDValue();
11181 
11182   unsigned CmpOpc = Cmp.getOpcode();
11183   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11184     return SDValue();
11185 
11186   // Only attempt folding if there is only one use of the flag and no use of the
11187   // value.
11188   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11189     return SDValue();
11190 
11191   SDValue LHS = Cmp.getOperand(0);
11192   SDValue RHS = Cmp.getOperand(1);
11193 
11194   assert(LHS.getValueType() == RHS.getValueType() &&
11195          "Expected the value type to be the same for both operands!");
11196   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11197     return SDValue();
11198 
11199   if (isNullConstant(LHS))
11200     std::swap(LHS, RHS);
11201 
11202   if (!isNullConstant(RHS))
11203     return SDValue();
11204 
11205   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11206       LHS.getOpcode() == ISD::SRL)
11207     return SDValue();
11208 
11209   // Fold the compare into the branch instruction.
11210   SDValue BR;
11211   if (CC == AArch64CC::EQ)
11212     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11213   else
11214     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11215 
11216   // Do not add new nodes to DAG combiner worklist.
11217   DCI.CombineTo(N, BR, false);
11218 
11219   return SDValue();
11220 }
11221 
11222 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
11223 // as well as whether the test should be inverted.  This code is required to
11224 // catch these cases (as opposed to standard dag combines) because
11225 // AArch64ISD::TBZ is matched during legalization.
11226 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11227                                  SelectionDAG &DAG) {
11228 
11229   if (!Op->hasOneUse())
11230     return Op;
11231 
11232   // We don't handle undef/constant-fold cases below, as they should have
11233   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11234   // etc.)
11235 
11236   // (tbz (trunc x), b) -> (tbz x, b)
11237   // This case is just here to enable more of the below cases to be caught.
11238   if (Op->getOpcode() == ISD::TRUNCATE &&
11239       Bit < Op->getValueType(0).getSizeInBits()) {
11240     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11241   }
11242 
11243   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11244   if (Op->getOpcode() == ISD::ANY_EXTEND &&
11245       Bit < Op->getOperand(0).getValueSizeInBits()) {
11246     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11247   }
11248 
11249   if (Op->getNumOperands() != 2)
11250     return Op;
11251 
11252   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11253   if (!C)
11254     return Op;
11255 
11256   switch (Op->getOpcode()) {
11257   default:
11258     return Op;
11259 
11260   // (tbz (and x, m), b) -> (tbz x, b)
11261   case ISD::AND:
11262     if ((C->getZExtValue() >> Bit) & 1)
11263       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11264     return Op;
11265 
11266   // (tbz (shl x, c), b) -> (tbz x, b-c)
11267   case ISD::SHL:
11268     if (C->getZExtValue() <= Bit &&
11269         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11270       Bit = Bit - C->getZExtValue();
11271       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11272     }
11273     return Op;
11274 
11275   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11276   case ISD::SRA:
11277     Bit = Bit + C->getZExtValue();
11278     if (Bit >= Op->getValueType(0).getSizeInBits())
11279       Bit = Op->getValueType(0).getSizeInBits() - 1;
11280     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11281 
11282   // (tbz (srl x, c), b) -> (tbz x, b+c)
11283   case ISD::SRL:
11284     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11285       Bit = Bit + C->getZExtValue();
11286       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11287     }
11288     return Op;
11289 
11290   // (tbz (xor x, -1), b) -> (tbnz x, b)
11291   case ISD::XOR:
11292     if ((C->getZExtValue() >> Bit) & 1)
11293       Invert = !Invert;
11294     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11295   }
11296 }
11297 
11298 // Optimize test single bit zero/non-zero and branch.
11299 static SDValue performTBZCombine(SDNode *N,
11300                                  TargetLowering::DAGCombinerInfo &DCI,
11301                                  SelectionDAG &DAG) {
11302   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11303   bool Invert = false;
11304   SDValue TestSrc = N->getOperand(1);
11305   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11306 
11307   if (TestSrc == NewTestSrc)
11308     return SDValue();
11309 
11310   unsigned NewOpc = N->getOpcode();
11311   if (Invert) {
11312     if (NewOpc == AArch64ISD::TBZ)
11313       NewOpc = AArch64ISD::TBNZ;
11314     else {
11315       assert(NewOpc == AArch64ISD::TBNZ);
11316       NewOpc = AArch64ISD::TBZ;
11317     }
11318   }
11319 
11320   SDLoc DL(N);
11321   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11322                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11323 }
11324 
11325 // vselect (v1i1 setcc) ->
11326 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
11327 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11328 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11329 // such VSELECT.
11330 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11331   SDValue N0 = N->getOperand(0);
11332   EVT CCVT = N0.getValueType();
11333 
11334   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11335       CCVT.getVectorElementType() != MVT::i1)
11336     return SDValue();
11337 
11338   EVT ResVT = N->getValueType(0);
11339   EVT CmpVT = N0.getOperand(0).getValueType();
11340   // Only combine when the result type is of the same size as the compared
11341   // operands.
11342   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11343     return SDValue();
11344 
11345   SDValue IfTrue = N->getOperand(1);
11346   SDValue IfFalse = N->getOperand(2);
11347   SDValue SetCC =
11348       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11349                    N0.getOperand(0), N0.getOperand(1),
11350                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
11351   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11352                      IfTrue, IfFalse);
11353 }
11354 
11355 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11356 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11357 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11358 /// with a vector one followed by a DUP shuffle on the result.
11359 static SDValue performSelectCombine(SDNode *N,
11360                                     TargetLowering::DAGCombinerInfo &DCI) {
11361   SelectionDAG &DAG = DCI.DAG;
11362   SDValue N0 = N->getOperand(0);
11363   EVT ResVT = N->getValueType(0);
11364 
11365   if (N0.getOpcode() != ISD::SETCC)
11366     return SDValue();
11367 
11368   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11369   // scalar SetCCResultType. We also don't expect vectors, because we assume
11370   // that selects fed by vector SETCCs are canonicalized to VSELECT.
11371   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11372          "Scalar-SETCC feeding SELECT has unexpected result type!");
11373 
11374   // If NumMaskElts == 0, the comparison is larger than select result. The
11375   // largest real NEON comparison is 64-bits per lane, which means the result is
11376   // at most 32-bits and an illegal vector. Just bail out for now.
11377   EVT SrcVT = N0.getOperand(0).getValueType();
11378 
11379   // Don't try to do this optimization when the setcc itself has i1 operands.
11380   // There are no legal vectors of i1, so this would be pointless.
11381   if (SrcVT == MVT::i1)
11382     return SDValue();
11383 
11384   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11385   if (!ResVT.isVector() || NumMaskElts == 0)
11386     return SDValue();
11387 
11388   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11389   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11390 
11391   // Also bail out if the vector CCVT isn't the same size as ResVT.
11392   // This can happen if the SETCC operand size doesn't divide the ResVT size
11393   // (e.g., f64 vs v3f32).
11394   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11395     return SDValue();
11396 
11397   // Make sure we didn't create illegal types, if we're not supposed to.
11398   assert(DCI.isBeforeLegalize() ||
11399          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11400 
11401   // First perform a vector comparison, where lane 0 is the one we're interested
11402   // in.
11403   SDLoc DL(N0);
11404   SDValue LHS =
11405       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11406   SDValue RHS =
11407       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11408   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11409 
11410   // Now duplicate the comparison mask we want across all other lanes.
11411   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11412   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11413   Mask = DAG.getNode(ISD::BITCAST, DL,
11414                      ResVT.changeVectorElementTypeToInteger(), Mask);
11415 
11416   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11417 }
11418 
11419 /// Get rid of unnecessary NVCASTs (that don't change the type).
11420 static SDValue performNVCASTCombine(SDNode *N) {
11421   if (N->getValueType(0) == N->getOperand(0).getValueType())
11422     return N->getOperand(0);
11423 
11424   return SDValue();
11425 }
11426 
11427 // If all users of the globaladdr are of the form (globaladdr + constant), find
11428 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11429 // globaladdr as (globaladdr + constant) - constant.
11430 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11431                                            const AArch64Subtarget *Subtarget,
11432                                            const TargetMachine &TM) {
11433   auto *GN = cast<GlobalAddressSDNode>(N);
11434   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11435       AArch64II::MO_NO_FLAG)
11436     return SDValue();
11437 
11438   uint64_t MinOffset = -1ull;
11439   for (SDNode *N : GN->uses()) {
11440     if (N->getOpcode() != ISD::ADD)
11441       return SDValue();
11442     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11443     if (!C)
11444       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11445     if (!C)
11446       return SDValue();
11447     MinOffset = std::min(MinOffset, C->getZExtValue());
11448   }
11449   uint64_t Offset = MinOffset + GN->getOffset();
11450 
11451   // Require that the new offset is larger than the existing one. Otherwise, we
11452   // can end up oscillating between two possible DAGs, for example,
11453   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11454   if (Offset <= uint64_t(GN->getOffset()))
11455     return SDValue();
11456 
11457   // Check whether folding this offset is legal. It must not go out of bounds of
11458   // the referenced object to avoid violating the code model, and must be
11459   // smaller than 2^21 because this is the largest offset expressible in all
11460   // object formats.
11461   //
11462   // This check also prevents us from folding negative offsets, which will end
11463   // up being treated in the same way as large positive ones. They could also
11464   // cause code model violations, and aren't really common enough to matter.
11465   if (Offset >= (1 << 21))
11466     return SDValue();
11467 
11468   const GlobalValue *GV = GN->getGlobal();
11469   Type *T = GV->getValueType();
11470   if (!T->isSized() ||
11471       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11472     return SDValue();
11473 
11474   SDLoc DL(GN);
11475   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11476   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11477                      DAG.getConstant(MinOffset, DL, MVT::i64));
11478 }
11479 
11480 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11481                                                  DAGCombinerInfo &DCI) const {
11482   SelectionDAG &DAG = DCI.DAG;
11483   switch (N->getOpcode()) {
11484   default:
11485     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11486     break;
11487   case ISD::ADD:
11488   case ISD::SUB:
11489     return performAddSubLongCombine(N, DCI, DAG);
11490   case ISD::XOR:
11491     return performXorCombine(N, DAG, DCI, Subtarget);
11492   case ISD::MUL:
11493     return performMulCombine(N, DAG, DCI, Subtarget);
11494   case ISD::SINT_TO_FP:
11495   case ISD::UINT_TO_FP:
11496     return performIntToFpCombine(N, DAG, Subtarget);
11497   case ISD::FP_TO_SINT:
11498   case ISD::FP_TO_UINT:
11499     return performFpToIntCombine(N, DAG, DCI, Subtarget);
11500   case ISD::FDIV:
11501     return performFDivCombine(N, DAG, DCI, Subtarget);
11502   case ISD::OR:
11503     return performORCombine(N, DCI, Subtarget);
11504   case ISD::AND:
11505     return performANDCombine(N, DCI);
11506   case ISD::SRL:
11507     return performSRLCombine(N, DCI);
11508   case ISD::INTRINSIC_WO_CHAIN:
11509     return performIntrinsicCombine(N, DCI, Subtarget);
11510   case ISD::ANY_EXTEND:
11511   case ISD::ZERO_EXTEND:
11512   case ISD::SIGN_EXTEND:
11513     return performExtendCombine(N, DCI, DAG);
11514   case ISD::BITCAST:
11515     return performBitcastCombine(N, DCI, DAG);
11516   case ISD::CONCAT_VECTORS:
11517     return performConcatVectorsCombine(N, DCI, DAG);
11518   case ISD::SELECT:
11519     return performSelectCombine(N, DCI);
11520   case ISD::VSELECT:
11521     return performVSelectCombine(N, DCI.DAG);
11522   case ISD::LOAD:
11523     if (performTBISimplification(N->getOperand(1), DCI, DAG))
11524       return SDValue(N, 0);
11525     break;
11526   case ISD::STORE:
11527     return performSTORECombine(N, DCI, DAG, Subtarget);
11528   case AArch64ISD::BRCOND:
11529     return performBRCONDCombine(N, DCI, DAG);
11530   case AArch64ISD::TBNZ:
11531   case AArch64ISD::TBZ:
11532     return performTBZCombine(N, DCI, DAG);
11533   case AArch64ISD::CSEL:
11534     return performCONDCombine(N, DCI, DAG, 2, 3);
11535   case AArch64ISD::DUP:
11536     return performPostLD1Combine(N, DCI, false);
11537   case AArch64ISD::NVCAST:
11538     return performNVCASTCombine(N);
11539   case ISD::INSERT_VECTOR_ELT:
11540     return performPostLD1Combine(N, DCI, true);
11541   case ISD::INTRINSIC_VOID:
11542   case ISD::INTRINSIC_W_CHAIN:
11543     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11544     case Intrinsic::aarch64_neon_ld2:
11545     case Intrinsic::aarch64_neon_ld3:
11546     case Intrinsic::aarch64_neon_ld4:
11547     case Intrinsic::aarch64_neon_ld1x2:
11548     case Intrinsic::aarch64_neon_ld1x3:
11549     case Intrinsic::aarch64_neon_ld1x4:
11550     case Intrinsic::aarch64_neon_ld2lane:
11551     case Intrinsic::aarch64_neon_ld3lane:
11552     case Intrinsic::aarch64_neon_ld4lane:
11553     case Intrinsic::aarch64_neon_ld2r:
11554     case Intrinsic::aarch64_neon_ld3r:
11555     case Intrinsic::aarch64_neon_ld4r:
11556     case Intrinsic::aarch64_neon_st2:
11557     case Intrinsic::aarch64_neon_st3:
11558     case Intrinsic::aarch64_neon_st4:
11559     case Intrinsic::aarch64_neon_st1x2:
11560     case Intrinsic::aarch64_neon_st1x3:
11561     case Intrinsic::aarch64_neon_st1x4:
11562     case Intrinsic::aarch64_neon_st2lane:
11563     case Intrinsic::aarch64_neon_st3lane:
11564     case Intrinsic::aarch64_neon_st4lane:
11565       return performNEONPostLDSTCombine(N, DCI, DAG);
11566     default:
11567       break;
11568     }
11569     break;
11570   case ISD::GlobalAddress:
11571     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11572   }
11573   return SDValue();
11574 }
11575 
11576 // Check if the return value is used as only a return value, as otherwise
11577 // we can't perform a tail-call. In particular, we need to check for
11578 // target ISD nodes that are returns and any other "odd" constructs
11579 // that the generic analysis code won't necessarily catch.
11580 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11581                                                SDValue &Chain) const {
11582   if (N->getNumValues() != 1)
11583     return false;
11584   if (!N->hasNUsesOfValue(1, 0))
11585     return false;
11586 
11587   SDValue TCChain = Chain;
11588   SDNode *Copy = *N->use_begin();
11589   if (Copy->getOpcode() == ISD::CopyToReg) {
11590     // If the copy has a glue operand, we conservatively assume it isn't safe to
11591     // perform a tail call.
11592     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11593         MVT::Glue)
11594       return false;
11595     TCChain = Copy->getOperand(0);
11596   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11597     return false;
11598 
11599   bool HasRet = false;
11600   for (SDNode *Node : Copy->uses()) {
11601     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11602       return false;
11603     HasRet = true;
11604   }
11605 
11606   if (!HasRet)
11607     return false;
11608 
11609   Chain = TCChain;
11610   return true;
11611 }
11612 
11613 // Return whether the an instruction can potentially be optimized to a tail
11614 // call. This will cause the optimizers to attempt to move, or duplicate,
11615 // return instructions to help enable tail call optimizations for this
11616 // instruction.
11617 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11618   return CI->isTailCall();
11619 }
11620 
11621 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11622                                                    SDValue &Offset,
11623                                                    ISD::MemIndexedMode &AM,
11624                                                    bool &IsInc,
11625                                                    SelectionDAG &DAG) const {
11626   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11627     return false;
11628 
11629   Base = Op->getOperand(0);
11630   // All of the indexed addressing mode instructions take a signed
11631   // 9 bit immediate offset.
11632   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11633     int64_t RHSC = RHS->getSExtValue();
11634     if (Op->getOpcode() == ISD::SUB)
11635       RHSC = -(uint64_t)RHSC;
11636     if (!isInt<9>(RHSC))
11637       return false;
11638     IsInc = (Op->getOpcode() == ISD::ADD);
11639     Offset = Op->getOperand(1);
11640     return true;
11641   }
11642   return false;
11643 }
11644 
11645 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11646                                                       SDValue &Offset,
11647                                                       ISD::MemIndexedMode &AM,
11648                                                       SelectionDAG &DAG) const {
11649   EVT VT;
11650   SDValue Ptr;
11651   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11652     VT = LD->getMemoryVT();
11653     Ptr = LD->getBasePtr();
11654   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11655     VT = ST->getMemoryVT();
11656     Ptr = ST->getBasePtr();
11657   } else
11658     return false;
11659 
11660   bool IsInc;
11661   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11662     return false;
11663   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11664   return true;
11665 }
11666 
11667 bool AArch64TargetLowering::getPostIndexedAddressParts(
11668     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11669     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11670   EVT VT;
11671   SDValue Ptr;
11672   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11673     VT = LD->getMemoryVT();
11674     Ptr = LD->getBasePtr();
11675   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11676     VT = ST->getMemoryVT();
11677     Ptr = ST->getBasePtr();
11678   } else
11679     return false;
11680 
11681   bool IsInc;
11682   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11683     return false;
11684   // Post-indexing updates the base, so it's not a valid transform
11685   // if that's not the same as the load's pointer.
11686   if (Ptr != Base)
11687     return false;
11688   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11689   return true;
11690 }
11691 
11692 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11693                                   SelectionDAG &DAG) {
11694   SDLoc DL(N);
11695   SDValue Op = N->getOperand(0);
11696 
11697   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11698     return;
11699 
11700   Op = SDValue(
11701       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11702                          DAG.getUNDEF(MVT::i32), Op,
11703                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11704       0);
11705   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11706   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11707 }
11708 
11709 static void ReplaceReductionResults(SDNode *N,
11710                                     SmallVectorImpl<SDValue> &Results,
11711                                     SelectionDAG &DAG, unsigned InterOp,
11712                                     unsigned AcrossOp) {
11713   EVT LoVT, HiVT;
11714   SDValue Lo, Hi;
11715   SDLoc dl(N);
11716   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11717   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11718   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11719   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11720   Results.push_back(SplitVal);
11721 }
11722 
11723 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11724   SDLoc DL(N);
11725   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11726   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11727                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11728                                        DAG.getConstant(64, DL, MVT::i64)));
11729   return std::make_pair(Lo, Hi);
11730 }
11731 
11732 // Create an even/odd pair of X registers holding integer value V.
11733 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11734   SDLoc dl(V.getNode());
11735   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11736   SDValue VHi = DAG.getAnyExtOrTrunc(
11737       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11738       dl, MVT::i64);
11739   if (DAG.getDataLayout().isBigEndian())
11740     std::swap (VLo, VHi);
11741   SDValue RegClass =
11742       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11743   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11744   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11745   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11746   return SDValue(
11747       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11748 }
11749 
11750 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11751                                        SmallVectorImpl<SDValue> &Results,
11752                                        SelectionDAG &DAG,
11753                                        const AArch64Subtarget *Subtarget) {
11754   assert(N->getValueType(0) == MVT::i128 &&
11755          "AtomicCmpSwap on types less than 128 should be legal");
11756 
11757   if (Subtarget->hasLSE()) {
11758     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11759     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11760     SDValue Ops[] = {
11761         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11762         createGPRPairNode(DAG, N->getOperand(3)), // Store value
11763         N->getOperand(1), // Ptr
11764         N->getOperand(0), // Chain in
11765     };
11766 
11767     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11768 
11769     unsigned Opcode;
11770     switch (MemOp->getOrdering()) {
11771     case AtomicOrdering::Monotonic:
11772       Opcode = AArch64::CASPX;
11773       break;
11774     case AtomicOrdering::Acquire:
11775       Opcode = AArch64::CASPAX;
11776       break;
11777     case AtomicOrdering::Release:
11778       Opcode = AArch64::CASPLX;
11779       break;
11780     case AtomicOrdering::AcquireRelease:
11781     case AtomicOrdering::SequentiallyConsistent:
11782       Opcode = AArch64::CASPALX;
11783       break;
11784     default:
11785       llvm_unreachable("Unexpected ordering!");
11786     }
11787 
11788     MachineSDNode *CmpSwap = DAG.getMachineNode(
11789         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11790     DAG.setNodeMemRefs(CmpSwap, {MemOp});
11791 
11792     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11793     if (DAG.getDataLayout().isBigEndian())
11794       std::swap(SubReg1, SubReg2);
11795     Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11796                                                  SDValue(CmpSwap, 0)));
11797     Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11798                                                  SDValue(CmpSwap, 0)));
11799     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11800     return;
11801   }
11802 
11803   auto Desired = splitInt128(N->getOperand(2), DAG);
11804   auto New = splitInt128(N->getOperand(3), DAG);
11805   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11806                    New.first,        New.second,    N->getOperand(0)};
11807   SDNode *CmpSwap = DAG.getMachineNode(
11808       AArch64::CMP_SWAP_128, SDLoc(N),
11809       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11810 
11811   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11812   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11813 
11814   Results.push_back(SDValue(CmpSwap, 0));
11815   Results.push_back(SDValue(CmpSwap, 1));
11816   Results.push_back(SDValue(CmpSwap, 3));
11817 }
11818 
11819 void AArch64TargetLowering::ReplaceNodeResults(
11820     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11821   switch (N->getOpcode()) {
11822   default:
11823     llvm_unreachable("Don't know how to custom expand this");
11824   case ISD::BITCAST:
11825     ReplaceBITCASTResults(N, Results, DAG);
11826     return;
11827   case ISD::VECREDUCE_ADD:
11828   case ISD::VECREDUCE_SMAX:
11829   case ISD::VECREDUCE_SMIN:
11830   case ISD::VECREDUCE_UMAX:
11831   case ISD::VECREDUCE_UMIN:
11832     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11833     return;
11834 
11835   case AArch64ISD::SADDV:
11836     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11837     return;
11838   case AArch64ISD::UADDV:
11839     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11840     return;
11841   case AArch64ISD::SMINV:
11842     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11843     return;
11844   case AArch64ISD::UMINV:
11845     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11846     return;
11847   case AArch64ISD::SMAXV:
11848     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11849     return;
11850   case AArch64ISD::UMAXV:
11851     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11852     return;
11853   case ISD::FP_TO_UINT:
11854   case ISD::FP_TO_SINT:
11855     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11856     // Let normal code take care of it by not adding anything to Results.
11857     return;
11858   case ISD::ATOMIC_CMP_SWAP:
11859     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11860     return;
11861   }
11862 }
11863 
11864 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11865   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11866     return TargetLowering::useLoadStackGuardNode();
11867   return true;
11868 }
11869 
11870 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11871   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11872   // reciprocal if there are three or more FDIVs.
11873   return 3;
11874 }
11875 
11876 TargetLoweringBase::LegalizeTypeAction
11877 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
11878   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
11879   // v4i16, v2i32 instead of to promote.
11880   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11881       VT == MVT::v1f32)
11882     return TypeWidenVector;
11883 
11884   return TargetLoweringBase::getPreferredVectorAction(VT);
11885 }
11886 
11887 // Loads and stores less than 128-bits are already atomic; ones above that
11888 // are doomed anyway, so defer to the default libcall and blame the OS when
11889 // things go wrong.
11890 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11891   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11892   return Size == 128;
11893 }
11894 
11895 // Loads and stores less than 128-bits are already atomic; ones above that
11896 // are doomed anyway, so defer to the default libcall and blame the OS when
11897 // things go wrong.
11898 TargetLowering::AtomicExpansionKind
11899 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11900   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11901   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11902 }
11903 
11904 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11905 TargetLowering::AtomicExpansionKind
11906 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11907   if (AI->isFloatingPointOperation())
11908     return AtomicExpansionKind::CmpXChg;
11909 
11910   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11911   if (Size > 128) return AtomicExpansionKind::None;
11912   // Nand not supported in LSE.
11913   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11914   // Leave 128 bits to LLSC.
11915   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11916 }
11917 
11918 TargetLowering::AtomicExpansionKind
11919 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11920     AtomicCmpXchgInst *AI) const {
11921   // If subtarget has LSE, leave cmpxchg intact for codegen.
11922   if (Subtarget->hasLSE())
11923     return AtomicExpansionKind::None;
11924   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11925   // implement cmpxchg without spilling. If the address being exchanged is also
11926   // on the stack and close enough to the spill slot, this can lead to a
11927   // situation where the monitor always gets cleared and the atomic operation
11928   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11929   if (getTargetMachine().getOptLevel() == 0)
11930     return AtomicExpansionKind::None;
11931   return AtomicExpansionKind::LLSC;
11932 }
11933 
11934 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11935                                              AtomicOrdering Ord) const {
11936   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11937   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11938   bool IsAcquire = isAcquireOrStronger(Ord);
11939 
11940   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11941   // intrinsic must return {i64, i64} and we have to recombine them into a
11942   // single i128 here.
11943   if (ValTy->getPrimitiveSizeInBits() == 128) {
11944     Intrinsic::ID Int =
11945         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11946     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11947 
11948     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11949     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11950 
11951     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11952     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11953     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11954     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11955     return Builder.CreateOr(
11956         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11957   }
11958 
11959   Type *Tys[] = { Addr->getType() };
11960   Intrinsic::ID Int =
11961       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11962   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11963 
11964   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11965 
11966   const DataLayout &DL = M->getDataLayout();
11967   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11968   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11969 
11970   return Builder.CreateBitCast(Trunc, EltTy);
11971 }
11972 
11973 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11974     IRBuilder<> &Builder) const {
11975   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11976   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11977 }
11978 
11979 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11980                                                    Value *Val, Value *Addr,
11981                                                    AtomicOrdering Ord) const {
11982   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11983   bool IsRelease = isReleaseOrStronger(Ord);
11984 
11985   // Since the intrinsics must have legal type, the i128 intrinsics take two
11986   // parameters: "i64, i64". We must marshal Val into the appropriate form
11987   // before the call.
11988   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
11989     Intrinsic::ID Int =
11990         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
11991     Function *Stxr = Intrinsic::getDeclaration(M, Int);
11992     Type *Int64Ty = Type::getInt64Ty(M->getContext());
11993 
11994     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
11995     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
11996     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11997     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
11998   }
11999 
12000   Intrinsic::ID Int =
12001       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12002   Type *Tys[] = { Addr->getType() };
12003   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12004 
12005   const DataLayout &DL = M->getDataLayout();
12006   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12007   Val = Builder.CreateBitCast(Val, IntValTy);
12008 
12009   return Builder.CreateCall(Stxr,
12010                             {Builder.CreateZExtOrBitCast(
12011                                  Val, Stxr->getFunctionType()->getParamType(0)),
12012                              Addr});
12013 }
12014 
12015 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12016     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12017   return Ty->isArrayTy();
12018 }
12019 
12020 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12021                                                             EVT) const {
12022   return false;
12023 }
12024 
12025 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
12026   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12027   Function *ThreadPointerFunc =
12028       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
12029   return IRB.CreatePointerCast(
12030       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12031                              Offset),
12032       IRB.getInt8PtrTy()->getPointerTo(0));
12033 }
12034 
12035 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12036   // Android provides a fixed TLS slot for the stack cookie. See the definition
12037   // of TLS_SLOT_STACK_GUARD in
12038   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12039   if (Subtarget->isTargetAndroid())
12040     return UseTlsOffset(IRB, 0x28);
12041 
12042   // Fuchsia is similar.
12043   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12044   if (Subtarget->isTargetFuchsia())
12045     return UseTlsOffset(IRB, -0x10);
12046 
12047   return TargetLowering::getIRStackGuard(IRB);
12048 }
12049 
12050 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12051   // MSVC CRT provides functionalities for stack protection.
12052   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12053     // MSVC CRT has a global variable holding security cookie.
12054     M.getOrInsertGlobal("__security_cookie",
12055                         Type::getInt8PtrTy(M.getContext()));
12056 
12057     // MSVC CRT has a function to validate security cookie.
12058     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12059         "__security_check_cookie", Type::getVoidTy(M.getContext()),
12060         Type::getInt8PtrTy(M.getContext()));
12061     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12062       F->setCallingConv(CallingConv::Win64);
12063       F->addAttribute(1, Attribute::AttrKind::InReg);
12064     }
12065     return;
12066   }
12067   TargetLowering::insertSSPDeclarations(M);
12068 }
12069 
12070 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12071   // MSVC CRT has a global variable holding security cookie.
12072   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12073     return M.getGlobalVariable("__security_cookie");
12074   return TargetLowering::getSDagStackGuard(M);
12075 }
12076 
12077 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
12078   // MSVC CRT has a function to validate security cookie.
12079   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12080     return M.getFunction("__security_check_cookie");
12081   return TargetLowering::getSSPStackGuardCheck(M);
12082 }
12083 
12084 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
12085   // Android provides a fixed TLS slot for the SafeStack pointer. See the
12086   // definition of TLS_SLOT_SAFESTACK in
12087   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12088   if (Subtarget->isTargetAndroid())
12089     return UseTlsOffset(IRB, 0x48);
12090 
12091   // Fuchsia is similar.
12092   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12093   if (Subtarget->isTargetFuchsia())
12094     return UseTlsOffset(IRB, -0x8);
12095 
12096   return TargetLowering::getSafeStackPointerLocation(IRB);
12097 }
12098 
12099 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12100     const Instruction &AndI) const {
12101   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12102   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
12103   // may be beneficial to sink in other cases, but we would have to check that
12104   // the cmp would not get folded into the br to form a cbz for these to be
12105   // beneficial.
12106   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12107   if (!Mask)
12108     return false;
12109   return Mask->getValue().isPowerOf2();
12110 }
12111 
12112 bool AArch64TargetLowering::
12113     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12114         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12115         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12116         SelectionDAG &DAG) const {
12117   // Does baseline recommend not to perform the fold by default?
12118   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12119           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12120     return false;
12121   // Else, if this is a vector shift, prefer 'shl'.
12122   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12123 }
12124 
12125 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12126   // Update IsSplitCSR in AArch64unctionInfo.
12127   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12128   AFI->setIsSplitCSR(true);
12129 }
12130 
12131 void AArch64TargetLowering::insertCopiesSplitCSR(
12132     MachineBasicBlock *Entry,
12133     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12134   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12135   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12136   if (!IStart)
12137     return;
12138 
12139   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12140   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12141   MachineBasicBlock::iterator MBBI = Entry->begin();
12142   for (const MCPhysReg *I = IStart; *I; ++I) {
12143     const TargetRegisterClass *RC = nullptr;
12144     if (AArch64::GPR64RegClass.contains(*I))
12145       RC = &AArch64::GPR64RegClass;
12146     else if (AArch64::FPR64RegClass.contains(*I))
12147       RC = &AArch64::FPR64RegClass;
12148     else
12149       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12150 
12151     unsigned NewVR = MRI->createVirtualRegister(RC);
12152     // Create copy from CSR to a virtual register.
12153     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12154     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12155     // nounwind. If we want to generalize this later, we may need to emit
12156     // CFI pseudo-instructions.
12157     assert(Entry->getParent()->getFunction().hasFnAttribute(
12158                Attribute::NoUnwind) &&
12159            "Function should be nounwind in insertCopiesSplitCSR!");
12160     Entry->addLiveIn(*I);
12161     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12162         .addReg(*I);
12163 
12164     // Insert the copy-back instructions right before the terminator.
12165     for (auto *Exit : Exits)
12166       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12167               TII->get(TargetOpcode::COPY), *I)
12168           .addReg(NewVR);
12169   }
12170 }
12171 
12172 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12173   // Integer division on AArch64 is expensive. However, when aggressively
12174   // optimizing for code size, we prefer to use a div instruction, as it is
12175   // usually smaller than the alternative sequence.
12176   // The exception to this is vector division. Since AArch64 doesn't have vector
12177   // integer division, leaving the division as-is is a loss even in terms of
12178   // size, because it will have to be scalarized, while the alternative code
12179   // sequence can be performed in vector form.
12180   bool OptSize =
12181       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12182   return OptSize && !VT.isVector();
12183 }
12184 
12185 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12186   // We want inc-of-add for scalars and sub-of-not for vectors.
12187   return VT.isScalarInteger();
12188 }
12189 
12190 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12191   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12192 }
12193 
12194 unsigned
12195 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
12196   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12197     return getPointerTy(DL).getSizeInBits();
12198 
12199   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12200 }
12201 
12202 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12203   MF.getFrameInfo().computeMaxCallFrameSize(MF);
12204   TargetLoweringBase::finalizeLowering(MF);
12205 }
12206 
12207 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12208 bool AArch64TargetLowering::needsFixedCatchObjects() const {
12209   return false;
12210 }
12211