1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64ISelLowering.h"
14 #include "AArch64CallingConvention.h"
15 #include "AArch64ExpandImm.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Triple.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/VectorUtils.h"
34 #include "llvm/CodeGen/CallingConvLower.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineInstrBuilder.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/IntrinsicsAArch64.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/OperandTraits.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/Value.h"
68 #include "llvm/MC/MCRegisterInfo.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CodeGen.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Compiler.h"
73 #include "llvm/Support/Debug.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/raw_ostream.h"
79 #include "llvm/Target/TargetMachine.h"
80 #include "llvm/Target/TargetOptions.h"
81 #include <algorithm>
82 #include <bitset>
83 #include <cassert>
84 #include <cctype>
85 #include <cstdint>
86 #include <cstdlib>
87 #include <iterator>
88 #include <limits>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
92 
93 using namespace llvm;
94 using namespace llvm::PatternMatch;
95 
96 #define DEBUG_TYPE "aarch64-lower"
97 
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
getPackedSVEVectorVT(EVT VT)119 static inline EVT getPackedSVEVectorVT(EVT VT) {
120   switch (VT.getSimpleVT().SimpleTy) {
121   default:
122     llvm_unreachable("unexpected element type for vector");
123   case MVT::i8:
124     return MVT::nxv16i8;
125   case MVT::i16:
126     return MVT::nxv8i16;
127   case MVT::i32:
128     return MVT::nxv4i32;
129   case MVT::i64:
130     return MVT::nxv2i64;
131   case MVT::f16:
132     return MVT::nxv8f16;
133   case MVT::f32:
134     return MVT::nxv4f32;
135   case MVT::f64:
136     return MVT::nxv2f64;
137   }
138 }
139 
getPromotedVTForPredicate(MVT VT)140 static inline MVT getPromotedVTForPredicate(MVT VT) {
141   assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
142          "Expected scalable predicate vector type!");
143   switch (VT.getVectorMinNumElements()) {
144   default:
145     llvm_unreachable("unexpected element count for vector");
146   case 2:
147     return MVT::nxv2i64;
148   case 4:
149     return MVT::nxv4i32;
150   case 8:
151     return MVT::nxv8i16;
152   case 16:
153     return MVT::nxv16i8;
154   }
155 }
156 
157 /// Returns true if VT's elements occupy the lowest bit positions of its
158 /// associated register class without any intervening space.
159 ///
160 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
161 /// same register class, but only nxv8f16 can be treated as a packed vector.
isPackedVectorType(EVT VT,SelectionDAG & DAG)162 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
163   assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
164          "Expected legal vector type!");
165   return VT.isFixedLengthVector() ||
166          VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
167 }
168 
169 // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
170 // predicate and end with a passthru value matching the result type.
isMergePassthruOpcode(unsigned Opc)171 static bool isMergePassthruOpcode(unsigned Opc) {
172   switch (Opc) {
173   default:
174     return false;
175   case AArch64ISD::DUP_MERGE_PASSTHRU:
176   case AArch64ISD::FNEG_MERGE_PASSTHRU:
177   case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
178   case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
179   case AArch64ISD::FCEIL_MERGE_PASSTHRU:
180   case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
181   case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
182   case AArch64ISD::FRINT_MERGE_PASSTHRU:
183   case AArch64ISD::FROUND_MERGE_PASSTHRU:
184   case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
185   case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
186   case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
187   case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
188   case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
189   case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
190   case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
191   case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
192   case AArch64ISD::FSQRT_MERGE_PASSTHRU:
193   case AArch64ISD::FRECPX_MERGE_PASSTHRU:
194   case AArch64ISD::FABS_MERGE_PASSTHRU:
195     return true;
196   }
197 }
198 
AArch64TargetLowering(const TargetMachine & TM,const AArch64Subtarget & STI)199 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
200                                              const AArch64Subtarget &STI)
201     : TargetLowering(TM), Subtarget(&STI) {
202   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
203   // we have to make something up. Arbitrarily, choose ZeroOrOne.
204   setBooleanContents(ZeroOrOneBooleanContent);
205   // When comparing vectors the result sets the different elements in the
206   // vector to all-one or all-zero.
207   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
208 
209   // Set up the register classes.
210   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
211   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
212 
213   if (Subtarget->hasFPARMv8()) {
214     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
215     addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
216     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
217     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
218     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
219   }
220 
221   if (Subtarget->hasNEON()) {
222     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
223     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
224     // Someone set us up the NEON.
225     addDRTypeForNEON(MVT::v2f32);
226     addDRTypeForNEON(MVT::v8i8);
227     addDRTypeForNEON(MVT::v4i16);
228     addDRTypeForNEON(MVT::v2i32);
229     addDRTypeForNEON(MVT::v1i64);
230     addDRTypeForNEON(MVT::v1f64);
231     addDRTypeForNEON(MVT::v4f16);
232     if (Subtarget->hasBF16())
233       addDRTypeForNEON(MVT::v4bf16);
234 
235     addQRTypeForNEON(MVT::v4f32);
236     addQRTypeForNEON(MVT::v2f64);
237     addQRTypeForNEON(MVT::v16i8);
238     addQRTypeForNEON(MVT::v8i16);
239     addQRTypeForNEON(MVT::v4i32);
240     addQRTypeForNEON(MVT::v2i64);
241     addQRTypeForNEON(MVT::v8f16);
242     if (Subtarget->hasBF16())
243       addQRTypeForNEON(MVT::v8bf16);
244   }
245 
246   if (Subtarget->hasSVE()) {
247     // Add legal sve predicate types
248     addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
249     addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
250     addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
251     addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
252 
253     // Add legal sve data types
254     addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
255     addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
256     addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
257     addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
258 
259     addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
260     addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
261     addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
262     addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
263     addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
264     addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
265 
266     if (Subtarget->hasBF16()) {
267       addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
268       addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
269       addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
270     }
271 
272     if (Subtarget->useSVEForFixedLengthVectors()) {
273       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
274         if (useSVEForFixedLengthVectorVT(VT))
275           addRegisterClass(VT, &AArch64::ZPRRegClass);
276 
277       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
278         if (useSVEForFixedLengthVectorVT(VT))
279           addRegisterClass(VT, &AArch64::ZPRRegClass);
280     }
281 
282     for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
283       setOperationAction(ISD::SADDSAT, VT, Legal);
284       setOperationAction(ISD::UADDSAT, VT, Legal);
285       setOperationAction(ISD::SSUBSAT, VT, Legal);
286       setOperationAction(ISD::USUBSAT, VT, Legal);
287       setOperationAction(ISD::UREM, VT, Expand);
288       setOperationAction(ISD::SREM, VT, Expand);
289       setOperationAction(ISD::SDIVREM, VT, Expand);
290       setOperationAction(ISD::UDIVREM, VT, Expand);
291     }
292 
293     for (auto VT :
294          { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
295            MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
296       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
297 
298     for (auto VT :
299          { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
300            MVT::nxv2f64 }) {
301       setCondCodeAction(ISD::SETO, VT, Expand);
302       setCondCodeAction(ISD::SETOLT, VT, Expand);
303       setCondCodeAction(ISD::SETLT, VT, Expand);
304       setCondCodeAction(ISD::SETOLE, VT, Expand);
305       setCondCodeAction(ISD::SETLE, VT, Expand);
306       setCondCodeAction(ISD::SETULT, VT, Expand);
307       setCondCodeAction(ISD::SETULE, VT, Expand);
308       setCondCodeAction(ISD::SETUGE, VT, Expand);
309       setCondCodeAction(ISD::SETUGT, VT, Expand);
310       setCondCodeAction(ISD::SETUEQ, VT, Expand);
311       setCondCodeAction(ISD::SETUNE, VT, Expand);
312     }
313   }
314 
315   // Compute derived properties from the register classes
316   computeRegisterProperties(Subtarget->getRegisterInfo());
317 
318   // Provide all sorts of operation actions
319   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
320   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
321   setOperationAction(ISD::SETCC, MVT::i32, Custom);
322   setOperationAction(ISD::SETCC, MVT::i64, Custom);
323   setOperationAction(ISD::SETCC, MVT::f16, Custom);
324   setOperationAction(ISD::SETCC, MVT::f32, Custom);
325   setOperationAction(ISD::SETCC, MVT::f64, Custom);
326   setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
327   setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
328   setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
329   setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
330   setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
331   setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
332   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
333   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
334   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
335   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
336   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
337   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
338   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
339   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
340   setOperationAction(ISD::SELECT, MVT::i32, Custom);
341   setOperationAction(ISD::SELECT, MVT::i64, Custom);
342   setOperationAction(ISD::SELECT, MVT::f16, Custom);
343   setOperationAction(ISD::SELECT, MVT::f32, Custom);
344   setOperationAction(ISD::SELECT, MVT::f64, Custom);
345   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
346   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
347   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
348   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
349   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
350   setOperationAction(ISD::BR_JT, MVT::Other, Custom);
351   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
352 
353   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
354   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
355   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
356 
357   setOperationAction(ISD::FREM, MVT::f32, Expand);
358   setOperationAction(ISD::FREM, MVT::f64, Expand);
359   setOperationAction(ISD::FREM, MVT::f80, Expand);
360 
361   setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
362 
363   // Custom lowering hooks are needed for XOR
364   // to fold it into CSINC/CSINV.
365   setOperationAction(ISD::XOR, MVT::i32, Custom);
366   setOperationAction(ISD::XOR, MVT::i64, Custom);
367 
368   // Virtually no operation on f128 is legal, but LLVM can't expand them when
369   // there's a valid register class, so we need custom operations in most cases.
370   setOperationAction(ISD::FABS, MVT::f128, Expand);
371   setOperationAction(ISD::FADD, MVT::f128, Custom);
372   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
373   setOperationAction(ISD::FCOS, MVT::f128, Expand);
374   setOperationAction(ISD::FDIV, MVT::f128, Custom);
375   setOperationAction(ISD::FMA, MVT::f128, Expand);
376   setOperationAction(ISD::FMUL, MVT::f128, Custom);
377   setOperationAction(ISD::FNEG, MVT::f128, Expand);
378   setOperationAction(ISD::FPOW, MVT::f128, Expand);
379   setOperationAction(ISD::FREM, MVT::f128, Expand);
380   setOperationAction(ISD::FRINT, MVT::f128, Expand);
381   setOperationAction(ISD::FSIN, MVT::f128, Expand);
382   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
383   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
384   setOperationAction(ISD::FSUB, MVT::f128, Custom);
385   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
386   setOperationAction(ISD::SETCC, MVT::f128, Custom);
387   setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
388   setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
389   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
390   setOperationAction(ISD::SELECT, MVT::f128, Custom);
391   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
392   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
393 
394   // Lowering for many of the conversions is actually specified by the non-f128
395   // type. The LowerXXX function will be trivial when f128 isn't involved.
396   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
397   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
398   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
399   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
400   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
401   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
402   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
403   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
404   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
405   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
406   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
407   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
408   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
409   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
410   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
411   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
412   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
413   setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
414   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
415   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
416   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
417   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
418   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
419   setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
420   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
421   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
422   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
423   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
424 
425   // Variable arguments.
426   setOperationAction(ISD::VASTART, MVT::Other, Custom);
427   setOperationAction(ISD::VAARG, MVT::Other, Custom);
428   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
429   setOperationAction(ISD::VAEND, MVT::Other, Expand);
430 
431   // Variable-sized objects.
432   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
433   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
434 
435   if (Subtarget->isTargetWindows())
436     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
437   else
438     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
439 
440   // Constant pool entries
441   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
442 
443   // BlockAddress
444   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
445 
446   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
447   setOperationAction(ISD::ADDC, MVT::i32, Custom);
448   setOperationAction(ISD::ADDE, MVT::i32, Custom);
449   setOperationAction(ISD::SUBC, MVT::i32, Custom);
450   setOperationAction(ISD::SUBE, MVT::i32, Custom);
451   setOperationAction(ISD::ADDC, MVT::i64, Custom);
452   setOperationAction(ISD::ADDE, MVT::i64, Custom);
453   setOperationAction(ISD::SUBC, MVT::i64, Custom);
454   setOperationAction(ISD::SUBE, MVT::i64, Custom);
455 
456   // AArch64 lacks both left-rotate and popcount instructions.
457   setOperationAction(ISD::ROTL, MVT::i32, Expand);
458   setOperationAction(ISD::ROTL, MVT::i64, Expand);
459   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
460     setOperationAction(ISD::ROTL, VT, Expand);
461     setOperationAction(ISD::ROTR, VT, Expand);
462   }
463 
464   // AArch64 doesn't have i32 MULH{S|U}.
465   setOperationAction(ISD::MULHU, MVT::i32, Expand);
466   setOperationAction(ISD::MULHS, MVT::i32, Expand);
467 
468   // AArch64 doesn't have {U|S}MUL_LOHI.
469   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
470   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
471 
472   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
473   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
474   setOperationAction(ISD::CTPOP, MVT::i128, Custom);
475 
476   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
477   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
478   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
479     setOperationAction(ISD::SDIVREM, VT, Expand);
480     setOperationAction(ISD::UDIVREM, VT, Expand);
481   }
482   setOperationAction(ISD::SREM, MVT::i32, Expand);
483   setOperationAction(ISD::SREM, MVT::i64, Expand);
484   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
485   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
486   setOperationAction(ISD::UREM, MVT::i32, Expand);
487   setOperationAction(ISD::UREM, MVT::i64, Expand);
488 
489   // Custom lower Add/Sub/Mul with overflow.
490   setOperationAction(ISD::SADDO, MVT::i32, Custom);
491   setOperationAction(ISD::SADDO, MVT::i64, Custom);
492   setOperationAction(ISD::UADDO, MVT::i32, Custom);
493   setOperationAction(ISD::UADDO, MVT::i64, Custom);
494   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
495   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
496   setOperationAction(ISD::USUBO, MVT::i32, Custom);
497   setOperationAction(ISD::USUBO, MVT::i64, Custom);
498   setOperationAction(ISD::SMULO, MVT::i32, Custom);
499   setOperationAction(ISD::SMULO, MVT::i64, Custom);
500   setOperationAction(ISD::UMULO, MVT::i32, Custom);
501   setOperationAction(ISD::UMULO, MVT::i64, Custom);
502 
503   setOperationAction(ISD::FSIN, MVT::f32, Expand);
504   setOperationAction(ISD::FSIN, MVT::f64, Expand);
505   setOperationAction(ISD::FCOS, MVT::f32, Expand);
506   setOperationAction(ISD::FCOS, MVT::f64, Expand);
507   setOperationAction(ISD::FPOW, MVT::f32, Expand);
508   setOperationAction(ISD::FPOW, MVT::f64, Expand);
509   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
510   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
511   if (Subtarget->hasFullFP16())
512     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
513   else
514     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
515 
516   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
517   setOperationAction(ISD::FREM,    MVT::v4f16, Expand);
518   setOperationAction(ISD::FREM,    MVT::v8f16, Expand);
519   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
520   setOperationAction(ISD::FPOW,    MVT::v4f16, Expand);
521   setOperationAction(ISD::FPOW,    MVT::v8f16, Expand);
522   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
523   setOperationAction(ISD::FPOWI,   MVT::v4f16, Expand);
524   setOperationAction(ISD::FPOWI,   MVT::v8f16, Expand);
525   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
526   setOperationAction(ISD::FCOS,    MVT::v4f16, Expand);
527   setOperationAction(ISD::FCOS,    MVT::v8f16, Expand);
528   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
529   setOperationAction(ISD::FSIN,    MVT::v4f16, Expand);
530   setOperationAction(ISD::FSIN,    MVT::v8f16, Expand);
531   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
532   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
533   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
534   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
535   setOperationAction(ISD::FEXP,    MVT::v4f16, Expand);
536   setOperationAction(ISD::FEXP,    MVT::v8f16, Expand);
537   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
538   setOperationAction(ISD::FEXP2,   MVT::v4f16, Expand);
539   setOperationAction(ISD::FEXP2,   MVT::v8f16, Expand);
540   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
541   setOperationAction(ISD::FLOG,    MVT::v4f16, Expand);
542   setOperationAction(ISD::FLOG,    MVT::v8f16, Expand);
543   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
544   setOperationAction(ISD::FLOG2,   MVT::v4f16, Expand);
545   setOperationAction(ISD::FLOG2,   MVT::v8f16, Expand);
546   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
547   setOperationAction(ISD::FLOG10,  MVT::v4f16, Expand);
548   setOperationAction(ISD::FLOG10,  MVT::v8f16, Expand);
549 
550   if (!Subtarget->hasFullFP16()) {
551     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
552     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
553     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
554     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
555     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
556     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
557     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
558     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
559     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
560     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
561     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
562     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
563     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
564     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
565     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
566     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
567     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
568     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
569     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
570     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
571     setOperationAction(ISD::FMINIMUM,    MVT::f16,  Promote);
572     setOperationAction(ISD::FMAXIMUM,    MVT::f16,  Promote);
573 
574     // promote v4f16 to v4f32 when that is known to be safe.
575     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
576     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
577     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
578     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
579     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
580     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
581     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
582     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
583 
584     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
585     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
586     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
587     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
588     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
589     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
590     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
591     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
592     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
593     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
594     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
595     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
596     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
597     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
598     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
599 
600     setOperationAction(ISD::FABS,        MVT::v8f16, Expand);
601     setOperationAction(ISD::FADD,        MVT::v8f16, Expand);
602     setOperationAction(ISD::FCEIL,       MVT::v8f16, Expand);
603     setOperationAction(ISD::FCOPYSIGN,   MVT::v8f16, Expand);
604     setOperationAction(ISD::FDIV,        MVT::v8f16, Expand);
605     setOperationAction(ISD::FFLOOR,      MVT::v8f16, Expand);
606     setOperationAction(ISD::FMA,         MVT::v8f16, Expand);
607     setOperationAction(ISD::FMUL,        MVT::v8f16, Expand);
608     setOperationAction(ISD::FNEARBYINT,  MVT::v8f16, Expand);
609     setOperationAction(ISD::FNEG,        MVT::v8f16, Expand);
610     setOperationAction(ISD::FROUND,      MVT::v8f16, Expand);
611     setOperationAction(ISD::FRINT,       MVT::v8f16, Expand);
612     setOperationAction(ISD::FSQRT,       MVT::v8f16, Expand);
613     setOperationAction(ISD::FSUB,        MVT::v8f16, Expand);
614     setOperationAction(ISD::FTRUNC,      MVT::v8f16, Expand);
615     setOperationAction(ISD::SETCC,       MVT::v8f16, Expand);
616     setOperationAction(ISD::BR_CC,       MVT::v8f16, Expand);
617     setOperationAction(ISD::SELECT,      MVT::v8f16, Expand);
618     setOperationAction(ISD::SELECT_CC,   MVT::v8f16, Expand);
619     setOperationAction(ISD::FP_EXTEND,   MVT::v8f16, Expand);
620   }
621 
622   // AArch64 has implementations of a lot of rounding-like FP operations.
623   for (MVT Ty : {MVT::f32, MVT::f64}) {
624     setOperationAction(ISD::FFLOOR, Ty, Legal);
625     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
626     setOperationAction(ISD::FCEIL, Ty, Legal);
627     setOperationAction(ISD::FRINT, Ty, Legal);
628     setOperationAction(ISD::FTRUNC, Ty, Legal);
629     setOperationAction(ISD::FROUND, Ty, Legal);
630     setOperationAction(ISD::FMINNUM, Ty, Legal);
631     setOperationAction(ISD::FMAXNUM, Ty, Legal);
632     setOperationAction(ISD::FMINIMUM, Ty, Legal);
633     setOperationAction(ISD::FMAXIMUM, Ty, Legal);
634     setOperationAction(ISD::LROUND, Ty, Legal);
635     setOperationAction(ISD::LLROUND, Ty, Legal);
636     setOperationAction(ISD::LRINT, Ty, Legal);
637     setOperationAction(ISD::LLRINT, Ty, Legal);
638   }
639 
640   if (Subtarget->hasFullFP16()) {
641     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
642     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
643     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
644     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
645     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
646     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
647     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
648     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
649     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
650     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
651   }
652 
653   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
654 
655   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
656 
657   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
658   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
659   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
660   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
661   setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
662 
663   // 128-bit loads and stores can be done without expanding
664   setOperationAction(ISD::LOAD, MVT::i128, Custom);
665   setOperationAction(ISD::STORE, MVT::i128, Custom);
666 
667   // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
668   // custom lowering, as there are no un-paired non-temporal stores and
669   // legalization will break up 256 bit inputs.
670   setOperationAction(ISD::STORE, MVT::v32i8, Custom);
671   setOperationAction(ISD::STORE, MVT::v16i16, Custom);
672   setOperationAction(ISD::STORE, MVT::v16f16, Custom);
673   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
674   setOperationAction(ISD::STORE, MVT::v8f32, Custom);
675   setOperationAction(ISD::STORE, MVT::v4f64, Custom);
676   setOperationAction(ISD::STORE, MVT::v4i64, Custom);
677 
678   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
679   // This requires the Performance Monitors extension.
680   if (Subtarget->hasPerfMon())
681     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
682 
683   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
684       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
685     // Issue __sincos_stret if available.
686     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
687     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
688   } else {
689     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
691   }
692 
693   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
694     // MSVCRT doesn't have powi; fall back to pow
695     setLibcallName(RTLIB::POWI_F32, nullptr);
696     setLibcallName(RTLIB::POWI_F64, nullptr);
697   }
698 
699   // Make floating-point constants legal for the large code model, so they don't
700   // become loads from the constant pool.
701   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
702     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
703     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
704   }
705 
706   // AArch64 does not have floating-point extending loads, i1 sign-extending
707   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
708   for (MVT VT : MVT::fp_valuetypes()) {
709     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
710     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
711     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
712     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
713   }
714   for (MVT VT : MVT::integer_valuetypes())
715     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
716 
717   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
718   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
719   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
720   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
721   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
722   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
723   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
724 
725   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
726   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
727   setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
728 
729   // Indexed loads and stores are supported.
730   for (unsigned im = (unsigned)ISD::PRE_INC;
731        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
732     setIndexedLoadAction(im, MVT::i8, Legal);
733     setIndexedLoadAction(im, MVT::i16, Legal);
734     setIndexedLoadAction(im, MVT::i32, Legal);
735     setIndexedLoadAction(im, MVT::i64, Legal);
736     setIndexedLoadAction(im, MVT::f64, Legal);
737     setIndexedLoadAction(im, MVT::f32, Legal);
738     setIndexedLoadAction(im, MVT::f16, Legal);
739     setIndexedLoadAction(im, MVT::bf16, Legal);
740     setIndexedStoreAction(im, MVT::i8, Legal);
741     setIndexedStoreAction(im, MVT::i16, Legal);
742     setIndexedStoreAction(im, MVT::i32, Legal);
743     setIndexedStoreAction(im, MVT::i64, Legal);
744     setIndexedStoreAction(im, MVT::f64, Legal);
745     setIndexedStoreAction(im, MVT::f32, Legal);
746     setIndexedStoreAction(im, MVT::f16, Legal);
747     setIndexedStoreAction(im, MVT::bf16, Legal);
748   }
749 
750   // Trap.
751   setOperationAction(ISD::TRAP, MVT::Other, Legal);
752   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
753 
754   // We combine OR nodes for bitfield operations.
755   setTargetDAGCombine(ISD::OR);
756   // Try to create BICs for vector ANDs.
757   setTargetDAGCombine(ISD::AND);
758 
759   // Vector add and sub nodes may conceal a high-half opportunity.
760   // Also, try to fold ADD into CSINC/CSINV..
761   setTargetDAGCombine(ISD::ADD);
762   setTargetDAGCombine(ISD::ABS);
763   setTargetDAGCombine(ISD::SUB);
764   setTargetDAGCombine(ISD::SRL);
765   setTargetDAGCombine(ISD::XOR);
766   setTargetDAGCombine(ISD::SINT_TO_FP);
767   setTargetDAGCombine(ISD::UINT_TO_FP);
768 
769   setTargetDAGCombine(ISD::FP_TO_SINT);
770   setTargetDAGCombine(ISD::FP_TO_UINT);
771   setTargetDAGCombine(ISD::FDIV);
772 
773   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
774 
775   setTargetDAGCombine(ISD::ANY_EXTEND);
776   setTargetDAGCombine(ISD::ZERO_EXTEND);
777   setTargetDAGCombine(ISD::SIGN_EXTEND);
778   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
779   setTargetDAGCombine(ISD::TRUNCATE);
780   setTargetDAGCombine(ISD::CONCAT_VECTORS);
781   setTargetDAGCombine(ISD::STORE);
782   if (Subtarget->supportsAddressTopByteIgnored())
783     setTargetDAGCombine(ISD::LOAD);
784 
785   setTargetDAGCombine(ISD::MUL);
786 
787   setTargetDAGCombine(ISD::SELECT);
788   setTargetDAGCombine(ISD::VSELECT);
789 
790   setTargetDAGCombine(ISD::INTRINSIC_VOID);
791   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
792   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
793   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
794   setTargetDAGCombine(ISD::VECREDUCE_ADD);
795 
796   setTargetDAGCombine(ISD::GlobalAddress);
797 
798   // In case of strict alignment, avoid an excessive number of byte wide stores.
799   MaxStoresPerMemsetOptSize = 8;
800   MaxStoresPerMemset = Subtarget->requiresStrictAlign()
801                        ? MaxStoresPerMemsetOptSize : 32;
802 
803   MaxGluedStoresPerMemcpy = 4;
804   MaxStoresPerMemcpyOptSize = 4;
805   MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
806                        ? MaxStoresPerMemcpyOptSize : 16;
807 
808   MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
809 
810   MaxLoadsPerMemcmpOptSize = 4;
811   MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
812                       ? MaxLoadsPerMemcmpOptSize : 8;
813 
814   setStackPointerRegisterToSaveRestore(AArch64::SP);
815 
816   setSchedulingPreference(Sched::Hybrid);
817 
818   EnableExtLdPromotion = true;
819 
820   // Set required alignment.
821   setMinFunctionAlignment(Align(4));
822   // Set preferred alignments.
823   setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
824   setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
825 
826   // Only change the limit for entries in a jump table if specified by
827   // the sub target, but not at the command line.
828   unsigned MaxJT = STI.getMaximumJumpTableSize();
829   if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
830     setMaximumJumpTableSize(MaxJT);
831 
832   setHasExtractBitsInsn(true);
833 
834   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
835 
836   if (Subtarget->hasNEON()) {
837     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
838     // silliness like this:
839     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
840     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
841     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
842     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
843     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
844     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
845     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
846     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
847     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
848     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
849     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
850     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
851     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
852     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
853     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
854     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
855     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
856     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
857     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
858     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
859     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
860     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
861     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
862     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
863     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
864 
865     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
866     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
867     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
868     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
869     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
870 
871     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
872 
873     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
874     // elements smaller than i32, so promote the input to i32 first.
875     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
876     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
877     // i8 vector elements also need promotion to i32 for v8i8
878     setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
879     setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
880     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
881     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
882     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
883     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
884     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
885     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
886     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
887     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
888     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
889 
890     if (Subtarget->hasFullFP16()) {
891       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
892       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
893       setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
894       setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
895     } else {
896       // when AArch64 doesn't have fullfp16 support, promote the input
897       // to i32 first.
898       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
899       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
900       setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
901       setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
902     }
903 
904     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
905     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
906 
907     // AArch64 doesn't have MUL.2d:
908     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
909     // Custom handling for some quad-vector types to detect MULL.
910     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
911     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
912     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
913 
914     // Saturates
915     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
916                     MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
917       setOperationAction(ISD::SADDSAT, VT, Legal);
918       setOperationAction(ISD::UADDSAT, VT, Legal);
919       setOperationAction(ISD::SSUBSAT, VT, Legal);
920       setOperationAction(ISD::USUBSAT, VT, Legal);
921     }
922 
923     // Vector reductions
924     for (MVT VT : { MVT::v4f16, MVT::v2f32,
925                     MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
926       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
927       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
928     }
929     for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
930                     MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
931       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
932       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
933       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
934       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
935       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
936     }
937     setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
938 
939     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
940     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
941     // Likewise, narrowing and extending vector loads/stores aren't handled
942     // directly.
943     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
944       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
945 
946       if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
947         setOperationAction(ISD::MULHS, VT, Legal);
948         setOperationAction(ISD::MULHU, VT, Legal);
949       } else {
950         setOperationAction(ISD::MULHS, VT, Expand);
951         setOperationAction(ISD::MULHU, VT, Expand);
952       }
953       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
954       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
955 
956       setOperationAction(ISD::BSWAP, VT, Expand);
957       setOperationAction(ISD::CTTZ, VT, Expand);
958 
959       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
960         setTruncStoreAction(VT, InnerVT, Expand);
961         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
962         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
963         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
964       }
965     }
966 
967     // AArch64 has implementations of a lot of rounding-like FP operations.
968     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
969       setOperationAction(ISD::FFLOOR, Ty, Legal);
970       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
971       setOperationAction(ISD::FCEIL, Ty, Legal);
972       setOperationAction(ISD::FRINT, Ty, Legal);
973       setOperationAction(ISD::FTRUNC, Ty, Legal);
974       setOperationAction(ISD::FROUND, Ty, Legal);
975     }
976 
977     if (Subtarget->hasFullFP16()) {
978       for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
979         setOperationAction(ISD::FFLOOR, Ty, Legal);
980         setOperationAction(ISD::FNEARBYINT, Ty, Legal);
981         setOperationAction(ISD::FCEIL, Ty, Legal);
982         setOperationAction(ISD::FRINT, Ty, Legal);
983         setOperationAction(ISD::FTRUNC, Ty, Legal);
984         setOperationAction(ISD::FROUND, Ty, Legal);
985       }
986     }
987 
988     if (Subtarget->hasSVE())
989       setOperationAction(ISD::VSCALE, MVT::i32, Custom);
990 
991     setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
992   }
993 
994   if (Subtarget->hasSVE()) {
995     // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
996     // splat of 0 or undef) once vector selects supported in SVE codegen. See
997     // D68877 for more details.
998     for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
999       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1000       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
1001       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
1002       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1003       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1004       setOperationAction(ISD::MSCATTER, VT, Custom);
1005       setOperationAction(ISD::MUL, VT, Custom);
1006       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1007       setOperationAction(ISD::SELECT, VT, Custom);
1008       setOperationAction(ISD::SDIV, VT, Custom);
1009       setOperationAction(ISD::UDIV, VT, Custom);
1010       setOperationAction(ISD::SMIN, VT, Custom);
1011       setOperationAction(ISD::UMIN, VT, Custom);
1012       setOperationAction(ISD::SMAX, VT, Custom);
1013       setOperationAction(ISD::UMAX, VT, Custom);
1014       setOperationAction(ISD::SHL, VT, Custom);
1015       setOperationAction(ISD::SRL, VT, Custom);
1016       setOperationAction(ISD::SRA, VT, Custom);
1017       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1018       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1019       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1020       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1021       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1022       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1023       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1024       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1025     }
1026 
1027     // Illegal unpacked integer vector types.
1028     for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
1029       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1030       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1031     }
1032 
1033     for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
1034       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1035       setOperationAction(ISD::SELECT, VT, Custom);
1036       setOperationAction(ISD::SETCC, VT, Custom);
1037       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1038       setOperationAction(ISD::TRUNCATE, VT, Custom);
1039       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1040       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1041       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1042 
1043       // There are no legal MVT::nxv16f## based types.
1044       if (VT != MVT::nxv16i1) {
1045         setOperationAction(ISD::SINT_TO_FP, VT, Promote);
1046         AddPromotedToType(ISD::SINT_TO_FP, VT, getPromotedVTForPredicate(VT));
1047         setOperationAction(ISD::UINT_TO_FP, VT, Promote);
1048         AddPromotedToType(ISD::UINT_TO_FP, VT, getPromotedVTForPredicate(VT));
1049       }
1050     }
1051 
1052     for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
1053                     MVT::nxv4f32, MVT::nxv2f64}) {
1054       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1055       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1056       setOperationAction(ISD::MSCATTER, VT, Custom);
1057       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1058       setOperationAction(ISD::SELECT, VT, Custom);
1059       setOperationAction(ISD::FADD, VT, Custom);
1060       setOperationAction(ISD::FDIV, VT, Custom);
1061       setOperationAction(ISD::FMA, VT, Custom);
1062       setOperationAction(ISD::FMUL, VT, Custom);
1063       setOperationAction(ISD::FNEG, VT, Custom);
1064       setOperationAction(ISD::FSUB, VT, Custom);
1065       setOperationAction(ISD::FCEIL, VT, Custom);
1066       setOperationAction(ISD::FFLOOR, VT, Custom);
1067       setOperationAction(ISD::FNEARBYINT, VT, Custom);
1068       setOperationAction(ISD::FRINT, VT, Custom);
1069       setOperationAction(ISD::FROUND, VT, Custom);
1070       setOperationAction(ISD::FROUNDEVEN, VT, Custom);
1071       setOperationAction(ISD::FTRUNC, VT, Custom);
1072       setOperationAction(ISD::FSQRT, VT, Custom);
1073       setOperationAction(ISD::FABS, VT, Custom);
1074       setOperationAction(ISD::FP_EXTEND, VT, Custom);
1075       setOperationAction(ISD::FP_ROUND, VT, Custom);
1076     }
1077 
1078     for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16})
1079       setOperationAction(ISD::MSCATTER, VT, Custom);
1080 
1081     setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
1082 
1083     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
1084     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
1085 
1086     // NOTE: Currently this has to happen after computeRegisterProperties rather
1087     // than the preferred option of combining it with the addRegisterClass call.
1088     if (Subtarget->useSVEForFixedLengthVectors()) {
1089       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
1090         if (useSVEForFixedLengthVectorVT(VT))
1091           addTypeForFixedLengthSVE(VT);
1092       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
1093         if (useSVEForFixedLengthVectorVT(VT))
1094           addTypeForFixedLengthSVE(VT);
1095 
1096       // 64bit results can mean a bigger than NEON input.
1097       for (auto VT : {MVT::v8i8, MVT::v4i16})
1098         setOperationAction(ISD::TRUNCATE, VT, Custom);
1099       setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
1100 
1101       // 128bit results imply a bigger than NEON input.
1102       for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
1103         setOperationAction(ISD::TRUNCATE, VT, Custom);
1104       for (auto VT : {MVT::v8f16, MVT::v4f32})
1105         setOperationAction(ISD::FP_ROUND, VT, Expand);
1106 
1107       // These operations are not supported on NEON but SVE can do them.
1108       setOperationAction(ISD::MUL, MVT::v1i64, Custom);
1109       setOperationAction(ISD::MUL, MVT::v2i64, Custom);
1110       setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
1111       setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
1112       setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
1113       setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1114       setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
1115       setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1116       setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
1117       setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
1118       setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
1119       setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
1120       setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
1121       setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
1122       setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
1123       setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
1124       setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
1125       setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
1126       setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
1127       setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
1128       setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
1129       setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
1130       setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
1131       setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
1132       setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
1133       setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
1134       setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
1135       setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
1136       setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
1137       setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
1138 
1139       // Int operations with no NEON support.
1140       for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
1141                       MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
1142         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1143         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1144         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1145       }
1146 
1147       // FP operations with no NEON support.
1148       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
1149                       MVT::v1f64, MVT::v2f64})
1150         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1151 
1152       // Use SVE for vectors with more than 2 elements.
1153       for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
1154         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1155     }
1156   }
1157 
1158   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
1159 }
1160 
addTypeForNEON(MVT VT,MVT PromotedBitwiseVT)1161 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
1162   assert(VT.isVector() && "VT should be a vector type");
1163 
1164   if (VT.isFloatingPoint()) {
1165     MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
1166     setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
1167     setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
1168   }
1169 
1170   // Mark vector float intrinsics as expand.
1171   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
1172     setOperationAction(ISD::FSIN, VT, Expand);
1173     setOperationAction(ISD::FCOS, VT, Expand);
1174     setOperationAction(ISD::FPOW, VT, Expand);
1175     setOperationAction(ISD::FLOG, VT, Expand);
1176     setOperationAction(ISD::FLOG2, VT, Expand);
1177     setOperationAction(ISD::FLOG10, VT, Expand);
1178     setOperationAction(ISD::FEXP, VT, Expand);
1179     setOperationAction(ISD::FEXP2, VT, Expand);
1180 
1181     // But we do support custom-lowering for FCOPYSIGN.
1182     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1183   }
1184 
1185   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1186   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1187   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1188   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1189   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1190   setOperationAction(ISD::SRA, VT, Custom);
1191   setOperationAction(ISD::SRL, VT, Custom);
1192   setOperationAction(ISD::SHL, VT, Custom);
1193   setOperationAction(ISD::OR, VT, Custom);
1194   setOperationAction(ISD::SETCC, VT, Custom);
1195   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1196 
1197   setOperationAction(ISD::SELECT, VT, Expand);
1198   setOperationAction(ISD::SELECT_CC, VT, Expand);
1199   setOperationAction(ISD::VSELECT, VT, Expand);
1200   for (MVT InnerVT : MVT::all_valuetypes())
1201     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1202 
1203   // CNT supports only B element sizes, then use UADDLP to widen.
1204   if (VT != MVT::v8i8 && VT != MVT::v16i8)
1205     setOperationAction(ISD::CTPOP, VT, Custom);
1206 
1207   setOperationAction(ISD::UDIV, VT, Expand);
1208   setOperationAction(ISD::SDIV, VT, Expand);
1209   setOperationAction(ISD::UREM, VT, Expand);
1210   setOperationAction(ISD::SREM, VT, Expand);
1211   setOperationAction(ISD::FREM, VT, Expand);
1212 
1213   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1214   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1215 
1216   if (!VT.isFloatingPoint())
1217     setOperationAction(ISD::ABS, VT, Legal);
1218 
1219   // [SU][MIN|MAX] are available for all NEON types apart from i64.
1220   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1221     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1222       setOperationAction(Opcode, VT, Legal);
1223 
1224   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1225   if (VT.isFloatingPoint() &&
1226       VT.getVectorElementType() != MVT::bf16 &&
1227       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1228     for (unsigned Opcode :
1229          {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1230       setOperationAction(Opcode, VT, Legal);
1231 
1232   if (Subtarget->isLittleEndian()) {
1233     for (unsigned im = (unsigned)ISD::PRE_INC;
1234          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1235       setIndexedLoadAction(im, VT, Legal);
1236       setIndexedStoreAction(im, VT, Legal);
1237     }
1238   }
1239 }
1240 
addTypeForFixedLengthSVE(MVT VT)1241 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1242   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1243 
1244   // By default everything must be expanded.
1245   for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1246     setOperationAction(Op, VT, Expand);
1247 
1248   // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1249   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1250 
1251   // Lower fixed length vector operations to scalable equivalents.
1252   setOperationAction(ISD::ADD, VT, Custom);
1253   setOperationAction(ISD::AND, VT, Custom);
1254   setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1255   setOperationAction(ISD::FADD, VT, Custom);
1256   setOperationAction(ISD::FCEIL, VT, Custom);
1257   setOperationAction(ISD::FDIV, VT, Custom);
1258   setOperationAction(ISD::FFLOOR, VT, Custom);
1259   setOperationAction(ISD::FMA, VT, Custom);
1260   setOperationAction(ISD::FMAXNUM, VT, Custom);
1261   setOperationAction(ISD::FMINNUM, VT, Custom);
1262   setOperationAction(ISD::FMUL, VT, Custom);
1263   setOperationAction(ISD::FNEARBYINT, VT, Custom);
1264   setOperationAction(ISD::FNEG, VT, Custom);
1265   setOperationAction(ISD::FRINT, VT, Custom);
1266   setOperationAction(ISD::FROUND, VT, Custom);
1267   setOperationAction(ISD::FSQRT, VT, Custom);
1268   setOperationAction(ISD::FSUB, VT, Custom);
1269   setOperationAction(ISD::FTRUNC, VT, Custom);
1270   setOperationAction(ISD::LOAD, VT, Custom);
1271   setOperationAction(ISD::MUL, VT, Custom);
1272   setOperationAction(ISD::OR, VT, Custom);
1273   setOperationAction(ISD::SDIV, VT, Custom);
1274   setOperationAction(ISD::SETCC, VT, Custom);
1275   setOperationAction(ISD::SHL, VT, Custom);
1276   setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1277   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
1278   setOperationAction(ISD::SMAX, VT, Custom);
1279   setOperationAction(ISD::SMIN, VT, Custom);
1280   setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
1281   setOperationAction(ISD::SRA, VT, Custom);
1282   setOperationAction(ISD::SRL, VT, Custom);
1283   setOperationAction(ISD::STORE, VT, Custom);
1284   setOperationAction(ISD::SUB, VT, Custom);
1285   setOperationAction(ISD::TRUNCATE, VT, Custom);
1286   setOperationAction(ISD::UDIV, VT, Custom);
1287   setOperationAction(ISD::UMAX, VT, Custom);
1288   setOperationAction(ISD::UMIN, VT, Custom);
1289   setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
1290   setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
1291   setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1292   setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1293   setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1294   setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1295   setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
1296   setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
1297   setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
1298   setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
1299   setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
1300   setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
1301   setOperationAction(ISD::VSELECT, VT, Custom);
1302   setOperationAction(ISD::XOR, VT, Custom);
1303   setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1304 }
1305 
addDRTypeForNEON(MVT VT)1306 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1307   addRegisterClass(VT, &AArch64::FPR64RegClass);
1308   addTypeForNEON(VT, MVT::v2i32);
1309 }
1310 
addQRTypeForNEON(MVT VT)1311 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1312   addRegisterClass(VT, &AArch64::FPR128RegClass);
1313   addTypeForNEON(VT, MVT::v4i32);
1314 }
1315 
getSetCCResultType(const DataLayout &,LLVMContext & C,EVT VT) const1316 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1317                                               LLVMContext &C, EVT VT) const {
1318   if (!VT.isVector())
1319     return MVT::i32;
1320   if (VT.isScalableVector())
1321     return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1322   return VT.changeVectorElementTypeToInteger();
1323 }
1324 
optimizeLogicalImm(SDValue Op,unsigned Size,uint64_t Imm,const APInt & Demanded,TargetLowering::TargetLoweringOpt & TLO,unsigned NewOpc)1325 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1326                                const APInt &Demanded,
1327                                TargetLowering::TargetLoweringOpt &TLO,
1328                                unsigned NewOpc) {
1329   uint64_t OldImm = Imm, NewImm, Enc;
1330   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1331 
1332   // Return if the immediate is already all zeros, all ones, a bimm32 or a
1333   // bimm64.
1334   if (Imm == 0 || Imm == Mask ||
1335       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1336     return false;
1337 
1338   unsigned EltSize = Size;
1339   uint64_t DemandedBits = Demanded.getZExtValue();
1340 
1341   // Clear bits that are not demanded.
1342   Imm &= DemandedBits;
1343 
1344   while (true) {
1345     // The goal here is to set the non-demanded bits in a way that minimizes
1346     // the number of switching between 0 and 1. In order to achieve this goal,
1347     // we set the non-demanded bits to the value of the preceding demanded bits.
1348     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1349     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1350     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1351     // The final result is 0b11000011.
1352     uint64_t NonDemandedBits = ~DemandedBits;
1353     uint64_t InvertedImm = ~Imm & DemandedBits;
1354     uint64_t RotatedImm =
1355         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1356         NonDemandedBits;
1357     uint64_t Sum = RotatedImm + NonDemandedBits;
1358     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1359     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1360     NewImm = (Imm | Ones) & Mask;
1361 
1362     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1363     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1364     // we halve the element size and continue the search.
1365     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1366       break;
1367 
1368     // We cannot shrink the element size any further if it is 2-bits.
1369     if (EltSize == 2)
1370       return false;
1371 
1372     EltSize /= 2;
1373     Mask >>= EltSize;
1374     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1375 
1376     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1377     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1378       return false;
1379 
1380     // Merge the upper and lower halves of Imm and DemandedBits.
1381     Imm |= Hi;
1382     DemandedBits |= DemandedBitsHi;
1383   }
1384 
1385   ++NumOptimizedImms;
1386 
1387   // Replicate the element across the register width.
1388   while (EltSize < Size) {
1389     NewImm |= NewImm << EltSize;
1390     EltSize *= 2;
1391   }
1392 
1393   (void)OldImm;
1394   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1395          "demanded bits should never be altered");
1396   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1397 
1398   // Create the new constant immediate node.
1399   EVT VT = Op.getValueType();
1400   SDLoc DL(Op);
1401   SDValue New;
1402 
1403   // If the new constant immediate is all-zeros or all-ones, let the target
1404   // independent DAG combine optimize this node.
1405   if (NewImm == 0 || NewImm == OrigMask) {
1406     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1407                           TLO.DAG.getConstant(NewImm, DL, VT));
1408   // Otherwise, create a machine node so that target independent DAG combine
1409   // doesn't undo this optimization.
1410   } else {
1411     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1412     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1413     New = SDValue(
1414         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1415   }
1416 
1417   return TLO.CombineTo(Op, New);
1418 }
1419 
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const1420 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1421     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1422     TargetLoweringOpt &TLO) const {
1423   // Delay this optimization to as late as possible.
1424   if (!TLO.LegalOps)
1425     return false;
1426 
1427   if (!EnableOptimizeLogicalImm)
1428     return false;
1429 
1430   EVT VT = Op.getValueType();
1431   if (VT.isVector())
1432     return false;
1433 
1434   unsigned Size = VT.getSizeInBits();
1435   assert((Size == 32 || Size == 64) &&
1436          "i32 or i64 is expected after legalization.");
1437 
1438   // Exit early if we demand all bits.
1439   if (DemandedBits.countPopulation() == Size)
1440     return false;
1441 
1442   unsigned NewOpc;
1443   switch (Op.getOpcode()) {
1444   default:
1445     return false;
1446   case ISD::AND:
1447     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1448     break;
1449   case ISD::OR:
1450     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1451     break;
1452   case ISD::XOR:
1453     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1454     break;
1455   }
1456   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1457   if (!C)
1458     return false;
1459   uint64_t Imm = C->getZExtValue();
1460   return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1461 }
1462 
1463 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1464 /// Mask are known to be either zero or one and return them Known.
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const1465 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1466     const SDValue Op, KnownBits &Known,
1467     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1468   switch (Op.getOpcode()) {
1469   default:
1470     break;
1471   case AArch64ISD::CSEL: {
1472     KnownBits Known2;
1473     Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1474     Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1475     Known = KnownBits::commonBits(Known, Known2);
1476     break;
1477   }
1478   case AArch64ISD::LOADgot:
1479   case AArch64ISD::ADDlow: {
1480     if (!Subtarget->isTargetILP32())
1481       break;
1482     // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1483     Known.Zero = APInt::getHighBitsSet(64, 32);
1484     break;
1485   }
1486   case ISD::INTRINSIC_W_CHAIN: {
1487     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1488     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1489     switch (IntID) {
1490     default: return;
1491     case Intrinsic::aarch64_ldaxr:
1492     case Intrinsic::aarch64_ldxr: {
1493       unsigned BitWidth = Known.getBitWidth();
1494       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1495       unsigned MemBits = VT.getScalarSizeInBits();
1496       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1497       return;
1498     }
1499     }
1500     break;
1501   }
1502   case ISD::INTRINSIC_WO_CHAIN:
1503   case ISD::INTRINSIC_VOID: {
1504     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1505     switch (IntNo) {
1506     default:
1507       break;
1508     case Intrinsic::aarch64_neon_umaxv:
1509     case Intrinsic::aarch64_neon_uminv: {
1510       // Figure out the datatype of the vector operand. The UMINV instruction
1511       // will zero extend the result, so we can mark as known zero all the
1512       // bits larger than the element datatype. 32-bit or larget doesn't need
1513       // this as those are legal types and will be handled by isel directly.
1514       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1515       unsigned BitWidth = Known.getBitWidth();
1516       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1517         assert(BitWidth >= 8 && "Unexpected width!");
1518         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1519         Known.Zero |= Mask;
1520       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1521         assert(BitWidth >= 16 && "Unexpected width!");
1522         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1523         Known.Zero |= Mask;
1524       }
1525       break;
1526     } break;
1527     }
1528   }
1529   }
1530 }
1531 
getScalarShiftAmountTy(const DataLayout & DL,EVT) const1532 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1533                                                   EVT) const {
1534   return MVT::i64;
1535 }
1536 
allowsMisalignedMemoryAccesses(EVT VT,unsigned AddrSpace,unsigned Align,MachineMemOperand::Flags Flags,bool * Fast) const1537 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1538     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1539     bool *Fast) const {
1540   if (Subtarget->requiresStrictAlign())
1541     return false;
1542 
1543   if (Fast) {
1544     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1545     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1546             // See comments in performSTORECombine() for more details about
1547             // these conditions.
1548 
1549             // Code that uses clang vector extensions can mark that it
1550             // wants unaligned accesses to be treated as fast by
1551             // underspecifying alignment to be 1 or 2.
1552             Align <= 2 ||
1553 
1554             // Disregard v2i64. Memcpy lowering produces those and splitting
1555             // them regresses performance on micro-benchmarks and olden/bh.
1556             VT == MVT::v2i64;
1557   }
1558   return true;
1559 }
1560 
1561 // Same as above but handling LLTs instead.
allowsMisalignedMemoryAccesses(LLT Ty,unsigned AddrSpace,Align Alignment,MachineMemOperand::Flags Flags,bool * Fast) const1562 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1563     LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1564     bool *Fast) const {
1565   if (Subtarget->requiresStrictAlign())
1566     return false;
1567 
1568   if (Fast) {
1569     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1570     *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1571             Ty.getSizeInBytes() != 16 ||
1572             // See comments in performSTORECombine() for more details about
1573             // these conditions.
1574 
1575             // Code that uses clang vector extensions can mark that it
1576             // wants unaligned accesses to be treated as fast by
1577             // underspecifying alignment to be 1 or 2.
1578             Alignment <= 2 ||
1579 
1580             // Disregard v2i64. Memcpy lowering produces those and splitting
1581             // them regresses performance on micro-benchmarks and olden/bh.
1582             Ty == LLT::vector(2, 64);
1583   }
1584   return true;
1585 }
1586 
1587 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const1588 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1589                                       const TargetLibraryInfo *libInfo) const {
1590   return AArch64::createFastISel(funcInfo, libInfo);
1591 }
1592 
getTargetNodeName(unsigned Opcode) const1593 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1594 #define MAKE_CASE(V)                                                           \
1595   case V:                                                                      \
1596     return #V;
1597   switch ((AArch64ISD::NodeType)Opcode) {
1598   case AArch64ISD::FIRST_NUMBER:
1599     break;
1600     MAKE_CASE(AArch64ISD::CALL)
1601     MAKE_CASE(AArch64ISD::ADRP)
1602     MAKE_CASE(AArch64ISD::ADR)
1603     MAKE_CASE(AArch64ISD::ADDlow)
1604     MAKE_CASE(AArch64ISD::LOADgot)
1605     MAKE_CASE(AArch64ISD::RET_FLAG)
1606     MAKE_CASE(AArch64ISD::BRCOND)
1607     MAKE_CASE(AArch64ISD::CSEL)
1608     MAKE_CASE(AArch64ISD::FCSEL)
1609     MAKE_CASE(AArch64ISD::CSINV)
1610     MAKE_CASE(AArch64ISD::CSNEG)
1611     MAKE_CASE(AArch64ISD::CSINC)
1612     MAKE_CASE(AArch64ISD::THREAD_POINTER)
1613     MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1614     MAKE_CASE(AArch64ISD::ADD_PRED)
1615     MAKE_CASE(AArch64ISD::MUL_PRED)
1616     MAKE_CASE(AArch64ISD::SDIV_PRED)
1617     MAKE_CASE(AArch64ISD::SHL_PRED)
1618     MAKE_CASE(AArch64ISD::SMAX_PRED)
1619     MAKE_CASE(AArch64ISD::SMIN_PRED)
1620     MAKE_CASE(AArch64ISD::SRA_PRED)
1621     MAKE_CASE(AArch64ISD::SRL_PRED)
1622     MAKE_CASE(AArch64ISD::SUB_PRED)
1623     MAKE_CASE(AArch64ISD::UDIV_PRED)
1624     MAKE_CASE(AArch64ISD::UMAX_PRED)
1625     MAKE_CASE(AArch64ISD::UMIN_PRED)
1626     MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
1627     MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
1628     MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
1629     MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
1630     MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
1631     MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
1632     MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
1633     MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
1634     MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
1635     MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
1636     MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
1637     MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
1638     MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
1639     MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
1640     MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
1641     MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
1642     MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
1643     MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
1644     MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
1645     MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1646     MAKE_CASE(AArch64ISD::ADC)
1647     MAKE_CASE(AArch64ISD::SBC)
1648     MAKE_CASE(AArch64ISD::ADDS)
1649     MAKE_CASE(AArch64ISD::SUBS)
1650     MAKE_CASE(AArch64ISD::ADCS)
1651     MAKE_CASE(AArch64ISD::SBCS)
1652     MAKE_CASE(AArch64ISD::ANDS)
1653     MAKE_CASE(AArch64ISD::CCMP)
1654     MAKE_CASE(AArch64ISD::CCMN)
1655     MAKE_CASE(AArch64ISD::FCCMP)
1656     MAKE_CASE(AArch64ISD::FCMP)
1657     MAKE_CASE(AArch64ISD::STRICT_FCMP)
1658     MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1659     MAKE_CASE(AArch64ISD::DUP)
1660     MAKE_CASE(AArch64ISD::DUPLANE8)
1661     MAKE_CASE(AArch64ISD::DUPLANE16)
1662     MAKE_CASE(AArch64ISD::DUPLANE32)
1663     MAKE_CASE(AArch64ISD::DUPLANE64)
1664     MAKE_CASE(AArch64ISD::MOVI)
1665     MAKE_CASE(AArch64ISD::MOVIshift)
1666     MAKE_CASE(AArch64ISD::MOVIedit)
1667     MAKE_CASE(AArch64ISD::MOVImsl)
1668     MAKE_CASE(AArch64ISD::FMOV)
1669     MAKE_CASE(AArch64ISD::MVNIshift)
1670     MAKE_CASE(AArch64ISD::MVNImsl)
1671     MAKE_CASE(AArch64ISD::BICi)
1672     MAKE_CASE(AArch64ISD::ORRi)
1673     MAKE_CASE(AArch64ISD::BSP)
1674     MAKE_CASE(AArch64ISD::NEG)
1675     MAKE_CASE(AArch64ISD::EXTR)
1676     MAKE_CASE(AArch64ISD::ZIP1)
1677     MAKE_CASE(AArch64ISD::ZIP2)
1678     MAKE_CASE(AArch64ISD::UZP1)
1679     MAKE_CASE(AArch64ISD::UZP2)
1680     MAKE_CASE(AArch64ISD::TRN1)
1681     MAKE_CASE(AArch64ISD::TRN2)
1682     MAKE_CASE(AArch64ISD::REV16)
1683     MAKE_CASE(AArch64ISD::REV32)
1684     MAKE_CASE(AArch64ISD::REV64)
1685     MAKE_CASE(AArch64ISD::EXT)
1686     MAKE_CASE(AArch64ISD::VSHL)
1687     MAKE_CASE(AArch64ISD::VLSHR)
1688     MAKE_CASE(AArch64ISD::VASHR)
1689     MAKE_CASE(AArch64ISD::VSLI)
1690     MAKE_CASE(AArch64ISD::VSRI)
1691     MAKE_CASE(AArch64ISD::CMEQ)
1692     MAKE_CASE(AArch64ISD::CMGE)
1693     MAKE_CASE(AArch64ISD::CMGT)
1694     MAKE_CASE(AArch64ISD::CMHI)
1695     MAKE_CASE(AArch64ISD::CMHS)
1696     MAKE_CASE(AArch64ISD::FCMEQ)
1697     MAKE_CASE(AArch64ISD::FCMGE)
1698     MAKE_CASE(AArch64ISD::FCMGT)
1699     MAKE_CASE(AArch64ISD::CMEQz)
1700     MAKE_CASE(AArch64ISD::CMGEz)
1701     MAKE_CASE(AArch64ISD::CMGTz)
1702     MAKE_CASE(AArch64ISD::CMLEz)
1703     MAKE_CASE(AArch64ISD::CMLTz)
1704     MAKE_CASE(AArch64ISD::FCMEQz)
1705     MAKE_CASE(AArch64ISD::FCMGEz)
1706     MAKE_CASE(AArch64ISD::FCMGTz)
1707     MAKE_CASE(AArch64ISD::FCMLEz)
1708     MAKE_CASE(AArch64ISD::FCMLTz)
1709     MAKE_CASE(AArch64ISD::SADDV)
1710     MAKE_CASE(AArch64ISD::UADDV)
1711     MAKE_CASE(AArch64ISD::SRHADD)
1712     MAKE_CASE(AArch64ISD::URHADD)
1713     MAKE_CASE(AArch64ISD::SHADD)
1714     MAKE_CASE(AArch64ISD::UHADD)
1715     MAKE_CASE(AArch64ISD::SMINV)
1716     MAKE_CASE(AArch64ISD::UMINV)
1717     MAKE_CASE(AArch64ISD::SMAXV)
1718     MAKE_CASE(AArch64ISD::UMAXV)
1719     MAKE_CASE(AArch64ISD::SADDV_PRED)
1720     MAKE_CASE(AArch64ISD::UADDV_PRED)
1721     MAKE_CASE(AArch64ISD::SMAXV_PRED)
1722     MAKE_CASE(AArch64ISD::UMAXV_PRED)
1723     MAKE_CASE(AArch64ISD::SMINV_PRED)
1724     MAKE_CASE(AArch64ISD::UMINV_PRED)
1725     MAKE_CASE(AArch64ISD::ORV_PRED)
1726     MAKE_CASE(AArch64ISD::EORV_PRED)
1727     MAKE_CASE(AArch64ISD::ANDV_PRED)
1728     MAKE_CASE(AArch64ISD::CLASTA_N)
1729     MAKE_CASE(AArch64ISD::CLASTB_N)
1730     MAKE_CASE(AArch64ISD::LASTA)
1731     MAKE_CASE(AArch64ISD::LASTB)
1732     MAKE_CASE(AArch64ISD::REV)
1733     MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1734     MAKE_CASE(AArch64ISD::TBL)
1735     MAKE_CASE(AArch64ISD::FADD_PRED)
1736     MAKE_CASE(AArch64ISD::FADDA_PRED)
1737     MAKE_CASE(AArch64ISD::FADDV_PRED)
1738     MAKE_CASE(AArch64ISD::FDIV_PRED)
1739     MAKE_CASE(AArch64ISD::FMA_PRED)
1740     MAKE_CASE(AArch64ISD::FMAXV_PRED)
1741     MAKE_CASE(AArch64ISD::FMAXNM_PRED)
1742     MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1743     MAKE_CASE(AArch64ISD::FMINV_PRED)
1744     MAKE_CASE(AArch64ISD::FMINNM_PRED)
1745     MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1746     MAKE_CASE(AArch64ISD::FMUL_PRED)
1747     MAKE_CASE(AArch64ISD::FSUB_PRED)
1748     MAKE_CASE(AArch64ISD::BIT)
1749     MAKE_CASE(AArch64ISD::CBZ)
1750     MAKE_CASE(AArch64ISD::CBNZ)
1751     MAKE_CASE(AArch64ISD::TBZ)
1752     MAKE_CASE(AArch64ISD::TBNZ)
1753     MAKE_CASE(AArch64ISD::TC_RETURN)
1754     MAKE_CASE(AArch64ISD::PREFETCH)
1755     MAKE_CASE(AArch64ISD::SITOF)
1756     MAKE_CASE(AArch64ISD::UITOF)
1757     MAKE_CASE(AArch64ISD::NVCAST)
1758     MAKE_CASE(AArch64ISD::SQSHL_I)
1759     MAKE_CASE(AArch64ISD::UQSHL_I)
1760     MAKE_CASE(AArch64ISD::SRSHR_I)
1761     MAKE_CASE(AArch64ISD::URSHR_I)
1762     MAKE_CASE(AArch64ISD::SQSHLU_I)
1763     MAKE_CASE(AArch64ISD::WrapperLarge)
1764     MAKE_CASE(AArch64ISD::LD2post)
1765     MAKE_CASE(AArch64ISD::LD3post)
1766     MAKE_CASE(AArch64ISD::LD4post)
1767     MAKE_CASE(AArch64ISD::ST2post)
1768     MAKE_CASE(AArch64ISD::ST3post)
1769     MAKE_CASE(AArch64ISD::ST4post)
1770     MAKE_CASE(AArch64ISD::LD1x2post)
1771     MAKE_CASE(AArch64ISD::LD1x3post)
1772     MAKE_CASE(AArch64ISD::LD1x4post)
1773     MAKE_CASE(AArch64ISD::ST1x2post)
1774     MAKE_CASE(AArch64ISD::ST1x3post)
1775     MAKE_CASE(AArch64ISD::ST1x4post)
1776     MAKE_CASE(AArch64ISD::LD1DUPpost)
1777     MAKE_CASE(AArch64ISD::LD2DUPpost)
1778     MAKE_CASE(AArch64ISD::LD3DUPpost)
1779     MAKE_CASE(AArch64ISD::LD4DUPpost)
1780     MAKE_CASE(AArch64ISD::LD1LANEpost)
1781     MAKE_CASE(AArch64ISD::LD2LANEpost)
1782     MAKE_CASE(AArch64ISD::LD3LANEpost)
1783     MAKE_CASE(AArch64ISD::LD4LANEpost)
1784     MAKE_CASE(AArch64ISD::ST2LANEpost)
1785     MAKE_CASE(AArch64ISD::ST3LANEpost)
1786     MAKE_CASE(AArch64ISD::ST4LANEpost)
1787     MAKE_CASE(AArch64ISD::SMULL)
1788     MAKE_CASE(AArch64ISD::UMULL)
1789     MAKE_CASE(AArch64ISD::FRECPE)
1790     MAKE_CASE(AArch64ISD::FRECPS)
1791     MAKE_CASE(AArch64ISD::FRSQRTE)
1792     MAKE_CASE(AArch64ISD::FRSQRTS)
1793     MAKE_CASE(AArch64ISD::STG)
1794     MAKE_CASE(AArch64ISD::STZG)
1795     MAKE_CASE(AArch64ISD::ST2G)
1796     MAKE_CASE(AArch64ISD::STZ2G)
1797     MAKE_CASE(AArch64ISD::SUNPKHI)
1798     MAKE_CASE(AArch64ISD::SUNPKLO)
1799     MAKE_CASE(AArch64ISD::UUNPKHI)
1800     MAKE_CASE(AArch64ISD::UUNPKLO)
1801     MAKE_CASE(AArch64ISD::INSR)
1802     MAKE_CASE(AArch64ISD::PTEST)
1803     MAKE_CASE(AArch64ISD::PTRUE)
1804     MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1805     MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1806     MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1807     MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1808     MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1809     MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1810     MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1811     MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1812     MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1813     MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1814     MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1815     MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1816     MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1817     MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1818     MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1819     MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1820     MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1821     MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1822     MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1823     MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1824     MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1825     MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1826     MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1827     MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1828     MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1829     MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1830     MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1831     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1832     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1833     MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1834     MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1835     MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1836     MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1837     MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1838     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1839     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1840     MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1841     MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1842     MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1843     MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1844     MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1845     MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1846     MAKE_CASE(AArch64ISD::ST1_PRED)
1847     MAKE_CASE(AArch64ISD::SST1_PRED)
1848     MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1849     MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1850     MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1851     MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1852     MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1853     MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1854     MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1855     MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1856     MAKE_CASE(AArch64ISD::LDP)
1857     MAKE_CASE(AArch64ISD::STP)
1858     MAKE_CASE(AArch64ISD::STNP)
1859     MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1860     MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1861     MAKE_CASE(AArch64ISD::UABD)
1862     MAKE_CASE(AArch64ISD::SABD)
1863   }
1864 #undef MAKE_CASE
1865   return nullptr;
1866 }
1867 
1868 MachineBasicBlock *
EmitF128CSEL(MachineInstr & MI,MachineBasicBlock * MBB) const1869 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1870                                     MachineBasicBlock *MBB) const {
1871   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1872   // phi node:
1873 
1874   // OrigBB:
1875   //     [... previous instrs leading to comparison ...]
1876   //     b.ne TrueBB
1877   //     b EndBB
1878   // TrueBB:
1879   //     ; Fallthrough
1880   // EndBB:
1881   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1882 
1883   MachineFunction *MF = MBB->getParent();
1884   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1885   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1886   DebugLoc DL = MI.getDebugLoc();
1887   MachineFunction::iterator It = ++MBB->getIterator();
1888 
1889   Register DestReg = MI.getOperand(0).getReg();
1890   Register IfTrueReg = MI.getOperand(1).getReg();
1891   Register IfFalseReg = MI.getOperand(2).getReg();
1892   unsigned CondCode = MI.getOperand(3).getImm();
1893   bool NZCVKilled = MI.getOperand(4).isKill();
1894 
1895   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1896   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1897   MF->insert(It, TrueBB);
1898   MF->insert(It, EndBB);
1899 
1900   // Transfer rest of current basic-block to EndBB
1901   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1902                 MBB->end());
1903   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1904 
1905   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1906   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1907   MBB->addSuccessor(TrueBB);
1908   MBB->addSuccessor(EndBB);
1909 
1910   // TrueBB falls through to the end.
1911   TrueBB->addSuccessor(EndBB);
1912 
1913   if (!NZCVKilled) {
1914     TrueBB->addLiveIn(AArch64::NZCV);
1915     EndBB->addLiveIn(AArch64::NZCV);
1916   }
1917 
1918   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1919       .addReg(IfTrueReg)
1920       .addMBB(TrueBB)
1921       .addReg(IfFalseReg)
1922       .addMBB(MBB);
1923 
1924   MI.eraseFromParent();
1925   return EndBB;
1926 }
1927 
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const1928 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1929        MachineInstr &MI, MachineBasicBlock *BB) const {
1930   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1931              BB->getParent()->getFunction().getPersonalityFn())) &&
1932          "SEH does not use catchret!");
1933   return BB;
1934 }
1935 
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const1936 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1937     MachineInstr &MI, MachineBasicBlock *BB) const {
1938   switch (MI.getOpcode()) {
1939   default:
1940 #ifndef NDEBUG
1941     MI.dump();
1942 #endif
1943     llvm_unreachable("Unexpected instruction for custom inserter!");
1944 
1945   case AArch64::F128CSEL:
1946     return EmitF128CSEL(MI, BB);
1947 
1948   case TargetOpcode::STACKMAP:
1949   case TargetOpcode::PATCHPOINT:
1950   case TargetOpcode::STATEPOINT:
1951     return emitPatchPoint(MI, BB);
1952 
1953   case AArch64::CATCHRET:
1954     return EmitLoweredCatchRet(MI, BB);
1955   }
1956 }
1957 
1958 //===----------------------------------------------------------------------===//
1959 // AArch64 Lowering private implementation.
1960 //===----------------------------------------------------------------------===//
1961 
1962 //===----------------------------------------------------------------------===//
1963 // Lowering Code
1964 //===----------------------------------------------------------------------===//
1965 
1966 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1967 /// CC
changeIntCCToAArch64CC(ISD::CondCode CC)1968 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1969   switch (CC) {
1970   default:
1971     llvm_unreachable("Unknown condition code!");
1972   case ISD::SETNE:
1973     return AArch64CC::NE;
1974   case ISD::SETEQ:
1975     return AArch64CC::EQ;
1976   case ISD::SETGT:
1977     return AArch64CC::GT;
1978   case ISD::SETGE:
1979     return AArch64CC::GE;
1980   case ISD::SETLT:
1981     return AArch64CC::LT;
1982   case ISD::SETLE:
1983     return AArch64CC::LE;
1984   case ISD::SETUGT:
1985     return AArch64CC::HI;
1986   case ISD::SETUGE:
1987     return AArch64CC::HS;
1988   case ISD::SETULT:
1989     return AArch64CC::LO;
1990   case ISD::SETULE:
1991     return AArch64CC::LS;
1992   }
1993 }
1994 
1995 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
changeFPCCToAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2)1996 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1997                                   AArch64CC::CondCode &CondCode,
1998                                   AArch64CC::CondCode &CondCode2) {
1999   CondCode2 = AArch64CC::AL;
2000   switch (CC) {
2001   default:
2002     llvm_unreachable("Unknown FP condition!");
2003   case ISD::SETEQ:
2004   case ISD::SETOEQ:
2005     CondCode = AArch64CC::EQ;
2006     break;
2007   case ISD::SETGT:
2008   case ISD::SETOGT:
2009     CondCode = AArch64CC::GT;
2010     break;
2011   case ISD::SETGE:
2012   case ISD::SETOGE:
2013     CondCode = AArch64CC::GE;
2014     break;
2015   case ISD::SETOLT:
2016     CondCode = AArch64CC::MI;
2017     break;
2018   case ISD::SETOLE:
2019     CondCode = AArch64CC::LS;
2020     break;
2021   case ISD::SETONE:
2022     CondCode = AArch64CC::MI;
2023     CondCode2 = AArch64CC::GT;
2024     break;
2025   case ISD::SETO:
2026     CondCode = AArch64CC::VC;
2027     break;
2028   case ISD::SETUO:
2029     CondCode = AArch64CC::VS;
2030     break;
2031   case ISD::SETUEQ:
2032     CondCode = AArch64CC::EQ;
2033     CondCode2 = AArch64CC::VS;
2034     break;
2035   case ISD::SETUGT:
2036     CondCode = AArch64CC::HI;
2037     break;
2038   case ISD::SETUGE:
2039     CondCode = AArch64CC::PL;
2040     break;
2041   case ISD::SETLT:
2042   case ISD::SETULT:
2043     CondCode = AArch64CC::LT;
2044     break;
2045   case ISD::SETLE:
2046   case ISD::SETULE:
2047     CondCode = AArch64CC::LE;
2048     break;
2049   case ISD::SETNE:
2050   case ISD::SETUNE:
2051     CondCode = AArch64CC::NE;
2052     break;
2053   }
2054 }
2055 
2056 /// Convert a DAG fp condition code to an AArch64 CC.
2057 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
2058 /// should be AND'ed instead of OR'ed.
changeFPCCToANDAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2)2059 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
2060                                      AArch64CC::CondCode &CondCode,
2061                                      AArch64CC::CondCode &CondCode2) {
2062   CondCode2 = AArch64CC::AL;
2063   switch (CC) {
2064   default:
2065     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2066     assert(CondCode2 == AArch64CC::AL);
2067     break;
2068   case ISD::SETONE:
2069     // (a one b)
2070     // == ((a olt b) || (a ogt b))
2071     // == ((a ord b) && (a une b))
2072     CondCode = AArch64CC::VC;
2073     CondCode2 = AArch64CC::NE;
2074     break;
2075   case ISD::SETUEQ:
2076     // (a ueq b)
2077     // == ((a uno b) || (a oeq b))
2078     // == ((a ule b) && (a uge b))
2079     CondCode = AArch64CC::PL;
2080     CondCode2 = AArch64CC::LE;
2081     break;
2082   }
2083 }
2084 
2085 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
2086 /// CC usable with the vector instructions. Fewer operations are available
2087 /// without a real NZCV register, so we have to use less efficient combinations
2088 /// to get the same effect.
changeVectorFPCCToAArch64CC(ISD::CondCode CC,AArch64CC::CondCode & CondCode,AArch64CC::CondCode & CondCode2,bool & Invert)2089 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
2090                                         AArch64CC::CondCode &CondCode,
2091                                         AArch64CC::CondCode &CondCode2,
2092                                         bool &Invert) {
2093   Invert = false;
2094   switch (CC) {
2095   default:
2096     // Mostly the scalar mappings work fine.
2097     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
2098     break;
2099   case ISD::SETUO:
2100     Invert = true;
2101     LLVM_FALLTHROUGH;
2102   case ISD::SETO:
2103     CondCode = AArch64CC::MI;
2104     CondCode2 = AArch64CC::GE;
2105     break;
2106   case ISD::SETUEQ:
2107   case ISD::SETULT:
2108   case ISD::SETULE:
2109   case ISD::SETUGT:
2110   case ISD::SETUGE:
2111     // All of the compare-mask comparisons are ordered, but we can switch
2112     // between the two by a double inversion. E.g. ULE == !OGT.
2113     Invert = true;
2114     changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
2115                           CondCode, CondCode2);
2116     break;
2117   }
2118 }
2119 
isLegalArithImmed(uint64_t C)2120 static bool isLegalArithImmed(uint64_t C) {
2121   // Matches AArch64DAGToDAGISel::SelectArithImmed().
2122   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
2123   LLVM_DEBUG(dbgs() << "Is imm " << C
2124                     << " legal: " << (IsLegal ? "yes\n" : "no\n"));
2125   return IsLegal;
2126 }
2127 
2128 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
2129 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
2130 // can be set differently by this operation. It comes down to whether
2131 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
2132 // everything is fine. If not then the optimization is wrong. Thus general
2133 // comparisons are only valid if op2 != 0.
2134 //
2135 // So, finally, the only LLVM-native comparisons that don't mention C and V
2136 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
2137 // the absence of information about op2.
isCMN(SDValue Op,ISD::CondCode CC)2138 static bool isCMN(SDValue Op, ISD::CondCode CC) {
2139   return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
2140          (CC == ISD::SETEQ || CC == ISD::SETNE);
2141 }
2142 
emitStrictFPComparison(SDValue LHS,SDValue RHS,const SDLoc & dl,SelectionDAG & DAG,SDValue Chain,bool IsSignaling)2143 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
2144                                       SelectionDAG &DAG, SDValue Chain,
2145                                       bool IsSignaling) {
2146   EVT VT = LHS.getValueType();
2147   assert(VT != MVT::f128);
2148   assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
2149   unsigned Opcode =
2150       IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
2151   return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
2152 }
2153 
emitComparison(SDValue LHS,SDValue RHS,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG)2154 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2155                               const SDLoc &dl, SelectionDAG &DAG) {
2156   EVT VT = LHS.getValueType();
2157   const bool FullFP16 =
2158     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2159 
2160   if (VT.isFloatingPoint()) {
2161     assert(VT != MVT::f128);
2162     if (VT == MVT::f16 && !FullFP16) {
2163       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
2164       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
2165       VT = MVT::f32;
2166     }
2167     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
2168   }
2169 
2170   // The CMP instruction is just an alias for SUBS, and representing it as
2171   // SUBS means that it's possible to get CSE with subtract operations.
2172   // A later phase can perform the optimization of setting the destination
2173   // register to WZR/XZR if it ends up being unused.
2174   unsigned Opcode = AArch64ISD::SUBS;
2175 
2176   if (isCMN(RHS, CC)) {
2177     // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
2178     Opcode = AArch64ISD::ADDS;
2179     RHS = RHS.getOperand(1);
2180   } else if (isCMN(LHS, CC)) {
2181     // As we are looking for EQ/NE compares, the operands can be commuted ; can
2182     // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
2183     Opcode = AArch64ISD::ADDS;
2184     LHS = LHS.getOperand(1);
2185   } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
2186     if (LHS.getOpcode() == ISD::AND) {
2187       // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
2188       // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
2189       // of the signed comparisons.
2190       const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
2191                                            DAG.getVTList(VT, MVT_CC),
2192                                            LHS.getOperand(0),
2193                                            LHS.getOperand(1));
2194       // Replace all users of (and X, Y) with newly generated (ands X, Y)
2195       DAG.ReplaceAllUsesWith(LHS, ANDSNode);
2196       return ANDSNode.getValue(1);
2197     } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
2198       // Use result of ANDS
2199       return LHS.getValue(1);
2200     }
2201   }
2202 
2203   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
2204       .getValue(1);
2205 }
2206 
2207 /// \defgroup AArch64CCMP CMP;CCMP matching
2208 ///
2209 /// These functions deal with the formation of CMP;CCMP;... sequences.
2210 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
2211 /// a comparison. They set the NZCV flags to a predefined value if their
2212 /// predicate is false. This allows to express arbitrary conjunctions, for
2213 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
2214 /// expressed as:
2215 ///   cmp A
2216 ///   ccmp B, inv(CB), CA
2217 ///   check for CB flags
2218 ///
2219 /// This naturally lets us implement chains of AND operations with SETCC
2220 /// operands. And we can even implement some other situations by transforming
2221 /// them:
2222 ///   - We can implement (NEG SETCC) i.e. negating a single comparison by
2223 ///     negating the flags used in a CCMP/FCCMP operations.
2224 ///   - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
2225 ///     by negating the flags we test for afterwards. i.e.
2226 ///     NEG (CMP CCMP CCCMP ...) can be implemented.
2227 ///   - Note that we can only ever negate all previously processed results.
2228 ///     What we can not implement by flipping the flags to test is a negation
2229 ///     of two sub-trees (because the negation affects all sub-trees emitted so
2230 ///     far, so the 2nd sub-tree we emit would also affect the first).
2231 /// With those tools we can implement some OR operations:
2232 ///   - (OR (SETCC A) (SETCC B)) can be implemented via:
2233 ///     NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
2234 ///   - After transforming OR to NEG/AND combinations we may be able to use NEG
2235 ///     elimination rules from earlier to implement the whole thing as a
2236 ///     CCMP/FCCMP chain.
2237 ///
2238 /// As complete example:
2239 ///     or (or (setCA (cmp A)) (setCB (cmp B)))
2240 ///        (and (setCC (cmp C)) (setCD (cmp D)))"
2241 /// can be reassociated to:
2242 ///     or (and (setCC (cmp C)) setCD (cmp D))
2243 //         (or (setCA (cmp A)) (setCB (cmp B)))
2244 /// can be transformed to:
2245 ///     not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
2246 ///              (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
2247 /// which can be implemented as:
2248 ///   cmp C
2249 ///   ccmp D, inv(CD), CC
2250 ///   ccmp A, CA, inv(CD)
2251 ///   ccmp B, CB, inv(CA)
2252 ///   check for CB flags
2253 ///
2254 /// A counterexample is "or (and A B) (and C D)" which translates to
2255 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2256 /// can only implement 1 of the inner (not) operations, but not both!
2257 /// @{
2258 
2259 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
emitConditionalComparison(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue CCOp,AArch64CC::CondCode Predicate,AArch64CC::CondCode OutCC,const SDLoc & DL,SelectionDAG & DAG)2260 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2261                                          ISD::CondCode CC, SDValue CCOp,
2262                                          AArch64CC::CondCode Predicate,
2263                                          AArch64CC::CondCode OutCC,
2264                                          const SDLoc &DL, SelectionDAG &DAG) {
2265   unsigned Opcode = 0;
2266   const bool FullFP16 =
2267     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2268 
2269   if (LHS.getValueType().isFloatingPoint()) {
2270     assert(LHS.getValueType() != MVT::f128);
2271     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2272       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2273       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2274     }
2275     Opcode = AArch64ISD::FCCMP;
2276   } else if (RHS.getOpcode() == ISD::SUB) {
2277     SDValue SubOp0 = RHS.getOperand(0);
2278     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2279       // See emitComparison() on why we can only do this for SETEQ and SETNE.
2280       Opcode = AArch64ISD::CCMN;
2281       RHS = RHS.getOperand(1);
2282     }
2283   }
2284   if (Opcode == 0)
2285     Opcode = AArch64ISD::CCMP;
2286 
2287   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2288   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2289   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2290   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2291   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2292 }
2293 
2294 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2295 /// expressed as a conjunction. See \ref AArch64CCMP.
2296 /// \param CanNegate    Set to true if we can negate the whole sub-tree just by
2297 ///                     changing the conditions on the SETCC tests.
2298 ///                     (this means we can call emitConjunctionRec() with
2299 ///                      Negate==true on this sub-tree)
2300 /// \param MustBeFirst  Set to true if this subtree needs to be negated and we
2301 ///                     cannot do the negation naturally. We are required to
2302 ///                     emit the subtree first in this case.
2303 /// \param WillNegate   Is true if are called when the result of this
2304 ///                     subexpression must be negated. This happens when the
2305 ///                     outer expression is an OR. We can use this fact to know
2306 ///                     that we have a double negation (or (or ...) ...) that
2307 ///                     can be implemented for free.
canEmitConjunction(const SDValue Val,bool & CanNegate,bool & MustBeFirst,bool WillNegate,unsigned Depth=0)2308 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2309                                bool &MustBeFirst, bool WillNegate,
2310                                unsigned Depth = 0) {
2311   if (!Val.hasOneUse())
2312     return false;
2313   unsigned Opcode = Val->getOpcode();
2314   if (Opcode == ISD::SETCC) {
2315     if (Val->getOperand(0).getValueType() == MVT::f128)
2316       return false;
2317     CanNegate = true;
2318     MustBeFirst = false;
2319     return true;
2320   }
2321   // Protect against exponential runtime and stack overflow.
2322   if (Depth > 6)
2323     return false;
2324   if (Opcode == ISD::AND || Opcode == ISD::OR) {
2325     bool IsOR = Opcode == ISD::OR;
2326     SDValue O0 = Val->getOperand(0);
2327     SDValue O1 = Val->getOperand(1);
2328     bool CanNegateL;
2329     bool MustBeFirstL;
2330     if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2331       return false;
2332     bool CanNegateR;
2333     bool MustBeFirstR;
2334     if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2335       return false;
2336 
2337     if (MustBeFirstL && MustBeFirstR)
2338       return false;
2339 
2340     if (IsOR) {
2341       // For an OR expression we need to be able to naturally negate at least
2342       // one side or we cannot do the transformation at all.
2343       if (!CanNegateL && !CanNegateR)
2344         return false;
2345       // If we the result of the OR will be negated and we can naturally negate
2346       // the leafs, then this sub-tree as a whole negates naturally.
2347       CanNegate = WillNegate && CanNegateL && CanNegateR;
2348       // If we cannot naturally negate the whole sub-tree, then this must be
2349       // emitted first.
2350       MustBeFirst = !CanNegate;
2351     } else {
2352       assert(Opcode == ISD::AND && "Must be OR or AND");
2353       // We cannot naturally negate an AND operation.
2354       CanNegate = false;
2355       MustBeFirst = MustBeFirstL || MustBeFirstR;
2356     }
2357     return true;
2358   }
2359   return false;
2360 }
2361 
2362 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2363 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2364 /// Tries to transform the given i1 producing node @p Val to a series compare
2365 /// and conditional compare operations. @returns an NZCV flags producing node
2366 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2367 /// transformation was not possible.
2368 /// \p Negate is true if we want this sub-tree being negated just by changing
2369 /// SETCC conditions.
emitConjunctionRec(SelectionDAG & DAG,SDValue Val,AArch64CC::CondCode & OutCC,bool Negate,SDValue CCOp,AArch64CC::CondCode Predicate)2370 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2371     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2372     AArch64CC::CondCode Predicate) {
2373   // We're at a tree leaf, produce a conditional comparison operation.
2374   unsigned Opcode = Val->getOpcode();
2375   if (Opcode == ISD::SETCC) {
2376     SDValue LHS = Val->getOperand(0);
2377     SDValue RHS = Val->getOperand(1);
2378     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2379     bool isInteger = LHS.getValueType().isInteger();
2380     if (Negate)
2381       CC = getSetCCInverse(CC, LHS.getValueType());
2382     SDLoc DL(Val);
2383     // Determine OutCC and handle FP special case.
2384     if (isInteger) {
2385       OutCC = changeIntCCToAArch64CC(CC);
2386     } else {
2387       assert(LHS.getValueType().isFloatingPoint());
2388       AArch64CC::CondCode ExtraCC;
2389       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2390       // Some floating point conditions can't be tested with a single condition
2391       // code. Construct an additional comparison in this case.
2392       if (ExtraCC != AArch64CC::AL) {
2393         SDValue ExtraCmp;
2394         if (!CCOp.getNode())
2395           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2396         else
2397           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2398                                                ExtraCC, DL, DAG);
2399         CCOp = ExtraCmp;
2400         Predicate = ExtraCC;
2401       }
2402     }
2403 
2404     // Produce a normal comparison if we are first in the chain
2405     if (!CCOp)
2406       return emitComparison(LHS, RHS, CC, DL, DAG);
2407     // Otherwise produce a ccmp.
2408     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2409                                      DAG);
2410   }
2411   assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2412 
2413   bool IsOR = Opcode == ISD::OR;
2414 
2415   SDValue LHS = Val->getOperand(0);
2416   bool CanNegateL;
2417   bool MustBeFirstL;
2418   bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2419   assert(ValidL && "Valid conjunction/disjunction tree");
2420   (void)ValidL;
2421 
2422   SDValue RHS = Val->getOperand(1);
2423   bool CanNegateR;
2424   bool MustBeFirstR;
2425   bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2426   assert(ValidR && "Valid conjunction/disjunction tree");
2427   (void)ValidR;
2428 
2429   // Swap sub-tree that must come first to the right side.
2430   if (MustBeFirstL) {
2431     assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2432     std::swap(LHS, RHS);
2433     std::swap(CanNegateL, CanNegateR);
2434     std::swap(MustBeFirstL, MustBeFirstR);
2435   }
2436 
2437   bool NegateR;
2438   bool NegateAfterR;
2439   bool NegateL;
2440   bool NegateAfterAll;
2441   if (Opcode == ISD::OR) {
2442     // Swap the sub-tree that we can negate naturally to the left.
2443     if (!CanNegateL) {
2444       assert(CanNegateR && "at least one side must be negatable");
2445       assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2446       assert(!Negate);
2447       std::swap(LHS, RHS);
2448       NegateR = false;
2449       NegateAfterR = true;
2450     } else {
2451       // Negate the left sub-tree if possible, otherwise negate the result.
2452       NegateR = CanNegateR;
2453       NegateAfterR = !CanNegateR;
2454     }
2455     NegateL = true;
2456     NegateAfterAll = !Negate;
2457   } else {
2458     assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2459     assert(!Negate && "Valid conjunction/disjunction tree");
2460 
2461     NegateL = false;
2462     NegateR = false;
2463     NegateAfterR = false;
2464     NegateAfterAll = false;
2465   }
2466 
2467   // Emit sub-trees.
2468   AArch64CC::CondCode RHSCC;
2469   SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2470   if (NegateAfterR)
2471     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2472   SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2473   if (NegateAfterAll)
2474     OutCC = AArch64CC::getInvertedCondCode(OutCC);
2475   return CmpL;
2476 }
2477 
2478 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2479 /// In some cases this is even possible with OR operations in the expression.
2480 /// See \ref AArch64CCMP.
2481 /// \see emitConjunctionRec().
emitConjunction(SelectionDAG & DAG,SDValue Val,AArch64CC::CondCode & OutCC)2482 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2483                                AArch64CC::CondCode &OutCC) {
2484   bool DummyCanNegate;
2485   bool DummyMustBeFirst;
2486   if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2487     return SDValue();
2488 
2489   return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2490 }
2491 
2492 /// @}
2493 
2494 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2495 /// extension operations.
getCmpOperandFoldingProfit(SDValue Op)2496 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2497   auto isSupportedExtend = [&](SDValue V) {
2498     if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2499       return true;
2500 
2501     if (V.getOpcode() == ISD::AND)
2502       if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2503         uint64_t Mask = MaskCst->getZExtValue();
2504         return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2505       }
2506 
2507     return false;
2508   };
2509 
2510   if (!Op.hasOneUse())
2511     return 0;
2512 
2513   if (isSupportedExtend(Op))
2514     return 1;
2515 
2516   unsigned Opc = Op.getOpcode();
2517   if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2518     if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2519       uint64_t Shift = ShiftCst->getZExtValue();
2520       if (isSupportedExtend(Op.getOperand(0)))
2521         return (Shift <= 4) ? 2 : 1;
2522       EVT VT = Op.getValueType();
2523       if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2524         return 1;
2525     }
2526 
2527   return 0;
2528 }
2529 
getAArch64Cmp(SDValue LHS,SDValue RHS,ISD::CondCode CC,SDValue & AArch64cc,SelectionDAG & DAG,const SDLoc & dl)2530 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2531                              SDValue &AArch64cc, SelectionDAG &DAG,
2532                              const SDLoc &dl) {
2533   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2534     EVT VT = RHS.getValueType();
2535     uint64_t C = RHSC->getZExtValue();
2536     if (!isLegalArithImmed(C)) {
2537       // Constant does not fit, try adjusting it by one?
2538       switch (CC) {
2539       default:
2540         break;
2541       case ISD::SETLT:
2542       case ISD::SETGE:
2543         if ((VT == MVT::i32 && C != 0x80000000 &&
2544              isLegalArithImmed((uint32_t)(C - 1))) ||
2545             (VT == MVT::i64 && C != 0x80000000ULL &&
2546              isLegalArithImmed(C - 1ULL))) {
2547           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2548           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2549           RHS = DAG.getConstant(C, dl, VT);
2550         }
2551         break;
2552       case ISD::SETULT:
2553       case ISD::SETUGE:
2554         if ((VT == MVT::i32 && C != 0 &&
2555              isLegalArithImmed((uint32_t)(C - 1))) ||
2556             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2557           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2558           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2559           RHS = DAG.getConstant(C, dl, VT);
2560         }
2561         break;
2562       case ISD::SETLE:
2563       case ISD::SETGT:
2564         if ((VT == MVT::i32 && C != INT32_MAX &&
2565              isLegalArithImmed((uint32_t)(C + 1))) ||
2566             (VT == MVT::i64 && C != INT64_MAX &&
2567              isLegalArithImmed(C + 1ULL))) {
2568           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2569           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2570           RHS = DAG.getConstant(C, dl, VT);
2571         }
2572         break;
2573       case ISD::SETULE:
2574       case ISD::SETUGT:
2575         if ((VT == MVT::i32 && C != UINT32_MAX &&
2576              isLegalArithImmed((uint32_t)(C + 1))) ||
2577             (VT == MVT::i64 && C != UINT64_MAX &&
2578              isLegalArithImmed(C + 1ULL))) {
2579           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2580           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2581           RHS = DAG.getConstant(C, dl, VT);
2582         }
2583         break;
2584       }
2585     }
2586   }
2587 
2588   // Comparisons are canonicalized so that the RHS operand is simpler than the
2589   // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2590   // can fold some shift+extend operations on the RHS operand, so swap the
2591   // operands if that can be done.
2592   //
2593   // For example:
2594   //    lsl     w13, w11, #1
2595   //    cmp     w13, w12
2596   // can be turned into:
2597   //    cmp     w12, w11, lsl #1
2598   if (!isa<ConstantSDNode>(RHS) ||
2599       !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2600     SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2601 
2602     if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2603       std::swap(LHS, RHS);
2604       CC = ISD::getSetCCSwappedOperands(CC);
2605     }
2606   }
2607 
2608   SDValue Cmp;
2609   AArch64CC::CondCode AArch64CC;
2610   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2611     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2612 
2613     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2614     // For the i8 operand, the largest immediate is 255, so this can be easily
2615     // encoded in the compare instruction. For the i16 operand, however, the
2616     // largest immediate cannot be encoded in the compare.
2617     // Therefore, use a sign extending load and cmn to avoid materializing the
2618     // -1 constant. For example,
2619     // movz w1, #65535
2620     // ldrh w0, [x0, #0]
2621     // cmp w0, w1
2622     // >
2623     // ldrsh w0, [x0, #0]
2624     // cmn w0, #1
2625     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2626     // if and only if (sext LHS) == (sext RHS). The checks are in place to
2627     // ensure both the LHS and RHS are truly zero extended and to make sure the
2628     // transformation is profitable.
2629     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2630         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2631         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2632         LHS.getNode()->hasNUsesOfValue(1, 0)) {
2633       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2634       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2635         SDValue SExt =
2636             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2637                         DAG.getValueType(MVT::i16));
2638         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2639                                                    RHS.getValueType()),
2640                              CC, dl, DAG);
2641         AArch64CC = changeIntCCToAArch64CC(CC);
2642       }
2643     }
2644 
2645     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2646       if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2647         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2648           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2649       }
2650     }
2651   }
2652 
2653   if (!Cmp) {
2654     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2655     AArch64CC = changeIntCCToAArch64CC(CC);
2656   }
2657   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2658   return Cmp;
2659 }
2660 
2661 static std::pair<SDValue, SDValue>
getAArch64XALUOOp(AArch64CC::CondCode & CC,SDValue Op,SelectionDAG & DAG)2662 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2663   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2664          "Unsupported value type");
2665   SDValue Value, Overflow;
2666   SDLoc DL(Op);
2667   SDValue LHS = Op.getOperand(0);
2668   SDValue RHS = Op.getOperand(1);
2669   unsigned Opc = 0;
2670   switch (Op.getOpcode()) {
2671   default:
2672     llvm_unreachable("Unknown overflow instruction!");
2673   case ISD::SADDO:
2674     Opc = AArch64ISD::ADDS;
2675     CC = AArch64CC::VS;
2676     break;
2677   case ISD::UADDO:
2678     Opc = AArch64ISD::ADDS;
2679     CC = AArch64CC::HS;
2680     break;
2681   case ISD::SSUBO:
2682     Opc = AArch64ISD::SUBS;
2683     CC = AArch64CC::VS;
2684     break;
2685   case ISD::USUBO:
2686     Opc = AArch64ISD::SUBS;
2687     CC = AArch64CC::LO;
2688     break;
2689   // Multiply needs a little bit extra work.
2690   case ISD::SMULO:
2691   case ISD::UMULO: {
2692     CC = AArch64CC::NE;
2693     bool IsSigned = Op.getOpcode() == ISD::SMULO;
2694     if (Op.getValueType() == MVT::i32) {
2695       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2696       // For a 32 bit multiply with overflow check we want the instruction
2697       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2698       // need to generate the following pattern:
2699       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2700       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2701       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2702       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2703       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2704                                 DAG.getConstant(0, DL, MVT::i64));
2705       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2706       // operation. We need to clear out the upper 32 bits, because we used a
2707       // widening multiply that wrote all 64 bits. In the end this should be a
2708       // noop.
2709       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2710       if (IsSigned) {
2711         // The signed overflow check requires more than just a simple check for
2712         // any bit set in the upper 32 bits of the result. These bits could be
2713         // just the sign bits of a negative number. To perform the overflow
2714         // check we have to arithmetic shift right the 32nd bit of the result by
2715         // 31 bits. Then we compare the result to the upper 32 bits.
2716         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2717                                         DAG.getConstant(32, DL, MVT::i64));
2718         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2719         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2720                                         DAG.getConstant(31, DL, MVT::i64));
2721         // It is important that LowerBits is last, otherwise the arithmetic
2722         // shift will not be folded into the compare (SUBS).
2723         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2724         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2725                        .getValue(1);
2726       } else {
2727         // The overflow check for unsigned multiply is easy. We only need to
2728         // check if any of the upper 32 bits are set. This can be done with a
2729         // CMP (shifted register). For that we need to generate the following
2730         // pattern:
2731         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2732         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2733                                         DAG.getConstant(32, DL, MVT::i64));
2734         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2735         Overflow =
2736             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2737                         DAG.getConstant(0, DL, MVT::i64),
2738                         UpperBits).getValue(1);
2739       }
2740       break;
2741     }
2742     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2743     // For the 64 bit multiply
2744     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2745     if (IsSigned) {
2746       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2747       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2748                                       DAG.getConstant(63, DL, MVT::i64));
2749       // It is important that LowerBits is last, otherwise the arithmetic
2750       // shift will not be folded into the compare (SUBS).
2751       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2752       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2753                      .getValue(1);
2754     } else {
2755       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2756       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2757       Overflow =
2758           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2759                       DAG.getConstant(0, DL, MVT::i64),
2760                       UpperBits).getValue(1);
2761     }
2762     break;
2763   }
2764   } // switch (...)
2765 
2766   if (Opc) {
2767     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2768 
2769     // Emit the AArch64 operation with overflow check.
2770     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2771     Overflow = Value.getValue(1);
2772   }
2773   return std::make_pair(Value, Overflow);
2774 }
2775 
LowerF128Call(SDValue Op,SelectionDAG & DAG,RTLIB::Libcall Call) const2776 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2777                                              RTLIB::Libcall Call) const {
2778   bool IsStrict = Op->isStrictFPOpcode();
2779   unsigned Offset = IsStrict ? 1 : 0;
2780   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2781   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2782   MakeLibCallOptions CallOptions;
2783   SDValue Result;
2784   SDLoc dl(Op);
2785   std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2786                                         CallOptions, dl, Chain);
2787   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2788 }
2789 
LowerXOR(SDValue Op,SelectionDAG & DAG) const2790 SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
2791   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
2792     return LowerToScalableOp(Op, DAG);
2793 
2794   SDValue Sel = Op.getOperand(0);
2795   SDValue Other = Op.getOperand(1);
2796   SDLoc dl(Sel);
2797 
2798   // If the operand is an overflow checking operation, invert the condition
2799   // code and kill the Not operation. I.e., transform:
2800   // (xor (overflow_op_bool, 1))
2801   //   -->
2802   // (csel 1, 0, invert(cc), overflow_op_bool)
2803   // ... which later gets transformed to just a cset instruction with an
2804   // inverted condition code, rather than a cset + eor sequence.
2805   if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2806     // Only lower legal XALUO ops.
2807     if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2808       return SDValue();
2809 
2810     SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2811     SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2812     AArch64CC::CondCode CC;
2813     SDValue Value, Overflow;
2814     std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2815     SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2816     return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2817                        CCVal, Overflow);
2818   }
2819   // If neither operand is a SELECT_CC, give up.
2820   if (Sel.getOpcode() != ISD::SELECT_CC)
2821     std::swap(Sel, Other);
2822   if (Sel.getOpcode() != ISD::SELECT_CC)
2823     return Op;
2824 
2825   // The folding we want to perform is:
2826   // (xor x, (select_cc a, b, cc, 0, -1) )
2827   //   -->
2828   // (csel x, (xor x, -1), cc ...)
2829   //
2830   // The latter will get matched to a CSINV instruction.
2831 
2832   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2833   SDValue LHS = Sel.getOperand(0);
2834   SDValue RHS = Sel.getOperand(1);
2835   SDValue TVal = Sel.getOperand(2);
2836   SDValue FVal = Sel.getOperand(3);
2837 
2838   // FIXME: This could be generalized to non-integer comparisons.
2839   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2840     return Op;
2841 
2842   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2843   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2844 
2845   // The values aren't constants, this isn't the pattern we're looking for.
2846   if (!CFVal || !CTVal)
2847     return Op;
2848 
2849   // We can commute the SELECT_CC by inverting the condition.  This
2850   // might be needed to make this fit into a CSINV pattern.
2851   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2852     std::swap(TVal, FVal);
2853     std::swap(CTVal, CFVal);
2854     CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2855   }
2856 
2857   // If the constants line up, perform the transform!
2858   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2859     SDValue CCVal;
2860     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2861 
2862     FVal = Other;
2863     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2864                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2865 
2866     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2867                        CCVal, Cmp);
2868   }
2869 
2870   return Op;
2871 }
2872 
LowerADDC_ADDE_SUBC_SUBE(SDValue Op,SelectionDAG & DAG)2873 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2874   EVT VT = Op.getValueType();
2875 
2876   // Let legalize expand this if it isn't a legal type yet.
2877   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2878     return SDValue();
2879 
2880   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2881 
2882   unsigned Opc;
2883   bool ExtraOp = false;
2884   switch (Op.getOpcode()) {
2885   default:
2886     llvm_unreachable("Invalid code");
2887   case ISD::ADDC:
2888     Opc = AArch64ISD::ADDS;
2889     break;
2890   case ISD::SUBC:
2891     Opc = AArch64ISD::SUBS;
2892     break;
2893   case ISD::ADDE:
2894     Opc = AArch64ISD::ADCS;
2895     ExtraOp = true;
2896     break;
2897   case ISD::SUBE:
2898     Opc = AArch64ISD::SBCS;
2899     ExtraOp = true;
2900     break;
2901   }
2902 
2903   if (!ExtraOp)
2904     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2905   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2906                      Op.getOperand(2));
2907 }
2908 
LowerXALUO(SDValue Op,SelectionDAG & DAG)2909 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2910   // Let legalize expand this if it isn't a legal type yet.
2911   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2912     return SDValue();
2913 
2914   SDLoc dl(Op);
2915   AArch64CC::CondCode CC;
2916   // The actual operation that sets the overflow or carry flag.
2917   SDValue Value, Overflow;
2918   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2919 
2920   // We use 0 and 1 as false and true values.
2921   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2922   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2923 
2924   // We use an inverted condition, because the conditional select is inverted
2925   // too. This will allow it to be selected to a single instruction:
2926   // CSINC Wd, WZR, WZR, invert(cond).
2927   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2928   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2929                          CCVal, Overflow);
2930 
2931   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2932   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2933 }
2934 
2935 // Prefetch operands are:
2936 // 1: Address to prefetch
2937 // 2: bool isWrite
2938 // 3: int locality (0 = no locality ... 3 = extreme locality)
2939 // 4: bool isDataCache
LowerPREFETCH(SDValue Op,SelectionDAG & DAG)2940 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2941   SDLoc DL(Op);
2942   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2943   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2944   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2945 
2946   bool IsStream = !Locality;
2947   // When the locality number is set
2948   if (Locality) {
2949     // The front-end should have filtered out the out-of-range values
2950     assert(Locality <= 3 && "Prefetch locality out-of-range");
2951     // The locality degree is the opposite of the cache speed.
2952     // Put the number the other way around.
2953     // The encoding starts at 0 for level 1
2954     Locality = 3 - Locality;
2955   }
2956 
2957   // built the mask value encoding the expected behavior.
2958   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2959                    (!IsData << 3) |     // IsDataCache bit
2960                    (Locality << 1) |    // Cache level bits
2961                    (unsigned)IsStream;  // Stream bit
2962   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2963                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2964 }
2965 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const2966 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2967                                               SelectionDAG &DAG) const {
2968   if (Op.getValueType().isScalableVector())
2969     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
2970 
2971   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2972 
2973   RTLIB::Libcall LC;
2974   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2975 
2976   return LowerF128Call(Op, DAG, LC);
2977 }
2978 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const2979 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2980                                              SelectionDAG &DAG) const {
2981   if (Op.getValueType().isScalableVector())
2982     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
2983 
2984   bool IsStrict = Op->isStrictFPOpcode();
2985   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2986   EVT SrcVT = SrcVal.getValueType();
2987 
2988   if (SrcVT != MVT::f128) {
2989     // Expand cases where the input is a vector bigger than NEON.
2990     if (useSVEForFixedLengthVectorVT(SrcVT))
2991       return SDValue();
2992 
2993     // It's legal except when f128 is involved
2994     return Op;
2995   }
2996 
2997   RTLIB::Libcall LC;
2998   LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2999 
3000   // FP_ROUND node has a second operand indicating whether it is known to be
3001   // precise. That doesn't take part in the LibCall so we can't directly use
3002   // LowerF128Call.
3003   MakeLibCallOptions CallOptions;
3004   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3005   SDValue Result;
3006   SDLoc dl(Op);
3007   std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
3008                                         CallOptions, dl, Chain);
3009   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
3010 }
3011 
LowerVectorFP_TO_INT(SDValue Op,SelectionDAG & DAG) const3012 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
3013                                                     SelectionDAG &DAG) const {
3014   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3015   // Any additional optimization in this function should be recorded
3016   // in the cost tables.
3017   EVT InVT = Op.getOperand(0).getValueType();
3018   EVT VT = Op.getValueType();
3019 
3020   if (VT.isScalableVector()) {
3021     unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
3022                           ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
3023                           : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
3024     return LowerToPredicatedOp(Op, DAG, Opcode);
3025   }
3026 
3027   unsigned NumElts = InVT.getVectorNumElements();
3028 
3029   // f16 conversions are promoted to f32 when full fp16 is not supported.
3030   if (InVT.getVectorElementType() == MVT::f16 &&
3031       !Subtarget->hasFullFP16()) {
3032     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
3033     SDLoc dl(Op);
3034     return DAG.getNode(
3035         Op.getOpcode(), dl, Op.getValueType(),
3036         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
3037   }
3038 
3039   uint64_t VTSize = VT.getFixedSizeInBits();
3040   uint64_t InVTSize = InVT.getFixedSizeInBits();
3041   if (VTSize < InVTSize) {
3042     SDLoc dl(Op);
3043     SDValue Cv =
3044         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
3045                     Op.getOperand(0));
3046     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
3047   }
3048 
3049   if (VTSize > InVTSize) {
3050     SDLoc dl(Op);
3051     MVT ExtVT =
3052         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
3053                          VT.getVectorNumElements());
3054     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
3055     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
3056   }
3057 
3058   // Type changing conversions are illegal.
3059   return Op;
3060 }
3061 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const3062 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
3063                                               SelectionDAG &DAG) const {
3064   bool IsStrict = Op->isStrictFPOpcode();
3065   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3066 
3067   if (SrcVal.getValueType().isVector())
3068     return LowerVectorFP_TO_INT(Op, DAG);
3069 
3070   // f16 conversions are promoted to f32 when full fp16 is not supported.
3071   if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
3072     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3073     SDLoc dl(Op);
3074     return DAG.getNode(
3075         Op.getOpcode(), dl, Op.getValueType(),
3076         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
3077   }
3078 
3079   if (SrcVal.getValueType() != MVT::f128) {
3080     // It's legal except when f128 is involved
3081     return Op;
3082   }
3083 
3084   RTLIB::Libcall LC;
3085   if (Op.getOpcode() == ISD::FP_TO_SINT ||
3086       Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
3087     LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
3088   else
3089     LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
3090 
3091   return LowerF128Call(Op, DAG, LC);
3092 }
3093 
LowerVectorINT_TO_FP(SDValue Op,SelectionDAG & DAG) const3094 SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
3095                                                     SelectionDAG &DAG) const {
3096   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
3097   // Any additional optimization in this function should be recorded
3098   // in the cost tables.
3099   EVT VT = Op.getValueType();
3100   SDLoc dl(Op);
3101   SDValue In = Op.getOperand(0);
3102   EVT InVT = In.getValueType();
3103 
3104   if (VT.isScalableVector()) {
3105     unsigned Opcode = Op.getOpcode() == ISD::UINT_TO_FP
3106                           ? AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU
3107                           : AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU;
3108     return LowerToPredicatedOp(Op, DAG, Opcode);
3109   }
3110 
3111   uint64_t VTSize = VT.getFixedSizeInBits();
3112   uint64_t InVTSize = InVT.getFixedSizeInBits();
3113   if (VTSize < InVTSize) {
3114     MVT CastVT =
3115         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
3116                          InVT.getVectorNumElements());
3117     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
3118     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
3119   }
3120 
3121   if (VTSize > InVTSize) {
3122     unsigned CastOpc =
3123         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3124     EVT CastVT = VT.changeVectorElementTypeToInteger();
3125     In = DAG.getNode(CastOpc, dl, CastVT, In);
3126     return DAG.getNode(Op.getOpcode(), dl, VT, In);
3127   }
3128 
3129   return Op;
3130 }
3131 
LowerINT_TO_FP(SDValue Op,SelectionDAG & DAG) const3132 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
3133                                             SelectionDAG &DAG) const {
3134   if (Op.getValueType().isVector())
3135     return LowerVectorINT_TO_FP(Op, DAG);
3136 
3137   bool IsStrict = Op->isStrictFPOpcode();
3138   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
3139 
3140   // f16 conversions are promoted to f32 when full fp16 is not supported.
3141   if (Op.getValueType() == MVT::f16 &&
3142       !Subtarget->hasFullFP16()) {
3143     assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
3144     SDLoc dl(Op);
3145     return DAG.getNode(
3146         ISD::FP_ROUND, dl, MVT::f16,
3147         DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
3148         DAG.getIntPtrConstant(0, dl));
3149   }
3150 
3151   // i128 conversions are libcalls.
3152   if (SrcVal.getValueType() == MVT::i128)
3153     return SDValue();
3154 
3155   // Other conversions are legal, unless it's to the completely software-based
3156   // fp128.
3157   if (Op.getValueType() != MVT::f128)
3158     return Op;
3159 
3160   RTLIB::Libcall LC;
3161   if (Op.getOpcode() == ISD::SINT_TO_FP ||
3162       Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
3163     LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
3164   else
3165     LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
3166 
3167   return LowerF128Call(Op, DAG, LC);
3168 }
3169 
LowerFSINCOS(SDValue Op,SelectionDAG & DAG) const3170 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
3171                                             SelectionDAG &DAG) const {
3172   // For iOS, we want to call an alternative entry point: __sincos_stret,
3173   // which returns the values in two S / D registers.
3174   SDLoc dl(Op);
3175   SDValue Arg = Op.getOperand(0);
3176   EVT ArgVT = Arg.getValueType();
3177   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3178 
3179   ArgListTy Args;
3180   ArgListEntry Entry;
3181 
3182   Entry.Node = Arg;
3183   Entry.Ty = ArgTy;
3184   Entry.IsSExt = false;
3185   Entry.IsZExt = false;
3186   Args.push_back(Entry);
3187 
3188   RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
3189                                         : RTLIB::SINCOS_STRET_F32;
3190   const char *LibcallName = getLibcallName(LC);
3191   SDValue Callee =
3192       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
3193 
3194   StructType *RetTy = StructType::get(ArgTy, ArgTy);
3195   TargetLowering::CallLoweringInfo CLI(DAG);
3196   CLI.setDebugLoc(dl)
3197       .setChain(DAG.getEntryNode())
3198       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
3199 
3200   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3201   return CallResult.first;
3202 }
3203 
LowerBITCAST(SDValue Op,SelectionDAG & DAG)3204 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
3205   EVT OpVT = Op.getValueType();
3206   if (OpVT != MVT::f16 && OpVT != MVT::bf16)
3207     return SDValue();
3208 
3209   assert(Op.getOperand(0).getValueType() == MVT::i16);
3210   SDLoc DL(Op);
3211 
3212   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
3213   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
3214   return SDValue(
3215       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
3216                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
3217       0);
3218 }
3219 
getExtensionTo64Bits(const EVT & OrigVT)3220 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
3221   if (OrigVT.getSizeInBits() >= 64)
3222     return OrigVT;
3223 
3224   assert(OrigVT.isSimple() && "Expecting a simple value type");
3225 
3226   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
3227   switch (OrigSimpleTy) {
3228   default: llvm_unreachable("Unexpected Vector Type");
3229   case MVT::v2i8:
3230   case MVT::v2i16:
3231      return MVT::v2i32;
3232   case MVT::v4i8:
3233     return  MVT::v4i16;
3234   }
3235 }
3236 
addRequiredExtensionForVectorMULL(SDValue N,SelectionDAG & DAG,const EVT & OrigTy,const EVT & ExtTy,unsigned ExtOpcode)3237 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
3238                                                  const EVT &OrigTy,
3239                                                  const EVT &ExtTy,
3240                                                  unsigned ExtOpcode) {
3241   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
3242   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
3243   // 64-bits we need to insert a new extension so that it will be 64-bits.
3244   assert(ExtTy.is128BitVector() && "Unexpected extension size");
3245   if (OrigTy.getSizeInBits() >= 64)
3246     return N;
3247 
3248   // Must extend size to at least 64 bits to be used as an operand for VMULL.
3249   EVT NewVT = getExtensionTo64Bits(OrigTy);
3250 
3251   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
3252 }
3253 
isExtendedBUILD_VECTOR(SDNode * N,SelectionDAG & DAG,bool isSigned)3254 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
3255                                    bool isSigned) {
3256   EVT VT = N->getValueType(0);
3257 
3258   if (N->getOpcode() != ISD::BUILD_VECTOR)
3259     return false;
3260 
3261   for (const SDValue &Elt : N->op_values()) {
3262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
3263       unsigned EltSize = VT.getScalarSizeInBits();
3264       unsigned HalfSize = EltSize / 2;
3265       if (isSigned) {
3266         if (!isIntN(HalfSize, C->getSExtValue()))
3267           return false;
3268       } else {
3269         if (!isUIntN(HalfSize, C->getZExtValue()))
3270           return false;
3271       }
3272       continue;
3273     }
3274     return false;
3275   }
3276 
3277   return true;
3278 }
3279 
skipExtensionForVectorMULL(SDNode * N,SelectionDAG & DAG)3280 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
3281   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
3282     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
3283                                              N->getOperand(0)->getValueType(0),
3284                                              N->getValueType(0),
3285                                              N->getOpcode());
3286 
3287   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3288   EVT VT = N->getValueType(0);
3289   SDLoc dl(N);
3290   unsigned EltSize = VT.getScalarSizeInBits() / 2;
3291   unsigned NumElts = VT.getVectorNumElements();
3292   MVT TruncVT = MVT::getIntegerVT(EltSize);
3293   SmallVector<SDValue, 8> Ops;
3294   for (unsigned i = 0; i != NumElts; ++i) {
3295     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3296     const APInt &CInt = C->getAPIntValue();
3297     // Element types smaller than 32 bits are not legal, so use i32 elements.
3298     // The values are implicitly truncated so sext vs. zext doesn't matter.
3299     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3300   }
3301   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3302 }
3303 
isSignExtended(SDNode * N,SelectionDAG & DAG)3304 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3305   return N->getOpcode() == ISD::SIGN_EXTEND ||
3306          isExtendedBUILD_VECTOR(N, DAG, true);
3307 }
3308 
isZeroExtended(SDNode * N,SelectionDAG & DAG)3309 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3310   return N->getOpcode() == ISD::ZERO_EXTEND ||
3311          isExtendedBUILD_VECTOR(N, DAG, false);
3312 }
3313 
isAddSubSExt(SDNode * N,SelectionDAG & DAG)3314 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3315   unsigned Opcode = N->getOpcode();
3316   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3317     SDNode *N0 = N->getOperand(0).getNode();
3318     SDNode *N1 = N->getOperand(1).getNode();
3319     return N0->hasOneUse() && N1->hasOneUse() &&
3320       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3321   }
3322   return false;
3323 }
3324 
isAddSubZExt(SDNode * N,SelectionDAG & DAG)3325 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3326   unsigned Opcode = N->getOpcode();
3327   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3328     SDNode *N0 = N->getOperand(0).getNode();
3329     SDNode *N1 = N->getOperand(1).getNode();
3330     return N0->hasOneUse() && N1->hasOneUse() &&
3331       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3332   }
3333   return false;
3334 }
3335 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const3336 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3337                                                 SelectionDAG &DAG) const {
3338   // The rounding mode is in bits 23:22 of the FPSCR.
3339   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3340   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3341   // so that the shift + and get folded into a bitfield extract.
3342   SDLoc dl(Op);
3343 
3344   SDValue Chain = Op.getOperand(0);
3345   SDValue FPCR_64 = DAG.getNode(
3346       ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3347       {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3348   Chain = FPCR_64.getValue(1);
3349   SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3350   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3351                                   DAG.getConstant(1U << 22, dl, MVT::i32));
3352   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3353                               DAG.getConstant(22, dl, MVT::i32));
3354   SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3355                             DAG.getConstant(3, dl, MVT::i32));
3356   return DAG.getMergeValues({AND, Chain}, dl);
3357 }
3358 
LowerMUL(SDValue Op,SelectionDAG & DAG) const3359 SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
3360   EVT VT = Op.getValueType();
3361 
3362   // If SVE is available then i64 vector multiplications can also be made legal.
3363   bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
3364 
3365   if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
3366     return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
3367 
3368   // Multiplications are only custom-lowered for 128-bit vectors so that
3369   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
3370   assert(VT.is128BitVector() && VT.isInteger() &&
3371          "unexpected type for custom-lowering ISD::MUL");
3372   SDNode *N0 = Op.getOperand(0).getNode();
3373   SDNode *N1 = Op.getOperand(1).getNode();
3374   unsigned NewOpc = 0;
3375   bool isMLA = false;
3376   bool isN0SExt = isSignExtended(N0, DAG);
3377   bool isN1SExt = isSignExtended(N1, DAG);
3378   if (isN0SExt && isN1SExt)
3379     NewOpc = AArch64ISD::SMULL;
3380   else {
3381     bool isN0ZExt = isZeroExtended(N0, DAG);
3382     bool isN1ZExt = isZeroExtended(N1, DAG);
3383     if (isN0ZExt && isN1ZExt)
3384       NewOpc = AArch64ISD::UMULL;
3385     else if (isN1SExt || isN1ZExt) {
3386       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3387       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3388       if (isN1SExt && isAddSubSExt(N0, DAG)) {
3389         NewOpc = AArch64ISD::SMULL;
3390         isMLA = true;
3391       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3392         NewOpc =  AArch64ISD::UMULL;
3393         isMLA = true;
3394       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3395         std::swap(N0, N1);
3396         NewOpc =  AArch64ISD::UMULL;
3397         isMLA = true;
3398       }
3399     }
3400 
3401     if (!NewOpc) {
3402       if (VT == MVT::v2i64)
3403         // Fall through to expand this.  It is not legal.
3404         return SDValue();
3405       else
3406         // Other vector multiplications are legal.
3407         return Op;
3408     }
3409   }
3410 
3411   // Legalize to a S/UMULL instruction
3412   SDLoc DL(Op);
3413   SDValue Op0;
3414   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3415   if (!isMLA) {
3416     Op0 = skipExtensionForVectorMULL(N0, DAG);
3417     assert(Op0.getValueType().is64BitVector() &&
3418            Op1.getValueType().is64BitVector() &&
3419            "unexpected types for extended operands to VMULL");
3420     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3421   }
3422   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3423   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3424   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3425   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3426   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3427   EVT Op1VT = Op1.getValueType();
3428   return DAG.getNode(N0->getOpcode(), DL, VT,
3429                      DAG.getNode(NewOpc, DL, VT,
3430                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3431                      DAG.getNode(NewOpc, DL, VT,
3432                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3433 }
3434 
getPTrue(SelectionDAG & DAG,SDLoc DL,EVT VT,int Pattern)3435 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3436                                int Pattern) {
3437   return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3438                      DAG.getTargetConstant(Pattern, DL, MVT::i32));
3439 }
3440 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const3441 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3442                                                      SelectionDAG &DAG) const {
3443   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3444   SDLoc dl(Op);
3445   switch (IntNo) {
3446   default: return SDValue();    // Don't custom lower most intrinsics.
3447   case Intrinsic::thread_pointer: {
3448     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3449     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3450   }
3451   case Intrinsic::aarch64_neon_abs: {
3452     EVT Ty = Op.getValueType();
3453     if (Ty == MVT::i64) {
3454       SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3455                                    Op.getOperand(1));
3456       Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3457       return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3458     } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3459       return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3460     } else {
3461       report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3462     }
3463   }
3464   case Intrinsic::aarch64_neon_smax:
3465     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3466                        Op.getOperand(1), Op.getOperand(2));
3467   case Intrinsic::aarch64_neon_umax:
3468     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3469                        Op.getOperand(1), Op.getOperand(2));
3470   case Intrinsic::aarch64_neon_smin:
3471     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3472                        Op.getOperand(1), Op.getOperand(2));
3473   case Intrinsic::aarch64_neon_umin:
3474     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3475                        Op.getOperand(1), Op.getOperand(2));
3476 
3477   case Intrinsic::aarch64_sve_sunpkhi:
3478     return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3479                        Op.getOperand(1));
3480   case Intrinsic::aarch64_sve_sunpklo:
3481     return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3482                        Op.getOperand(1));
3483   case Intrinsic::aarch64_sve_uunpkhi:
3484     return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3485                        Op.getOperand(1));
3486   case Intrinsic::aarch64_sve_uunpklo:
3487     return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3488                        Op.getOperand(1));
3489   case Intrinsic::aarch64_sve_clasta_n:
3490     return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3491                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3492   case Intrinsic::aarch64_sve_clastb_n:
3493     return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3494                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3495   case Intrinsic::aarch64_sve_lasta:
3496     return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3497                        Op.getOperand(1), Op.getOperand(2));
3498   case Intrinsic::aarch64_sve_lastb:
3499     return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3500                        Op.getOperand(1), Op.getOperand(2));
3501   case Intrinsic::aarch64_sve_rev:
3502     return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3503                        Op.getOperand(1));
3504   case Intrinsic::aarch64_sve_tbl:
3505     return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3506                        Op.getOperand(1), Op.getOperand(2));
3507   case Intrinsic::aarch64_sve_trn1:
3508     return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3509                        Op.getOperand(1), Op.getOperand(2));
3510   case Intrinsic::aarch64_sve_trn2:
3511     return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3512                        Op.getOperand(1), Op.getOperand(2));
3513   case Intrinsic::aarch64_sve_uzp1:
3514     return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3515                        Op.getOperand(1), Op.getOperand(2));
3516   case Intrinsic::aarch64_sve_uzp2:
3517     return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3518                        Op.getOperand(1), Op.getOperand(2));
3519   case Intrinsic::aarch64_sve_zip1:
3520     return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3521                        Op.getOperand(1), Op.getOperand(2));
3522   case Intrinsic::aarch64_sve_zip2:
3523     return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3524                        Op.getOperand(1), Op.getOperand(2));
3525   case Intrinsic::aarch64_sve_ptrue:
3526     return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3527                        Op.getOperand(1));
3528   case Intrinsic::aarch64_sve_dupq_lane:
3529     return LowerDUPQLane(Op, DAG);
3530   case Intrinsic::aarch64_sve_convert_from_svbool:
3531     return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3532                        Op.getOperand(1));
3533   case Intrinsic::aarch64_sve_fneg:
3534     return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
3535                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3536   case Intrinsic::aarch64_sve_frintp:
3537     return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
3538                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3539   case Intrinsic::aarch64_sve_frintm:
3540     return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
3541                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3542   case Intrinsic::aarch64_sve_frinti:
3543     return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3544                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3545   case Intrinsic::aarch64_sve_frintx:
3546     return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
3547                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3548   case Intrinsic::aarch64_sve_frinta:
3549     return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
3550                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3551   case Intrinsic::aarch64_sve_frintn:
3552     return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
3553                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3554   case Intrinsic::aarch64_sve_frintz:
3555     return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
3556                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3557   case Intrinsic::aarch64_sve_ucvtf:
3558     return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
3559                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3560                        Op.getOperand(1));
3561   case Intrinsic::aarch64_sve_scvtf:
3562     return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
3563                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3564                        Op.getOperand(1));
3565   case Intrinsic::aarch64_sve_fcvtzu:
3566     return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
3567                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3568                        Op.getOperand(1));
3569   case Intrinsic::aarch64_sve_fcvtzs:
3570     return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
3571                        Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
3572                        Op.getOperand(1));
3573   case Intrinsic::aarch64_sve_fsqrt:
3574     return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
3575                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3576   case Intrinsic::aarch64_sve_frecpx:
3577     return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
3578                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3579   case Intrinsic::aarch64_sve_fabs:
3580     return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
3581                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
3582   case Intrinsic::aarch64_sve_convert_to_svbool: {
3583     EVT OutVT = Op.getValueType();
3584     EVT InVT = Op.getOperand(1).getValueType();
3585     // Return the operand if the cast isn't changing type,
3586     // i.e. <n x 16 x i1> -> <n x 16 x i1>
3587     if (InVT == OutVT)
3588       return Op.getOperand(1);
3589     // Otherwise, zero the newly introduced lanes.
3590     SDValue Reinterpret =
3591         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3592     SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3593     SDValue MaskReinterpret =
3594         DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3595     return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3596   }
3597 
3598   case Intrinsic::aarch64_sve_insr: {
3599     SDValue Scalar = Op.getOperand(2);
3600     EVT ScalarTy = Scalar.getValueType();
3601     if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3602       Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3603 
3604     return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3605                        Op.getOperand(1), Scalar);
3606   }
3607 
3608   case Intrinsic::aarch64_sve_sxtb:
3609     return DAG.getNode(
3610         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3611         Op.getOperand(2), Op.getOperand(3),
3612         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3613         Op.getOperand(1));
3614   case Intrinsic::aarch64_sve_sxth:
3615     return DAG.getNode(
3616         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3617         Op.getOperand(2), Op.getOperand(3),
3618         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3619         Op.getOperand(1));
3620   case Intrinsic::aarch64_sve_sxtw:
3621     return DAG.getNode(
3622         AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3623         Op.getOperand(2), Op.getOperand(3),
3624         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3625         Op.getOperand(1));
3626   case Intrinsic::aarch64_sve_uxtb:
3627     return DAG.getNode(
3628         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3629         Op.getOperand(2), Op.getOperand(3),
3630         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
3631         Op.getOperand(1));
3632   case Intrinsic::aarch64_sve_uxth:
3633     return DAG.getNode(
3634         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3635         Op.getOperand(2), Op.getOperand(3),
3636         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
3637         Op.getOperand(1));
3638   case Intrinsic::aarch64_sve_uxtw:
3639     return DAG.getNode(
3640         AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
3641         Op.getOperand(2), Op.getOperand(3),
3642         DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
3643         Op.getOperand(1));
3644 
3645   case Intrinsic::localaddress: {
3646     const auto &MF = DAG.getMachineFunction();
3647     const auto *RegInfo = Subtarget->getRegisterInfo();
3648     unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3649     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3650                               Op.getSimpleValueType());
3651   }
3652 
3653   case Intrinsic::eh_recoverfp: {
3654     // FIXME: This needs to be implemented to correctly handle highly aligned
3655     // stack objects. For now we simply return the incoming FP. Refer D53541
3656     // for more details.
3657     SDValue FnOp = Op.getOperand(1);
3658     SDValue IncomingFPOp = Op.getOperand(2);
3659     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3660     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3661     if (!Fn)
3662       report_fatal_error(
3663           "llvm.eh.recoverfp must take a function as the first argument");
3664     return IncomingFPOp;
3665   }
3666 
3667   case Intrinsic::aarch64_neon_vsri:
3668   case Intrinsic::aarch64_neon_vsli: {
3669     EVT Ty = Op.getValueType();
3670 
3671     if (!Ty.isVector())
3672       report_fatal_error("Unexpected type for aarch64_neon_vsli");
3673 
3674     assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3675 
3676     bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3677     unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3678     return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3679                        Op.getOperand(3));
3680   }
3681 
3682   case Intrinsic::aarch64_neon_srhadd:
3683   case Intrinsic::aarch64_neon_urhadd:
3684   case Intrinsic::aarch64_neon_shadd:
3685   case Intrinsic::aarch64_neon_uhadd: {
3686     bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3687                         IntNo == Intrinsic::aarch64_neon_shadd);
3688     bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
3689                           IntNo == Intrinsic::aarch64_neon_urhadd);
3690     unsigned Opcode =
3691         IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
3692                     : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
3693     return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3694                        Op.getOperand(2));
3695   }
3696 
3697   case Intrinsic::aarch64_neon_uabd: {
3698     return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(),
3699                        Op.getOperand(1), Op.getOperand(2));
3700   }
3701   case Intrinsic::aarch64_neon_sabd: {
3702     return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(),
3703                        Op.getOperand(1), Op.getOperand(2));
3704   }
3705   }
3706 }
3707 
isVectorLoadExtDesirable(SDValue ExtVal) const3708 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3709   return ExtVal.getValueType().isScalableVector();
3710 }
3711 
getScatterVecOpcode(bool IsScaled,bool IsSigned,bool NeedsExtend)3712 unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
3713   std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
3714       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
3715        AArch64ISD::SST1_PRED},
3716       {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
3717        AArch64ISD::SST1_UXTW_PRED},
3718       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
3719        AArch64ISD::SST1_PRED},
3720       {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
3721        AArch64ISD::SST1_SXTW_PRED},
3722       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
3723        AArch64ISD::SST1_SCALED_PRED},
3724       {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
3725        AArch64ISD::SST1_UXTW_SCALED_PRED},
3726       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
3727        AArch64ISD::SST1_SCALED_PRED},
3728       {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
3729        AArch64ISD::SST1_SXTW_SCALED_PRED},
3730   };
3731   auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
3732   return AddrModes.find(Key)->second;
3733 }
3734 
getScatterIndexIsExtended(SDValue Index)3735 bool getScatterIndexIsExtended(SDValue Index) {
3736   unsigned Opcode = Index.getOpcode();
3737   if (Opcode == ISD::SIGN_EXTEND_INREG)
3738     return true;
3739 
3740   if (Opcode == ISD::AND) {
3741     SDValue Splat = Index.getOperand(1);
3742     if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
3743       return false;
3744     ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
3745     if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
3746       return false;
3747     return true;
3748   }
3749 
3750   return false;
3751 }
3752 
LowerMSCATTER(SDValue Op,SelectionDAG & DAG) const3753 SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
3754                                              SelectionDAG &DAG) const {
3755   SDLoc DL(Op);
3756   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
3757   assert(MSC && "Can only custom lower scatter store nodes");
3758 
3759   SDValue Index = MSC->getIndex();
3760   SDValue Chain = MSC->getChain();
3761   SDValue StoreVal = MSC->getValue();
3762   SDValue Mask = MSC->getMask();
3763   SDValue BasePtr = MSC->getBasePtr();
3764 
3765   ISD::MemIndexType IndexType = MSC->getIndexType();
3766   bool IsScaled =
3767       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
3768   bool IsSigned =
3769       IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
3770   bool NeedsExtend =
3771       getScatterIndexIsExtended(Index) ||
3772       Index.getSimpleValueType().getVectorElementType() == MVT::i32;
3773 
3774   EVT VT = StoreVal.getSimpleValueType();
3775   SDVTList VTs = DAG.getVTList(MVT::Other);
3776   EVT MemVT = MSC->getMemoryVT();
3777   SDValue InputVT = DAG.getValueType(MemVT);
3778 
3779   if (VT.getVectorElementType() == MVT::bf16 &&
3780       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
3781     return SDValue();
3782 
3783   // Handle FP data
3784   if (VT.isFloatingPoint()) {
3785     VT = VT.changeVectorElementTypeToInteger();
3786     ElementCount EC = VT.getVectorElementCount();
3787     auto ScalarIntVT =
3788         MVT::getIntegerVT(AArch64::SVEBitsPerBlock / EC.getKnownMinValue());
3789     StoreVal = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL,
3790                            MVT::getVectorVT(ScalarIntVT, EC), StoreVal);
3791 
3792     InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
3793   }
3794 
3795   if (getScatterIndexIsExtended(Index)) {
3796     if (Index.getOpcode() == ISD::AND)
3797       IsSigned = false;
3798     Index = Index.getOperand(0);
3799   }
3800 
3801   SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
3802   return DAG.getNode(getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend), DL,
3803                      VTs, Ops);
3804 }
3805 
3806 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
LowerTruncateVectorStore(SDLoc DL,StoreSDNode * ST,EVT VT,EVT MemVT,SelectionDAG & DAG)3807 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3808                                         EVT VT, EVT MemVT,
3809                                         SelectionDAG &DAG) {
3810   assert(VT.isVector() && "VT should be a vector type");
3811   assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3812 
3813   SDValue Value = ST->getValue();
3814 
3815   // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3816   // the word lane which represent the v4i8 subvector.  It optimizes the store
3817   // to:
3818   //
3819   //   xtn  v0.8b, v0.8h
3820   //   str  s0, [x0]
3821 
3822   SDValue Undef = DAG.getUNDEF(MVT::i16);
3823   SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3824                                         {Undef, Undef, Undef, Undef});
3825 
3826   SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3827                                  Value, UndefVec);
3828   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3829 
3830   Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3831   SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3832                                      Trunc, DAG.getConstant(0, DL, MVT::i64));
3833 
3834   return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3835                       ST->getBasePtr(), ST->getMemOperand());
3836 }
3837 
3838 // Custom lowering for any store, vector or scalar and/or default or with
3839 // a truncate operations.  Currently only custom lower truncate operation
3840 // from vector v4i16 to v4i8 or volatile stores of i128.
LowerSTORE(SDValue Op,SelectionDAG & DAG) const3841 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3842                                           SelectionDAG &DAG) const {
3843   SDLoc Dl(Op);
3844   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3845   assert (StoreNode && "Can only custom lower store nodes");
3846 
3847   SDValue Value = StoreNode->getValue();
3848 
3849   EVT VT = Value.getValueType();
3850   EVT MemVT = StoreNode->getMemoryVT();
3851 
3852   if (VT.isVector()) {
3853     if (useSVEForFixedLengthVectorVT(VT))
3854       return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3855 
3856     unsigned AS = StoreNode->getAddressSpace();
3857     Align Alignment = StoreNode->getAlign();
3858     if (Alignment < MemVT.getStoreSize() &&
3859         !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3860                                         StoreNode->getMemOperand()->getFlags(),
3861                                         nullptr)) {
3862       return scalarizeVectorStore(StoreNode, DAG);
3863     }
3864 
3865     if (StoreNode->isTruncatingStore()) {
3866       return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3867     }
3868     // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3869     // the custom lowering, as there are no un-paired non-temporal stores and
3870     // legalization will break up 256 bit inputs.
3871     ElementCount EC = MemVT.getVectorElementCount();
3872     if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3873         EC.isKnownEven() &&
3874         ((MemVT.getScalarSizeInBits() == 8u ||
3875           MemVT.getScalarSizeInBits() == 16u ||
3876           MemVT.getScalarSizeInBits() == 32u ||
3877           MemVT.getScalarSizeInBits() == 64u))) {
3878       SDValue Lo =
3879           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3880                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3881                       StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3882       SDValue Hi =
3883           DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3884                       MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3885                       StoreNode->getValue(),
3886                       DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
3887       SDValue Result = DAG.getMemIntrinsicNode(
3888           AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3889           {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3890           StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3891       return Result;
3892     }
3893   } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3894     assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3895     SDValue Lo =
3896         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3897                     DAG.getConstant(0, Dl, MVT::i64));
3898     SDValue Hi =
3899         DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3900                     DAG.getConstant(1, Dl, MVT::i64));
3901     SDValue Result = DAG.getMemIntrinsicNode(
3902         AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3903         {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3904         StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3905     return Result;
3906   }
3907 
3908   return SDValue();
3909 }
3910 
LowerOperation(SDValue Op,SelectionDAG & DAG) const3911 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3912                                               SelectionDAG &DAG) const {
3913   LLVM_DEBUG(dbgs() << "Custom lowering: ");
3914   LLVM_DEBUG(Op.dump());
3915 
3916   switch (Op.getOpcode()) {
3917   default:
3918     llvm_unreachable("unimplemented operand");
3919     return SDValue();
3920   case ISD::BITCAST:
3921     return LowerBITCAST(Op, DAG);
3922   case ISD::GlobalAddress:
3923     return LowerGlobalAddress(Op, DAG);
3924   case ISD::GlobalTLSAddress:
3925     return LowerGlobalTLSAddress(Op, DAG);
3926   case ISD::SETCC:
3927   case ISD::STRICT_FSETCC:
3928   case ISD::STRICT_FSETCCS:
3929     return LowerSETCC(Op, DAG);
3930   case ISD::BR_CC:
3931     return LowerBR_CC(Op, DAG);
3932   case ISD::SELECT:
3933     return LowerSELECT(Op, DAG);
3934   case ISD::SELECT_CC:
3935     return LowerSELECT_CC(Op, DAG);
3936   case ISD::JumpTable:
3937     return LowerJumpTable(Op, DAG);
3938   case ISD::BR_JT:
3939     return LowerBR_JT(Op, DAG);
3940   case ISD::ConstantPool:
3941     return LowerConstantPool(Op, DAG);
3942   case ISD::BlockAddress:
3943     return LowerBlockAddress(Op, DAG);
3944   case ISD::VASTART:
3945     return LowerVASTART(Op, DAG);
3946   case ISD::VACOPY:
3947     return LowerVACOPY(Op, DAG);
3948   case ISD::VAARG:
3949     return LowerVAARG(Op, DAG);
3950   case ISD::ADDC:
3951   case ISD::ADDE:
3952   case ISD::SUBC:
3953   case ISD::SUBE:
3954     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3955   case ISD::SADDO:
3956   case ISD::UADDO:
3957   case ISD::SSUBO:
3958   case ISD::USUBO:
3959   case ISD::SMULO:
3960   case ISD::UMULO:
3961     return LowerXALUO(Op, DAG);
3962   case ISD::FADD:
3963     if (Op.getValueType() == MVT::f128)
3964       return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3965     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3966   case ISD::FSUB:
3967     if (Op.getValueType() == MVT::f128)
3968       return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3969     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
3970   case ISD::FMUL:
3971     if (Op.getValueType() == MVT::f128)
3972       return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3973     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
3974   case ISD::FMA:
3975     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3976   case ISD::FDIV:
3977     if (Op.getValueType() == MVT::f128)
3978       return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3979     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
3980   case ISD::FNEG:
3981     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
3982   case ISD::FCEIL:
3983     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
3984   case ISD::FFLOOR:
3985     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
3986   case ISD::FNEARBYINT:
3987     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
3988   case ISD::FRINT:
3989     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
3990   case ISD::FROUND:
3991     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
3992   case ISD::FROUNDEVEN:
3993     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
3994   case ISD::FTRUNC:
3995     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
3996   case ISD::FSQRT:
3997     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
3998   case ISD::FABS:
3999     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
4000   case ISD::FP_ROUND:
4001   case ISD::STRICT_FP_ROUND:
4002     return LowerFP_ROUND(Op, DAG);
4003   case ISD::FP_EXTEND:
4004     return LowerFP_EXTEND(Op, DAG);
4005   case ISD::FRAMEADDR:
4006     return LowerFRAMEADDR(Op, DAG);
4007   case ISD::SPONENTRY:
4008     return LowerSPONENTRY(Op, DAG);
4009   case ISD::RETURNADDR:
4010     return LowerRETURNADDR(Op, DAG);
4011   case ISD::ADDROFRETURNADDR:
4012     return LowerADDROFRETURNADDR(Op, DAG);
4013   case ISD::CONCAT_VECTORS:
4014     return LowerCONCAT_VECTORS(Op, DAG);
4015   case ISD::INSERT_VECTOR_ELT:
4016     return LowerINSERT_VECTOR_ELT(Op, DAG);
4017   case ISD::EXTRACT_VECTOR_ELT:
4018     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
4019   case ISD::BUILD_VECTOR:
4020     return LowerBUILD_VECTOR(Op, DAG);
4021   case ISD::VECTOR_SHUFFLE:
4022     return LowerVECTOR_SHUFFLE(Op, DAG);
4023   case ISD::SPLAT_VECTOR:
4024     return LowerSPLAT_VECTOR(Op, DAG);
4025   case ISD::EXTRACT_SUBVECTOR:
4026     return LowerEXTRACT_SUBVECTOR(Op, DAG);
4027   case ISD::INSERT_SUBVECTOR:
4028     return LowerINSERT_SUBVECTOR(Op, DAG);
4029   case ISD::SDIV:
4030   case ISD::UDIV:
4031     return LowerDIV(Op, DAG);
4032   case ISD::SMIN:
4033     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
4034                                /*OverrideNEON=*/true);
4035   case ISD::UMIN:
4036     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
4037                                /*OverrideNEON=*/true);
4038   case ISD::SMAX:
4039     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
4040                                /*OverrideNEON=*/true);
4041   case ISD::UMAX:
4042     return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
4043                                /*OverrideNEON=*/true);
4044   case ISD::SRA:
4045   case ISD::SRL:
4046   case ISD::SHL:
4047     return LowerVectorSRA_SRL_SHL(Op, DAG);
4048   case ISD::SHL_PARTS:
4049     return LowerShiftLeftParts(Op, DAG);
4050   case ISD::SRL_PARTS:
4051   case ISD::SRA_PARTS:
4052     return LowerShiftRightParts(Op, DAG);
4053   case ISD::CTPOP:
4054     return LowerCTPOP(Op, DAG);
4055   case ISD::FCOPYSIGN:
4056     return LowerFCOPYSIGN(Op, DAG);
4057   case ISD::OR:
4058     return LowerVectorOR(Op, DAG);
4059   case ISD::XOR:
4060     return LowerXOR(Op, DAG);
4061   case ISD::PREFETCH:
4062     return LowerPREFETCH(Op, DAG);
4063   case ISD::SINT_TO_FP:
4064   case ISD::UINT_TO_FP:
4065   case ISD::STRICT_SINT_TO_FP:
4066   case ISD::STRICT_UINT_TO_FP:
4067     return LowerINT_TO_FP(Op, DAG);
4068   case ISD::FP_TO_SINT:
4069   case ISD::FP_TO_UINT:
4070   case ISD::STRICT_FP_TO_SINT:
4071   case ISD::STRICT_FP_TO_UINT:
4072     return LowerFP_TO_INT(Op, DAG);
4073   case ISD::FSINCOS:
4074     return LowerFSINCOS(Op, DAG);
4075   case ISD::FLT_ROUNDS_:
4076     return LowerFLT_ROUNDS_(Op, DAG);
4077   case ISD::MUL:
4078     return LowerMUL(Op, DAG);
4079   case ISD::INTRINSIC_WO_CHAIN:
4080     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4081   case ISD::STORE:
4082     return LowerSTORE(Op, DAG);
4083   case ISD::MSCATTER:
4084     return LowerMSCATTER(Op, DAG);
4085   case ISD::VECREDUCE_SEQ_FADD:
4086     return LowerVECREDUCE_SEQ_FADD(Op, DAG);
4087   case ISD::VECREDUCE_ADD:
4088   case ISD::VECREDUCE_AND:
4089   case ISD::VECREDUCE_OR:
4090   case ISD::VECREDUCE_XOR:
4091   case ISD::VECREDUCE_SMAX:
4092   case ISD::VECREDUCE_SMIN:
4093   case ISD::VECREDUCE_UMAX:
4094   case ISD::VECREDUCE_UMIN:
4095   case ISD::VECREDUCE_FADD:
4096   case ISD::VECREDUCE_FMAX:
4097   case ISD::VECREDUCE_FMIN:
4098     return LowerVECREDUCE(Op, DAG);
4099   case ISD::ATOMIC_LOAD_SUB:
4100     return LowerATOMIC_LOAD_SUB(Op, DAG);
4101   case ISD::ATOMIC_LOAD_AND:
4102     return LowerATOMIC_LOAD_AND(Op, DAG);
4103   case ISD::DYNAMIC_STACKALLOC:
4104     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4105   case ISD::VSCALE:
4106     return LowerVSCALE(Op, DAG);
4107   case ISD::ANY_EXTEND:
4108   case ISD::SIGN_EXTEND:
4109   case ISD::ZERO_EXTEND:
4110     return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
4111   case ISD::SIGN_EXTEND_INREG: {
4112     // Only custom lower when ExtraVT has a legal byte based element type.
4113     EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4114     EVT ExtraEltVT = ExtraVT.getVectorElementType();
4115     if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
4116         (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
4117       return SDValue();
4118 
4119     return LowerToPredicatedOp(Op, DAG,
4120                                AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
4121   }
4122   case ISD::TRUNCATE:
4123     return LowerTRUNCATE(Op, DAG);
4124   case ISD::LOAD:
4125     if (useSVEForFixedLengthVectorVT(Op.getValueType()))
4126       return LowerFixedLengthVectorLoadToSVE(Op, DAG);
4127     llvm_unreachable("Unexpected request to lower ISD::LOAD");
4128   case ISD::ADD:
4129     return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
4130   case ISD::AND:
4131     return LowerToScalableOp(Op, DAG);
4132   case ISD::SUB:
4133     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
4134   case ISD::FMAXNUM:
4135     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
4136   case ISD::FMINNUM:
4137     return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
4138   case ISD::VSELECT:
4139     return LowerFixedLengthVectorSelectToSVE(Op, DAG);
4140   }
4141 }
4142 
mergeStoresAfterLegalization(EVT VT) const4143 bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
4144   return !Subtarget->useSVEForFixedLengthVectors();
4145 }
4146 
useSVEForFixedLengthVectorVT(EVT VT,bool OverrideNEON) const4147 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
4148     EVT VT, bool OverrideNEON) const {
4149   if (!Subtarget->useSVEForFixedLengthVectors())
4150     return false;
4151 
4152   if (!VT.isFixedLengthVector())
4153     return false;
4154 
4155   // Don't use SVE for vectors we cannot scalarize if required.
4156   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
4157   // Fixed length predicates should be promoted to i8.
4158   // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
4159   case MVT::i1:
4160   default:
4161     return false;
4162   case MVT::i8:
4163   case MVT::i16:
4164   case MVT::i32:
4165   case MVT::i64:
4166   case MVT::f16:
4167   case MVT::f32:
4168   case MVT::f64:
4169     break;
4170   }
4171 
4172   // All SVE implementations support NEON sized vectors.
4173   if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
4174     return true;
4175 
4176   // Ensure NEON MVTs only belong to a single register class.
4177   if (VT.getFixedSizeInBits() <= 128)
4178     return false;
4179 
4180   // Don't use SVE for types that don't fit.
4181   if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
4182     return false;
4183 
4184   // TODO: Perhaps an artificial restriction, but worth having whilst getting
4185   // the base fixed length SVE support in place.
4186   if (!VT.isPow2VectorType())
4187     return false;
4188 
4189   return true;
4190 }
4191 
4192 //===----------------------------------------------------------------------===//
4193 //                      Calling Convention Implementation
4194 //===----------------------------------------------------------------------===//
4195 
4196 /// Selects the correct CCAssignFn for a given CallingConvention value.
CCAssignFnForCall(CallingConv::ID CC,bool IsVarArg) const4197 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
4198                                                      bool IsVarArg) const {
4199   switch (CC) {
4200   default:
4201     report_fatal_error("Unsupported calling convention.");
4202   case CallingConv::WebKit_JS:
4203     return CC_AArch64_WebKit_JS;
4204   case CallingConv::GHC:
4205     return CC_AArch64_GHC;
4206   case CallingConv::C:
4207   case CallingConv::Fast:
4208   case CallingConv::PreserveMost:
4209   case CallingConv::CXX_FAST_TLS:
4210   case CallingConv::Swift:
4211     if (Subtarget->isTargetWindows() && IsVarArg)
4212       return CC_AArch64_Win64_VarArg;
4213     if (!Subtarget->isTargetDarwin())
4214       return CC_AArch64_AAPCS;
4215     if (!IsVarArg)
4216       return CC_AArch64_DarwinPCS;
4217     return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
4218                                       : CC_AArch64_DarwinPCS_VarArg;
4219    case CallingConv::Win64:
4220     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
4221    case CallingConv::CFGuard_Check:
4222      return CC_AArch64_Win64_CFGuard_Check;
4223    case CallingConv::AArch64_VectorCall:
4224    case CallingConv::AArch64_SVE_VectorCall:
4225      return CC_AArch64_AAPCS;
4226   }
4227 }
4228 
4229 CCAssignFn *
CCAssignFnForReturn(CallingConv::ID CC) const4230 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
4231   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
4232                                       : RetCC_AArch64_AAPCS;
4233 }
4234 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const4235 SDValue AArch64TargetLowering::LowerFormalArguments(
4236     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4237     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4238     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4239   MachineFunction &MF = DAG.getMachineFunction();
4240   MachineFrameInfo &MFI = MF.getFrameInfo();
4241   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4242 
4243   // Assign locations to all of the incoming arguments.
4244   SmallVector<CCValAssign, 16> ArgLocs;
4245   DenseMap<unsigned, SDValue> CopiedRegs;
4246   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4247                  *DAG.getContext());
4248 
4249   // At this point, Ins[].VT may already be promoted to i32. To correctly
4250   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4251   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4252   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
4253   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
4254   // LocVT.
4255   unsigned NumArgs = Ins.size();
4256   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4257   unsigned CurArgIdx = 0;
4258   for (unsigned i = 0; i != NumArgs; ++i) {
4259     MVT ValVT = Ins[i].VT;
4260     if (Ins[i].isOrigArg()) {
4261       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
4262       CurArgIdx = Ins[i].getOrigArgIndex();
4263 
4264       // Get type of the original argument.
4265       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
4266                                   /*AllowUnknown*/ true);
4267       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
4268       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4269       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4270         ValVT = MVT::i8;
4271       else if (ActualMVT == MVT::i16)
4272         ValVT = MVT::i16;
4273     }
4274     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4275     bool Res =
4276         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
4277     assert(!Res && "Call operand has unhandled type");
4278     (void)Res;
4279   }
4280   assert(ArgLocs.size() == Ins.size());
4281   SmallVector<SDValue, 16> ArgValues;
4282   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4283     CCValAssign &VA = ArgLocs[i];
4284 
4285     if (Ins[i].Flags.isByVal()) {
4286       // Byval is used for HFAs in the PCS, but the system should work in a
4287       // non-compliant manner for larger structs.
4288       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4289       int Size = Ins[i].Flags.getByValSize();
4290       unsigned NumRegs = (Size + 7) / 8;
4291 
4292       // FIXME: This works on big-endian for composite byvals, which are the common
4293       // case. It should also work for fundamental types too.
4294       unsigned FrameIdx =
4295         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
4296       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
4297       InVals.push_back(FrameIdxN);
4298 
4299       continue;
4300     }
4301 
4302     SDValue ArgValue;
4303     if (VA.isRegLoc()) {
4304       // Arguments stored in registers.
4305       EVT RegVT = VA.getLocVT();
4306       const TargetRegisterClass *RC;
4307 
4308       if (RegVT == MVT::i32)
4309         RC = &AArch64::GPR32RegClass;
4310       else if (RegVT == MVT::i64)
4311         RC = &AArch64::GPR64RegClass;
4312       else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4313         RC = &AArch64::FPR16RegClass;
4314       else if (RegVT == MVT::f32)
4315         RC = &AArch64::FPR32RegClass;
4316       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
4317         RC = &AArch64::FPR64RegClass;
4318       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
4319         RC = &AArch64::FPR128RegClass;
4320       else if (RegVT.isScalableVector() &&
4321                RegVT.getVectorElementType() == MVT::i1)
4322         RC = &AArch64::PPRRegClass;
4323       else if (RegVT.isScalableVector())
4324         RC = &AArch64::ZPRRegClass;
4325       else
4326         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4327 
4328       // Transform the arguments in physical registers into virtual ones.
4329       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4330       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
4331 
4332       // If this is an 8, 16 or 32-bit value, it is really passed promoted
4333       // to 64 bits.  Insert an assert[sz]ext to capture this, then
4334       // truncate to the right size.
4335       switch (VA.getLocInfo()) {
4336       default:
4337         llvm_unreachable("Unknown loc info!");
4338       case CCValAssign::Full:
4339         break;
4340       case CCValAssign::Indirect:
4341         assert(VA.getValVT().isScalableVector() &&
4342                "Only scalable vectors can be passed indirectly");
4343         break;
4344       case CCValAssign::BCvt:
4345         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
4346         break;
4347       case CCValAssign::AExt:
4348       case CCValAssign::SExt:
4349       case CCValAssign::ZExt:
4350         break;
4351       case CCValAssign::AExtUpper:
4352         ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
4353                                DAG.getConstant(32, DL, RegVT));
4354         ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
4355         break;
4356       }
4357     } else { // VA.isRegLoc()
4358       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
4359       unsigned ArgOffset = VA.getLocMemOffset();
4360       unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
4361                               ? VA.getLocVT().getSizeInBits()
4362                               : VA.getValVT().getSizeInBits()) / 8;
4363 
4364       uint32_t BEAlign = 0;
4365       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
4366           !Ins[i].Flags.isInConsecutiveRegs())
4367         BEAlign = 8 - ArgSize;
4368 
4369       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
4370 
4371       // Create load nodes to retrieve arguments from the stack.
4372       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4373 
4374       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
4375       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4376       MVT MemVT = VA.getValVT();
4377 
4378       switch (VA.getLocInfo()) {
4379       default:
4380         break;
4381       case CCValAssign::Trunc:
4382       case CCValAssign::BCvt:
4383         MemVT = VA.getLocVT();
4384         break;
4385       case CCValAssign::Indirect:
4386         assert(VA.getValVT().isScalableVector() &&
4387                "Only scalable vectors can be passed indirectly");
4388         MemVT = VA.getLocVT();
4389         break;
4390       case CCValAssign::SExt:
4391         ExtType = ISD::SEXTLOAD;
4392         break;
4393       case CCValAssign::ZExt:
4394         ExtType = ISD::ZEXTLOAD;
4395         break;
4396       case CCValAssign::AExt:
4397         ExtType = ISD::EXTLOAD;
4398         break;
4399       }
4400 
4401       ArgValue = DAG.getExtLoad(
4402           ExtType, DL, VA.getLocVT(), Chain, FIN,
4403           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
4404           MemVT);
4405 
4406     }
4407 
4408     if (VA.getLocInfo() == CCValAssign::Indirect) {
4409       assert(VA.getValVT().isScalableVector() &&
4410            "Only scalable vectors can be passed indirectly");
4411       // If value is passed via pointer - do a load.
4412       ArgValue =
4413           DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
4414     }
4415 
4416     if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
4417       ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
4418                              ArgValue, DAG.getValueType(MVT::i32));
4419     InVals.push_back(ArgValue);
4420   }
4421 
4422   // varargs
4423   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4424   if (isVarArg) {
4425     if (!Subtarget->isTargetDarwin() || IsWin64) {
4426       // The AAPCS variadic function ABI is identical to the non-variadic
4427       // one. As a result there may be more arguments in registers and we should
4428       // save them for future reference.
4429       // Win64 variadic functions also pass arguments in registers, but all float
4430       // arguments are passed in integer registers.
4431       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
4432     }
4433 
4434     // This will point to the next argument passed via stack.
4435     unsigned StackOffset = CCInfo.getNextStackOffset();
4436     // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
4437     StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
4438     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
4439 
4440     if (MFI.hasMustTailInVarArgFunc()) {
4441       SmallVector<MVT, 2> RegParmTypes;
4442       RegParmTypes.push_back(MVT::i64);
4443       RegParmTypes.push_back(MVT::f128);
4444       // Compute the set of forwarded registers. The rest are scratch.
4445       SmallVectorImpl<ForwardedRegister> &Forwards =
4446                                        FuncInfo->getForwardedMustTailRegParms();
4447       CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
4448                                                CC_AArch64_AAPCS);
4449 
4450       // Conservatively forward X8, since it might be used for aggregate return.
4451       if (!CCInfo.isAllocated(AArch64::X8)) {
4452         unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
4453         Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
4454       }
4455     }
4456   }
4457 
4458   // On Windows, InReg pointers must be returned, so record the pointer in a
4459   // virtual register at the start of the function so it can be returned in the
4460   // epilogue.
4461   if (IsWin64) {
4462     for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
4463       if (Ins[I].Flags.isInReg()) {
4464         assert(!FuncInfo->getSRetReturnReg());
4465 
4466         MVT PtrTy = getPointerTy(DAG.getDataLayout());
4467         Register Reg =
4468             MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
4469         FuncInfo->setSRetReturnReg(Reg);
4470 
4471         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
4472         Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
4473         break;
4474       }
4475     }
4476   }
4477 
4478   unsigned StackArgSize = CCInfo.getNextStackOffset();
4479   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4480   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
4481     // This is a non-standard ABI so by fiat I say we're allowed to make full
4482     // use of the stack area to be popped, which must be aligned to 16 bytes in
4483     // any case:
4484     StackArgSize = alignTo(StackArgSize, 16);
4485 
4486     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
4487     // a multiple of 16.
4488     FuncInfo->setArgumentStackToRestore(StackArgSize);
4489 
4490     // This realignment carries over to the available bytes below. Our own
4491     // callers will guarantee the space is free by giving an aligned value to
4492     // CALLSEQ_START.
4493   }
4494   // Even if we're not expected to free up the space, it's useful to know how
4495   // much is there while considering tail calls (because we can reuse it).
4496   FuncInfo->setBytesInStackArgArea(StackArgSize);
4497 
4498   if (Subtarget->hasCustomCallingConv())
4499     Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
4500 
4501   return Chain;
4502 }
4503 
saveVarArgRegisters(CCState & CCInfo,SelectionDAG & DAG,const SDLoc & DL,SDValue & Chain) const4504 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
4505                                                 SelectionDAG &DAG,
4506                                                 const SDLoc &DL,
4507                                                 SDValue &Chain) const {
4508   MachineFunction &MF = DAG.getMachineFunction();
4509   MachineFrameInfo &MFI = MF.getFrameInfo();
4510   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4511   auto PtrVT = getPointerTy(DAG.getDataLayout());
4512   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
4513 
4514   SmallVector<SDValue, 8> MemOps;
4515 
4516   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
4517                                           AArch64::X3, AArch64::X4, AArch64::X5,
4518                                           AArch64::X6, AArch64::X7 };
4519   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
4520   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
4521 
4522   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
4523   int GPRIdx = 0;
4524   if (GPRSaveSize != 0) {
4525     if (IsWin64) {
4526       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
4527       if (GPRSaveSize & 15)
4528         // The extra size here, if triggered, will always be 8.
4529         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
4530     } else
4531       GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
4532 
4533     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
4534 
4535     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
4536       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
4537       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
4538       SDValue Store = DAG.getStore(
4539           Val.getValue(1), DL, Val, FIN,
4540           IsWin64
4541               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
4542                                                   GPRIdx,
4543                                                   (i - FirstVariadicGPR) * 8)
4544               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
4545       MemOps.push_back(Store);
4546       FIN =
4547           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
4548     }
4549   }
4550   FuncInfo->setVarArgsGPRIndex(GPRIdx);
4551   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4552 
4553   if (Subtarget->hasFPARMv8() && !IsWin64) {
4554     static const MCPhysReg FPRArgRegs[] = {
4555         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4556         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4557     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4558     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4559 
4560     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4561     int FPRIdx = 0;
4562     if (FPRSaveSize != 0) {
4563       FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4564 
4565       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4566 
4567       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4568         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4569         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4570 
4571         SDValue Store = DAG.getStore(
4572             Val.getValue(1), DL, Val, FIN,
4573             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4574         MemOps.push_back(Store);
4575         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4576                           DAG.getConstant(16, DL, PtrVT));
4577       }
4578     }
4579     FuncInfo->setVarArgsFPRIndex(FPRIdx);
4580     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4581   }
4582 
4583   if (!MemOps.empty()) {
4584     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4585   }
4586 }
4587 
4588 /// LowerCallResult - Lower the result values of a call into the
4589 /// appropriate copies out of appropriate physical registers.
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & DL,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,bool isThisReturn,SDValue ThisVal) const4590 SDValue AArch64TargetLowering::LowerCallResult(
4591     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4592     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4593     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4594     SDValue ThisVal) const {
4595   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
4596   // Assign locations to each value returned by this call.
4597   SmallVector<CCValAssign, 16> RVLocs;
4598   DenseMap<unsigned, SDValue> CopiedRegs;
4599   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4600                  *DAG.getContext());
4601   CCInfo.AnalyzeCallResult(Ins, RetCC);
4602 
4603   // Copy all of the result registers out of their specified physreg.
4604   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4605     CCValAssign VA = RVLocs[i];
4606 
4607     // Pass 'this' value directly from the argument to return value, to avoid
4608     // reg unit interference
4609     if (i == 0 && isThisReturn) {
4610       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4611              "unexpected return calling convention register assignment");
4612       InVals.push_back(ThisVal);
4613       continue;
4614     }
4615 
4616     // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4617     // allows one use of a physreg per block.
4618     SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4619     if (!Val) {
4620       Val =
4621           DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4622       Chain = Val.getValue(1);
4623       InFlag = Val.getValue(2);
4624       CopiedRegs[VA.getLocReg()] = Val;
4625     }
4626 
4627     switch (VA.getLocInfo()) {
4628     default:
4629       llvm_unreachable("Unknown loc info!");
4630     case CCValAssign::Full:
4631       break;
4632     case CCValAssign::BCvt:
4633       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4634       break;
4635     case CCValAssign::AExtUpper:
4636       Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4637                         DAG.getConstant(32, DL, VA.getLocVT()));
4638       LLVM_FALLTHROUGH;
4639     case CCValAssign::AExt:
4640       LLVM_FALLTHROUGH;
4641     case CCValAssign::ZExt:
4642       Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4643       break;
4644     }
4645 
4646     InVals.push_back(Val);
4647   }
4648 
4649   return Chain;
4650 }
4651 
4652 /// Return true if the calling convention is one that we can guarantee TCO for.
canGuaranteeTCO(CallingConv::ID CC)4653 static bool canGuaranteeTCO(CallingConv::ID CC) {
4654   return CC == CallingConv::Fast;
4655 }
4656 
4657 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)4658 static bool mayTailCallThisCC(CallingConv::ID CC) {
4659   switch (CC) {
4660   case CallingConv::C:
4661   case CallingConv::AArch64_SVE_VectorCall:
4662   case CallingConv::PreserveMost:
4663   case CallingConv::Swift:
4664     return true;
4665   default:
4666     return canGuaranteeTCO(CC);
4667   }
4668 }
4669 
isEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const4670 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4671     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4672     const SmallVectorImpl<ISD::OutputArg> &Outs,
4673     const SmallVectorImpl<SDValue> &OutVals,
4674     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4675   if (!mayTailCallThisCC(CalleeCC))
4676     return false;
4677 
4678   MachineFunction &MF = DAG.getMachineFunction();
4679   const Function &CallerF = MF.getFunction();
4680   CallingConv::ID CallerCC = CallerF.getCallingConv();
4681 
4682   // If this function uses the C calling convention but has an SVE signature,
4683   // then it preserves more registers and should assume the SVE_VectorCall CC.
4684   // The check for matching callee-saved regs will determine whether it is
4685   // eligible for TCO.
4686   if (CallerCC == CallingConv::C &&
4687       AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
4688     CallerCC = CallingConv::AArch64_SVE_VectorCall;
4689 
4690   bool CCMatch = CallerCC == CalleeCC;
4691 
4692   // When using the Windows calling convention on a non-windows OS, we want
4693   // to back up and restore X18 in such functions; we can't do a tail call
4694   // from those functions.
4695   if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4696       CalleeCC != CallingConv::Win64)
4697     return false;
4698 
4699   // Byval parameters hand the function a pointer directly into the stack area
4700   // we want to reuse during a tail call. Working around this *is* possible (see
4701   // X86) but less efficient and uglier in LowerCall.
4702   for (Function::const_arg_iterator i = CallerF.arg_begin(),
4703                                     e = CallerF.arg_end();
4704        i != e; ++i) {
4705     if (i->hasByValAttr())
4706       return false;
4707 
4708     // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4709     // In this case, it is necessary to save/restore X0 in the callee. Tail
4710     // call opt interferes with this. So we disable tail call opt when the
4711     // caller has an argument with "inreg" attribute.
4712 
4713     // FIXME: Check whether the callee also has an "inreg" argument.
4714     if (i->hasInRegAttr())
4715       return false;
4716   }
4717 
4718   if (getTargetMachine().Options.GuaranteedTailCallOpt)
4719     return canGuaranteeTCO(CalleeCC) && CCMatch;
4720 
4721   // Externally-defined functions with weak linkage should not be
4722   // tail-called on AArch64 when the OS does not support dynamic
4723   // pre-emption of symbols, as the AAELF spec requires normal calls
4724   // to undefined weak functions to be replaced with a NOP or jump to the
4725   // next instruction. The behaviour of branch instructions in this
4726   // situation (as used for tail calls) is implementation-defined, so we
4727   // cannot rely on the linker replacing the tail call with a return.
4728   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4729     const GlobalValue *GV = G->getGlobal();
4730     const Triple &TT = getTargetMachine().getTargetTriple();
4731     if (GV->hasExternalWeakLinkage() &&
4732         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4733       return false;
4734   }
4735 
4736   // Now we search for cases where we can use a tail call without changing the
4737   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4738   // concept.
4739 
4740   // I want anyone implementing a new calling convention to think long and hard
4741   // about this assert.
4742   assert((!isVarArg || CalleeCC == CallingConv::C) &&
4743          "Unexpected variadic calling convention");
4744 
4745   LLVMContext &C = *DAG.getContext();
4746   if (isVarArg && !Outs.empty()) {
4747     // At least two cases here: if caller is fastcc then we can't have any
4748     // memory arguments (we'd be expected to clean up the stack afterwards). If
4749     // caller is C then we could potentially use its argument area.
4750 
4751     // FIXME: for now we take the most conservative of these in both cases:
4752     // disallow all variadic memory operands.
4753     SmallVector<CCValAssign, 16> ArgLocs;
4754     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4755 
4756     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4757     for (const CCValAssign &ArgLoc : ArgLocs)
4758       if (!ArgLoc.isRegLoc())
4759         return false;
4760   }
4761 
4762   // Check that the call results are passed in the same way.
4763   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4764                                   CCAssignFnForCall(CalleeCC, isVarArg),
4765                                   CCAssignFnForCall(CallerCC, isVarArg)))
4766     return false;
4767   // The callee has to preserve all registers the caller needs to preserve.
4768   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4769   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4770   if (!CCMatch) {
4771     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4772     if (Subtarget->hasCustomCallingConv()) {
4773       TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4774       TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4775     }
4776     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4777       return false;
4778   }
4779 
4780   // Nothing more to check if the callee is taking no arguments
4781   if (Outs.empty())
4782     return true;
4783 
4784   SmallVector<CCValAssign, 16> ArgLocs;
4785   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4786 
4787   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4788 
4789   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4790 
4791   // If any of the arguments is passed indirectly, it must be SVE, so the
4792   // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4793   // allocate space on the stack. That is why we determine this explicitly here
4794   // the call cannot be a tailcall.
4795   if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4796         assert((A.getLocInfo() != CCValAssign::Indirect ||
4797                 A.getValVT().isScalableVector()) &&
4798                "Expected value to be scalable");
4799         return A.getLocInfo() == CCValAssign::Indirect;
4800       }))
4801     return false;
4802 
4803   // If the stack arguments for this call do not fit into our own save area then
4804   // the call cannot be made tail.
4805   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4806     return false;
4807 
4808   const MachineRegisterInfo &MRI = MF.getRegInfo();
4809   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4810     return false;
4811 
4812   return true;
4813 }
4814 
addTokenForArgument(SDValue Chain,SelectionDAG & DAG,MachineFrameInfo & MFI,int ClobberedFI) const4815 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4816                                                    SelectionDAG &DAG,
4817                                                    MachineFrameInfo &MFI,
4818                                                    int ClobberedFI) const {
4819   SmallVector<SDValue, 8> ArgChains;
4820   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4821   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4822 
4823   // Include the original chain at the beginning of the list. When this is
4824   // used by target LowerCall hooks, this helps legalize find the
4825   // CALLSEQ_BEGIN node.
4826   ArgChains.push_back(Chain);
4827 
4828   // Add a chain value for each stack argument corresponding
4829   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4830                             UE = DAG.getEntryNode().getNode()->use_end();
4831        U != UE; ++U)
4832     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4833       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4834         if (FI->getIndex() < 0) {
4835           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4836           int64_t InLastByte = InFirstByte;
4837           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4838 
4839           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4840               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4841             ArgChains.push_back(SDValue(L, 1));
4842         }
4843 
4844   // Build a tokenfactor for all the chains.
4845   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4846 }
4847 
DoesCalleeRestoreStack(CallingConv::ID CallCC,bool TailCallOpt) const4848 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4849                                                    bool TailCallOpt) const {
4850   return CallCC == CallingConv::Fast && TailCallOpt;
4851 }
4852 
4853 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4854 /// and add input and output parameter nodes.
4855 SDValue
LowerCall(CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const4856 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4857                                  SmallVectorImpl<SDValue> &InVals) const {
4858   SelectionDAG &DAG = CLI.DAG;
4859   SDLoc &DL = CLI.DL;
4860   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4861   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4862   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4863   SDValue Chain = CLI.Chain;
4864   SDValue Callee = CLI.Callee;
4865   bool &IsTailCall = CLI.IsTailCall;
4866   CallingConv::ID CallConv = CLI.CallConv;
4867   bool IsVarArg = CLI.IsVarArg;
4868 
4869   MachineFunction &MF = DAG.getMachineFunction();
4870   MachineFunction::CallSiteInfo CSInfo;
4871   bool IsThisReturn = false;
4872 
4873   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4874   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4875   bool IsSibCall = false;
4876 
4877   // Check callee args/returns for SVE registers and set calling convention
4878   // accordingly.
4879   if (CallConv == CallingConv::C) {
4880     bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4881       return Out.VT.isScalableVector();
4882     });
4883     bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4884       return In.VT.isScalableVector();
4885     });
4886 
4887     if (CalleeInSVE || CalleeOutSVE)
4888       CallConv = CallingConv::AArch64_SVE_VectorCall;
4889   }
4890 
4891   if (IsTailCall) {
4892     // Check if it's really possible to do a tail call.
4893     IsTailCall = isEligibleForTailCallOptimization(
4894         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4895     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4896       report_fatal_error("failed to perform tail call elimination on a call "
4897                          "site marked musttail");
4898 
4899     // A sibling call is one where we're under the usual C ABI and not planning
4900     // to change that but can still do a tail call:
4901     if (!TailCallOpt && IsTailCall)
4902       IsSibCall = true;
4903 
4904     if (IsTailCall)
4905       ++NumTailCalls;
4906   }
4907 
4908   // Analyze operands of the call, assigning locations to each operand.
4909   SmallVector<CCValAssign, 16> ArgLocs;
4910   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4911                  *DAG.getContext());
4912 
4913   if (IsVarArg) {
4914     // Handle fixed and variable vector arguments differently.
4915     // Variable vector arguments always go into memory.
4916     unsigned NumArgs = Outs.size();
4917 
4918     for (unsigned i = 0; i != NumArgs; ++i) {
4919       MVT ArgVT = Outs[i].VT;
4920       if (!Outs[i].IsFixed && ArgVT.isScalableVector())
4921         report_fatal_error("Passing SVE types to variadic functions is "
4922                            "currently not supported");
4923 
4924       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4925       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4926                                                /*IsVarArg=*/ !Outs[i].IsFixed);
4927       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4928       assert(!Res && "Call operand has unhandled type");
4929       (void)Res;
4930     }
4931   } else {
4932     // At this point, Outs[].VT may already be promoted to i32. To correctly
4933     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4934     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4935     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4936     // we use a special version of AnalyzeCallOperands to pass in ValVT and
4937     // LocVT.
4938     unsigned NumArgs = Outs.size();
4939     for (unsigned i = 0; i != NumArgs; ++i) {
4940       MVT ValVT = Outs[i].VT;
4941       // Get type of the original argument.
4942       EVT ActualVT = getValueType(DAG.getDataLayout(),
4943                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4944                                   /*AllowUnknown*/ true);
4945       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4946       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4947       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4948       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4949         ValVT = MVT::i8;
4950       else if (ActualMVT == MVT::i16)
4951         ValVT = MVT::i16;
4952 
4953       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4954       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4955       assert(!Res && "Call operand has unhandled type");
4956       (void)Res;
4957     }
4958   }
4959 
4960   // Get a count of how many bytes are to be pushed on the stack.
4961   unsigned NumBytes = CCInfo.getNextStackOffset();
4962 
4963   if (IsSibCall) {
4964     // Since we're not changing the ABI to make this a tail call, the memory
4965     // operands are already available in the caller's incoming argument space.
4966     NumBytes = 0;
4967   }
4968 
4969   // FPDiff is the byte offset of the call's argument area from the callee's.
4970   // Stores to callee stack arguments will be placed in FixedStackSlots offset
4971   // by this amount for a tail call. In a sibling call it must be 0 because the
4972   // caller will deallocate the entire stack and the callee still expects its
4973   // arguments to begin at SP+0. Completely unused for non-tail calls.
4974   int FPDiff = 0;
4975 
4976   if (IsTailCall && !IsSibCall) {
4977     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4978 
4979     // Since callee will pop argument stack as a tail call, we must keep the
4980     // popped size 16-byte aligned.
4981     NumBytes = alignTo(NumBytes, 16);
4982 
4983     // FPDiff will be negative if this tail call requires more space than we
4984     // would automatically have in our incoming argument space. Positive if we
4985     // can actually shrink the stack.
4986     FPDiff = NumReusableBytes - NumBytes;
4987 
4988     // The stack pointer must be 16-byte aligned at all times it's used for a
4989     // memory operation, which in practice means at *all* times and in
4990     // particular across call boundaries. Therefore our own arguments started at
4991     // a 16-byte aligned SP and the delta applied for the tail call should
4992     // satisfy the same constraint.
4993     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4994   }
4995 
4996   // Adjust the stack pointer for the new arguments...
4997   // These operations are automatically eliminated by the prolog/epilog pass
4998   if (!IsSibCall)
4999     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
5000 
5001   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
5002                                         getPointerTy(DAG.getDataLayout()));
5003 
5004   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5005   SmallSet<unsigned, 8> RegsUsed;
5006   SmallVector<SDValue, 8> MemOpChains;
5007   auto PtrVT = getPointerTy(DAG.getDataLayout());
5008 
5009   if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
5010     const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
5011     for (const auto &F : Forwards) {
5012       SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
5013        RegsToPass.emplace_back(F.PReg, Val);
5014     }
5015   }
5016 
5017   // Walk the register/memloc assignments, inserting copies/loads.
5018   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
5019     CCValAssign &VA = ArgLocs[i];
5020     SDValue Arg = OutVals[i];
5021     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5022 
5023     // Promote the value if needed.
5024     switch (VA.getLocInfo()) {
5025     default:
5026       llvm_unreachable("Unknown loc info!");
5027     case CCValAssign::Full:
5028       break;
5029     case CCValAssign::SExt:
5030       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
5031       break;
5032     case CCValAssign::ZExt:
5033       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5034       break;
5035     case CCValAssign::AExt:
5036       if (Outs[i].ArgVT == MVT::i1) {
5037         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
5038         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5039         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
5040       }
5041       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
5042       break;
5043     case CCValAssign::AExtUpper:
5044       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5045       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
5046       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5047                         DAG.getConstant(32, DL, VA.getLocVT()));
5048       break;
5049     case CCValAssign::BCvt:
5050       Arg = DAG.getBitcast(VA.getLocVT(), Arg);
5051       break;
5052     case CCValAssign::Trunc:
5053       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5054       break;
5055     case CCValAssign::FPExt:
5056       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
5057       break;
5058     case CCValAssign::Indirect:
5059       assert(VA.getValVT().isScalableVector() &&
5060              "Only scalable vectors can be passed indirectly");
5061       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5062       Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
5063       Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
5064       int FI = MFI.CreateStackObject(
5065           VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
5066       MFI.setStackID(FI, TargetStackID::SVEVector);
5067 
5068       SDValue SpillSlot = DAG.getFrameIndex(
5069           FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
5070       Chain = DAG.getStore(
5071           Chain, DL, Arg, SpillSlot,
5072           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
5073       Arg = SpillSlot;
5074       break;
5075     }
5076 
5077     if (VA.isRegLoc()) {
5078       if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
5079           Outs[0].VT == MVT::i64) {
5080         assert(VA.getLocVT() == MVT::i64 &&
5081                "unexpected calling convention register assignment");
5082         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
5083                "unexpected use of 'returned'");
5084         IsThisReturn = true;
5085       }
5086       if (RegsUsed.count(VA.getLocReg())) {
5087         // If this register has already been used then we're trying to pack
5088         // parts of an [N x i32] into an X-register. The extension type will
5089         // take care of putting the two halves in the right place but we have to
5090         // combine them.
5091         SDValue &Bits =
5092             std::find_if(RegsToPass.begin(), RegsToPass.end(),
5093                          [=](const std::pair<unsigned, SDValue> &Elt) {
5094                            return Elt.first == VA.getLocReg();
5095                          })
5096                 ->second;
5097         Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5098         // Call site info is used for function's parameter entry value
5099         // tracking. For now we track only simple cases when parameter
5100         // is transferred through whole register.
5101         CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
5102                                     [&VA](MachineFunction::ArgRegPair ArgReg) {
5103                                       return ArgReg.Reg == VA.getLocReg();
5104                                     }),
5105                      CSInfo.end());
5106       } else {
5107         RegsToPass.emplace_back(VA.getLocReg(), Arg);
5108         RegsUsed.insert(VA.getLocReg());
5109         const TargetOptions &Options = DAG.getTarget().Options;
5110         if (Options.EmitCallSiteInfo)
5111           CSInfo.emplace_back(VA.getLocReg(), i);
5112       }
5113     } else {
5114       assert(VA.isMemLoc());
5115 
5116       SDValue DstAddr;
5117       MachinePointerInfo DstInfo;
5118 
5119       // FIXME: This works on big-endian for composite byvals, which are the
5120       // common case. It should also work for fundamental types too.
5121       uint32_t BEAlign = 0;
5122       unsigned OpSize;
5123       if (VA.getLocInfo() == CCValAssign::Indirect)
5124         OpSize = VA.getLocVT().getSizeInBits();
5125       else
5126         OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
5127                                  : VA.getValVT().getSizeInBits();
5128       OpSize = (OpSize + 7) / 8;
5129       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
5130           !Flags.isInConsecutiveRegs()) {
5131         if (OpSize < 8)
5132           BEAlign = 8 - OpSize;
5133       }
5134       unsigned LocMemOffset = VA.getLocMemOffset();
5135       int32_t Offset = LocMemOffset + BEAlign;
5136       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5137       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5138 
5139       if (IsTailCall) {
5140         Offset = Offset + FPDiff;
5141         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5142 
5143         DstAddr = DAG.getFrameIndex(FI, PtrVT);
5144         DstInfo =
5145             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
5146 
5147         // Make sure any stack arguments overlapping with where we're storing
5148         // are loaded before this eventual operation. Otherwise they'll be
5149         // clobbered.
5150         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
5151       } else {
5152         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
5153 
5154         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
5155         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
5156                                                LocMemOffset);
5157       }
5158 
5159       if (Outs[i].Flags.isByVal()) {
5160         SDValue SizeNode =
5161             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
5162         SDValue Cpy = DAG.getMemcpy(
5163             Chain, DL, DstAddr, Arg, SizeNode,
5164             Outs[i].Flags.getNonZeroByValAlign(),
5165             /*isVol = */ false, /*AlwaysInline = */ false,
5166             /*isTailCall = */ false, DstInfo, MachinePointerInfo());
5167 
5168         MemOpChains.push_back(Cpy);
5169       } else {
5170         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
5171         // promoted to a legal register type i32, we should truncate Arg back to
5172         // i1/i8/i16.
5173         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
5174             VA.getValVT() == MVT::i16)
5175           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
5176 
5177         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
5178         MemOpChains.push_back(Store);
5179       }
5180     }
5181   }
5182 
5183   if (!MemOpChains.empty())
5184     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
5185 
5186   // Build a sequence of copy-to-reg nodes chained together with token chain
5187   // and flag operands which copy the outgoing args into the appropriate regs.
5188   SDValue InFlag;
5189   for (auto &RegToPass : RegsToPass) {
5190     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
5191                              RegToPass.second, InFlag);
5192     InFlag = Chain.getValue(1);
5193   }
5194 
5195   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
5196   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
5197   // node so that legalize doesn't hack it.
5198   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5199     auto GV = G->getGlobal();
5200     unsigned OpFlags =
5201         Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
5202     if (OpFlags & AArch64II::MO_GOT) {
5203       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
5204       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5205     } else {
5206       const GlobalValue *GV = G->getGlobal();
5207       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
5208     }
5209   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5210     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5211         Subtarget->isTargetMachO()) {
5212       const char *Sym = S->getSymbol();
5213       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
5214       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
5215     } else {
5216       const char *Sym = S->getSymbol();
5217       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
5218     }
5219   }
5220 
5221   // We don't usually want to end the call-sequence here because we would tidy
5222   // the frame up *after* the call, however in the ABI-changing tail-call case
5223   // we've carefully laid out the parameters so that when sp is reset they'll be
5224   // in the correct location.
5225   if (IsTailCall && !IsSibCall) {
5226     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5227                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
5228     InFlag = Chain.getValue(1);
5229   }
5230 
5231   std::vector<SDValue> Ops;
5232   Ops.push_back(Chain);
5233   Ops.push_back(Callee);
5234 
5235   if (IsTailCall) {
5236     // Each tail call may have to adjust the stack by a different amount, so
5237     // this information must travel along with the operation for eventual
5238     // consumption by emitEpilogue.
5239     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
5240   }
5241 
5242   // Add argument registers to the end of the list so that they are known live
5243   // into the call.
5244   for (auto &RegToPass : RegsToPass)
5245     Ops.push_back(DAG.getRegister(RegToPass.first,
5246                                   RegToPass.second.getValueType()));
5247 
5248   // Add a register mask operand representing the call-preserved registers.
5249   const uint32_t *Mask;
5250   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5251   if (IsThisReturn) {
5252     // For 'this' returns, use the X0-preserving mask if applicable
5253     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
5254     if (!Mask) {
5255       IsThisReturn = false;
5256       Mask = TRI->getCallPreservedMask(MF, CallConv);
5257     }
5258   } else
5259     Mask = TRI->getCallPreservedMask(MF, CallConv);
5260 
5261   if (Subtarget->hasCustomCallingConv())
5262     TRI->UpdateCustomCallPreservedMask(MF, &Mask);
5263 
5264   if (TRI->isAnyArgRegReserved(MF))
5265     TRI->emitReservedArgRegCallError(MF);
5266 
5267   assert(Mask && "Missing call preserved mask for calling convention");
5268   Ops.push_back(DAG.getRegisterMask(Mask));
5269 
5270   if (InFlag.getNode())
5271     Ops.push_back(InFlag);
5272 
5273   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5274 
5275   // If we're doing a tall call, use a TC_RETURN here rather than an
5276   // actual call instruction.
5277   if (IsTailCall) {
5278     MF.getFrameInfo().setHasTailCall();
5279     SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
5280     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
5281     return Ret;
5282   }
5283 
5284   // Returns a chain and a flag for retval copy to use.
5285   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
5286   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
5287   InFlag = Chain.getValue(1);
5288   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
5289 
5290   uint64_t CalleePopBytes =
5291       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
5292 
5293   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
5294                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
5295                              InFlag, DL);
5296   if (!Ins.empty())
5297     InFlag = Chain.getValue(1);
5298 
5299   // Handle result values, copying them out of physregs into vregs that we
5300   // return.
5301   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
5302                          InVals, IsThisReturn,
5303                          IsThisReturn ? OutVals[0] : SDValue());
5304 }
5305 
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const5306 bool AArch64TargetLowering::CanLowerReturn(
5307     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
5308     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
5309   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5310   SmallVector<CCValAssign, 16> RVLocs;
5311   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5312   return CCInfo.CheckReturn(Outs, RetCC);
5313 }
5314 
5315 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & DL,SelectionDAG & DAG) const5316 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
5317                                    bool isVarArg,
5318                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
5319                                    const SmallVectorImpl<SDValue> &OutVals,
5320                                    const SDLoc &DL, SelectionDAG &DAG) const {
5321   auto &MF = DAG.getMachineFunction();
5322   auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5323 
5324   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
5325   SmallVector<CCValAssign, 16> RVLocs;
5326   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5327                  *DAG.getContext());
5328   CCInfo.AnalyzeReturn(Outs, RetCC);
5329 
5330   // Copy the result values into the output registers.
5331   SDValue Flag;
5332   SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
5333   SmallSet<unsigned, 4> RegsUsed;
5334   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
5335        ++i, ++realRVLocIdx) {
5336     CCValAssign &VA = RVLocs[i];
5337     assert(VA.isRegLoc() && "Can only return in registers!");
5338     SDValue Arg = OutVals[realRVLocIdx];
5339 
5340     switch (VA.getLocInfo()) {
5341     default:
5342       llvm_unreachable("Unknown loc info!");
5343     case CCValAssign::Full:
5344       if (Outs[i].ArgVT == MVT::i1) {
5345         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
5346         // value. This is strictly redundant on Darwin (which uses "zeroext
5347         // i1"), but will be optimised out before ISel.
5348         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
5349         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
5350       }
5351       break;
5352     case CCValAssign::BCvt:
5353       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
5354       break;
5355     case CCValAssign::AExt:
5356     case CCValAssign::ZExt:
5357       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5358       break;
5359     case CCValAssign::AExtUpper:
5360       assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
5361       Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
5362       Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
5363                         DAG.getConstant(32, DL, VA.getLocVT()));
5364       break;
5365     }
5366 
5367     if (RegsUsed.count(VA.getLocReg())) {
5368       SDValue &Bits =
5369           std::find_if(RetVals.begin(), RetVals.end(),
5370                        [=](const std::pair<unsigned, SDValue> &Elt) {
5371                          return Elt.first == VA.getLocReg();
5372                        })
5373               ->second;
5374       Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
5375     } else {
5376       RetVals.emplace_back(VA.getLocReg(), Arg);
5377       RegsUsed.insert(VA.getLocReg());
5378     }
5379   }
5380 
5381   SmallVector<SDValue, 4> RetOps(1, Chain);
5382   for (auto &RetVal : RetVals) {
5383     Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
5384     Flag = Chain.getValue(1);
5385     RetOps.push_back(
5386         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
5387   }
5388 
5389   // Windows AArch64 ABIs require that for returning structs by value we copy
5390   // the sret argument into X0 for the return.
5391   // We saved the argument into a virtual register in the entry block,
5392   // so now we copy the value out and into X0.
5393   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
5394     SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
5395                                      getPointerTy(MF.getDataLayout()));
5396 
5397     unsigned RetValReg = AArch64::X0;
5398     Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
5399     Flag = Chain.getValue(1);
5400 
5401     RetOps.push_back(
5402       DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
5403   }
5404 
5405   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5406   const MCPhysReg *I =
5407       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
5408   if (I) {
5409     for (; *I; ++I) {
5410       if (AArch64::GPR64RegClass.contains(*I))
5411         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
5412       else if (AArch64::FPR64RegClass.contains(*I))
5413         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
5414       else
5415         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
5416     }
5417   }
5418 
5419   RetOps[0] = Chain; // Update chain.
5420 
5421   // Add the flag if we have it.
5422   if (Flag.getNode())
5423     RetOps.push_back(Flag);
5424 
5425   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
5426 }
5427 
5428 //===----------------------------------------------------------------------===//
5429 //  Other Lowering Code
5430 //===----------------------------------------------------------------------===//
5431 
getTargetNode(GlobalAddressSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const5432 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
5433                                              SelectionDAG &DAG,
5434                                              unsigned Flag) const {
5435   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
5436                                     N->getOffset(), Flag);
5437 }
5438 
getTargetNode(JumpTableSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const5439 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
5440                                              SelectionDAG &DAG,
5441                                              unsigned Flag) const {
5442   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
5443 }
5444 
getTargetNode(ConstantPoolSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const5445 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
5446                                              SelectionDAG &DAG,
5447                                              unsigned Flag) const {
5448   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
5449                                    N->getOffset(), Flag);
5450 }
5451 
getTargetNode(BlockAddressSDNode * N,EVT Ty,SelectionDAG & DAG,unsigned Flag) const5452 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
5453                                              SelectionDAG &DAG,
5454                                              unsigned Flag) const {
5455   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
5456 }
5457 
5458 // (loadGOT sym)
5459 template <class NodeTy>
getGOT(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const5460 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
5461                                       unsigned Flags) const {
5462   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
5463   SDLoc DL(N);
5464   EVT Ty = getPointerTy(DAG.getDataLayout());
5465   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
5466   // FIXME: Once remat is capable of dealing with instructions with register
5467   // operands, expand this into two nodes instead of using a wrapper node.
5468   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
5469 }
5470 
5471 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
5472 template <class NodeTy>
getAddrLarge(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const5473 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
5474                                             unsigned Flags) const {
5475   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
5476   SDLoc DL(N);
5477   EVT Ty = getPointerTy(DAG.getDataLayout());
5478   const unsigned char MO_NC = AArch64II::MO_NC;
5479   return DAG.getNode(
5480       AArch64ISD::WrapperLarge, DL, Ty,
5481       getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
5482       getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
5483       getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
5484       getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
5485 }
5486 
5487 // (addlow (adrp %hi(sym)) %lo(sym))
5488 template <class NodeTy>
getAddr(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const5489 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
5490                                        unsigned Flags) const {
5491   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
5492   SDLoc DL(N);
5493   EVT Ty = getPointerTy(DAG.getDataLayout());
5494   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
5495   SDValue Lo = getTargetNode(N, Ty, DAG,
5496                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
5497   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
5498   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
5499 }
5500 
5501 // (adr sym)
5502 template <class NodeTy>
getAddrTiny(NodeTy * N,SelectionDAG & DAG,unsigned Flags) const5503 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
5504                                            unsigned Flags) const {
5505   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
5506   SDLoc DL(N);
5507   EVT Ty = getPointerTy(DAG.getDataLayout());
5508   SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
5509   return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
5510 }
5511 
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const5512 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
5513                                                   SelectionDAG &DAG) const {
5514   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
5515   const GlobalValue *GV = GN->getGlobal();
5516   unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5517 
5518   if (OpFlags != AArch64II::MO_NO_FLAG)
5519     assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
5520            "unexpected offset in global node");
5521 
5522   // This also catches the large code model case for Darwin, and tiny code
5523   // model with got relocations.
5524   if ((OpFlags & AArch64II::MO_GOT) != 0) {
5525     return getGOT(GN, DAG, OpFlags);
5526   }
5527 
5528   SDValue Result;
5529   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5530     Result = getAddrLarge(GN, DAG, OpFlags);
5531   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5532     Result = getAddrTiny(GN, DAG, OpFlags);
5533   } else {
5534     Result = getAddr(GN, DAG, OpFlags);
5535   }
5536   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5537   SDLoc DL(GN);
5538   if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
5539     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
5540                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
5541   return Result;
5542 }
5543 
5544 /// Convert a TLS address reference into the correct sequence of loads
5545 /// and calls to compute the variable's address (for Darwin, currently) and
5546 /// return an SDValue containing the final node.
5547 
5548 /// Darwin only has one TLS scheme which must be capable of dealing with the
5549 /// fully general situation, in the worst case. This means:
5550 ///     + "extern __thread" declaration.
5551 ///     + Defined in a possibly unknown dynamic library.
5552 ///
5553 /// The general system is that each __thread variable has a [3 x i64] descriptor
5554 /// which contains information used by the runtime to calculate the address. The
5555 /// only part of this the compiler needs to know about is the first xword, which
5556 /// contains a function pointer that must be called with the address of the
5557 /// entire descriptor in "x0".
5558 ///
5559 /// Since this descriptor may be in a different unit, in general even the
5560 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5561 /// is:
5562 ///     adrp x0, _var@TLVPPAGE
5563 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
5564 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
5565 ///                                      ; the function pointer
5566 ///     blr x1                           ; Uses descriptor address in x0
5567 ///     ; Address of _var is now in x0.
5568 ///
5569 /// If the address of _var's descriptor *is* known to the linker, then it can
5570 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5571 /// a slight efficiency gain.
5572 SDValue
LowerDarwinGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const5573 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5574                                                    SelectionDAG &DAG) const {
5575   assert(Subtarget->isTargetDarwin() &&
5576          "This function expects a Darwin target");
5577 
5578   SDLoc DL(Op);
5579   MVT PtrVT = getPointerTy(DAG.getDataLayout());
5580   MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5581   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5582 
5583   SDValue TLVPAddr =
5584       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5585   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5586 
5587   // The first entry in the descriptor is a function pointer that we must call
5588   // to obtain the address of the variable.
5589   SDValue Chain = DAG.getEntryNode();
5590   SDValue FuncTLVGet = DAG.getLoad(
5591       PtrMemVT, DL, Chain, DescAddr,
5592       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5593       Align(PtrMemVT.getSizeInBits() / 8),
5594       MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5595   Chain = FuncTLVGet.getValue(1);
5596 
5597   // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5598   FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5599 
5600   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5601   MFI.setAdjustsStack(true);
5602 
5603   // TLS calls preserve all registers except those that absolutely must be
5604   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5605   // silly).
5606   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5607   const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5608   if (Subtarget->hasCustomCallingConv())
5609     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5610 
5611   // Finally, we can make the call. This is just a degenerate version of a
5612   // normal AArch64 call node: x0 takes the address of the descriptor, and
5613   // returns the address of the variable in this thread.
5614   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5615   Chain =
5616       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5617                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5618                   DAG.getRegisterMask(Mask), Chain.getValue(1));
5619   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5620 }
5621 
5622 /// Convert a thread-local variable reference into a sequence of instructions to
5623 /// compute the variable's address for the local exec TLS model of ELF targets.
5624 /// The sequence depends on the maximum TLS area size.
LowerELFTLSLocalExec(const GlobalValue * GV,SDValue ThreadBase,const SDLoc & DL,SelectionDAG & DAG) const5625 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5626                                                     SDValue ThreadBase,
5627                                                     const SDLoc &DL,
5628                                                     SelectionDAG &DAG) const {
5629   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5630   SDValue TPOff, Addr;
5631 
5632   switch (DAG.getTarget().Options.TLSSize) {
5633   default:
5634     llvm_unreachable("Unexpected TLS size");
5635 
5636   case 12: {
5637     // mrs   x0, TPIDR_EL0
5638     // add   x0, x0, :tprel_lo12:a
5639     SDValue Var = DAG.getTargetGlobalAddress(
5640         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5641     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5642                                       Var,
5643                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5644                    0);
5645   }
5646 
5647   case 24: {
5648     // mrs   x0, TPIDR_EL0
5649     // add   x0, x0, :tprel_hi12:a
5650     // add   x0, x0, :tprel_lo12_nc:a
5651     SDValue HiVar = DAG.getTargetGlobalAddress(
5652         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5653     SDValue LoVar = DAG.getTargetGlobalAddress(
5654         GV, DL, PtrVT, 0,
5655         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5656     Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5657                                       HiVar,
5658                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5659                    0);
5660     return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5661                                       LoVar,
5662                                       DAG.getTargetConstant(0, DL, MVT::i32)),
5663                    0);
5664   }
5665 
5666   case 32: {
5667     // mrs   x1, TPIDR_EL0
5668     // movz  x0, #:tprel_g1:a
5669     // movk  x0, #:tprel_g0_nc:a
5670     // add   x0, x1, x0
5671     SDValue HiVar = DAG.getTargetGlobalAddress(
5672         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5673     SDValue LoVar = DAG.getTargetGlobalAddress(
5674         GV, DL, PtrVT, 0,
5675         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5676     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5677                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5678                     0);
5679     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5680                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5681                     0);
5682     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5683   }
5684 
5685   case 48: {
5686     // mrs   x1, TPIDR_EL0
5687     // movz  x0, #:tprel_g2:a
5688     // movk  x0, #:tprel_g1_nc:a
5689     // movk  x0, #:tprel_g0_nc:a
5690     // add   x0, x1, x0
5691     SDValue HiVar = DAG.getTargetGlobalAddress(
5692         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5693     SDValue MiVar = DAG.getTargetGlobalAddress(
5694         GV, DL, PtrVT, 0,
5695         AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5696     SDValue LoVar = DAG.getTargetGlobalAddress(
5697         GV, DL, PtrVT, 0,
5698         AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5699     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5700                                        DAG.getTargetConstant(32, DL, MVT::i32)),
5701                     0);
5702     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5703                                        DAG.getTargetConstant(16, DL, MVT::i32)),
5704                     0);
5705     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5706                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5707                     0);
5708     return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5709   }
5710   }
5711 }
5712 
5713 /// When accessing thread-local variables under either the general-dynamic or
5714 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5715 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5716 /// is a function pointer to carry out the resolution.
5717 ///
5718 /// The sequence is:
5719 ///    adrp  x0, :tlsdesc:var
5720 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
5721 ///    add   x0, x0, #:tlsdesc_lo12:var
5722 ///    .tlsdesccall var
5723 ///    blr   x1
5724 ///    (TPIDR_EL0 offset now in x0)
5725 ///
5726 ///  The above sequence must be produced unscheduled, to enable the linker to
5727 ///  optimize/relax this sequence.
5728 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5729 ///  above sequence, and expanded really late in the compilation flow, to ensure
5730 ///  the sequence is produced as per above.
LowerELFTLSDescCallSeq(SDValue SymAddr,const SDLoc & DL,SelectionDAG & DAG) const5731 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5732                                                       const SDLoc &DL,
5733                                                       SelectionDAG &DAG) const {
5734   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5735 
5736   SDValue Chain = DAG.getEntryNode();
5737   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5738 
5739   Chain =
5740       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5741   SDValue Glue = Chain.getValue(1);
5742 
5743   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5744 }
5745 
5746 SDValue
LowerELFGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const5747 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5748                                                 SelectionDAG &DAG) const {
5749   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5750 
5751   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5752 
5753   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5754 
5755   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5756     if (Model == TLSModel::LocalDynamic)
5757       Model = TLSModel::GeneralDynamic;
5758   }
5759 
5760   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5761       Model != TLSModel::LocalExec)
5762     report_fatal_error("ELF TLS only supported in small memory model or "
5763                        "in local exec TLS model");
5764   // Different choices can be made for the maximum size of the TLS area for a
5765   // module. For the small address model, the default TLS size is 16MiB and the
5766   // maximum TLS size is 4GiB.
5767   // FIXME: add tiny and large code model support for TLS access models other
5768   // than local exec. We currently generate the same code as small for tiny,
5769   // which may be larger than needed.
5770 
5771   SDValue TPOff;
5772   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5773   SDLoc DL(Op);
5774   const GlobalValue *GV = GA->getGlobal();
5775 
5776   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5777 
5778   if (Model == TLSModel::LocalExec) {
5779     return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5780   } else if (Model == TLSModel::InitialExec) {
5781     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5782     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5783   } else if (Model == TLSModel::LocalDynamic) {
5784     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5785     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5786     // the beginning of the module's TLS region, followed by a DTPREL offset
5787     // calculation.
5788 
5789     // These accesses will need deduplicating if there's more than one.
5790     AArch64FunctionInfo *MFI =
5791         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5792     MFI->incNumLocalDynamicTLSAccesses();
5793 
5794     // The call needs a relocation too for linker relaxation. It doesn't make
5795     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5796     // the address.
5797     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5798                                                   AArch64II::MO_TLS);
5799 
5800     // Now we can calculate the offset from TPIDR_EL0 to this module's
5801     // thread-local area.
5802     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5803 
5804     // Now use :dtprel_whatever: operations to calculate this variable's offset
5805     // in its thread-storage area.
5806     SDValue HiVar = DAG.getTargetGlobalAddress(
5807         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5808     SDValue LoVar = DAG.getTargetGlobalAddress(
5809         GV, DL, MVT::i64, 0,
5810         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5811 
5812     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5813                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5814                     0);
5815     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5816                                        DAG.getTargetConstant(0, DL, MVT::i32)),
5817                     0);
5818   } else if (Model == TLSModel::GeneralDynamic) {
5819     // The call needs a relocation too for linker relaxation. It doesn't make
5820     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5821     // the address.
5822     SDValue SymAddr =
5823         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5824 
5825     // Finally we can make a call to calculate the offset from tpidr_el0.
5826     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5827   } else
5828     llvm_unreachable("Unsupported ELF TLS access model");
5829 
5830   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5831 }
5832 
5833 SDValue
LowerWindowsGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const5834 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5835                                                     SelectionDAG &DAG) const {
5836   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5837 
5838   SDValue Chain = DAG.getEntryNode();
5839   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5840   SDLoc DL(Op);
5841 
5842   SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5843 
5844   // Load the ThreadLocalStoragePointer from the TEB
5845   // A pointer to the TLS array is located at offset 0x58 from the TEB.
5846   SDValue TLSArray =
5847       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5848   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5849   Chain = TLSArray.getValue(1);
5850 
5851   // Load the TLS index from the C runtime;
5852   // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5853   // This also does the same as LOADgot, but using a generic i32 load,
5854   // while LOADgot only loads i64.
5855   SDValue TLSIndexHi =
5856       DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5857   SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5858       "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5859   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5860   SDValue TLSIndex =
5861       DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5862   TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5863   Chain = TLSIndex.getValue(1);
5864 
5865   // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5866   // offset into the TLSArray.
5867   TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5868   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5869                              DAG.getConstant(3, DL, PtrVT));
5870   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5871                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5872                             MachinePointerInfo());
5873   Chain = TLS.getValue(1);
5874 
5875   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5876   const GlobalValue *GV = GA->getGlobal();
5877   SDValue TGAHi = DAG.getTargetGlobalAddress(
5878       GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5879   SDValue TGALo = DAG.getTargetGlobalAddress(
5880       GV, DL, PtrVT, 0,
5881       AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5882 
5883   // Add the offset from the start of the .tls section (section base).
5884   SDValue Addr =
5885       SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5886                                  DAG.getTargetConstant(0, DL, MVT::i32)),
5887               0);
5888   Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5889   return Addr;
5890 }
5891 
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const5892 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5893                                                      SelectionDAG &DAG) const {
5894   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5895   if (DAG.getTarget().useEmulatedTLS())
5896     return LowerToTLSEmulatedModel(GA, DAG);
5897 
5898   if (Subtarget->isTargetDarwin())
5899     return LowerDarwinGlobalTLSAddress(Op, DAG);
5900   if (Subtarget->isTargetELF())
5901     return LowerELFGlobalTLSAddress(Op, DAG);
5902   if (Subtarget->isTargetWindows())
5903     return LowerWindowsGlobalTLSAddress(Op, DAG);
5904 
5905   llvm_unreachable("Unexpected platform trying to use TLS");
5906 }
5907 
5908 // Looks through \param Val to determine the bit that can be used to
5909 // check the sign of the value. It returns the unextended value and
5910 // the sign bit position.
lookThroughSignExtension(SDValue Val)5911 std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
5912   if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
5913     return {Val.getOperand(0),
5914             cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
5915                 1};
5916 
5917   if (Val.getOpcode() == ISD::SIGN_EXTEND)
5918     return {Val.getOperand(0),
5919             Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
5920 
5921   return {Val, Val.getValueSizeInBits() - 1};
5922 }
5923 
LowerBR_CC(SDValue Op,SelectionDAG & DAG) const5924 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5925   SDValue Chain = Op.getOperand(0);
5926   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5927   SDValue LHS = Op.getOperand(2);
5928   SDValue RHS = Op.getOperand(3);
5929   SDValue Dest = Op.getOperand(4);
5930   SDLoc dl(Op);
5931 
5932   MachineFunction &MF = DAG.getMachineFunction();
5933   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5934   // will not be produced, as they are conditional branch instructions that do
5935   // not set flags.
5936   bool ProduceNonFlagSettingCondBr =
5937       !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5938 
5939   // Handle f128 first, since lowering it will result in comparing the return
5940   // value of a libcall against zero, which is just what the rest of LowerBR_CC
5941   // is expecting to deal with.
5942   if (LHS.getValueType() == MVT::f128) {
5943     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5944 
5945     // If softenSetCCOperands returned a scalar, we need to compare the result
5946     // against zero to select between true and false values.
5947     if (!RHS.getNode()) {
5948       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5949       CC = ISD::SETNE;
5950     }
5951   }
5952 
5953   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5954   // instruction.
5955   if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5956       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5957     // Only lower legal XALUO ops.
5958     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5959       return SDValue();
5960 
5961     // The actual operation with overflow check.
5962     AArch64CC::CondCode OFCC;
5963     SDValue Value, Overflow;
5964     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5965 
5966     if (CC == ISD::SETNE)
5967       OFCC = getInvertedCondCode(OFCC);
5968     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5969 
5970     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5971                        Overflow);
5972   }
5973 
5974   if (LHS.getValueType().isInteger()) {
5975     assert((LHS.getValueType() == RHS.getValueType()) &&
5976            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5977 
5978     // If the RHS of the comparison is zero, we can potentially fold this
5979     // to a specialized branch.
5980     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5981     if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5982       if (CC == ISD::SETEQ) {
5983         // See if we can use a TBZ to fold in an AND as well.
5984         // TBZ has a smaller branch displacement than CBZ.  If the offset is
5985         // out of bounds, a late MI-layer pass rewrites branches.
5986         // 403.gcc is an example that hits this case.
5987         if (LHS.getOpcode() == ISD::AND &&
5988             isa<ConstantSDNode>(LHS.getOperand(1)) &&
5989             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5990           SDValue Test = LHS.getOperand(0);
5991           uint64_t Mask = LHS.getConstantOperandVal(1);
5992           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5993                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5994                              Dest);
5995         }
5996 
5997         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5998       } else if (CC == ISD::SETNE) {
5999         // See if we can use a TBZ to fold in an AND as well.
6000         // TBZ has a smaller branch displacement than CBZ.  If the offset is
6001         // out of bounds, a late MI-layer pass rewrites branches.
6002         // 403.gcc is an example that hits this case.
6003         if (LHS.getOpcode() == ISD::AND &&
6004             isa<ConstantSDNode>(LHS.getOperand(1)) &&
6005             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
6006           SDValue Test = LHS.getOperand(0);
6007           uint64_t Mask = LHS.getConstantOperandVal(1);
6008           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
6009                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
6010                              Dest);
6011         }
6012 
6013         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
6014       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
6015         // Don't combine AND since emitComparison converts the AND to an ANDS
6016         // (a.k.a. TST) and the test in the test bit and branch instruction
6017         // becomes redundant.  This would also increase register pressure.
6018         uint64_t SignBitPos;
6019         std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
6020         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
6021                            DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
6022       }
6023     }
6024     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
6025         LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
6026       // Don't combine AND since emitComparison converts the AND to an ANDS
6027       // (a.k.a. TST) and the test in the test bit and branch instruction
6028       // becomes redundant.  This would also increase register pressure.
6029       uint64_t SignBitPos;
6030       std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
6031       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
6032                          DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
6033     }
6034 
6035     SDValue CCVal;
6036     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6037     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
6038                        Cmp);
6039   }
6040 
6041   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
6042          LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
6043 
6044   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6045   // clean.  Some of them require two branches to implement.
6046   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6047   AArch64CC::CondCode CC1, CC2;
6048   changeFPCCToAArch64CC(CC, CC1, CC2);
6049   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6050   SDValue BR1 =
6051       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
6052   if (CC2 != AArch64CC::AL) {
6053     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6054     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
6055                        Cmp);
6056   }
6057 
6058   return BR1;
6059 }
6060 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG) const6061 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
6062                                               SelectionDAG &DAG) const {
6063   EVT VT = Op.getValueType();
6064   SDLoc DL(Op);
6065 
6066   SDValue In1 = Op.getOperand(0);
6067   SDValue In2 = Op.getOperand(1);
6068   EVT SrcVT = In2.getValueType();
6069 
6070   if (SrcVT.bitsLT(VT))
6071     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
6072   else if (SrcVT.bitsGT(VT))
6073     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
6074 
6075   EVT VecVT;
6076   uint64_t EltMask;
6077   SDValue VecVal1, VecVal2;
6078 
6079   auto setVecVal = [&] (int Idx) {
6080     if (!VT.isVector()) {
6081       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
6082                                           DAG.getUNDEF(VecVT), In1);
6083       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
6084                                           DAG.getUNDEF(VecVT), In2);
6085     } else {
6086       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
6087       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
6088     }
6089   };
6090 
6091   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
6092     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
6093     EltMask = 0x80000000ULL;
6094     setVecVal(AArch64::ssub);
6095   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
6096     VecVT = MVT::v2i64;
6097 
6098     // We want to materialize a mask with the high bit set, but the AdvSIMD
6099     // immediate moves cannot materialize that in a single instruction for
6100     // 64-bit elements. Instead, materialize zero and then negate it.
6101     EltMask = 0;
6102 
6103     setVecVal(AArch64::dsub);
6104   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
6105     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
6106     EltMask = 0x8000ULL;
6107     setVecVal(AArch64::hsub);
6108   } else {
6109     llvm_unreachable("Invalid type for copysign!");
6110   }
6111 
6112   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
6113 
6114   // If we couldn't materialize the mask above, then the mask vector will be
6115   // the zero vector, and we need to negate it here.
6116   if (VT == MVT::f64 || VT == MVT::v2f64) {
6117     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
6118     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
6119     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
6120   }
6121 
6122   SDValue Sel =
6123       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
6124 
6125   if (VT == MVT::f16)
6126     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
6127   if (VT == MVT::f32)
6128     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
6129   else if (VT == MVT::f64)
6130     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
6131   else
6132     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
6133 }
6134 
LowerCTPOP(SDValue Op,SelectionDAG & DAG) const6135 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
6136   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
6137           Attribute::NoImplicitFloat))
6138     return SDValue();
6139 
6140   if (!Subtarget->hasNEON())
6141     return SDValue();
6142 
6143   // While there is no integer popcount instruction, it can
6144   // be more efficiently lowered to the following sequence that uses
6145   // AdvSIMD registers/instructions as long as the copies to/from
6146   // the AdvSIMD registers are cheap.
6147   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
6148   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
6149   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
6150   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
6151   SDValue Val = Op.getOperand(0);
6152   SDLoc DL(Op);
6153   EVT VT = Op.getValueType();
6154 
6155   if (VT == MVT::i32 || VT == MVT::i64) {
6156     if (VT == MVT::i32)
6157       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
6158     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
6159 
6160     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
6161     SDValue UaddLV = DAG.getNode(
6162         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6163         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6164 
6165     if (VT == MVT::i64)
6166       UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
6167     return UaddLV;
6168   } else if (VT == MVT::i128) {
6169     Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
6170 
6171     SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
6172     SDValue UaddLV = DAG.getNode(
6173         ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
6174         DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
6175 
6176     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
6177   }
6178 
6179   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6180           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6181          "Unexpected type for custom ctpop lowering");
6182 
6183   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6184   Val = DAG.getBitcast(VT8Bit, Val);
6185   Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
6186 
6187   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6188   unsigned EltSize = 8;
6189   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6190   while (EltSize != VT.getScalarSizeInBits()) {
6191     EltSize *= 2;
6192     NumElts /= 2;
6193     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6194     Val = DAG.getNode(
6195         ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
6196         DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
6197   }
6198 
6199   return Val;
6200 }
6201 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const6202 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6203 
6204   if (Op.getValueType().isVector())
6205     return LowerVSETCC(Op, DAG);
6206 
6207   bool IsStrict = Op->isStrictFPOpcode();
6208   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
6209   unsigned OpNo = IsStrict ? 1 : 0;
6210   SDValue Chain;
6211   if (IsStrict)
6212     Chain = Op.getOperand(0);
6213   SDValue LHS = Op.getOperand(OpNo + 0);
6214   SDValue RHS = Op.getOperand(OpNo + 1);
6215   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
6216   SDLoc dl(Op);
6217 
6218   // We chose ZeroOrOneBooleanContents, so use zero and one.
6219   EVT VT = Op.getValueType();
6220   SDValue TVal = DAG.getConstant(1, dl, VT);
6221   SDValue FVal = DAG.getConstant(0, dl, VT);
6222 
6223   // Handle f128 first, since one possible outcome is a normal integer
6224   // comparison which gets picked up by the next if statement.
6225   if (LHS.getValueType() == MVT::f128) {
6226     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
6227                         IsSignaling);
6228 
6229     // If softenSetCCOperands returned a scalar, use it.
6230     if (!RHS.getNode()) {
6231       assert(LHS.getValueType() == Op.getValueType() &&
6232              "Unexpected setcc expansion!");
6233       return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
6234     }
6235   }
6236 
6237   if (LHS.getValueType().isInteger()) {
6238     SDValue CCVal;
6239     SDValue Cmp = getAArch64Cmp(
6240         LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
6241 
6242     // Note that we inverted the condition above, so we reverse the order of
6243     // the true and false operands here.  This will allow the setcc to be
6244     // matched to a single CSINC instruction.
6245     SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
6246     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
6247   }
6248 
6249   // Now we know we're dealing with FP values.
6250   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6251          LHS.getValueType() == MVT::f64);
6252 
6253   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
6254   // and do the comparison.
6255   SDValue Cmp;
6256   if (IsStrict)
6257     Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
6258   else
6259     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6260 
6261   AArch64CC::CondCode CC1, CC2;
6262   changeFPCCToAArch64CC(CC, CC1, CC2);
6263   SDValue Res;
6264   if (CC2 == AArch64CC::AL) {
6265     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
6266                           CC2);
6267     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6268 
6269     // Note that we inverted the condition above, so we reverse the order of
6270     // the true and false operands here.  This will allow the setcc to be
6271     // matched to a single CSINC instruction.
6272     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
6273   } else {
6274     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
6275     // totally clean.  Some of them require two CSELs to implement.  As is in
6276     // this case, we emit the first CSEL and then emit a second using the output
6277     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
6278 
6279     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
6280     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6281     SDValue CS1 =
6282         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6283 
6284     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6285     Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6286   }
6287   return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
6288 }
6289 
LowerSELECT_CC(ISD::CondCode CC,SDValue LHS,SDValue RHS,SDValue TVal,SDValue FVal,const SDLoc & dl,SelectionDAG & DAG) const6290 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
6291                                               SDValue RHS, SDValue TVal,
6292                                               SDValue FVal, const SDLoc &dl,
6293                                               SelectionDAG &DAG) const {
6294   // Handle f128 first, because it will result in a comparison of some RTLIB
6295   // call result against zero.
6296   if (LHS.getValueType() == MVT::f128) {
6297     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
6298 
6299     // If softenSetCCOperands returned a scalar, we need to compare the result
6300     // against zero to select between true and false values.
6301     if (!RHS.getNode()) {
6302       RHS = DAG.getConstant(0, dl, LHS.getValueType());
6303       CC = ISD::SETNE;
6304     }
6305   }
6306 
6307   // Also handle f16, for which we need to do a f32 comparison.
6308   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
6309     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
6310     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
6311   }
6312 
6313   // Next, handle integers.
6314   if (LHS.getValueType().isInteger()) {
6315     assert((LHS.getValueType() == RHS.getValueType()) &&
6316            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
6317 
6318     unsigned Opcode = AArch64ISD::CSEL;
6319 
6320     // If both the TVal and the FVal are constants, see if we can swap them in
6321     // order to for a CSINV or CSINC out of them.
6322     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
6323     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
6324 
6325     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
6326       std::swap(TVal, FVal);
6327       std::swap(CTVal, CFVal);
6328       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6329     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
6330       std::swap(TVal, FVal);
6331       std::swap(CTVal, CFVal);
6332       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6333     } else if (TVal.getOpcode() == ISD::XOR) {
6334       // If TVal is a NOT we want to swap TVal and FVal so that we can match
6335       // with a CSINV rather than a CSEL.
6336       if (isAllOnesConstant(TVal.getOperand(1))) {
6337         std::swap(TVal, FVal);
6338         std::swap(CTVal, CFVal);
6339         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6340       }
6341     } else if (TVal.getOpcode() == ISD::SUB) {
6342       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
6343       // that we can match with a CSNEG rather than a CSEL.
6344       if (isNullConstant(TVal.getOperand(0))) {
6345         std::swap(TVal, FVal);
6346         std::swap(CTVal, CFVal);
6347         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6348       }
6349     } else if (CTVal && CFVal) {
6350       const int64_t TrueVal = CTVal->getSExtValue();
6351       const int64_t FalseVal = CFVal->getSExtValue();
6352       bool Swap = false;
6353 
6354       // If both TVal and FVal are constants, see if FVal is the
6355       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
6356       // instead of a CSEL in that case.
6357       if (TrueVal == ~FalseVal) {
6358         Opcode = AArch64ISD::CSINV;
6359       } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
6360                  TrueVal == -FalseVal) {
6361         Opcode = AArch64ISD::CSNEG;
6362       } else if (TVal.getValueType() == MVT::i32) {
6363         // If our operands are only 32-bit wide, make sure we use 32-bit
6364         // arithmetic for the check whether we can use CSINC. This ensures that
6365         // the addition in the check will wrap around properly in case there is
6366         // an overflow (which would not be the case if we do the check with
6367         // 64-bit arithmetic).
6368         const uint32_t TrueVal32 = CTVal->getZExtValue();
6369         const uint32_t FalseVal32 = CFVal->getZExtValue();
6370 
6371         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
6372           Opcode = AArch64ISD::CSINC;
6373 
6374           if (TrueVal32 > FalseVal32) {
6375             Swap = true;
6376           }
6377         }
6378         // 64-bit check whether we can use CSINC.
6379       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
6380         Opcode = AArch64ISD::CSINC;
6381 
6382         if (TrueVal > FalseVal) {
6383           Swap = true;
6384         }
6385       }
6386 
6387       // Swap TVal and FVal if necessary.
6388       if (Swap) {
6389         std::swap(TVal, FVal);
6390         std::swap(CTVal, CFVal);
6391         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
6392       }
6393 
6394       if (Opcode != AArch64ISD::CSEL) {
6395         // Drop FVal since we can get its value by simply inverting/negating
6396         // TVal.
6397         FVal = TVal;
6398       }
6399     }
6400 
6401     // Avoid materializing a constant when possible by reusing a known value in
6402     // a register.  However, don't perform this optimization if the known value
6403     // is one, zero or negative one in the case of a CSEL.  We can always
6404     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
6405     // FVal, respectively.
6406     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
6407     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
6408         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
6409       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6410       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
6411       // "a != C ? x : a" to avoid materializing C.
6412       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
6413         TVal = LHS;
6414       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
6415         FVal = LHS;
6416     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
6417       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
6418       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
6419       // avoid materializing C.
6420       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6421       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
6422         Opcode = AArch64ISD::CSINV;
6423         TVal = LHS;
6424         FVal = DAG.getConstant(0, dl, FVal.getValueType());
6425       }
6426     }
6427 
6428     SDValue CCVal;
6429     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
6430     EVT VT = TVal.getValueType();
6431     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
6432   }
6433 
6434   // Now we know we're dealing with FP values.
6435   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
6436          LHS.getValueType() == MVT::f64);
6437   assert(LHS.getValueType() == RHS.getValueType());
6438   EVT VT = TVal.getValueType();
6439   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
6440 
6441   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6442   // clean.  Some of them require two CSELs to implement.
6443   AArch64CC::CondCode CC1, CC2;
6444   changeFPCCToAArch64CC(CC, CC1, CC2);
6445 
6446   if (DAG.getTarget().Options.UnsafeFPMath) {
6447     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
6448     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
6449     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
6450     if (RHSVal && RHSVal->isZero()) {
6451       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
6452       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
6453 
6454       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
6455           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
6456         TVal = LHS;
6457       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
6458                CFVal && CFVal->isZero() &&
6459                FVal.getValueType() == LHS.getValueType())
6460         FVal = LHS;
6461     }
6462   }
6463 
6464   // Emit first, and possibly only, CSEL.
6465   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
6466   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
6467 
6468   // If we need a second CSEL, emit it, using the output of the first as the
6469   // RHS.  We're effectively OR'ing the two CC's together.
6470   if (CC2 != AArch64CC::AL) {
6471     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
6472     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
6473   }
6474 
6475   // Otherwise, return the output of the first CSEL.
6476   return CS1;
6477 }
6478 
LowerSELECT_CC(SDValue Op,SelectionDAG & DAG) const6479 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
6480                                               SelectionDAG &DAG) const {
6481   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6482   SDValue LHS = Op.getOperand(0);
6483   SDValue RHS = Op.getOperand(1);
6484   SDValue TVal = Op.getOperand(2);
6485   SDValue FVal = Op.getOperand(3);
6486   SDLoc DL(Op);
6487   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6488 }
6489 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const6490 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
6491                                            SelectionDAG &DAG) const {
6492   SDValue CCVal = Op->getOperand(0);
6493   SDValue TVal = Op->getOperand(1);
6494   SDValue FVal = Op->getOperand(2);
6495   SDLoc DL(Op);
6496 
6497   EVT Ty = Op.getValueType();
6498   if (Ty.isScalableVector()) {
6499     SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
6500     MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
6501     SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
6502     return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
6503   }
6504 
6505   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
6506   // instruction.
6507   if (ISD::isOverflowIntrOpRes(CCVal)) {
6508     // Only lower legal XALUO ops.
6509     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
6510       return SDValue();
6511 
6512     AArch64CC::CondCode OFCC;
6513     SDValue Value, Overflow;
6514     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
6515     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
6516 
6517     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
6518                        CCVal, Overflow);
6519   }
6520 
6521   // Lower it the same way as we would lower a SELECT_CC node.
6522   ISD::CondCode CC;
6523   SDValue LHS, RHS;
6524   if (CCVal.getOpcode() == ISD::SETCC) {
6525     LHS = CCVal.getOperand(0);
6526     RHS = CCVal.getOperand(1);
6527     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
6528   } else {
6529     LHS = CCVal;
6530     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
6531     CC = ISD::SETNE;
6532   }
6533   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
6534 }
6535 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const6536 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
6537                                               SelectionDAG &DAG) const {
6538   // Jump table entries as PC relative offsets. No additional tweaking
6539   // is necessary here. Just get the address of the jump table.
6540   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
6541 
6542   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6543       !Subtarget->isTargetMachO()) {
6544     return getAddrLarge(JT, DAG);
6545   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6546     return getAddrTiny(JT, DAG);
6547   }
6548   return getAddr(JT, DAG);
6549 }
6550 
LowerBR_JT(SDValue Op,SelectionDAG & DAG) const6551 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
6552                                           SelectionDAG &DAG) const {
6553   // Jump table entries as PC relative offsets. No additional tweaking
6554   // is necessary here. Just get the address of the jump table.
6555   SDLoc DL(Op);
6556   SDValue JT = Op.getOperand(1);
6557   SDValue Entry = Op.getOperand(2);
6558   int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
6559 
6560   auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6561   AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
6562 
6563   SDNode *Dest =
6564       DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
6565                          Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
6566   return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
6567                      SDValue(Dest, 0));
6568 }
6569 
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const6570 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
6571                                                  SelectionDAG &DAG) const {
6572   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
6573 
6574   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
6575     // Use the GOT for the large code model on iOS.
6576     if (Subtarget->isTargetMachO()) {
6577       return getGOT(CP, DAG);
6578     }
6579     return getAddrLarge(CP, DAG);
6580   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6581     return getAddrTiny(CP, DAG);
6582   } else {
6583     return getAddr(CP, DAG);
6584   }
6585 }
6586 
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const6587 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6588                                                SelectionDAG &DAG) const {
6589   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6590   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6591       !Subtarget->isTargetMachO()) {
6592     return getAddrLarge(BA, DAG);
6593   } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6594     return getAddrTiny(BA, DAG);
6595   }
6596   return getAddr(BA, DAG);
6597 }
6598 
LowerDarwin_VASTART(SDValue Op,SelectionDAG & DAG) const6599 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6600                                                  SelectionDAG &DAG) const {
6601   AArch64FunctionInfo *FuncInfo =
6602       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6603 
6604   SDLoc DL(Op);
6605   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6606                                  getPointerTy(DAG.getDataLayout()));
6607   FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6608   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6609   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6610                       MachinePointerInfo(SV));
6611 }
6612 
LowerWin64_VASTART(SDValue Op,SelectionDAG & DAG) const6613 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6614                                                   SelectionDAG &DAG) const {
6615   AArch64FunctionInfo *FuncInfo =
6616       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6617 
6618   SDLoc DL(Op);
6619   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6620                                      ? FuncInfo->getVarArgsGPRIndex()
6621                                      : FuncInfo->getVarArgsStackIndex(),
6622                                  getPointerTy(DAG.getDataLayout()));
6623   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6624   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6625                       MachinePointerInfo(SV));
6626 }
6627 
LowerAAPCS_VASTART(SDValue Op,SelectionDAG & DAG) const6628 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6629                                                 SelectionDAG &DAG) const {
6630   // The layout of the va_list struct is specified in the AArch64 Procedure Call
6631   // Standard, section B.3.
6632   MachineFunction &MF = DAG.getMachineFunction();
6633   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6634   auto PtrVT = getPointerTy(DAG.getDataLayout());
6635   SDLoc DL(Op);
6636 
6637   SDValue Chain = Op.getOperand(0);
6638   SDValue VAList = Op.getOperand(1);
6639   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6640   SmallVector<SDValue, 4> MemOps;
6641 
6642   // void *__stack at offset 0
6643   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6644   MemOps.push_back(
6645       DAG.getStore(Chain, DL, Stack, VAList, MachinePointerInfo(SV), Align(8)));
6646 
6647   // void *__gr_top at offset 8
6648   int GPRSize = FuncInfo->getVarArgsGPRSize();
6649   if (GPRSize > 0) {
6650     SDValue GRTop, GRTopAddr;
6651 
6652     GRTopAddr =
6653         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6654 
6655     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6656     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6657                         DAG.getConstant(GPRSize, DL, PtrVT));
6658 
6659     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6660                                   MachinePointerInfo(SV, 8), Align(8)));
6661   }
6662 
6663   // void *__vr_top at offset 16
6664   int FPRSize = FuncInfo->getVarArgsFPRSize();
6665   if (FPRSize > 0) {
6666     SDValue VRTop, VRTopAddr;
6667     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6668                             DAG.getConstant(16, DL, PtrVT));
6669 
6670     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6671     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6672                         DAG.getConstant(FPRSize, DL, PtrVT));
6673 
6674     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6675                                   MachinePointerInfo(SV, 16), Align(8)));
6676   }
6677 
6678   // int __gr_offs at offset 24
6679   SDValue GROffsAddr =
6680       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6681   MemOps.push_back(
6682       DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
6683                    GROffsAddr, MachinePointerInfo(SV, 24), Align(4)));
6684 
6685   // int __vr_offs at offset 28
6686   SDValue VROffsAddr =
6687       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6688   MemOps.push_back(
6689       DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
6690                    VROffsAddr, MachinePointerInfo(SV, 28), Align(4)));
6691 
6692   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6693 }
6694 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const6695 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6696                                             SelectionDAG &DAG) const {
6697   MachineFunction &MF = DAG.getMachineFunction();
6698 
6699   if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6700     return LowerWin64_VASTART(Op, DAG);
6701   else if (Subtarget->isTargetDarwin())
6702     return LowerDarwin_VASTART(Op, DAG);
6703   else
6704     return LowerAAPCS_VASTART(Op, DAG);
6705 }
6706 
LowerVACOPY(SDValue Op,SelectionDAG & DAG) const6707 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6708                                            SelectionDAG &DAG) const {
6709   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6710   // pointer.
6711   SDLoc DL(Op);
6712   unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6713   unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6714                          Subtarget->isTargetWindows()) ? PtrSize : 32;
6715   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6716   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6717 
6718   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6719                        DAG.getConstant(VaListSize, DL, MVT::i32),
6720                        Align(PtrSize), false, false, false,
6721                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6722 }
6723 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const6724 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6725   assert(Subtarget->isTargetDarwin() &&
6726          "automatic va_arg instruction only works on Darwin");
6727 
6728   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6729   EVT VT = Op.getValueType();
6730   SDLoc DL(Op);
6731   SDValue Chain = Op.getOperand(0);
6732   SDValue Addr = Op.getOperand(1);
6733   MaybeAlign Align(Op.getConstantOperandVal(3));
6734   unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6735   auto PtrVT = getPointerTy(DAG.getDataLayout());
6736   auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6737   SDValue VAList =
6738       DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6739   Chain = VAList.getValue(1);
6740   VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6741 
6742   if (VT.isScalableVector())
6743     report_fatal_error("Passing SVE types to variadic functions is "
6744                        "currently not supported");
6745 
6746   if (Align && *Align > MinSlotSize) {
6747     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6748                          DAG.getConstant(Align->value() - 1, DL, PtrVT));
6749     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6750                          DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6751   }
6752 
6753   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6754   unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6755 
6756   // Scalar integer and FP values smaller than 64 bits are implicitly extended
6757   // up to 64 bits.  At the very least, we have to increase the striding of the
6758   // vaargs list to match this, and for FP values we need to introduce
6759   // FP_ROUND nodes as well.
6760   if (VT.isInteger() && !VT.isVector())
6761     ArgSize = std::max(ArgSize, MinSlotSize);
6762   bool NeedFPTrunc = false;
6763   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6764     ArgSize = 8;
6765     NeedFPTrunc = true;
6766   }
6767 
6768   // Increment the pointer, VAList, to the next vaarg
6769   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6770                                DAG.getConstant(ArgSize, DL, PtrVT));
6771   VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6772 
6773   // Store the incremented VAList to the legalized pointer
6774   SDValue APStore =
6775       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6776 
6777   // Load the actual argument out of the pointer VAList
6778   if (NeedFPTrunc) {
6779     // Load the value as an f64.
6780     SDValue WideFP =
6781         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6782     // Round the value down to an f32.
6783     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6784                                    DAG.getIntPtrConstant(1, DL));
6785     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6786     // Merge the rounded value with the chain output of the load.
6787     return DAG.getMergeValues(Ops, DL);
6788   }
6789 
6790   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6791 }
6792 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const6793 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6794                                               SelectionDAG &DAG) const {
6795   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6796   MFI.setFrameAddressIsTaken(true);
6797 
6798   EVT VT = Op.getValueType();
6799   SDLoc DL(Op);
6800   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6801   SDValue FrameAddr =
6802       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6803   while (Depth--)
6804     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6805                             MachinePointerInfo());
6806 
6807   if (Subtarget->isTargetILP32())
6808     FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6809                             DAG.getValueType(VT));
6810 
6811   return FrameAddr;
6812 }
6813 
LowerSPONENTRY(SDValue Op,SelectionDAG & DAG) const6814 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6815                                               SelectionDAG &DAG) const {
6816   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6817 
6818   EVT VT = getPointerTy(DAG.getDataLayout());
6819   SDLoc DL(Op);
6820   int FI = MFI.CreateFixedObject(4, 0, false);
6821   return DAG.getFrameIndex(FI, VT);
6822 }
6823 
6824 #define GET_REGISTER_MATCHER
6825 #include "AArch64GenAsmMatcher.inc"
6826 
6827 // FIXME? Maybe this could be a TableGen attribute on some registers and
6828 // this table could be generated automatically from RegInfo.
6829 Register AArch64TargetLowering::
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const6830 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6831   Register Reg = MatchRegisterName(RegName);
6832   if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6833     const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6834     unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6835     if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6836       Reg = 0;
6837   }
6838   if (Reg)
6839     return Reg;
6840   report_fatal_error(Twine("Invalid register name \""
6841                               + StringRef(RegName)  + "\"."));
6842 }
6843 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const6844 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6845                                                      SelectionDAG &DAG) const {
6846   DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6847 
6848   EVT VT = Op.getValueType();
6849   SDLoc DL(Op);
6850 
6851   SDValue FrameAddr =
6852       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6853   SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6854 
6855   return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6856 }
6857 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const6858 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6859                                                SelectionDAG &DAG) const {
6860   MachineFunction &MF = DAG.getMachineFunction();
6861   MachineFrameInfo &MFI = MF.getFrameInfo();
6862   MFI.setReturnAddressIsTaken(true);
6863 
6864   EVT VT = Op.getValueType();
6865   SDLoc DL(Op);
6866   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6867   SDValue ReturnAddress;
6868   if (Depth) {
6869     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6870     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6871     ReturnAddress = DAG.getLoad(
6872         VT, DL, DAG.getEntryNode(),
6873         DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
6874   } else {
6875     // Return LR, which contains the return address. Mark it an implicit
6876     // live-in.
6877     unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6878     ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6879   }
6880 
6881   // The XPACLRI instruction assembles to a hint-space instruction before
6882   // Armv8.3-A therefore this instruction can be safely used for any pre
6883   // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
6884   // that instead.
6885   SDNode *St;
6886   if (Subtarget->hasV8_3aOps()) {
6887     St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
6888   } else {
6889     // XPACLRI operates on LR therefore we must move the operand accordingly.
6890     SDValue Chain =
6891         DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
6892     St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
6893   }
6894   return SDValue(St, 0);
6895 }
6896 
6897 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6898 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
LowerShiftRightParts(SDValue Op,SelectionDAG & DAG) const6899 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6900                                                     SelectionDAG &DAG) const {
6901   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6902   EVT VT = Op.getValueType();
6903   unsigned VTBits = VT.getSizeInBits();
6904   SDLoc dl(Op);
6905   SDValue ShOpLo = Op.getOperand(0);
6906   SDValue ShOpHi = Op.getOperand(1);
6907   SDValue ShAmt = Op.getOperand(2);
6908   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6909 
6910   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6911 
6912   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6913                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6914   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6915 
6916   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6917   // is "undef". We wanted 0, so CSEL it directly.
6918   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6919                                ISD::SETEQ, dl, DAG);
6920   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6921   HiBitsForLo =
6922       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6923                   HiBitsForLo, CCVal, Cmp);
6924 
6925   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6926                                    DAG.getConstant(VTBits, dl, MVT::i64));
6927 
6928   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6929   SDValue LoForNormalShift =
6930       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6931 
6932   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6933                        dl, DAG);
6934   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6935   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6936   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6937                            LoForNormalShift, CCVal, Cmp);
6938 
6939   // AArch64 shifts larger than the register width are wrapped rather than
6940   // clamped, so we can't just emit "hi >> x".
6941   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6942   SDValue HiForBigShift =
6943       Opc == ISD::SRA
6944           ? DAG.getNode(Opc, dl, VT, ShOpHi,
6945                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
6946           : DAG.getConstant(0, dl, VT);
6947   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6948                            HiForNormalShift, CCVal, Cmp);
6949 
6950   SDValue Ops[2] = { Lo, Hi };
6951   return DAG.getMergeValues(Ops, dl);
6952 }
6953 
6954 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6955 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
LowerShiftLeftParts(SDValue Op,SelectionDAG & DAG) const6956 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6957                                                    SelectionDAG &DAG) const {
6958   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6959   EVT VT = Op.getValueType();
6960   unsigned VTBits = VT.getSizeInBits();
6961   SDLoc dl(Op);
6962   SDValue ShOpLo = Op.getOperand(0);
6963   SDValue ShOpHi = Op.getOperand(1);
6964   SDValue ShAmt = Op.getOperand(2);
6965 
6966   assert(Op.getOpcode() == ISD::SHL_PARTS);
6967   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6968                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6969   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6970 
6971   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6972   // is "undef". We wanted 0, so CSEL it directly.
6973   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6974                                ISD::SETEQ, dl, DAG);
6975   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6976   LoBitsForHi =
6977       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6978                   LoBitsForHi, CCVal, Cmp);
6979 
6980   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6981                                    DAG.getConstant(VTBits, dl, MVT::i64));
6982   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6983   SDValue HiForNormalShift =
6984       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6985 
6986   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6987 
6988   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6989                        dl, DAG);
6990   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6991   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6992                            HiForNormalShift, CCVal, Cmp);
6993 
6994   // AArch64 shifts of larger than register sizes are wrapped rather than
6995   // clamped, so we can't just emit "lo << a" if a is too big.
6996   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6997   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6998   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6999                            LoForNormalShift, CCVal, Cmp);
7000 
7001   SDValue Ops[2] = { Lo, Hi };
7002   return DAG.getMergeValues(Ops, dl);
7003 }
7004 
isOffsetFoldingLegal(const GlobalAddressSDNode * GA) const7005 bool AArch64TargetLowering::isOffsetFoldingLegal(
7006     const GlobalAddressSDNode *GA) const {
7007   // Offsets are folded in the DAG combine rather than here so that we can
7008   // intelligently choose an offset based on the uses.
7009   return false;
7010 }
7011 
isFPImmLegal(const APFloat & Imm,EVT VT,bool OptForSize) const7012 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
7013                                          bool OptForSize) const {
7014   bool IsLegal = false;
7015   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
7016   // 16-bit case when target has full fp16 support.
7017   // FIXME: We should be able to handle f128 as well with a clever lowering.
7018   const APInt ImmInt = Imm.bitcastToAPInt();
7019   if (VT == MVT::f64)
7020     IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
7021   else if (VT == MVT::f32)
7022     IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
7023   else if (VT == MVT::f16 && Subtarget->hasFullFP16())
7024     IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
7025   // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
7026   //       generate that fmov.
7027 
7028   // If we can not materialize in immediate field for fmov, check if the
7029   // value can be encoded as the immediate operand of a logical instruction.
7030   // The immediate value will be created with either MOVZ, MOVN, or ORR.
7031   if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
7032     // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
7033     // however the mov+fmov sequence is always better because of the reduced
7034     // cache pressure. The timings are still the same if you consider
7035     // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
7036     // movw+movk is fused). So we limit up to 2 instrdduction at most.
7037     SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
7038     AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
7039 			      Insn);
7040     unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
7041     IsLegal = Insn.size() <= Limit;
7042   }
7043 
7044   LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
7045                     << " imm value: "; Imm.dump(););
7046   return IsLegal;
7047 }
7048 
7049 //===----------------------------------------------------------------------===//
7050 //                          AArch64 Optimization Hooks
7051 //===----------------------------------------------------------------------===//
7052 
getEstimate(const AArch64Subtarget * ST,unsigned Opcode,SDValue Operand,SelectionDAG & DAG,int & ExtraSteps)7053 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
7054                            SDValue Operand, SelectionDAG &DAG,
7055                            int &ExtraSteps) {
7056   EVT VT = Operand.getValueType();
7057   if (ST->hasNEON() &&
7058       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
7059        VT == MVT::f32 || VT == MVT::v1f32 ||
7060        VT == MVT::v2f32 || VT == MVT::v4f32)) {
7061     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
7062       // For the reciprocal estimates, convergence is quadratic, so the number
7063       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
7064       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
7065       // the result for float (23 mantissa bits) is 2 and for double (52
7066       // mantissa bits) is 3.
7067       ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
7068 
7069     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
7070   }
7071 
7072   return SDValue();
7073 }
7074 
getSqrtEstimate(SDValue Operand,SelectionDAG & DAG,int Enabled,int & ExtraSteps,bool & UseOneConst,bool Reciprocal) const7075 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
7076                                                SelectionDAG &DAG, int Enabled,
7077                                                int &ExtraSteps,
7078                                                bool &UseOneConst,
7079                                                bool Reciprocal) const {
7080   if (Enabled == ReciprocalEstimate::Enabled ||
7081       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
7082     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
7083                                        DAG, ExtraSteps)) {
7084       SDLoc DL(Operand);
7085       EVT VT = Operand.getValueType();
7086 
7087       SDNodeFlags Flags;
7088       Flags.setAllowReassociation(true);
7089 
7090       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
7091       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
7092       for (int i = ExtraSteps; i > 0; --i) {
7093         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
7094                                    Flags);
7095         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
7096         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
7097       }
7098       if (!Reciprocal) {
7099         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
7100                                       VT);
7101         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7102         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
7103 
7104         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
7105         // Correct the result if the operand is 0.0.
7106         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
7107                                VT, Eq, Operand, Estimate);
7108       }
7109 
7110       ExtraSteps = 0;
7111       return Estimate;
7112     }
7113 
7114   return SDValue();
7115 }
7116 
getRecipEstimate(SDValue Operand,SelectionDAG & DAG,int Enabled,int & ExtraSteps) const7117 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
7118                                                 SelectionDAG &DAG, int Enabled,
7119                                                 int &ExtraSteps) const {
7120   if (Enabled == ReciprocalEstimate::Enabled)
7121     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
7122                                        DAG, ExtraSteps)) {
7123       SDLoc DL(Operand);
7124       EVT VT = Operand.getValueType();
7125 
7126       SDNodeFlags Flags;
7127       Flags.setAllowReassociation(true);
7128 
7129       // Newton reciprocal iteration: E * (2 - X * E)
7130       // AArch64 reciprocal iteration instruction: (2 - M * N)
7131       for (int i = ExtraSteps; i > 0; --i) {
7132         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
7133                                    Estimate, Flags);
7134         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
7135       }
7136 
7137       ExtraSteps = 0;
7138       return Estimate;
7139     }
7140 
7141   return SDValue();
7142 }
7143 
7144 //===----------------------------------------------------------------------===//
7145 //                          AArch64 Inline Assembly Support
7146 //===----------------------------------------------------------------------===//
7147 
7148 // Table of Constraints
7149 // TODO: This is the current set of constraints supported by ARM for the
7150 // compiler, not all of them may make sense.
7151 //
7152 // r - A general register
7153 // w - An FP/SIMD register of some size in the range v0-v31
7154 // x - An FP/SIMD register of some size in the range v0-v15
7155 // I - Constant that can be used with an ADD instruction
7156 // J - Constant that can be used with a SUB instruction
7157 // K - Constant that can be used with a 32-bit logical instruction
7158 // L - Constant that can be used with a 64-bit logical instruction
7159 // M - Constant that can be used as a 32-bit MOV immediate
7160 // N - Constant that can be used as a 64-bit MOV immediate
7161 // Q - A memory reference with base register and no offset
7162 // S - A symbolic address
7163 // Y - Floating point constant zero
7164 // Z - Integer constant zero
7165 //
7166 //   Note that general register operands will be output using their 64-bit x
7167 // register name, whatever the size of the variable, unless the asm operand
7168 // is prefixed by the %w modifier. Floating-point and SIMD register operands
7169 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
7170 // %q modifier.
LowerXConstraint(EVT ConstraintVT) const7171 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
7172   // At this point, we have to lower this constraint to something else, so we
7173   // lower it to an "r" or "w". However, by doing this we will force the result
7174   // to be in register, while the X constraint is much more permissive.
7175   //
7176   // Although we are correct (we are free to emit anything, without
7177   // constraints), we might break use cases that would expect us to be more
7178   // efficient and emit something else.
7179   if (!Subtarget->hasFPARMv8())
7180     return "r";
7181 
7182   if (ConstraintVT.isFloatingPoint())
7183     return "w";
7184 
7185   if (ConstraintVT.isVector() &&
7186      (ConstraintVT.getSizeInBits() == 64 ||
7187       ConstraintVT.getSizeInBits() == 128))
7188     return "w";
7189 
7190   return "r";
7191 }
7192 
7193 enum PredicateConstraint {
7194   Upl,
7195   Upa,
7196   Invalid
7197 };
7198 
parsePredicateConstraint(StringRef Constraint)7199 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
7200   PredicateConstraint P = PredicateConstraint::Invalid;
7201   if (Constraint == "Upa")
7202     P = PredicateConstraint::Upa;
7203   if (Constraint == "Upl")
7204     P = PredicateConstraint::Upl;
7205   return P;
7206 }
7207 
7208 /// getConstraintType - Given a constraint letter, return the type of
7209 /// constraint it is for this target.
7210 AArch64TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const7211 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
7212   if (Constraint.size() == 1) {
7213     switch (Constraint[0]) {
7214     default:
7215       break;
7216     case 'x':
7217     case 'w':
7218     case 'y':
7219       return C_RegisterClass;
7220     // An address with a single base register. Due to the way we
7221     // currently handle addresses it is the same as 'r'.
7222     case 'Q':
7223       return C_Memory;
7224     case 'I':
7225     case 'J':
7226     case 'K':
7227     case 'L':
7228     case 'M':
7229     case 'N':
7230     case 'Y':
7231     case 'Z':
7232       return C_Immediate;
7233     case 'z':
7234     case 'S': // A symbolic address
7235       return C_Other;
7236     }
7237   } else if (parsePredicateConstraint(Constraint) !=
7238              PredicateConstraint::Invalid)
7239       return C_RegisterClass;
7240   return TargetLowering::getConstraintType(Constraint);
7241 }
7242 
7243 /// Examine constraint type and operand type and determine a weight value.
7244 /// This object must already have been set up with the operand type
7245 /// and the current alternative constraint selected.
7246 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const7247 AArch64TargetLowering::getSingleConstraintMatchWeight(
7248     AsmOperandInfo &info, const char *constraint) const {
7249   ConstraintWeight weight = CW_Invalid;
7250   Value *CallOperandVal = info.CallOperandVal;
7251   // If we don't have a value, we can't do a match,
7252   // but allow it at the lowest weight.
7253   if (!CallOperandVal)
7254     return CW_Default;
7255   Type *type = CallOperandVal->getType();
7256   // Look at the constraint type.
7257   switch (*constraint) {
7258   default:
7259     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7260     break;
7261   case 'x':
7262   case 'w':
7263   case 'y':
7264     if (type->isFloatingPointTy() || type->isVectorTy())
7265       weight = CW_Register;
7266     break;
7267   case 'z':
7268     weight = CW_Constant;
7269     break;
7270   case 'U':
7271     if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
7272       weight = CW_Register;
7273     break;
7274   }
7275   return weight;
7276 }
7277 
7278 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const7279 AArch64TargetLowering::getRegForInlineAsmConstraint(
7280     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
7281   if (Constraint.size() == 1) {
7282     switch (Constraint[0]) {
7283     case 'r':
7284       if (VT.getSizeInBits() == 64)
7285         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
7286       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
7287     case 'w':
7288       if (!Subtarget->hasFPARMv8())
7289         break;
7290       if (VT.isScalableVector())
7291         return std::make_pair(0U, &AArch64::ZPRRegClass);
7292       if (VT.getSizeInBits() == 16)
7293         return std::make_pair(0U, &AArch64::FPR16RegClass);
7294       if (VT.getSizeInBits() == 32)
7295         return std::make_pair(0U, &AArch64::FPR32RegClass);
7296       if (VT.getSizeInBits() == 64)
7297         return std::make_pair(0U, &AArch64::FPR64RegClass);
7298       if (VT.getSizeInBits() == 128)
7299         return std::make_pair(0U, &AArch64::FPR128RegClass);
7300       break;
7301     // The instructions that this constraint is designed for can
7302     // only take 128-bit registers so just use that regclass.
7303     case 'x':
7304       if (!Subtarget->hasFPARMv8())
7305         break;
7306       if (VT.isScalableVector())
7307         return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
7308       if (VT.getSizeInBits() == 128)
7309         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
7310       break;
7311     case 'y':
7312       if (!Subtarget->hasFPARMv8())
7313         break;
7314       if (VT.isScalableVector())
7315         return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
7316       break;
7317     }
7318   } else {
7319     PredicateConstraint PC = parsePredicateConstraint(Constraint);
7320     if (PC != PredicateConstraint::Invalid) {
7321       assert(VT.isScalableVector());
7322       bool restricted = (PC == PredicateConstraint::Upl);
7323       return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
7324                           : std::make_pair(0U, &AArch64::PPRRegClass);
7325     }
7326   }
7327   if (StringRef("{cc}").equals_lower(Constraint))
7328     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
7329 
7330   // Use the default implementation in TargetLowering to convert the register
7331   // constraint into a member of a register class.
7332   std::pair<unsigned, const TargetRegisterClass *> Res;
7333   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7334 
7335   // Not found as a standard register?
7336   if (!Res.second) {
7337     unsigned Size = Constraint.size();
7338     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
7339         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
7340       int RegNo;
7341       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
7342       if (!Failed && RegNo >= 0 && RegNo <= 31) {
7343         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
7344         // By default we'll emit v0-v31 for this unless there's a modifier where
7345         // we'll emit the correct register as well.
7346         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
7347           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
7348           Res.second = &AArch64::FPR64RegClass;
7349         } else {
7350           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
7351           Res.second = &AArch64::FPR128RegClass;
7352         }
7353       }
7354     }
7355   }
7356 
7357   if (Res.second && !Subtarget->hasFPARMv8() &&
7358       !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
7359       !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
7360     return std::make_pair(0U, nullptr);
7361 
7362   return Res;
7363 }
7364 
7365 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7366 /// vector.  If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const7367 void AArch64TargetLowering::LowerAsmOperandForConstraint(
7368     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
7369     SelectionDAG &DAG) const {
7370   SDValue Result;
7371 
7372   // Currently only support length 1 constraints.
7373   if (Constraint.length() != 1)
7374     return;
7375 
7376   char ConstraintLetter = Constraint[0];
7377   switch (ConstraintLetter) {
7378   default:
7379     break;
7380 
7381   // This set of constraints deal with valid constants for various instructions.
7382   // Validate and return a target constant for them if we can.
7383   case 'z': {
7384     // 'z' maps to xzr or wzr so it needs an input of 0.
7385     if (!isNullConstant(Op))
7386       return;
7387 
7388     if (Op.getValueType() == MVT::i64)
7389       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
7390     else
7391       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
7392     break;
7393   }
7394   case 'S': {
7395     // An absolute symbolic address or label reference.
7396     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
7397       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
7398                                           GA->getValueType(0));
7399     } else if (const BlockAddressSDNode *BA =
7400                    dyn_cast<BlockAddressSDNode>(Op)) {
7401       Result =
7402           DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
7403     } else if (const ExternalSymbolSDNode *ES =
7404                    dyn_cast<ExternalSymbolSDNode>(Op)) {
7405       Result =
7406           DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
7407     } else
7408       return;
7409     break;
7410   }
7411 
7412   case 'I':
7413   case 'J':
7414   case 'K':
7415   case 'L':
7416   case 'M':
7417   case 'N':
7418     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
7419     if (!C)
7420       return;
7421 
7422     // Grab the value and do some validation.
7423     uint64_t CVal = C->getZExtValue();
7424     switch (ConstraintLetter) {
7425     // The I constraint applies only to simple ADD or SUB immediate operands:
7426     // i.e. 0 to 4095 with optional shift by 12
7427     // The J constraint applies only to ADD or SUB immediates that would be
7428     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
7429     // instruction [or vice versa], in other words -1 to -4095 with optional
7430     // left shift by 12.
7431     case 'I':
7432       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
7433         break;
7434       return;
7435     case 'J': {
7436       uint64_t NVal = -C->getSExtValue();
7437       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
7438         CVal = C->getSExtValue();
7439         break;
7440       }
7441       return;
7442     }
7443     // The K and L constraints apply *only* to logical immediates, including
7444     // what used to be the MOVI alias for ORR (though the MOVI alias has now
7445     // been removed and MOV should be used). So these constraints have to
7446     // distinguish between bit patterns that are valid 32-bit or 64-bit
7447     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
7448     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
7449     // versa.
7450     case 'K':
7451       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7452         break;
7453       return;
7454     case 'L':
7455       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7456         break;
7457       return;
7458     // The M and N constraints are a superset of K and L respectively, for use
7459     // with the MOV (immediate) alias. As well as the logical immediates they
7460     // also match 32 or 64-bit immediates that can be loaded either using a
7461     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
7462     // (M) or 64-bit 0x1234000000000000 (N) etc.
7463     // As a note some of this code is liberally stolen from the asm parser.
7464     case 'M': {
7465       if (!isUInt<32>(CVal))
7466         return;
7467       if (AArch64_AM::isLogicalImmediate(CVal, 32))
7468         break;
7469       if ((CVal & 0xFFFF) == CVal)
7470         break;
7471       if ((CVal & 0xFFFF0000ULL) == CVal)
7472         break;
7473       uint64_t NCVal = ~(uint32_t)CVal;
7474       if ((NCVal & 0xFFFFULL) == NCVal)
7475         break;
7476       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7477         break;
7478       return;
7479     }
7480     case 'N': {
7481       if (AArch64_AM::isLogicalImmediate(CVal, 64))
7482         break;
7483       if ((CVal & 0xFFFFULL) == CVal)
7484         break;
7485       if ((CVal & 0xFFFF0000ULL) == CVal)
7486         break;
7487       if ((CVal & 0xFFFF00000000ULL) == CVal)
7488         break;
7489       if ((CVal & 0xFFFF000000000000ULL) == CVal)
7490         break;
7491       uint64_t NCVal = ~CVal;
7492       if ((NCVal & 0xFFFFULL) == NCVal)
7493         break;
7494       if ((NCVal & 0xFFFF0000ULL) == NCVal)
7495         break;
7496       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
7497         break;
7498       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
7499         break;
7500       return;
7501     }
7502     default:
7503       return;
7504     }
7505 
7506     // All assembler immediates are 64-bit integers.
7507     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
7508     break;
7509   }
7510 
7511   if (Result.getNode()) {
7512     Ops.push_back(Result);
7513     return;
7514   }
7515 
7516   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7517 }
7518 
7519 //===----------------------------------------------------------------------===//
7520 //                     AArch64 Advanced SIMD Support
7521 //===----------------------------------------------------------------------===//
7522 
7523 /// WidenVector - Given a value in the V64 register class, produce the
7524 /// equivalent value in the V128 register class.
WidenVector(SDValue V64Reg,SelectionDAG & DAG)7525 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
7526   EVT VT = V64Reg.getValueType();
7527   unsigned NarrowSize = VT.getVectorNumElements();
7528   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7529   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
7530   SDLoc DL(V64Reg);
7531 
7532   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
7533                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
7534 }
7535 
7536 /// getExtFactor - Determine the adjustment factor for the position when
7537 /// generating an "extract from vector registers" instruction.
getExtFactor(SDValue & V)7538 static unsigned getExtFactor(SDValue &V) {
7539   EVT EltType = V.getValueType().getVectorElementType();
7540   return EltType.getSizeInBits() / 8;
7541 }
7542 
7543 /// NarrowVector - Given a value in the V128 register class, produce the
7544 /// equivalent value in the V64 register class.
NarrowVector(SDValue V128Reg,SelectionDAG & DAG)7545 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
7546   EVT VT = V128Reg.getValueType();
7547   unsigned WideSize = VT.getVectorNumElements();
7548   MVT EltTy = VT.getVectorElementType().getSimpleVT();
7549   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
7550   SDLoc DL(V128Reg);
7551 
7552   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
7553 }
7554 
7555 // Gather data to see if the operation can be modelled as a
7556 // shuffle in combination with VEXTs.
ReconstructShuffle(SDValue Op,SelectionDAG & DAG) const7557 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
7558                                                   SelectionDAG &DAG) const {
7559   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7560   LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
7561   SDLoc dl(Op);
7562   EVT VT = Op.getValueType();
7563   assert(!VT.isScalableVector() &&
7564          "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
7565   unsigned NumElts = VT.getVectorNumElements();
7566 
7567   struct ShuffleSourceInfo {
7568     SDValue Vec;
7569     unsigned MinElt;
7570     unsigned MaxElt;
7571 
7572     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7573     // be compatible with the shuffle we intend to construct. As a result
7574     // ShuffleVec will be some sliding window into the original Vec.
7575     SDValue ShuffleVec;
7576 
7577     // Code should guarantee that element i in Vec starts at element "WindowBase
7578     // + i * WindowScale in ShuffleVec".
7579     int WindowBase;
7580     int WindowScale;
7581 
7582     ShuffleSourceInfo(SDValue Vec)
7583       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
7584           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
7585 
7586     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7587   };
7588 
7589   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7590   // node.
7591   SmallVector<ShuffleSourceInfo, 2> Sources;
7592   for (unsigned i = 0; i < NumElts; ++i) {
7593     SDValue V = Op.getOperand(i);
7594     if (V.isUndef())
7595       continue;
7596     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7597              !isa<ConstantSDNode>(V.getOperand(1))) {
7598       LLVM_DEBUG(
7599           dbgs() << "Reshuffle failed: "
7600                     "a shuffle can only come from building a vector from "
7601                     "various elements of other vectors, provided their "
7602                     "indices are constant\n");
7603       return SDValue();
7604     }
7605 
7606     // Add this element source to the list if it's not already there.
7607     SDValue SourceVec = V.getOperand(0);
7608     auto Source = find(Sources, SourceVec);
7609     if (Source == Sources.end())
7610       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7611 
7612     // Update the minimum and maximum lane number seen.
7613     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7614     Source->MinElt = std::min(Source->MinElt, EltNo);
7615     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7616   }
7617 
7618   if (Sources.size() > 2) {
7619     LLVM_DEBUG(
7620         dbgs() << "Reshuffle failed: currently only do something sane when at "
7621                   "most two source vectors are involved\n");
7622     return SDValue();
7623   }
7624 
7625   // Find out the smallest element size among result and two sources, and use
7626   // it as element size to build the shuffle_vector.
7627   EVT SmallestEltTy = VT.getVectorElementType();
7628   for (auto &Source : Sources) {
7629     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7630     if (SrcEltTy.bitsLT(SmallestEltTy)) {
7631       SmallestEltTy = SrcEltTy;
7632     }
7633   }
7634   unsigned ResMultiplier =
7635       VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
7636   uint64_t VTSize = VT.getFixedSizeInBits();
7637   NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
7638   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7639 
7640   // If the source vector is too wide or too narrow, we may nevertheless be able
7641   // to construct a compatible shuffle either by concatenating it with UNDEF or
7642   // extracting a suitable range of elements.
7643   for (auto &Src : Sources) {
7644     EVT SrcVT = Src.ShuffleVec.getValueType();
7645 
7646     uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
7647     if (SrcVTSize == VTSize)
7648       continue;
7649 
7650     // This stage of the search produces a source with the same element type as
7651     // the original, but with a total width matching the BUILD_VECTOR output.
7652     EVT EltVT = SrcVT.getVectorElementType();
7653     unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
7654     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7655 
7656     if (SrcVTSize < VTSize) {
7657       assert(2 * SrcVTSize == VTSize);
7658       // We can pad out the smaller vector for free, so if it's part of a
7659       // shuffle...
7660       Src.ShuffleVec =
7661           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7662                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7663       continue;
7664     }
7665 
7666     if (SrcVTSize != 2 * VTSize) {
7667       LLVM_DEBUG(
7668           dbgs() << "Reshuffle failed: result vector too small to extract\n");
7669       return SDValue();
7670     }
7671 
7672     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7673       LLVM_DEBUG(
7674           dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7675       return SDValue();
7676     }
7677 
7678     if (Src.MinElt >= NumSrcElts) {
7679       // The extraction can just take the second half
7680       Src.ShuffleVec =
7681           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7682                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7683       Src.WindowBase = -NumSrcElts;
7684     } else if (Src.MaxElt < NumSrcElts) {
7685       // The extraction can just take the first half
7686       Src.ShuffleVec =
7687           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7688                       DAG.getConstant(0, dl, MVT::i64));
7689     } else {
7690       // An actual VEXT is needed
7691       SDValue VEXTSrc1 =
7692           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7693                       DAG.getConstant(0, dl, MVT::i64));
7694       SDValue VEXTSrc2 =
7695           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7696                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
7697       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7698 
7699       if (!SrcVT.is64BitVector()) {
7700         LLVM_DEBUG(
7701           dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
7702                     "for SVE vectors.");
7703         return SDValue();
7704       }
7705 
7706       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7707                                    VEXTSrc2,
7708                                    DAG.getConstant(Imm, dl, MVT::i32));
7709       Src.WindowBase = -Src.MinElt;
7710     }
7711   }
7712 
7713   // Another possible incompatibility occurs from the vector element types. We
7714   // can fix this by bitcasting the source vectors to the same type we intend
7715   // for the shuffle.
7716   for (auto &Src : Sources) {
7717     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7718     if (SrcEltTy == SmallestEltTy)
7719       continue;
7720     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7721     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7722     Src.WindowScale =
7723         SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
7724     Src.WindowBase *= Src.WindowScale;
7725   }
7726 
7727   // Final sanity check before we try to actually produce a shuffle.
7728   LLVM_DEBUG(for (auto Src
7729                   : Sources)
7730                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7731 
7732   // The stars all align, our next step is to produce the mask for the shuffle.
7733   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7734   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7735   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7736     SDValue Entry = Op.getOperand(i);
7737     if (Entry.isUndef())
7738       continue;
7739 
7740     auto Src = find(Sources, Entry.getOperand(0));
7741     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7742 
7743     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7744     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7745     // segment.
7746     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7747     int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
7748                                VT.getScalarSizeInBits());
7749     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7750 
7751     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7752     // starting at the appropriate offset.
7753     int *LaneMask = &Mask[i * ResMultiplier];
7754 
7755     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7756     ExtractBase += NumElts * (Src - Sources.begin());
7757     for (int j = 0; j < LanesDefined; ++j)
7758       LaneMask[j] = ExtractBase + j;
7759   }
7760 
7761   // Final check before we try to produce nonsense...
7762   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7763     LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7764     return SDValue();
7765   }
7766 
7767   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7768   for (unsigned i = 0; i < Sources.size(); ++i)
7769     ShuffleOps[i] = Sources[i].ShuffleVec;
7770 
7771   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7772                                          ShuffleOps[1], Mask);
7773   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7774 
7775   LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7776              dbgs() << "Reshuffle, creating node: "; V.dump(););
7777 
7778   return V;
7779 }
7780 
7781 // check if an EXT instruction can handle the shuffle mask when the
7782 // vector sources of the shuffle are the same.
isSingletonEXTMask(ArrayRef<int> M,EVT VT,unsigned & Imm)7783 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7784   unsigned NumElts = VT.getVectorNumElements();
7785 
7786   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
7787   if (M[0] < 0)
7788     return false;
7789 
7790   Imm = M[0];
7791 
7792   // If this is a VEXT shuffle, the immediate value is the index of the first
7793   // element.  The other shuffle indices must be the successive elements after
7794   // the first one.
7795   unsigned ExpectedElt = Imm;
7796   for (unsigned i = 1; i < NumElts; ++i) {
7797     // Increment the expected index.  If it wraps around, just follow it
7798     // back to index zero and keep going.
7799     ++ExpectedElt;
7800     if (ExpectedElt == NumElts)
7801       ExpectedElt = 0;
7802 
7803     if (M[i] < 0)
7804       continue; // ignore UNDEF indices
7805     if (ExpectedElt != static_cast<unsigned>(M[i]))
7806       return false;
7807   }
7808 
7809   return true;
7810 }
7811 
7812 /// Check if a vector shuffle corresponds to a DUP instructions with a larger
7813 /// element width than the vector lane type. If that is the case the function
7814 /// returns true and writes the value of the DUP instruction lane operand into
7815 /// DupLaneOp
isWideDUPMask(ArrayRef<int> M,EVT VT,unsigned BlockSize,unsigned & DupLaneOp)7816 static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
7817                           unsigned &DupLaneOp) {
7818   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7819          "Only possible block sizes for wide DUP are: 16, 32, 64");
7820 
7821   if (BlockSize <= VT.getScalarSizeInBits())
7822     return false;
7823   if (BlockSize % VT.getScalarSizeInBits() != 0)
7824     return false;
7825   if (VT.getSizeInBits() % BlockSize != 0)
7826     return false;
7827 
7828   size_t SingleVecNumElements = VT.getVectorNumElements();
7829   size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
7830   size_t NumBlocks = VT.getSizeInBits() / BlockSize;
7831 
7832   // We are looking for masks like
7833   // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
7834   // might be replaced by 'undefined'. BlockIndices will eventually contain
7835   // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
7836   // for the above examples)
7837   SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
7838   for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
7839     for (size_t I = 0; I < NumEltsPerBlock; I++) {
7840       int Elt = M[BlockIndex * NumEltsPerBlock + I];
7841       if (Elt < 0)
7842         continue;
7843       // For now we don't support shuffles that use the second operand
7844       if ((unsigned)Elt >= SingleVecNumElements)
7845         return false;
7846       if (BlockElts[I] < 0)
7847         BlockElts[I] = Elt;
7848       else if (BlockElts[I] != Elt)
7849         return false;
7850     }
7851 
7852   // We found a candidate block (possibly with some undefs). It must be a
7853   // sequence of consecutive integers starting with a value divisible by
7854   // NumEltsPerBlock with some values possibly replaced by undef-s.
7855 
7856   // Find first non-undef element
7857   auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
7858   assert(FirstRealEltIter != BlockElts.end() &&
7859          "Shuffle with all-undefs must have been caught by previous cases, "
7860          "e.g. isSplat()");
7861   if (FirstRealEltIter == BlockElts.end()) {
7862     DupLaneOp = 0;
7863     return true;
7864   }
7865 
7866   // Index of FirstRealElt in BlockElts
7867   size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
7868 
7869   if ((unsigned)*FirstRealEltIter < FirstRealIndex)
7870     return false;
7871   // BlockElts[0] must have the following value if it isn't undef:
7872   size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
7873 
7874   // Check the first element
7875   if (Elt0 % NumEltsPerBlock != 0)
7876     return false;
7877   // Check that the sequence indeed consists of consecutive integers (modulo
7878   // undefs)
7879   for (size_t I = 0; I < NumEltsPerBlock; I++)
7880     if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
7881       return false;
7882 
7883   DupLaneOp = Elt0 / NumEltsPerBlock;
7884   return true;
7885 }
7886 
7887 // check if an EXT instruction can handle the shuffle mask when the
7888 // vector sources of the shuffle are different.
isEXTMask(ArrayRef<int> M,EVT VT,bool & ReverseEXT,unsigned & Imm)7889 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7890                       unsigned &Imm) {
7891   // Look for the first non-undef element.
7892   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7893 
7894   // Benefit form APInt to handle overflow when calculating expected element.
7895   unsigned NumElts = VT.getVectorNumElements();
7896   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7897   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7898   // The following shuffle indices must be the successive elements after the
7899   // first real element.
7900   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7901       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7902   if (FirstWrongElt != M.end())
7903     return false;
7904 
7905   // The index of an EXT is the first element if it is not UNDEF.
7906   // Watch out for the beginning UNDEFs. The EXT index should be the expected
7907   // value of the first element.  E.g.
7908   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7909   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7910   // ExpectedElt is the last mask index plus 1.
7911   Imm = ExpectedElt.getZExtValue();
7912 
7913   // There are two difference cases requiring to reverse input vectors.
7914   // For example, for vector <4 x i32> we have the following cases,
7915   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7916   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7917   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7918   // to reverse two input vectors.
7919   if (Imm < NumElts)
7920     ReverseEXT = true;
7921   else
7922     Imm -= NumElts;
7923 
7924   return true;
7925 }
7926 
7927 /// isREVMask - Check if a vector shuffle corresponds to a REV
7928 /// instruction with the specified blocksize.  (The order of the elements
7929 /// within each block of the vector is reversed.)
isREVMask(ArrayRef<int> M,EVT VT,unsigned BlockSize)7930 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7931   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7932          "Only possible block sizes for REV are: 16, 32, 64");
7933 
7934   unsigned EltSz = VT.getScalarSizeInBits();
7935   if (EltSz == 64)
7936     return false;
7937 
7938   unsigned NumElts = VT.getVectorNumElements();
7939   unsigned BlockElts = M[0] + 1;
7940   // If the first shuffle index is UNDEF, be optimistic.
7941   if (M[0] < 0)
7942     BlockElts = BlockSize / EltSz;
7943 
7944   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7945     return false;
7946 
7947   for (unsigned i = 0; i < NumElts; ++i) {
7948     if (M[i] < 0)
7949       continue; // ignore UNDEF indices
7950     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7951       return false;
7952   }
7953 
7954   return true;
7955 }
7956 
isZIPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7957 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7958   unsigned NumElts = VT.getVectorNumElements();
7959   if (NumElts % 2 != 0)
7960     return false;
7961   WhichResult = (M[0] == 0 ? 0 : 1);
7962   unsigned Idx = WhichResult * NumElts / 2;
7963   for (unsigned i = 0; i != NumElts; i += 2) {
7964     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7965         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7966       return false;
7967     Idx += 1;
7968   }
7969 
7970   return true;
7971 }
7972 
isUZPMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7973 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7974   unsigned NumElts = VT.getVectorNumElements();
7975   WhichResult = (M[0] == 0 ? 0 : 1);
7976   for (unsigned i = 0; i != NumElts; ++i) {
7977     if (M[i] < 0)
7978       continue; // ignore UNDEF indices
7979     if ((unsigned)M[i] != 2 * i + WhichResult)
7980       return false;
7981   }
7982 
7983   return true;
7984 }
7985 
isTRNMask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)7986 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7987   unsigned NumElts = VT.getVectorNumElements();
7988   if (NumElts % 2 != 0)
7989     return false;
7990   WhichResult = (M[0] == 0 ? 0 : 1);
7991   for (unsigned i = 0; i < NumElts; i += 2) {
7992     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7993         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7994       return false;
7995   }
7996   return true;
7997 }
7998 
7999 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
8000 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8001 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
isZIP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)8002 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8003   unsigned NumElts = VT.getVectorNumElements();
8004   if (NumElts % 2 != 0)
8005     return false;
8006   WhichResult = (M[0] == 0 ? 0 : 1);
8007   unsigned Idx = WhichResult * NumElts / 2;
8008   for (unsigned i = 0; i != NumElts; i += 2) {
8009     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
8010         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
8011       return false;
8012     Idx += 1;
8013   }
8014 
8015   return true;
8016 }
8017 
8018 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
8019 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8020 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
isUZP_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)8021 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8022   unsigned Half = VT.getVectorNumElements() / 2;
8023   WhichResult = (M[0] == 0 ? 0 : 1);
8024   for (unsigned j = 0; j != 2; ++j) {
8025     unsigned Idx = WhichResult;
8026     for (unsigned i = 0; i != Half; ++i) {
8027       int MIdx = M[i + j * Half];
8028       if (MIdx >= 0 && (unsigned)MIdx != Idx)
8029         return false;
8030       Idx += 2;
8031     }
8032   }
8033 
8034   return true;
8035 }
8036 
8037 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
8038 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
8039 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
isTRN_v_undef_Mask(ArrayRef<int> M,EVT VT,unsigned & WhichResult)8040 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
8041   unsigned NumElts = VT.getVectorNumElements();
8042   if (NumElts % 2 != 0)
8043     return false;
8044   WhichResult = (M[0] == 0 ? 0 : 1);
8045   for (unsigned i = 0; i < NumElts; i += 2) {
8046     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
8047         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
8048       return false;
8049   }
8050   return true;
8051 }
8052 
isINSMask(ArrayRef<int> M,int NumInputElements,bool & DstIsLeft,int & Anomaly)8053 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
8054                       bool &DstIsLeft, int &Anomaly) {
8055   if (M.size() != static_cast<size_t>(NumInputElements))
8056     return false;
8057 
8058   int NumLHSMatch = 0, NumRHSMatch = 0;
8059   int LastLHSMismatch = -1, LastRHSMismatch = -1;
8060 
8061   for (int i = 0; i < NumInputElements; ++i) {
8062     if (M[i] == -1) {
8063       ++NumLHSMatch;
8064       ++NumRHSMatch;
8065       continue;
8066     }
8067 
8068     if (M[i] == i)
8069       ++NumLHSMatch;
8070     else
8071       LastLHSMismatch = i;
8072 
8073     if (M[i] == i + NumInputElements)
8074       ++NumRHSMatch;
8075     else
8076       LastRHSMismatch = i;
8077   }
8078 
8079   if (NumLHSMatch == NumInputElements - 1) {
8080     DstIsLeft = true;
8081     Anomaly = LastLHSMismatch;
8082     return true;
8083   } else if (NumRHSMatch == NumInputElements - 1) {
8084     DstIsLeft = false;
8085     Anomaly = LastRHSMismatch;
8086     return true;
8087   }
8088 
8089   return false;
8090 }
8091 
isConcatMask(ArrayRef<int> Mask,EVT VT,bool SplitLHS)8092 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
8093   if (VT.getSizeInBits() != 128)
8094     return false;
8095 
8096   unsigned NumElts = VT.getVectorNumElements();
8097 
8098   for (int I = 0, E = NumElts / 2; I != E; I++) {
8099     if (Mask[I] != I)
8100       return false;
8101   }
8102 
8103   int Offset = NumElts / 2;
8104   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
8105     if (Mask[I] != I + SplitLHS * Offset)
8106       return false;
8107   }
8108 
8109   return true;
8110 }
8111 
tryFormConcatFromShuffle(SDValue Op,SelectionDAG & DAG)8112 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
8113   SDLoc DL(Op);
8114   EVT VT = Op.getValueType();
8115   SDValue V0 = Op.getOperand(0);
8116   SDValue V1 = Op.getOperand(1);
8117   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
8118 
8119   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
8120       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
8121     return SDValue();
8122 
8123   bool SplitV0 = V0.getValueSizeInBits() == 128;
8124 
8125   if (!isConcatMask(Mask, VT, SplitV0))
8126     return SDValue();
8127 
8128   EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8129   if (SplitV0) {
8130     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
8131                      DAG.getConstant(0, DL, MVT::i64));
8132   }
8133   if (V1.getValueSizeInBits() == 128) {
8134     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
8135                      DAG.getConstant(0, DL, MVT::i64));
8136   }
8137   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
8138 }
8139 
8140 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8141 /// the specified operations to build the shuffle.
GeneratePerfectShuffle(unsigned PFEntry,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const SDLoc & dl)8142 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8143                                       SDValue RHS, SelectionDAG &DAG,
8144                                       const SDLoc &dl) {
8145   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8146   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
8147   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
8148 
8149   enum {
8150     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8151     OP_VREV,
8152     OP_VDUP0,
8153     OP_VDUP1,
8154     OP_VDUP2,
8155     OP_VDUP3,
8156     OP_VEXT1,
8157     OP_VEXT2,
8158     OP_VEXT3,
8159     OP_VUZPL, // VUZP, left result
8160     OP_VUZPR, // VUZP, right result
8161     OP_VZIPL, // VZIP, left result
8162     OP_VZIPR, // VZIP, right result
8163     OP_VTRNL, // VTRN, left result
8164     OP_VTRNR  // VTRN, right result
8165   };
8166 
8167   if (OpNum == OP_COPY) {
8168     if (LHSID == (1 * 9 + 2) * 9 + 3)
8169       return LHS;
8170     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
8171     return RHS;
8172   }
8173 
8174   SDValue OpLHS, OpRHS;
8175   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8176   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8177   EVT VT = OpLHS.getValueType();
8178 
8179   switch (OpNum) {
8180   default:
8181     llvm_unreachable("Unknown shuffle opcode!");
8182   case OP_VREV:
8183     // VREV divides the vector in half and swaps within the half.
8184     if (VT.getVectorElementType() == MVT::i32 ||
8185         VT.getVectorElementType() == MVT::f32)
8186       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
8187     // vrev <4 x i16> -> REV32
8188     if (VT.getVectorElementType() == MVT::i16 ||
8189         VT.getVectorElementType() == MVT::f16 ||
8190         VT.getVectorElementType() == MVT::bf16)
8191       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
8192     // vrev <4 x i8> -> REV16
8193     assert(VT.getVectorElementType() == MVT::i8);
8194     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
8195   case OP_VDUP0:
8196   case OP_VDUP1:
8197   case OP_VDUP2:
8198   case OP_VDUP3: {
8199     EVT EltTy = VT.getVectorElementType();
8200     unsigned Opcode;
8201     if (EltTy == MVT::i8)
8202       Opcode = AArch64ISD::DUPLANE8;
8203     else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
8204       Opcode = AArch64ISD::DUPLANE16;
8205     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
8206       Opcode = AArch64ISD::DUPLANE32;
8207     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
8208       Opcode = AArch64ISD::DUPLANE64;
8209     else
8210       llvm_unreachable("Invalid vector element type?");
8211 
8212     if (VT.getSizeInBits() == 64)
8213       OpLHS = WidenVector(OpLHS, DAG);
8214     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
8215     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
8216   }
8217   case OP_VEXT1:
8218   case OP_VEXT2:
8219   case OP_VEXT3: {
8220     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
8221     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
8222                        DAG.getConstant(Imm, dl, MVT::i32));
8223   }
8224   case OP_VUZPL:
8225     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
8226                        OpRHS);
8227   case OP_VUZPR:
8228     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
8229                        OpRHS);
8230   case OP_VZIPL:
8231     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
8232                        OpRHS);
8233   case OP_VZIPR:
8234     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
8235                        OpRHS);
8236   case OP_VTRNL:
8237     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
8238                        OpRHS);
8239   case OP_VTRNR:
8240     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
8241                        OpRHS);
8242   }
8243 }
8244 
GenerateTBL(SDValue Op,ArrayRef<int> ShuffleMask,SelectionDAG & DAG)8245 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
8246                            SelectionDAG &DAG) {
8247   // Check to see if we can use the TBL instruction.
8248   SDValue V1 = Op.getOperand(0);
8249   SDValue V2 = Op.getOperand(1);
8250   SDLoc DL(Op);
8251 
8252   EVT EltVT = Op.getValueType().getVectorElementType();
8253   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
8254 
8255   SmallVector<SDValue, 8> TBLMask;
8256   for (int Val : ShuffleMask) {
8257     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
8258       unsigned Offset = Byte + Val * BytesPerElt;
8259       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
8260     }
8261   }
8262 
8263   MVT IndexVT = MVT::v8i8;
8264   unsigned IndexLen = 8;
8265   if (Op.getValueSizeInBits() == 128) {
8266     IndexVT = MVT::v16i8;
8267     IndexLen = 16;
8268   }
8269 
8270   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
8271   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
8272 
8273   SDValue Shuffle;
8274   if (V2.getNode()->isUndef()) {
8275     if (IndexLen == 8)
8276       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
8277     Shuffle = DAG.getNode(
8278         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8279         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8280         DAG.getBuildVector(IndexVT, DL,
8281                            makeArrayRef(TBLMask.data(), IndexLen)));
8282   } else {
8283     if (IndexLen == 8) {
8284       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
8285       Shuffle = DAG.getNode(
8286           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8287           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
8288           DAG.getBuildVector(IndexVT, DL,
8289                              makeArrayRef(TBLMask.data(), IndexLen)));
8290     } else {
8291       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
8292       // cannot currently represent the register constraints on the input
8293       // table registers.
8294       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
8295       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
8296       //                   IndexLen));
8297       Shuffle = DAG.getNode(
8298           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
8299           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
8300           V2Cst, DAG.getBuildVector(IndexVT, DL,
8301                                     makeArrayRef(TBLMask.data(), IndexLen)));
8302     }
8303   }
8304   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
8305 }
8306 
getDUPLANEOp(EVT EltType)8307 static unsigned getDUPLANEOp(EVT EltType) {
8308   if (EltType == MVT::i8)
8309     return AArch64ISD::DUPLANE8;
8310   if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
8311     return AArch64ISD::DUPLANE16;
8312   if (EltType == MVT::i32 || EltType == MVT::f32)
8313     return AArch64ISD::DUPLANE32;
8314   if (EltType == MVT::i64 || EltType == MVT::f64)
8315     return AArch64ISD::DUPLANE64;
8316 
8317   llvm_unreachable("Invalid vector element type?");
8318 }
8319 
constructDup(SDValue V,int Lane,SDLoc dl,EVT VT,unsigned Opcode,SelectionDAG & DAG)8320 static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
8321                             unsigned Opcode, SelectionDAG &DAG) {
8322   // Try to eliminate a bitcasted extract subvector before a DUPLANE.
8323   auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
8324     // Match: dup (bitcast (extract_subv X, C)), LaneC
8325     if (BitCast.getOpcode() != ISD::BITCAST ||
8326         BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
8327       return false;
8328 
8329     // The extract index must align in the destination type. That may not
8330     // happen if the bitcast is from narrow to wide type.
8331     SDValue Extract = BitCast.getOperand(0);
8332     unsigned ExtIdx = Extract.getConstantOperandVal(1);
8333     unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
8334     unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
8335     unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
8336     if (ExtIdxInBits % CastedEltBitWidth != 0)
8337       return false;
8338 
8339     // Update the lane value by offsetting with the scaled extract index.
8340     LaneC += ExtIdxInBits / CastedEltBitWidth;
8341 
8342     // Determine the casted vector type of the wide vector input.
8343     // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
8344     // Examples:
8345     // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
8346     // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
8347     unsigned SrcVecNumElts =
8348         Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
8349     CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
8350                               SrcVecNumElts);
8351     return true;
8352   };
8353   MVT CastVT;
8354   if (getScaledOffsetDup(V, Lane, CastVT)) {
8355     V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
8356   } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8357     // The lane is incremented by the index of the extract.
8358     // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
8359     Lane += V.getConstantOperandVal(1);
8360     V = V.getOperand(0);
8361   } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
8362     // The lane is decremented if we are splatting from the 2nd operand.
8363     // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
8364     unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
8365     Lane -= Idx * VT.getVectorNumElements() / 2;
8366     V = WidenVector(V.getOperand(Idx), DAG);
8367   } else if (VT.getSizeInBits() == 64) {
8368     // Widen the operand to 128-bit register with undef.
8369     V = WidenVector(V, DAG);
8370   }
8371   return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
8372 }
8373 
LowerVECTOR_SHUFFLE(SDValue Op,SelectionDAG & DAG) const8374 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8375                                                    SelectionDAG &DAG) const {
8376   SDLoc dl(Op);
8377   EVT VT = Op.getValueType();
8378 
8379   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8380 
8381   // Convert shuffles that are directly supported on NEON to target-specific
8382   // DAG nodes, instead of keeping them as shuffles and matching them again
8383   // during code selection.  This is more efficient and avoids the possibility
8384   // of inconsistencies between legalization and selection.
8385   ArrayRef<int> ShuffleMask = SVN->getMask();
8386 
8387   SDValue V1 = Op.getOperand(0);
8388   SDValue V2 = Op.getOperand(1);
8389 
8390   if (SVN->isSplat()) {
8391     int Lane = SVN->getSplatIndex();
8392     // If this is undef splat, generate it via "just" vdup, if possible.
8393     if (Lane == -1)
8394       Lane = 0;
8395 
8396     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
8397       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
8398                          V1.getOperand(0));
8399     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
8400     // constant. If so, we can just reference the lane's definition directly.
8401     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
8402         !isa<ConstantSDNode>(V1.getOperand(Lane)))
8403       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
8404 
8405     // Otherwise, duplicate from the lane of the input vector.
8406     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
8407     return constructDup(V1, Lane, dl, VT, Opcode, DAG);
8408   }
8409 
8410   // Check if the mask matches a DUP for a wider element
8411   for (unsigned LaneSize : {64U, 32U, 16U}) {
8412     unsigned Lane = 0;
8413     if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
8414       unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
8415                                        : LaneSize == 32 ? AArch64ISD::DUPLANE32
8416                                                         : AArch64ISD::DUPLANE16;
8417       // Cast V1 to an integer vector with required lane size
8418       MVT NewEltTy = MVT::getIntegerVT(LaneSize);
8419       unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
8420       MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
8421       V1 = DAG.getBitcast(NewVecTy, V1);
8422       // Constuct the DUP instruction
8423       V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
8424       // Cast back to the original type
8425       return DAG.getBitcast(VT, V1);
8426     }
8427   }
8428 
8429   if (isREVMask(ShuffleMask, VT, 64))
8430     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
8431   if (isREVMask(ShuffleMask, VT, 32))
8432     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
8433   if (isREVMask(ShuffleMask, VT, 16))
8434     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
8435 
8436   bool ReverseEXT = false;
8437   unsigned Imm;
8438   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
8439     if (ReverseEXT)
8440       std::swap(V1, V2);
8441     Imm *= getExtFactor(V1);
8442     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
8443                        DAG.getConstant(Imm, dl, MVT::i32));
8444   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
8445     Imm *= getExtFactor(V1);
8446     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
8447                        DAG.getConstant(Imm, dl, MVT::i32));
8448   }
8449 
8450   unsigned WhichResult;
8451   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
8452     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8453     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8454   }
8455   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
8456     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8457     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8458   }
8459   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
8460     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8461     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
8462   }
8463 
8464   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8465     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
8466     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8467   }
8468   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8469     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
8470     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8471   }
8472   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
8473     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
8474     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
8475   }
8476 
8477   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
8478     return Concat;
8479 
8480   bool DstIsLeft;
8481   int Anomaly;
8482   int NumInputElements = V1.getValueType().getVectorNumElements();
8483   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
8484     SDValue DstVec = DstIsLeft ? V1 : V2;
8485     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
8486 
8487     SDValue SrcVec = V1;
8488     int SrcLane = ShuffleMask[Anomaly];
8489     if (SrcLane >= NumInputElements) {
8490       SrcVec = V2;
8491       SrcLane -= VT.getVectorNumElements();
8492     }
8493     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
8494 
8495     EVT ScalarVT = VT.getVectorElementType();
8496 
8497     if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
8498       ScalarVT = MVT::i32;
8499 
8500     return DAG.getNode(
8501         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8502         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
8503         DstLaneV);
8504   }
8505 
8506   // If the shuffle is not directly supported and it has 4 elements, use
8507   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8508   unsigned NumElts = VT.getVectorNumElements();
8509   if (NumElts == 4) {
8510     unsigned PFIndexes[4];
8511     for (unsigned i = 0; i != 4; ++i) {
8512       if (ShuffleMask[i] < 0)
8513         PFIndexes[i] = 8;
8514       else
8515         PFIndexes[i] = ShuffleMask[i];
8516     }
8517 
8518     // Compute the index in the perfect shuffle table.
8519     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8520                             PFIndexes[2] * 9 + PFIndexes[3];
8521     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8522     unsigned Cost = (PFEntry >> 30);
8523 
8524     if (Cost <= 4)
8525       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8526   }
8527 
8528   return GenerateTBL(Op, ShuffleMask, DAG);
8529 }
8530 
LowerSPLAT_VECTOR(SDValue Op,SelectionDAG & DAG) const8531 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
8532                                                  SelectionDAG &DAG) const {
8533   SDLoc dl(Op);
8534   EVT VT = Op.getValueType();
8535   EVT ElemVT = VT.getScalarType();
8536   SDValue SplatVal = Op.getOperand(0);
8537 
8538   if (useSVEForFixedLengthVectorVT(VT))
8539     return LowerToScalableOp(Op, DAG);
8540 
8541   // Extend input splat value where needed to fit into a GPR (32b or 64b only)
8542   // FPRs don't have this restriction.
8543   switch (ElemVT.getSimpleVT().SimpleTy) {
8544   case MVT::i1: {
8545     // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
8546     // lowering code.
8547     if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
8548       if (ConstVal->isOne())
8549         return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
8550       // TODO: Add special case for constant false
8551     }
8552     // The general case of i1.  There isn't any natural way to do this,
8553     // so we use some trickery with whilelo.
8554     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8555     SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
8556                            DAG.getValueType(MVT::i1));
8557     SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
8558                                        MVT::i64);
8559     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
8560                        DAG.getConstant(0, dl, MVT::i64), SplatVal);
8561   }
8562   case MVT::i8:
8563   case MVT::i16:
8564   case MVT::i32:
8565     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
8566     break;
8567   case MVT::i64:
8568     SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
8569     break;
8570   case MVT::f16:
8571   case MVT::bf16:
8572   case MVT::f32:
8573   case MVT::f64:
8574     // Fine as is
8575     break;
8576   default:
8577     report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
8578   }
8579 
8580   return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
8581 }
8582 
LowerDUPQLane(SDValue Op,SelectionDAG & DAG) const8583 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
8584                                              SelectionDAG &DAG) const {
8585   SDLoc DL(Op);
8586 
8587   EVT VT = Op.getValueType();
8588   if (!isTypeLegal(VT) || !VT.isScalableVector())
8589     return SDValue();
8590 
8591   // Current lowering only supports the SVE-ACLE types.
8592   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
8593     return SDValue();
8594 
8595   // The DUPQ operation is indepedent of element type so normalise to i64s.
8596   SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
8597   SDValue Idx128 = Op.getOperand(2);
8598 
8599   // DUPQ can be used when idx is in range.
8600   auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
8601   if (CIdx && (CIdx->getZExtValue() <= 3)) {
8602     SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
8603     SDNode *DUPQ =
8604         DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
8605     return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
8606   }
8607 
8608   // The ACLE says this must produce the same result as:
8609   //   svtbl(data, svadd_x(svptrue_b64(),
8610   //                       svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
8611   //                       index * 2))
8612   SDValue One = DAG.getConstant(1, DL, MVT::i64);
8613   SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
8614 
8615   // create the vector 0,1,0,1,...
8616   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
8617   SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
8618                            DL, MVT::nxv2i64, Zero, One);
8619   SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
8620 
8621   // create the vector idx64,idx64+1,idx64,idx64+1,...
8622   SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
8623   SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
8624   SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
8625 
8626   // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
8627   SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
8628   return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
8629 }
8630 
8631 
resolveBuildVector(BuildVectorSDNode * BVN,APInt & CnstBits,APInt & UndefBits)8632 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
8633                                APInt &UndefBits) {
8634   EVT VT = BVN->getValueType(0);
8635   APInt SplatBits, SplatUndef;
8636   unsigned SplatBitSize;
8637   bool HasAnyUndefs;
8638   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8639     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
8640 
8641     for (unsigned i = 0; i < NumSplats; ++i) {
8642       CnstBits <<= SplatBitSize;
8643       UndefBits <<= SplatBitSize;
8644       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
8645       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
8646     }
8647 
8648     return true;
8649   }
8650 
8651   return false;
8652 }
8653 
8654 // Try 64-bit splatted SIMD immediate.
tryAdvSIMDModImm64(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)8655 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8656                                  const APInt &Bits) {
8657   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8658     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8659     EVT VT = Op.getValueType();
8660     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
8661 
8662     if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
8663       Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
8664 
8665       SDLoc dl(Op);
8666       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8667                                 DAG.getConstant(Value, dl, MVT::i32));
8668       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8669     }
8670   }
8671 
8672   return SDValue();
8673 }
8674 
8675 // Try 32-bit splatted SIMD immediate.
tryAdvSIMDModImm32(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits,const SDValue * LHS=nullptr)8676 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8677                                   const APInt &Bits,
8678                                   const SDValue *LHS = nullptr) {
8679   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8680     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8681     EVT VT = Op.getValueType();
8682     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8683     bool isAdvSIMDModImm = false;
8684     uint64_t Shift;
8685 
8686     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
8687       Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
8688       Shift = 0;
8689     }
8690     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
8691       Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
8692       Shift = 8;
8693     }
8694     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
8695       Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
8696       Shift = 16;
8697     }
8698     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
8699       Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
8700       Shift = 24;
8701     }
8702 
8703     if (isAdvSIMDModImm) {
8704       SDLoc dl(Op);
8705       SDValue Mov;
8706 
8707       if (LHS)
8708         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8709                           DAG.getConstant(Value, dl, MVT::i32),
8710                           DAG.getConstant(Shift, dl, MVT::i32));
8711       else
8712         Mov = DAG.getNode(NewOp, dl, MovTy,
8713                           DAG.getConstant(Value, dl, MVT::i32),
8714                           DAG.getConstant(Shift, dl, MVT::i32));
8715 
8716       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8717     }
8718   }
8719 
8720   return SDValue();
8721 }
8722 
8723 // Try 16-bit splatted SIMD immediate.
tryAdvSIMDModImm16(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits,const SDValue * LHS=nullptr)8724 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8725                                   const APInt &Bits,
8726                                   const SDValue *LHS = nullptr) {
8727   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8728     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8729     EVT VT = Op.getValueType();
8730     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8731     bool isAdvSIMDModImm = false;
8732     uint64_t Shift;
8733 
8734     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8735       Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8736       Shift = 0;
8737     }
8738     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8739       Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8740       Shift = 8;
8741     }
8742 
8743     if (isAdvSIMDModImm) {
8744       SDLoc dl(Op);
8745       SDValue Mov;
8746 
8747       if (LHS)
8748         Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8749                           DAG.getConstant(Value, dl, MVT::i32),
8750                           DAG.getConstant(Shift, dl, MVT::i32));
8751       else
8752         Mov = DAG.getNode(NewOp, dl, MovTy,
8753                           DAG.getConstant(Value, dl, MVT::i32),
8754                           DAG.getConstant(Shift, dl, MVT::i32));
8755 
8756       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8757     }
8758   }
8759 
8760   return SDValue();
8761 }
8762 
8763 // Try 32-bit splatted SIMD immediate with shifted ones.
tryAdvSIMDModImm321s(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)8764 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8765                                     SelectionDAG &DAG, const APInt &Bits) {
8766   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8767     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8768     EVT VT = Op.getValueType();
8769     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8770     bool isAdvSIMDModImm = false;
8771     uint64_t Shift;
8772 
8773     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8774       Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8775       Shift = 264;
8776     }
8777     else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8778       Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8779       Shift = 272;
8780     }
8781 
8782     if (isAdvSIMDModImm) {
8783       SDLoc dl(Op);
8784       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8785                                 DAG.getConstant(Value, dl, MVT::i32),
8786                                 DAG.getConstant(Shift, dl, MVT::i32));
8787       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8788     }
8789   }
8790 
8791   return SDValue();
8792 }
8793 
8794 // Try 8-bit splatted SIMD immediate.
tryAdvSIMDModImm8(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)8795 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8796                                  const APInt &Bits) {
8797   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8798     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8799     EVT VT = Op.getValueType();
8800     MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8801 
8802     if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8803       Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8804 
8805       SDLoc dl(Op);
8806       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8807                                 DAG.getConstant(Value, dl, MVT::i32));
8808       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8809     }
8810   }
8811 
8812   return SDValue();
8813 }
8814 
8815 // Try FP splatted SIMD immediate.
tryAdvSIMDModImmFP(unsigned NewOp,SDValue Op,SelectionDAG & DAG,const APInt & Bits)8816 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8817                                   const APInt &Bits) {
8818   if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8819     uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8820     EVT VT = Op.getValueType();
8821     bool isWide = (VT.getSizeInBits() == 128);
8822     MVT MovTy;
8823     bool isAdvSIMDModImm = false;
8824 
8825     if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8826       Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8827       MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8828     }
8829     else if (isWide &&
8830              (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8831       Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8832       MovTy = MVT::v2f64;
8833     }
8834 
8835     if (isAdvSIMDModImm) {
8836       SDLoc dl(Op);
8837       SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8838                                 DAG.getConstant(Value, dl, MVT::i32));
8839       return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8840     }
8841   }
8842 
8843   return SDValue();
8844 }
8845 
8846 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8847 // consists of only the same constant int value, returned in reference arg
8848 // ConstVal
isAllConstantBuildVector(const SDValue & PotentialBVec,uint64_t & ConstVal)8849 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8850                                      uint64_t &ConstVal) {
8851   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8852   if (!Bvec)
8853     return false;
8854   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8855   if (!FirstElt)
8856     return false;
8857   EVT VT = Bvec->getValueType(0);
8858   unsigned NumElts = VT.getVectorNumElements();
8859   for (unsigned i = 1; i < NumElts; ++i)
8860     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8861       return false;
8862   ConstVal = FirstElt->getZExtValue();
8863   return true;
8864 }
8865 
getIntrinsicID(const SDNode * N)8866 static unsigned getIntrinsicID(const SDNode *N) {
8867   unsigned Opcode = N->getOpcode();
8868   switch (Opcode) {
8869   default:
8870     return Intrinsic::not_intrinsic;
8871   case ISD::INTRINSIC_WO_CHAIN: {
8872     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8873     if (IID < Intrinsic::num_intrinsics)
8874       return IID;
8875     return Intrinsic::not_intrinsic;
8876   }
8877   }
8878 }
8879 
8880 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8881 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8882 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8883 //   - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8884 //   - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8885 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
tryLowerToSLI(SDNode * N,SelectionDAG & DAG)8886 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8887   EVT VT = N->getValueType(0);
8888 
8889   if (!VT.isVector())
8890     return SDValue();
8891 
8892   SDLoc DL(N);
8893 
8894   SDValue And;
8895   SDValue Shift;
8896 
8897   SDValue FirstOp = N->getOperand(0);
8898   unsigned FirstOpc = FirstOp.getOpcode();
8899   SDValue SecondOp = N->getOperand(1);
8900   unsigned SecondOpc = SecondOp.getOpcode();
8901 
8902   // Is one of the operands an AND or a BICi? The AND may have been optimised to
8903   // a BICi in order to use an immediate instead of a register.
8904   // Is the other operand an shl or lshr? This will have been turned into:
8905   // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8906   if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8907       (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8908     And = FirstOp;
8909     Shift = SecondOp;
8910 
8911   } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8912              (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8913     And = SecondOp;
8914     Shift = FirstOp;
8915   } else
8916     return SDValue();
8917 
8918   bool IsAnd = And.getOpcode() == ISD::AND;
8919   bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8920 
8921   // Is the shift amount constant?
8922   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8923   if (!C2node)
8924     return SDValue();
8925 
8926   uint64_t C1;
8927   if (IsAnd) {
8928     // Is the and mask vector all constant?
8929     if (!isAllConstantBuildVector(And.getOperand(1), C1))
8930       return SDValue();
8931   } else {
8932     // Reconstruct the corresponding AND immediate from the two BICi immediates.
8933     ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8934     ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8935     assert(C1nodeImm && C1nodeShift);
8936     C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8937   }
8938 
8939   // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8940   // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8941   // how much one can shift elements of a particular size?
8942   uint64_t C2 = C2node->getZExtValue();
8943   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8944   if (C2 > ElemSizeInBits)
8945     return SDValue();
8946 
8947   APInt C1AsAPInt(ElemSizeInBits, C1);
8948   APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8949                                   : APInt::getLowBitsSet(ElemSizeInBits, C2);
8950   if (C1AsAPInt != RequiredC1)
8951     return SDValue();
8952 
8953   SDValue X = And.getOperand(0);
8954   SDValue Y = Shift.getOperand(0);
8955 
8956   unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8957   SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8958 
8959   LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8960   LLVM_DEBUG(N->dump(&DAG));
8961   LLVM_DEBUG(dbgs() << "into: \n");
8962   LLVM_DEBUG(ResultSLI->dump(&DAG));
8963 
8964   ++NumShiftInserts;
8965   return ResultSLI;
8966 }
8967 
LowerVectorOR(SDValue Op,SelectionDAG & DAG) const8968 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8969                                              SelectionDAG &DAG) const {
8970   if (useSVEForFixedLengthVectorVT(Op.getValueType()))
8971     return LowerToScalableOp(Op, DAG);
8972 
8973   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8974   if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8975     return Res;
8976 
8977   EVT VT = Op.getValueType();
8978 
8979   SDValue LHS = Op.getOperand(0);
8980   BuildVectorSDNode *BVN =
8981       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8982   if (!BVN) {
8983     // OR commutes, so try swapping the operands.
8984     LHS = Op.getOperand(1);
8985     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8986   }
8987   if (!BVN)
8988     return Op;
8989 
8990   APInt DefBits(VT.getSizeInBits(), 0);
8991   APInt UndefBits(VT.getSizeInBits(), 0);
8992   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8993     SDValue NewOp;
8994 
8995     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8996                                     DefBits, &LHS)) ||
8997         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8998                                     DefBits, &LHS)))
8999       return NewOp;
9000 
9001     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
9002                                     UndefBits, &LHS)) ||
9003         (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
9004                                     UndefBits, &LHS)))
9005       return NewOp;
9006   }
9007 
9008   // We can always fall back to a non-immediate OR.
9009   return Op;
9010 }
9011 
9012 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
9013 // be truncated to fit element width.
NormalizeBuildVector(SDValue Op,SelectionDAG & DAG)9014 static SDValue NormalizeBuildVector(SDValue Op,
9015                                     SelectionDAG &DAG) {
9016   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
9017   SDLoc dl(Op);
9018   EVT VT = Op.getValueType();
9019   EVT EltTy= VT.getVectorElementType();
9020 
9021   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
9022     return Op;
9023 
9024   SmallVector<SDValue, 16> Ops;
9025   for (SDValue Lane : Op->ops()) {
9026     // For integer vectors, type legalization would have promoted the
9027     // operands already. Otherwise, if Op is a floating-point splat
9028     // (with operands cast to integers), then the only possibilities
9029     // are constants and UNDEFs.
9030     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
9031       APInt LowBits(EltTy.getSizeInBits(),
9032                     CstLane->getZExtValue());
9033       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
9034     } else if (Lane.getNode()->isUndef()) {
9035       Lane = DAG.getUNDEF(MVT::i32);
9036     } else {
9037       assert(Lane.getValueType() == MVT::i32 &&
9038              "Unexpected BUILD_VECTOR operand type");
9039     }
9040     Ops.push_back(Lane);
9041   }
9042   return DAG.getBuildVector(VT, dl, Ops);
9043 }
9044 
ConstantBuildVector(SDValue Op,SelectionDAG & DAG)9045 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
9046   EVT VT = Op.getValueType();
9047 
9048   APInt DefBits(VT.getSizeInBits(), 0);
9049   APInt UndefBits(VT.getSizeInBits(), 0);
9050   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
9051   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9052     SDValue NewOp;
9053     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
9054         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9055         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
9056         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9057         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
9058         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
9059       return NewOp;
9060 
9061     DefBits = ~DefBits;
9062     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
9063         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
9064         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
9065       return NewOp;
9066 
9067     DefBits = UndefBits;
9068     if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
9069         (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9070         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
9071         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
9072         (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
9073         (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
9074       return NewOp;
9075 
9076     DefBits = ~UndefBits;
9077     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
9078         (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
9079         (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
9080       return NewOp;
9081   }
9082 
9083   return SDValue();
9084 }
9085 
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const9086 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
9087                                                  SelectionDAG &DAG) const {
9088   EVT VT = Op.getValueType();
9089 
9090   // Try to build a simple constant vector.
9091   Op = NormalizeBuildVector(Op, DAG);
9092   if (VT.isInteger()) {
9093     // Certain vector constants, used to express things like logical NOT and
9094     // arithmetic NEG, are passed through unmodified.  This allows special
9095     // patterns for these operations to match, which will lower these constants
9096     // to whatever is proven necessary.
9097     BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
9098     if (BVN->isConstant())
9099       if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
9100         unsigned BitSize = VT.getVectorElementType().getSizeInBits();
9101         APInt Val(BitSize,
9102                   Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
9103         if (Val.isNullValue() || Val.isAllOnesValue())
9104           return Op;
9105       }
9106   }
9107 
9108   if (SDValue V = ConstantBuildVector(Op, DAG))
9109     return V;
9110 
9111   // Scan through the operands to find some interesting properties we can
9112   // exploit:
9113   //   1) If only one value is used, we can use a DUP, or
9114   //   2) if only the low element is not undef, we can just insert that, or
9115   //   3) if only one constant value is used (w/ some non-constant lanes),
9116   //      we can splat the constant value into the whole vector then fill
9117   //      in the non-constant lanes.
9118   //   4) FIXME: If different constant values are used, but we can intelligently
9119   //             select the values we'll be overwriting for the non-constant
9120   //             lanes such that we can directly materialize the vector
9121   //             some other way (MOVI, e.g.), we can be sneaky.
9122   //   5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
9123   SDLoc dl(Op);
9124   unsigned NumElts = VT.getVectorNumElements();
9125   bool isOnlyLowElement = true;
9126   bool usesOnlyOneValue = true;
9127   bool usesOnlyOneConstantValue = true;
9128   bool isConstant = true;
9129   bool AllLanesExtractElt = true;
9130   unsigned NumConstantLanes = 0;
9131   unsigned NumDifferentLanes = 0;
9132   unsigned NumUndefLanes = 0;
9133   SDValue Value;
9134   SDValue ConstantValue;
9135   for (unsigned i = 0; i < NumElts; ++i) {
9136     SDValue V = Op.getOperand(i);
9137     if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9138       AllLanesExtractElt = false;
9139     if (V.isUndef()) {
9140       ++NumUndefLanes;
9141       continue;
9142     }
9143     if (i > 0)
9144       isOnlyLowElement = false;
9145     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
9146       isConstant = false;
9147 
9148     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
9149       ++NumConstantLanes;
9150       if (!ConstantValue.getNode())
9151         ConstantValue = V;
9152       else if (ConstantValue != V)
9153         usesOnlyOneConstantValue = false;
9154     }
9155 
9156     if (!Value.getNode())
9157       Value = V;
9158     else if (V != Value) {
9159       usesOnlyOneValue = false;
9160       ++NumDifferentLanes;
9161     }
9162   }
9163 
9164   if (!Value.getNode()) {
9165     LLVM_DEBUG(
9166         dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
9167     return DAG.getUNDEF(VT);
9168   }
9169 
9170   // Convert BUILD_VECTOR where all elements but the lowest are undef into
9171   // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
9172   // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
9173   if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
9174     LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
9175                          "SCALAR_TO_VECTOR node\n");
9176     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
9177   }
9178 
9179   if (AllLanesExtractElt) {
9180     SDNode *Vector = nullptr;
9181     bool Even = false;
9182     bool Odd = false;
9183     // Check whether the extract elements match the Even pattern <0,2,4,...> or
9184     // the Odd pattern <1,3,5,...>.
9185     for (unsigned i = 0; i < NumElts; ++i) {
9186       SDValue V = Op.getOperand(i);
9187       const SDNode *N = V.getNode();
9188       if (!isa<ConstantSDNode>(N->getOperand(1)))
9189         break;
9190       SDValue N0 = N->getOperand(0);
9191 
9192       // All elements are extracted from the same vector.
9193       if (!Vector) {
9194         Vector = N0.getNode();
9195         // Check that the type of EXTRACT_VECTOR_ELT matches the type of
9196         // BUILD_VECTOR.
9197         if (VT.getVectorElementType() !=
9198             N0.getValueType().getVectorElementType())
9199           break;
9200       } else if (Vector != N0.getNode()) {
9201         Odd = false;
9202         Even = false;
9203         break;
9204       }
9205 
9206       // Extracted values are either at Even indices <0,2,4,...> or at Odd
9207       // indices <1,3,5,...>.
9208       uint64_t Val = N->getConstantOperandVal(1);
9209       if (Val == 2 * i) {
9210         Even = true;
9211         continue;
9212       }
9213       if (Val - 1 == 2 * i) {
9214         Odd = true;
9215         continue;
9216       }
9217 
9218       // Something does not match: abort.
9219       Odd = false;
9220       Even = false;
9221       break;
9222     }
9223     if (Even || Odd) {
9224       SDValue LHS =
9225           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9226                       DAG.getConstant(0, dl, MVT::i64));
9227       SDValue RHS =
9228           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
9229                       DAG.getConstant(NumElts, dl, MVT::i64));
9230 
9231       if (Even && !Odd)
9232         return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
9233                            RHS);
9234       if (Odd && !Even)
9235         return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
9236                            RHS);
9237     }
9238   }
9239 
9240   // Use DUP for non-constant splats. For f32 constant splats, reduce to
9241   // i32 and try again.
9242   if (usesOnlyOneValue) {
9243     if (!isConstant) {
9244       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9245           Value.getValueType() != VT) {
9246         LLVM_DEBUG(
9247             dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
9248         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
9249       }
9250 
9251       // This is actually a DUPLANExx operation, which keeps everything vectory.
9252 
9253       SDValue Lane = Value.getOperand(1);
9254       Value = Value.getOperand(0);
9255       if (Value.getValueSizeInBits() == 64) {
9256         LLVM_DEBUG(
9257             dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
9258                       "widening it\n");
9259         Value = WidenVector(Value, DAG);
9260       }
9261 
9262       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
9263       return DAG.getNode(Opcode, dl, VT, Value, Lane);
9264     }
9265 
9266     if (VT.getVectorElementType().isFloatingPoint()) {
9267       SmallVector<SDValue, 8> Ops;
9268       EVT EltTy = VT.getVectorElementType();
9269       assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
9270                EltTy == MVT::f64) && "Unsupported floating-point vector type");
9271       LLVM_DEBUG(
9272           dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
9273                     "BITCASTS, and try again\n");
9274       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
9275       for (unsigned i = 0; i < NumElts; ++i)
9276         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
9277       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
9278       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
9279       LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
9280                  Val.dump(););
9281       Val = LowerBUILD_VECTOR(Val, DAG);
9282       if (Val.getNode())
9283         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
9284     }
9285   }
9286 
9287   // If we need to insert a small number of different non-constant elements and
9288   // the vector width is sufficiently large, prefer using DUP with the common
9289   // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
9290   // skip the constant lane handling below.
9291   bool PreferDUPAndInsert =
9292       !isConstant && NumDifferentLanes >= 1 &&
9293       NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
9294       NumDifferentLanes >= NumConstantLanes;
9295 
9296   // If there was only one constant value used and for more than one lane,
9297   // start by splatting that value, then replace the non-constant lanes. This
9298   // is better than the default, which will perform a separate initialization
9299   // for each lane.
9300   if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
9301     // Firstly, try to materialize the splat constant.
9302     SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
9303             Val = ConstantBuildVector(Vec, DAG);
9304     if (!Val) {
9305       // Otherwise, materialize the constant and splat it.
9306       Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
9307       DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
9308     }
9309 
9310     // Now insert the non-constant lanes.
9311     for (unsigned i = 0; i < NumElts; ++i) {
9312       SDValue V = Op.getOperand(i);
9313       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9314       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
9315         // Note that type legalization likely mucked about with the VT of the
9316         // source operand, so we may have to convert it here before inserting.
9317         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
9318     }
9319     return Val;
9320   }
9321 
9322   // This will generate a load from the constant pool.
9323   if (isConstant) {
9324     LLVM_DEBUG(
9325         dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
9326                   "expansion\n");
9327     return SDValue();
9328   }
9329 
9330   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
9331   if (NumElts >= 4) {
9332     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
9333       return shuffle;
9334   }
9335 
9336   if (PreferDUPAndInsert) {
9337     // First, build a constant vector with the common element.
9338     SmallVector<SDValue, 8> Ops;
9339     for (unsigned I = 0; I < NumElts; ++I)
9340       Ops.push_back(Value);
9341     SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
9342     // Next, insert the elements that do not match the common value.
9343     for (unsigned I = 0; I < NumElts; ++I)
9344       if (Op.getOperand(I) != Value)
9345         NewVector =
9346             DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
9347                         Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
9348 
9349     return NewVector;
9350   }
9351 
9352   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
9353   // know the default expansion would otherwise fall back on something even
9354   // worse. For a vector with one or two non-undef values, that's
9355   // scalar_to_vector for the elements followed by a shuffle (provided the
9356   // shuffle is valid for the target) and materialization element by element
9357   // on the stack followed by a load for everything else.
9358   if (!isConstant && !usesOnlyOneValue) {
9359     LLVM_DEBUG(
9360         dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
9361                   "of INSERT_VECTOR_ELT\n");
9362 
9363     SDValue Vec = DAG.getUNDEF(VT);
9364     SDValue Op0 = Op.getOperand(0);
9365     unsigned i = 0;
9366 
9367     // Use SCALAR_TO_VECTOR for lane zero to
9368     // a) Avoid a RMW dependency on the full vector register, and
9369     // b) Allow the register coalescer to fold away the copy if the
9370     //    value is already in an S or D register, and we're forced to emit an
9371     //    INSERT_SUBREG that we can't fold anywhere.
9372     //
9373     // We also allow types like i8 and i16 which are illegal scalar but legal
9374     // vector element types. After type-legalization the inserted value is
9375     // extended (i32) and it is safe to cast them to the vector type by ignoring
9376     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
9377     if (!Op0.isUndef()) {
9378       LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
9379       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
9380       ++i;
9381     }
9382     LLVM_DEBUG(if (i < NumElts) dbgs()
9383                    << "Creating nodes for the other vector elements:\n";);
9384     for (; i < NumElts; ++i) {
9385       SDValue V = Op.getOperand(i);
9386       if (V.isUndef())
9387         continue;
9388       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
9389       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
9390     }
9391     return Vec;
9392   }
9393 
9394   LLVM_DEBUG(
9395       dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
9396                 "better alternative\n");
9397   return SDValue();
9398 }
9399 
LowerCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG) const9400 SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
9401                                                    SelectionDAG &DAG) const {
9402   assert(Op.getValueType().isScalableVector() &&
9403          isTypeLegal(Op.getValueType()) &&
9404          "Expected legal scalable vector type!");
9405 
9406   if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2)
9407     return Op;
9408 
9409   return SDValue();
9410 }
9411 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const9412 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9413                                                       SelectionDAG &DAG) const {
9414   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
9415 
9416   // Check for non-constant or out of range lane.
9417   EVT VT = Op.getOperand(0).getValueType();
9418   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9419   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9420     return SDValue();
9421 
9422 
9423   // Insertion/extraction are legal for V128 types.
9424   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9425       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9426       VT == MVT::v8f16 || VT == MVT::v8bf16)
9427     return Op;
9428 
9429   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9430       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9431       VT != MVT::v4bf16)
9432     return SDValue();
9433 
9434   // For V64 types, we perform insertion by expanding the value
9435   // to a V128 type and perform the insertion on that.
9436   SDLoc DL(Op);
9437   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9438   EVT WideTy = WideVec.getValueType();
9439 
9440   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
9441                              Op.getOperand(1), Op.getOperand(2));
9442   // Re-narrow the resultant vector.
9443   return NarrowVector(Node, DAG);
9444 }
9445 
9446 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const9447 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9448                                                SelectionDAG &DAG) const {
9449   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
9450 
9451   // Check for non-constant or out of range lane.
9452   EVT VT = Op.getOperand(0).getValueType();
9453   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9454   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
9455     return SDValue();
9456 
9457 
9458   // Insertion/extraction are legal for V128 types.
9459   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
9460       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
9461       VT == MVT::v8f16 || VT == MVT::v8bf16)
9462     return Op;
9463 
9464   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
9465       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
9466       VT != MVT::v4bf16)
9467     return SDValue();
9468 
9469   // For V64 types, we perform extraction by expanding the value
9470   // to a V128 type and perform the extraction on that.
9471   SDLoc DL(Op);
9472   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
9473   EVT WideTy = WideVec.getValueType();
9474 
9475   EVT ExtrTy = WideTy.getVectorElementType();
9476   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
9477     ExtrTy = MVT::i32;
9478 
9479   // For extractions, we just return the result directly.
9480   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
9481                      Op.getOperand(1));
9482 }
9483 
LowerEXTRACT_SUBVECTOR(SDValue Op,SelectionDAG & DAG) const9484 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
9485                                                       SelectionDAG &DAG) const {
9486   assert(Op.getValueType().isFixedLengthVector() &&
9487          "Only cases that extract a fixed length vector are supported!");
9488 
9489   EVT InVT = Op.getOperand(0).getValueType();
9490   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9491   unsigned Size = Op.getValueSizeInBits();
9492 
9493   if (InVT.isScalableVector()) {
9494     // This will be matched by custom code during ISelDAGToDAG.
9495     if (Idx == 0 && isPackedVectorType(InVT, DAG))
9496       return Op;
9497 
9498     return SDValue();
9499   }
9500 
9501   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
9502   if (Idx == 0 && InVT.getSizeInBits() <= 128)
9503     return Op;
9504 
9505   // If this is extracting the upper 64-bits of a 128-bit vector, we match
9506   // that directly.
9507   if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
9508       InVT.getSizeInBits() == 128)
9509     return Op;
9510 
9511   return SDValue();
9512 }
9513 
LowerINSERT_SUBVECTOR(SDValue Op,SelectionDAG & DAG) const9514 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
9515                                                      SelectionDAG &DAG) const {
9516   assert(Op.getValueType().isScalableVector() &&
9517          "Only expect to lower inserts into scalable vectors!");
9518 
9519   EVT InVT = Op.getOperand(1).getValueType();
9520   unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
9521 
9522   if (InVT.isScalableVector()) {
9523     SDLoc DL(Op);
9524     EVT VT = Op.getValueType();
9525 
9526     if (!isTypeLegal(VT) || !VT.isInteger())
9527       return SDValue();
9528 
9529     SDValue Vec0 = Op.getOperand(0);
9530     SDValue Vec1 = Op.getOperand(1);
9531 
9532     // Ensure the subvector is half the size of the main vector.
9533     if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
9534       return SDValue();
9535 
9536     // Extend elements of smaller vector...
9537     EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
9538     SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
9539 
9540     if (Idx == 0) {
9541       SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
9542       return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
9543     } else if (Idx == InVT.getVectorMinNumElements()) {
9544       SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
9545       return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
9546     }
9547 
9548     return SDValue();
9549   }
9550 
9551   // This will be matched by custom code during ISelDAGToDAG.
9552   if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
9553     return Op;
9554 
9555   return SDValue();
9556 }
9557 
LowerDIV(SDValue Op,SelectionDAG & DAG) const9558 SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
9559   EVT VT = Op.getValueType();
9560 
9561   if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
9562     return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
9563 
9564   assert(VT.isScalableVector() && "Expected a scalable vector.");
9565 
9566   bool Signed = Op.getOpcode() == ISD::SDIV;
9567   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
9568 
9569   if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
9570     return LowerToPredicatedOp(Op, DAG, PredOpcode);
9571 
9572   // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
9573   // operations, and truncate the result.
9574   EVT WidenedVT;
9575   if (VT == MVT::nxv16i8)
9576     WidenedVT = MVT::nxv8i16;
9577   else if (VT == MVT::nxv8i16)
9578     WidenedVT = MVT::nxv4i32;
9579   else
9580     llvm_unreachable("Unexpected Custom DIV operation");
9581 
9582   SDLoc dl(Op);
9583   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
9584   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
9585   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
9586   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
9587   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
9588   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
9589   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
9590   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
9591   return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
9592 }
9593 
isShuffleMaskLegal(ArrayRef<int> M,EVT VT) const9594 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
9595   // Currently no fixed length shuffles that require SVE are legal.
9596   if (useSVEForFixedLengthVectorVT(VT))
9597     return false;
9598 
9599   if (VT.getVectorNumElements() == 4 &&
9600       (VT.is128BitVector() || VT.is64BitVector())) {
9601     unsigned PFIndexes[4];
9602     for (unsigned i = 0; i != 4; ++i) {
9603       if (M[i] < 0)
9604         PFIndexes[i] = 8;
9605       else
9606         PFIndexes[i] = M[i];
9607     }
9608 
9609     // Compute the index in the perfect shuffle table.
9610     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
9611                             PFIndexes[2] * 9 + PFIndexes[3];
9612     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9613     unsigned Cost = (PFEntry >> 30);
9614 
9615     if (Cost <= 4)
9616       return true;
9617   }
9618 
9619   bool DummyBool;
9620   int DummyInt;
9621   unsigned DummyUnsigned;
9622 
9623   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
9624           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
9625           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
9626           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
9627           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
9628           isZIPMask(M, VT, DummyUnsigned) ||
9629           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
9630           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
9631           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
9632           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
9633           isConcatMask(M, VT, VT.getSizeInBits() == 128));
9634 }
9635 
9636 /// getVShiftImm - Check if this is a valid build_vector for the immediate
9637 /// operand of a vector shift operation, where all the elements of the
9638 /// build_vector must have the same constant integer value.
getVShiftImm(SDValue Op,unsigned ElementBits,int64_t & Cnt)9639 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9640   // Ignore bit_converts.
9641   while (Op.getOpcode() == ISD::BITCAST)
9642     Op = Op.getOperand(0);
9643   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9644   APInt SplatBits, SplatUndef;
9645   unsigned SplatBitSize;
9646   bool HasAnyUndefs;
9647   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9648                                     HasAnyUndefs, ElementBits) ||
9649       SplatBitSize > ElementBits)
9650     return false;
9651   Cnt = SplatBits.getSExtValue();
9652   return true;
9653 }
9654 
9655 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9656 /// operand of a vector shift left operation.  That value must be in the range:
9657 ///   0 <= Value < ElementBits for a left shift; or
9658 ///   0 <= Value <= ElementBits for a long left shift.
isVShiftLImm(SDValue Op,EVT VT,bool isLong,int64_t & Cnt)9659 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9660   assert(VT.isVector() && "vector shift count is not a vector type");
9661   int64_t ElementBits = VT.getScalarSizeInBits();
9662   if (!getVShiftImm(Op, ElementBits, Cnt))
9663     return false;
9664   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
9665 }
9666 
9667 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9668 /// operand of a vector shift right operation. The value must be in the range:
9669 ///   1 <= Value <= ElementBits for a right shift; or
isVShiftRImm(SDValue Op,EVT VT,bool isNarrow,int64_t & Cnt)9670 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
9671   assert(VT.isVector() && "vector shift count is not a vector type");
9672   int64_t ElementBits = VT.getScalarSizeInBits();
9673   if (!getVShiftImm(Op, ElementBits, Cnt))
9674     return false;
9675   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
9676 }
9677 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const9678 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
9679                                              SelectionDAG &DAG) const {
9680   EVT VT = Op.getValueType();
9681 
9682   if (VT.getScalarType() == MVT::i1) {
9683     // Lower i1 truncate to `(x & 1) != 0`.
9684     SDLoc dl(Op);
9685     EVT OpVT = Op.getOperand(0).getValueType();
9686     SDValue Zero = DAG.getConstant(0, dl, OpVT);
9687     SDValue One = DAG.getConstant(1, dl, OpVT);
9688     SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
9689     return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
9690   }
9691 
9692   if (!VT.isVector() || VT.isScalableVector())
9693     return SDValue();
9694 
9695   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9696     return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
9697 
9698   return SDValue();
9699 }
9700 
LowerVectorSRA_SRL_SHL(SDValue Op,SelectionDAG & DAG) const9701 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
9702                                                       SelectionDAG &DAG) const {
9703   EVT VT = Op.getValueType();
9704   SDLoc DL(Op);
9705   int64_t Cnt;
9706 
9707   if (!Op.getOperand(1).getValueType().isVector())
9708     return Op;
9709   unsigned EltSize = VT.getScalarSizeInBits();
9710 
9711   switch (Op.getOpcode()) {
9712   default:
9713     llvm_unreachable("unexpected shift opcode");
9714 
9715   case ISD::SHL:
9716     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
9717       return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
9718 
9719     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
9720       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
9721                          DAG.getConstant(Cnt, DL, MVT::i32));
9722     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9723                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
9724                                        MVT::i32),
9725                        Op.getOperand(0), Op.getOperand(1));
9726   case ISD::SRA:
9727   case ISD::SRL:
9728     if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
9729       unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
9730                                                 : AArch64ISD::SRL_PRED;
9731       return LowerToPredicatedOp(Op, DAG, Opc);
9732     }
9733 
9734     // Right shift immediate
9735     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
9736       unsigned Opc =
9737           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
9738       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
9739                          DAG.getConstant(Cnt, DL, MVT::i32));
9740     }
9741 
9742     // Right shift register.  Note, there is not a shift right register
9743     // instruction, but the shift left register instruction takes a signed
9744     // value, where negative numbers specify a right shift.
9745     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
9746                                                 : Intrinsic::aarch64_neon_ushl;
9747     // negate the shift amount
9748     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
9749     SDValue NegShiftLeft =
9750         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9751                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
9752                     NegShift);
9753     return NegShiftLeft;
9754   }
9755 
9756   return SDValue();
9757 }
9758 
EmitVectorComparison(SDValue LHS,SDValue RHS,AArch64CC::CondCode CC,bool NoNans,EVT VT,const SDLoc & dl,SelectionDAG & DAG)9759 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
9760                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
9761                                     const SDLoc &dl, SelectionDAG &DAG) {
9762   EVT SrcVT = LHS.getValueType();
9763   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9764          "function only supposed to emit natural comparisons");
9765 
9766   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9767   APInt CnstBits(VT.getSizeInBits(), 0);
9768   APInt UndefBits(VT.getSizeInBits(), 0);
9769   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9770   bool IsZero = IsCnst && (CnstBits == 0);
9771 
9772   if (SrcVT.getVectorElementType().isFloatingPoint()) {
9773     switch (CC) {
9774     default:
9775       return SDValue();
9776     case AArch64CC::NE: {
9777       SDValue Fcmeq;
9778       if (IsZero)
9779         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9780       else
9781         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9782       return DAG.getNOT(dl, Fcmeq, VT);
9783     }
9784     case AArch64CC::EQ:
9785       if (IsZero)
9786         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9787       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9788     case AArch64CC::GE:
9789       if (IsZero)
9790         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9791       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9792     case AArch64CC::GT:
9793       if (IsZero)
9794         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9795       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9796     case AArch64CC::LS:
9797       if (IsZero)
9798         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9799       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9800     case AArch64CC::LT:
9801       if (!NoNans)
9802         return SDValue();
9803       // If we ignore NaNs then we can use to the MI implementation.
9804       LLVM_FALLTHROUGH;
9805     case AArch64CC::MI:
9806       if (IsZero)
9807         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9808       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9809     }
9810   }
9811 
9812   switch (CC) {
9813   default:
9814     return SDValue();
9815   case AArch64CC::NE: {
9816     SDValue Cmeq;
9817     if (IsZero)
9818       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9819     else
9820       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9821     return DAG.getNOT(dl, Cmeq, VT);
9822   }
9823   case AArch64CC::EQ:
9824     if (IsZero)
9825       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9826     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9827   case AArch64CC::GE:
9828     if (IsZero)
9829       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9830     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9831   case AArch64CC::GT:
9832     if (IsZero)
9833       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9834     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9835   case AArch64CC::LE:
9836     if (IsZero)
9837       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9838     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9839   case AArch64CC::LS:
9840     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9841   case AArch64CC::LO:
9842     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9843   case AArch64CC::LT:
9844     if (IsZero)
9845       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9846     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9847   case AArch64CC::HI:
9848     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9849   case AArch64CC::HS:
9850     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9851   }
9852 }
9853 
LowerVSETCC(SDValue Op,SelectionDAG & DAG) const9854 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9855                                            SelectionDAG &DAG) const {
9856   if (Op.getValueType().isScalableVector()) {
9857     if (Op.getOperand(0).getValueType().isFloatingPoint())
9858       return Op;
9859     return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9860   }
9861 
9862   if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
9863     return LowerFixedLengthVectorSetccToSVE(Op, DAG);
9864 
9865   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9866   SDValue LHS = Op.getOperand(0);
9867   SDValue RHS = Op.getOperand(1);
9868   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9869   SDLoc dl(Op);
9870 
9871   if (LHS.getValueType().getVectorElementType().isInteger()) {
9872     assert(LHS.getValueType() == RHS.getValueType());
9873     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9874     SDValue Cmp =
9875         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9876     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9877   }
9878 
9879   const bool FullFP16 =
9880     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9881 
9882   // Make v4f16 (only) fcmp operations utilise vector instructions
9883   // v8f16 support will be a litle more complicated
9884   if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9885     if (LHS.getValueType().getVectorNumElements() == 4) {
9886       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9887       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9888       SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9889       DAG.ReplaceAllUsesWith(Op, NewSetcc);
9890       CmpVT = MVT::v4i32;
9891     } else
9892       return SDValue();
9893   }
9894 
9895   assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9896           LHS.getValueType().getVectorElementType() != MVT::f128);
9897 
9898   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9899   // clean.  Some of them require two branches to implement.
9900   AArch64CC::CondCode CC1, CC2;
9901   bool ShouldInvert;
9902   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9903 
9904   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9905   SDValue Cmp =
9906       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9907   if (!Cmp.getNode())
9908     return SDValue();
9909 
9910   if (CC2 != AArch64CC::AL) {
9911     SDValue Cmp2 =
9912         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9913     if (!Cmp2.getNode())
9914       return SDValue();
9915 
9916     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9917   }
9918 
9919   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9920 
9921   if (ShouldInvert)
9922     Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9923 
9924   return Cmp;
9925 }
9926 
getReductionSDNode(unsigned Op,SDLoc DL,SDValue ScalarOp,SelectionDAG & DAG)9927 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9928                                   SelectionDAG &DAG) {
9929   SDValue VecOp = ScalarOp.getOperand(0);
9930   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9931   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9932                      DAG.getConstant(0, DL, MVT::i64));
9933 }
9934 
LowerVECREDUCE(SDValue Op,SelectionDAG & DAG) const9935 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9936                                               SelectionDAG &DAG) const {
9937   SDValue Src = Op.getOperand(0);
9938 
9939   // Try to lower fixed length reductions to SVE.
9940   EVT SrcVT = Src.getValueType();
9941   bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
9942                       Op.getOpcode() == ISD::VECREDUCE_OR ||
9943                       Op.getOpcode() == ISD::VECREDUCE_XOR ||
9944                       Op.getOpcode() == ISD::VECREDUCE_FADD ||
9945                       (Op.getOpcode() != ISD::VECREDUCE_ADD &&
9946                        SrcVT.getVectorElementType() == MVT::i64);
9947   if (SrcVT.isScalableVector() ||
9948       useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
9949 
9950     if (SrcVT.getVectorElementType() == MVT::i1)
9951       return LowerPredReductionToSVE(Op, DAG);
9952 
9953     switch (Op.getOpcode()) {
9954     case ISD::VECREDUCE_ADD:
9955       return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
9956     case ISD::VECREDUCE_AND:
9957       return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
9958     case ISD::VECREDUCE_OR:
9959       return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
9960     case ISD::VECREDUCE_SMAX:
9961       return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
9962     case ISD::VECREDUCE_SMIN:
9963       return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
9964     case ISD::VECREDUCE_UMAX:
9965       return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
9966     case ISD::VECREDUCE_UMIN:
9967       return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
9968     case ISD::VECREDUCE_XOR:
9969       return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
9970     case ISD::VECREDUCE_FADD:
9971       return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
9972     case ISD::VECREDUCE_FMAX:
9973       return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
9974     case ISD::VECREDUCE_FMIN:
9975       return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
9976     default:
9977       llvm_unreachable("Unhandled fixed length reduction");
9978     }
9979   }
9980 
9981   // Lower NEON reductions.
9982   SDLoc dl(Op);
9983   switch (Op.getOpcode()) {
9984   case ISD::VECREDUCE_ADD:
9985     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9986   case ISD::VECREDUCE_SMAX:
9987     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9988   case ISD::VECREDUCE_SMIN:
9989     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9990   case ISD::VECREDUCE_UMAX:
9991     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9992   case ISD::VECREDUCE_UMIN:
9993     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9994   case ISD::VECREDUCE_FMAX: {
9995     return DAG.getNode(
9996         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9997         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9998         Src);
9999   }
10000   case ISD::VECREDUCE_FMIN: {
10001     return DAG.getNode(
10002         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
10003         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
10004         Src);
10005   }
10006   default:
10007     llvm_unreachable("Unhandled reduction");
10008   }
10009 }
10010 
LowerATOMIC_LOAD_SUB(SDValue Op,SelectionDAG & DAG) const10011 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
10012                                                     SelectionDAG &DAG) const {
10013   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
10014   if (!Subtarget.hasLSE())
10015     return SDValue();
10016 
10017   // LSE has an atomic load-add instruction, but not a load-sub.
10018   SDLoc dl(Op);
10019   MVT VT = Op.getSimpleValueType();
10020   SDValue RHS = Op.getOperand(2);
10021   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
10022   RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
10023   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
10024                        Op.getOperand(0), Op.getOperand(1), RHS,
10025                        AN->getMemOperand());
10026 }
10027 
LowerATOMIC_LOAD_AND(SDValue Op,SelectionDAG & DAG) const10028 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
10029                                                     SelectionDAG &DAG) const {
10030   auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
10031   if (!Subtarget.hasLSE())
10032     return SDValue();
10033 
10034   // LSE has an atomic load-clear instruction, but not a load-and.
10035   SDLoc dl(Op);
10036   MVT VT = Op.getSimpleValueType();
10037   SDValue RHS = Op.getOperand(2);
10038   AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
10039   RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
10040   return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
10041                        Op.getOperand(0), Op.getOperand(1), RHS,
10042                        AN->getMemOperand());
10043 }
10044 
LowerWindowsDYNAMIC_STACKALLOC(SDValue Op,SDValue Chain,SDValue & Size,SelectionDAG & DAG) const10045 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
10046     SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
10047   SDLoc dl(Op);
10048   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10049   SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
10050 
10051   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10052   const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
10053   if (Subtarget->hasCustomCallingConv())
10054     TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
10055 
10056   Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
10057                      DAG.getConstant(4, dl, MVT::i64));
10058   Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
10059   Chain =
10060       DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
10061                   Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
10062                   DAG.getRegisterMask(Mask), Chain.getValue(1));
10063   // To match the actual intent better, we should read the output from X15 here
10064   // again (instead of potentially spilling it to the stack), but rereading Size
10065   // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
10066   // here.
10067 
10068   Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
10069                      DAG.getConstant(4, dl, MVT::i64));
10070   return Chain;
10071 }
10072 
10073 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const10074 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10075                                                SelectionDAG &DAG) const {
10076   assert(Subtarget->isTargetWindows() &&
10077          "Only Windows alloca probing supported");
10078   SDLoc dl(Op);
10079   // Get the inputs.
10080   SDNode *Node = Op.getNode();
10081   SDValue Chain = Op.getOperand(0);
10082   SDValue Size = Op.getOperand(1);
10083   MaybeAlign Align =
10084       cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
10085   EVT VT = Node->getValueType(0);
10086 
10087   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
10088           "no-stack-arg-probe")) {
10089     SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
10090     Chain = SP.getValue(1);
10091     SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
10092     if (Align)
10093       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10094                        DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
10095     Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
10096     SDValue Ops[2] = {SP, Chain};
10097     return DAG.getMergeValues(Ops, dl);
10098   }
10099 
10100   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
10101 
10102   Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
10103 
10104   SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
10105   Chain = SP.getValue(1);
10106   SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
10107   if (Align)
10108     SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
10109                      DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
10110   Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
10111 
10112   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
10113                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
10114 
10115   SDValue Ops[2] = {SP, Chain};
10116   return DAG.getMergeValues(Ops, dl);
10117 }
10118 
LowerVSCALE(SDValue Op,SelectionDAG & DAG) const10119 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
10120                                            SelectionDAG &DAG) const {
10121   EVT VT = Op.getValueType();
10122   assert(VT != MVT::i64 && "Expected illegal VSCALE node");
10123 
10124   SDLoc DL(Op);
10125   APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
10126   return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
10127                             DL, VT);
10128 }
10129 
10130 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
10131 template <unsigned NumVecs>
10132 static bool
setInfoSVEStN(const AArch64TargetLowering & TLI,const DataLayout & DL,AArch64TargetLowering::IntrinsicInfo & Info,const CallInst & CI)10133 setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
10134               AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
10135   Info.opc = ISD::INTRINSIC_VOID;
10136   // Retrieve EC from first vector argument.
10137   const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
10138   ElementCount EC = VT.getVectorElementCount();
10139 #ifndef NDEBUG
10140   // Check the assumption that all input vectors are the same type.
10141   for (unsigned I = 0; I < NumVecs; ++I)
10142     assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
10143            "Invalid type.");
10144 #endif
10145   // memVT is `NumVecs * VT`.
10146   Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
10147                                 EC * NumVecs);
10148   Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
10149   Info.offset = 0;
10150   Info.align.reset();
10151   Info.flags = MachineMemOperand::MOStore;
10152   return true;
10153 }
10154 
10155 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10156 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10157 /// specified in the intrinsic calls.
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const10158 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10159                                                const CallInst &I,
10160                                                MachineFunction &MF,
10161                                                unsigned Intrinsic) const {
10162   auto &DL = I.getModule()->getDataLayout();
10163   switch (Intrinsic) {
10164   case Intrinsic::aarch64_sve_st2:
10165     return setInfoSVEStN<2>(*this, DL, Info, I);
10166   case Intrinsic::aarch64_sve_st3:
10167     return setInfoSVEStN<3>(*this, DL, Info, I);
10168   case Intrinsic::aarch64_sve_st4:
10169     return setInfoSVEStN<4>(*this, DL, Info, I);
10170   case Intrinsic::aarch64_neon_ld2:
10171   case Intrinsic::aarch64_neon_ld3:
10172   case Intrinsic::aarch64_neon_ld4:
10173   case Intrinsic::aarch64_neon_ld1x2:
10174   case Intrinsic::aarch64_neon_ld1x3:
10175   case Intrinsic::aarch64_neon_ld1x4:
10176   case Intrinsic::aarch64_neon_ld2lane:
10177   case Intrinsic::aarch64_neon_ld3lane:
10178   case Intrinsic::aarch64_neon_ld4lane:
10179   case Intrinsic::aarch64_neon_ld2r:
10180   case Intrinsic::aarch64_neon_ld3r:
10181   case Intrinsic::aarch64_neon_ld4r: {
10182     Info.opc = ISD::INTRINSIC_W_CHAIN;
10183     // Conservatively set memVT to the entire set of vectors loaded.
10184     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
10185     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10186     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10187     Info.offset = 0;
10188     Info.align.reset();
10189     // volatile loads with NEON intrinsics not supported
10190     Info.flags = MachineMemOperand::MOLoad;
10191     return true;
10192   }
10193   case Intrinsic::aarch64_neon_st2:
10194   case Intrinsic::aarch64_neon_st3:
10195   case Intrinsic::aarch64_neon_st4:
10196   case Intrinsic::aarch64_neon_st1x2:
10197   case Intrinsic::aarch64_neon_st1x3:
10198   case Intrinsic::aarch64_neon_st1x4:
10199   case Intrinsic::aarch64_neon_st2lane:
10200   case Intrinsic::aarch64_neon_st3lane:
10201   case Intrinsic::aarch64_neon_st4lane: {
10202     Info.opc = ISD::INTRINSIC_VOID;
10203     // Conservatively set memVT to the entire set of vectors stored.
10204     unsigned NumElts = 0;
10205     for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10206       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10207       if (!ArgTy->isVectorTy())
10208         break;
10209       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
10210     }
10211     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10212     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
10213     Info.offset = 0;
10214     Info.align.reset();
10215     // volatile stores with NEON intrinsics not supported
10216     Info.flags = MachineMemOperand::MOStore;
10217     return true;
10218   }
10219   case Intrinsic::aarch64_ldaxr:
10220   case Intrinsic::aarch64_ldxr: {
10221     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10222     Info.opc = ISD::INTRINSIC_W_CHAIN;
10223     Info.memVT = MVT::getVT(PtrTy->getElementType());
10224     Info.ptrVal = I.getArgOperand(0);
10225     Info.offset = 0;
10226     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10227     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10228     return true;
10229   }
10230   case Intrinsic::aarch64_stlxr:
10231   case Intrinsic::aarch64_stxr: {
10232     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10233     Info.opc = ISD::INTRINSIC_W_CHAIN;
10234     Info.memVT = MVT::getVT(PtrTy->getElementType());
10235     Info.ptrVal = I.getArgOperand(1);
10236     Info.offset = 0;
10237     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10238     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10239     return true;
10240   }
10241   case Intrinsic::aarch64_ldaxp:
10242   case Intrinsic::aarch64_ldxp:
10243     Info.opc = ISD::INTRINSIC_W_CHAIN;
10244     Info.memVT = MVT::i128;
10245     Info.ptrVal = I.getArgOperand(0);
10246     Info.offset = 0;
10247     Info.align = Align(16);
10248     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
10249     return true;
10250   case Intrinsic::aarch64_stlxp:
10251   case Intrinsic::aarch64_stxp:
10252     Info.opc = ISD::INTRINSIC_W_CHAIN;
10253     Info.memVT = MVT::i128;
10254     Info.ptrVal = I.getArgOperand(2);
10255     Info.offset = 0;
10256     Info.align = Align(16);
10257     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
10258     return true;
10259   case Intrinsic::aarch64_sve_ldnt1: {
10260     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10261     Info.opc = ISD::INTRINSIC_W_CHAIN;
10262     Info.memVT = MVT::getVT(I.getType());
10263     Info.ptrVal = I.getArgOperand(1);
10264     Info.offset = 0;
10265     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10266     Info.flags = MachineMemOperand::MOLoad;
10267     if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
10268       Info.flags |= MachineMemOperand::MONonTemporal;
10269     return true;
10270   }
10271   case Intrinsic::aarch64_sve_stnt1: {
10272     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
10273     Info.opc = ISD::INTRINSIC_W_CHAIN;
10274     Info.memVT = MVT::getVT(I.getOperand(0)->getType());
10275     Info.ptrVal = I.getArgOperand(2);
10276     Info.offset = 0;
10277     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
10278     Info.flags = MachineMemOperand::MOStore;
10279     if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
10280       Info.flags |= MachineMemOperand::MONonTemporal;
10281     return true;
10282   }
10283   default:
10284     break;
10285   }
10286 
10287   return false;
10288 }
10289 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const10290 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
10291                                                   ISD::LoadExtType ExtTy,
10292                                                   EVT NewVT) const {
10293   // TODO: This may be worth removing. Check regression tests for diffs.
10294   if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
10295     return false;
10296 
10297   // If we're reducing the load width in order to avoid having to use an extra
10298   // instruction to do extension then it's probably a good idea.
10299   if (ExtTy != ISD::NON_EXTLOAD)
10300     return true;
10301   // Don't reduce load width if it would prevent us from combining a shift into
10302   // the offset.
10303   MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
10304   assert(Mem);
10305   const SDValue &Base = Mem->getBasePtr();
10306   if (Base.getOpcode() == ISD::ADD &&
10307       Base.getOperand(1).getOpcode() == ISD::SHL &&
10308       Base.getOperand(1).hasOneUse() &&
10309       Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
10310     // The shift can be combined if it matches the size of the value being
10311     // loaded (and so reducing the width would make it not match).
10312     uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
10313     uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
10314     if (ShiftAmount == Log2_32(LoadBytes))
10315       return false;
10316   }
10317   // We have no reason to disallow reducing the load width, so allow it.
10318   return true;
10319 }
10320 
10321 // Truncations from 64-bit GPR to 32-bit GPR is free.
isTruncateFree(Type * Ty1,Type * Ty2) const10322 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10323   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10324     return false;
10325   uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
10326   uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
10327   return NumBits1 > NumBits2;
10328 }
isTruncateFree(EVT VT1,EVT VT2) const10329 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10330   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10331     return false;
10332   uint64_t NumBits1 = VT1.getFixedSizeInBits();
10333   uint64_t NumBits2 = VT2.getFixedSizeInBits();
10334   return NumBits1 > NumBits2;
10335 }
10336 
10337 /// Check if it is profitable to hoist instruction in then/else to if.
10338 /// Not profitable if I and it's user can form a FMA instruction
10339 /// because we prefer FMSUB/FMADD.
isProfitableToHoist(Instruction * I) const10340 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
10341   if (I->getOpcode() != Instruction::FMul)
10342     return true;
10343 
10344   if (!I->hasOneUse())
10345     return true;
10346 
10347   Instruction *User = I->user_back();
10348 
10349   if (User &&
10350       !(User->getOpcode() == Instruction::FSub ||
10351         User->getOpcode() == Instruction::FAdd))
10352     return true;
10353 
10354   const TargetOptions &Options = getTargetMachine().Options;
10355   const Function *F = I->getFunction();
10356   const DataLayout &DL = F->getParent()->getDataLayout();
10357   Type *Ty = User->getOperand(0)->getType();
10358 
10359   return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
10360            isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
10361            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
10362             Options.UnsafeFPMath));
10363 }
10364 
10365 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
10366 // 64-bit GPR.
isZExtFree(Type * Ty1,Type * Ty2) const10367 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10368   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10369     return false;
10370   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10371   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10372   return NumBits1 == 32 && NumBits2 == 64;
10373 }
isZExtFree(EVT VT1,EVT VT2) const10374 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10375   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
10376     return false;
10377   unsigned NumBits1 = VT1.getSizeInBits();
10378   unsigned NumBits2 = VT2.getSizeInBits();
10379   return NumBits1 == 32 && NumBits2 == 64;
10380 }
10381 
isZExtFree(SDValue Val,EVT VT2) const10382 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10383   EVT VT1 = Val.getValueType();
10384   if (isZExtFree(VT1, VT2)) {
10385     return true;
10386   }
10387 
10388   if (Val.getOpcode() != ISD::LOAD)
10389     return false;
10390 
10391   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
10392   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
10393           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
10394           VT1.getSizeInBits() <= 32);
10395 }
10396 
isExtFreeImpl(const Instruction * Ext) const10397 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
10398   if (isa<FPExtInst>(Ext))
10399     return false;
10400 
10401   // Vector types are not free.
10402   if (Ext->getType()->isVectorTy())
10403     return false;
10404 
10405   for (const Use &U : Ext->uses()) {
10406     // The extension is free if we can fold it with a left shift in an
10407     // addressing mode or an arithmetic operation: add, sub, and cmp.
10408 
10409     // Is there a shift?
10410     const Instruction *Instr = cast<Instruction>(U.getUser());
10411 
10412     // Is this a constant shift?
10413     switch (Instr->getOpcode()) {
10414     case Instruction::Shl:
10415       if (!isa<ConstantInt>(Instr->getOperand(1)))
10416         return false;
10417       break;
10418     case Instruction::GetElementPtr: {
10419       gep_type_iterator GTI = gep_type_begin(Instr);
10420       auto &DL = Ext->getModule()->getDataLayout();
10421       std::advance(GTI, U.getOperandNo()-1);
10422       Type *IdxTy = GTI.getIndexedType();
10423       // This extension will end up with a shift because of the scaling factor.
10424       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
10425       // Get the shift amount based on the scaling factor:
10426       // log2(sizeof(IdxTy)) - log2(8).
10427       uint64_t ShiftAmt =
10428         countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
10429       // Is the constant foldable in the shift of the addressing mode?
10430       // I.e., shift amount is between 1 and 4 inclusive.
10431       if (ShiftAmt == 0 || ShiftAmt > 4)
10432         return false;
10433       break;
10434     }
10435     case Instruction::Trunc:
10436       // Check if this is a noop.
10437       // trunc(sext ty1 to ty2) to ty1.
10438       if (Instr->getType() == Ext->getOperand(0)->getType())
10439         continue;
10440       LLVM_FALLTHROUGH;
10441     default:
10442       return false;
10443     }
10444 
10445     // At this point we can use the bfm family, so this extension is free
10446     // for that use.
10447   }
10448   return true;
10449 }
10450 
10451 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
10452 /// or upper half of the vector elements.
areExtractShuffleVectors(Value * Op1,Value * Op2)10453 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
10454   auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
10455     auto *FullTy = FullV->getType();
10456     auto *HalfTy = HalfV->getType();
10457     return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
10458            2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
10459   };
10460 
10461   auto extractHalf = [](Value *FullV, Value *HalfV) {
10462     auto *FullVT = cast<FixedVectorType>(FullV->getType());
10463     auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
10464     return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
10465   };
10466 
10467   ArrayRef<int> M1, M2;
10468   Value *S1Op1, *S2Op1;
10469   if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
10470       !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
10471     return false;
10472 
10473   // Check that the operands are half as wide as the result and we extract
10474   // half of the elements of the input vectors.
10475   if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
10476       !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
10477     return false;
10478 
10479   // Check the mask extracts either the lower or upper half of vector
10480   // elements.
10481   int M1Start = -1;
10482   int M2Start = -1;
10483   int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
10484   if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
10485       !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
10486       M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
10487     return false;
10488 
10489   return true;
10490 }
10491 
10492 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
10493 /// of the vector elements.
areExtractExts(Value * Ext1,Value * Ext2)10494 static bool areExtractExts(Value *Ext1, Value *Ext2) {
10495   auto areExtDoubled = [](Instruction *Ext) {
10496     return Ext->getType()->getScalarSizeInBits() ==
10497            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
10498   };
10499 
10500   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
10501       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
10502       !areExtDoubled(cast<Instruction>(Ext1)) ||
10503       !areExtDoubled(cast<Instruction>(Ext2)))
10504     return false;
10505 
10506   return true;
10507 }
10508 
10509 /// Check if Op could be used with vmull_high_p64 intrinsic.
isOperandOfVmullHighP64(Value * Op)10510 static bool isOperandOfVmullHighP64(Value *Op) {
10511   Value *VectorOperand = nullptr;
10512   ConstantInt *ElementIndex = nullptr;
10513   return match(Op, m_ExtractElt(m_Value(VectorOperand),
10514                                 m_ConstantInt(ElementIndex))) &&
10515          ElementIndex->getValue() == 1 &&
10516          isa<FixedVectorType>(VectorOperand->getType()) &&
10517          cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
10518 }
10519 
10520 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
areOperandsOfVmullHighP64(Value * Op1,Value * Op2)10521 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
10522   return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
10523 }
10524 
10525 /// Check if sinking \p I's operands to I's basic block is profitable, because
10526 /// the operands can be folded into a target instruction, e.g.
10527 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
shouldSinkOperands(Instruction * I,SmallVectorImpl<Use * > & Ops) const10528 bool AArch64TargetLowering::shouldSinkOperands(
10529     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
10530   if (!I->getType()->isVectorTy())
10531     return false;
10532 
10533   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
10534     switch (II->getIntrinsicID()) {
10535     case Intrinsic::aarch64_neon_umull:
10536       if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
10537         return false;
10538       Ops.push_back(&II->getOperandUse(0));
10539       Ops.push_back(&II->getOperandUse(1));
10540       return true;
10541 
10542     case Intrinsic::aarch64_neon_pmull64:
10543       if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
10544                                      II->getArgOperand(1)))
10545         return false;
10546       Ops.push_back(&II->getArgOperandUse(0));
10547       Ops.push_back(&II->getArgOperandUse(1));
10548       return true;
10549 
10550     default:
10551       return false;
10552     }
10553   }
10554 
10555   switch (I->getOpcode()) {
10556   case Instruction::Sub:
10557   case Instruction::Add: {
10558     if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
10559       return false;
10560 
10561     // If the exts' operands extract either the lower or upper elements, we
10562     // can sink them too.
10563     auto Ext1 = cast<Instruction>(I->getOperand(0));
10564     auto Ext2 = cast<Instruction>(I->getOperand(1));
10565     if (areExtractShuffleVectors(Ext1, Ext2)) {
10566       Ops.push_back(&Ext1->getOperandUse(0));
10567       Ops.push_back(&Ext2->getOperandUse(0));
10568     }
10569 
10570     Ops.push_back(&I->getOperandUse(0));
10571     Ops.push_back(&I->getOperandUse(1));
10572 
10573     return true;
10574   }
10575   default:
10576     return false;
10577   }
10578   return false;
10579 }
10580 
hasPairedLoad(EVT LoadedType,Align & RequiredAligment) const10581 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
10582                                           Align &RequiredAligment) const {
10583   if (!LoadedType.isSimple() ||
10584       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
10585     return false;
10586   // Cyclone supports unaligned accesses.
10587   RequiredAligment = Align(1);
10588   unsigned NumBits = LoadedType.getSizeInBits();
10589   return NumBits == 32 || NumBits == 64;
10590 }
10591 
10592 /// A helper function for determining the number of interleaved accesses we
10593 /// will generate when lowering accesses of the given type.
10594 unsigned
getNumInterleavedAccesses(VectorType * VecTy,const DataLayout & DL) const10595 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
10596                                                  const DataLayout &DL) const {
10597   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
10598 }
10599 
10600 MachineMemOperand::Flags
getTargetMMOFlags(const Instruction & I) const10601 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
10602   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
10603       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
10604     return MOStridedAccess;
10605   return MachineMemOperand::MONone;
10606 }
10607 
isLegalInterleavedAccessType(VectorType * VecTy,const DataLayout & DL) const10608 bool AArch64TargetLowering::isLegalInterleavedAccessType(
10609     VectorType *VecTy, const DataLayout &DL) const {
10610 
10611   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
10612   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
10613 
10614   // Ensure the number of vector elements is greater than 1.
10615   if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
10616     return false;
10617 
10618   // Ensure the element type is legal.
10619   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
10620     return false;
10621 
10622   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
10623   // 128 will be split into multiple interleaved accesses.
10624   return VecSize == 64 || VecSize % 128 == 0;
10625 }
10626 
10627 /// Lower an interleaved load into a ldN intrinsic.
10628 ///
10629 /// E.g. Lower an interleaved load (Factor = 2):
10630 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
10631 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
10632 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
10633 ///
10634 ///      Into:
10635 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
10636 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
10637 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
lowerInterleavedLoad(LoadInst * LI,ArrayRef<ShuffleVectorInst * > Shuffles,ArrayRef<unsigned> Indices,unsigned Factor) const10638 bool AArch64TargetLowering::lowerInterleavedLoad(
10639     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
10640     ArrayRef<unsigned> Indices, unsigned Factor) const {
10641   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10642          "Invalid interleave factor");
10643   assert(!Shuffles.empty() && "Empty shufflevector input");
10644   assert(Shuffles.size() == Indices.size() &&
10645          "Unmatched number of shufflevectors and indices");
10646 
10647   const DataLayout &DL = LI->getModule()->getDataLayout();
10648 
10649   VectorType *VTy = Shuffles[0]->getType();
10650 
10651   // Skip if we do not have NEON and skip illegal vector types. We can
10652   // "legalize" wide vector types into multiple interleaved accesses as long as
10653   // the vector types are divisible by 128.
10654   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
10655     return false;
10656 
10657   unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
10658 
10659   auto *FVTy = cast<FixedVectorType>(VTy);
10660 
10661   // A pointer vector can not be the return type of the ldN intrinsics. Need to
10662   // load integer vectors first and then convert to pointer vectors.
10663   Type *EltTy = FVTy->getElementType();
10664   if (EltTy->isPointerTy())
10665     FVTy =
10666         FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
10667 
10668   IRBuilder<> Builder(LI);
10669 
10670   // The base address of the load.
10671   Value *BaseAddr = LI->getPointerOperand();
10672 
10673   if (NumLoads > 1) {
10674     // If we're going to generate more than one load, reset the sub-vector type
10675     // to something legal.
10676     FVTy = FixedVectorType::get(FVTy->getElementType(),
10677                                 FVTy->getNumElements() / NumLoads);
10678 
10679     // We will compute the pointer operand of each load from the original base
10680     // address using GEPs. Cast the base address to a pointer to the scalar
10681     // element type.
10682     BaseAddr = Builder.CreateBitCast(
10683         BaseAddr,
10684         FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
10685   }
10686 
10687   Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
10688   Type *Tys[2] = {FVTy, PtrTy};
10689   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
10690                                             Intrinsic::aarch64_neon_ld3,
10691                                             Intrinsic::aarch64_neon_ld4};
10692   Function *LdNFunc =
10693       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
10694 
10695   // Holds sub-vectors extracted from the load intrinsic return values. The
10696   // sub-vectors are associated with the shufflevector instructions they will
10697   // replace.
10698   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
10699 
10700   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
10701 
10702     // If we're generating more than one load, compute the base address of
10703     // subsequent loads as an offset from the previous.
10704     if (LoadCount > 0)
10705       BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
10706                                             FVTy->getNumElements() * Factor);
10707 
10708     CallInst *LdN = Builder.CreateCall(
10709         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
10710 
10711     // Extract and store the sub-vectors returned by the load intrinsic.
10712     for (unsigned i = 0; i < Shuffles.size(); i++) {
10713       ShuffleVectorInst *SVI = Shuffles[i];
10714       unsigned Index = Indices[i];
10715 
10716       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
10717 
10718       // Convert the integer vector to pointer vector if the element is pointer.
10719       if (EltTy->isPointerTy())
10720         SubVec = Builder.CreateIntToPtr(
10721             SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
10722                                          FVTy->getNumElements()));
10723       SubVecs[SVI].push_back(SubVec);
10724     }
10725   }
10726 
10727   // Replace uses of the shufflevector instructions with the sub-vectors
10728   // returned by the load intrinsic. If a shufflevector instruction is
10729   // associated with more than one sub-vector, those sub-vectors will be
10730   // concatenated into a single wide vector.
10731   for (ShuffleVectorInst *SVI : Shuffles) {
10732     auto &SubVec = SubVecs[SVI];
10733     auto *WideVec =
10734         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
10735     SVI->replaceAllUsesWith(WideVec);
10736   }
10737 
10738   return true;
10739 }
10740 
10741 /// Lower an interleaved store into a stN intrinsic.
10742 ///
10743 /// E.g. Lower an interleaved store (Factor = 3):
10744 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
10745 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
10746 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10747 ///
10748 ///      Into:
10749 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
10750 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
10751 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
10752 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
10753 ///
10754 /// Note that the new shufflevectors will be removed and we'll only generate one
10755 /// st3 instruction in CodeGen.
10756 ///
10757 /// Example for a more general valid mask (Factor 3). Lower:
10758 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
10759 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
10760 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
10761 ///
10762 ///      Into:
10763 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
10764 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
10765 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
10766 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
lowerInterleavedStore(StoreInst * SI,ShuffleVectorInst * SVI,unsigned Factor) const10767 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
10768                                                   ShuffleVectorInst *SVI,
10769                                                   unsigned Factor) const {
10770   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
10771          "Invalid interleave factor");
10772 
10773   auto *VecTy = cast<FixedVectorType>(SVI->getType());
10774   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
10775 
10776   unsigned LaneLen = VecTy->getNumElements() / Factor;
10777   Type *EltTy = VecTy->getElementType();
10778   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
10779 
10780   const DataLayout &DL = SI->getModule()->getDataLayout();
10781 
10782   // Skip if we do not have NEON and skip illegal vector types. We can
10783   // "legalize" wide vector types into multiple interleaved accesses as long as
10784   // the vector types are divisible by 128.
10785   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
10786     return false;
10787 
10788   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
10789 
10790   Value *Op0 = SVI->getOperand(0);
10791   Value *Op1 = SVI->getOperand(1);
10792   IRBuilder<> Builder(SI);
10793 
10794   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
10795   // vectors to integer vectors.
10796   if (EltTy->isPointerTy()) {
10797     Type *IntTy = DL.getIntPtrType(EltTy);
10798     unsigned NumOpElts =
10799         cast<FixedVectorType>(Op0->getType())->getNumElements();
10800 
10801     // Convert to the corresponding integer vector.
10802     auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
10803     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
10804     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
10805 
10806     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
10807   }
10808 
10809   // The base address of the store.
10810   Value *BaseAddr = SI->getPointerOperand();
10811 
10812   if (NumStores > 1) {
10813     // If we're going to generate more than one store, reset the lane length
10814     // and sub-vector type to something legal.
10815     LaneLen /= NumStores;
10816     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10817 
10818     // We will compute the pointer operand of each store from the original base
10819     // address using GEPs. Cast the base address to a pointer to the scalar
10820     // element type.
10821     BaseAddr = Builder.CreateBitCast(
10822         BaseAddr,
10823         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10824   }
10825 
10826   auto Mask = SVI->getShuffleMask();
10827 
10828   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10829   Type *Tys[2] = {SubVecTy, PtrTy};
10830   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10831                                              Intrinsic::aarch64_neon_st3,
10832                                              Intrinsic::aarch64_neon_st4};
10833   Function *StNFunc =
10834       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10835 
10836   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10837 
10838     SmallVector<Value *, 5> Ops;
10839 
10840     // Split the shufflevector operands into sub vectors for the new stN call.
10841     for (unsigned i = 0; i < Factor; i++) {
10842       unsigned IdxI = StoreCount * LaneLen * Factor + i;
10843       if (Mask[IdxI] >= 0) {
10844         Ops.push_back(Builder.CreateShuffleVector(
10845             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10846       } else {
10847         unsigned StartMask = 0;
10848         for (unsigned j = 1; j < LaneLen; j++) {
10849           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10850           if (Mask[IdxJ * Factor + IdxI] >= 0) {
10851             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10852             break;
10853           }
10854         }
10855         // Note: Filling undef gaps with random elements is ok, since
10856         // those elements were being written anyway (with undefs).
10857         // In the case of all undefs we're defaulting to using elems from 0
10858         // Note: StartMask cannot be negative, it's checked in
10859         // isReInterleaveMask
10860         Ops.push_back(Builder.CreateShuffleVector(
10861             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10862       }
10863     }
10864 
10865     // If we generating more than one store, we compute the base address of
10866     // subsequent stores as an offset from the previous.
10867     if (StoreCount > 0)
10868       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10869                                             BaseAddr, LaneLen * Factor);
10870 
10871     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10872     Builder.CreateCall(StNFunc, Ops);
10873   }
10874   return true;
10875 }
10876 
10877 // Lower an SVE structured load intrinsic returning a tuple type to target
10878 // specific intrinsic taking the same input but returning a multi-result value
10879 // of the split tuple type.
10880 //
10881 // E.g. Lowering an LD3:
10882 //
10883 //  call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10884 //                                                    <vscale x 4 x i1> %pred,
10885 //                                                    <vscale x 4 x i32>* %addr)
10886 //
10887 //  Output DAG:
10888 //
10889 //    t0: ch = EntryToken
10890 //        t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10891 //        t4: i64,ch = CopyFromReg t0, Register:i64 %1
10892 //    t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10893 //    t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10894 //
10895 // This is called pre-legalization to avoid widening/splitting issues with
10896 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
LowerSVEStructLoad(unsigned Intrinsic,ArrayRef<SDValue> LoadOps,EVT VT,SelectionDAG & DAG,const SDLoc & DL) const10897 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10898                                                   ArrayRef<SDValue> LoadOps,
10899                                                   EVT VT, SelectionDAG &DAG,
10900                                                   const SDLoc &DL) const {
10901   assert(VT.isScalableVector() && "Can only lower scalable vectors");
10902 
10903   unsigned N, Opcode;
10904   static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10905       {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10906       {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10907       {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10908 
10909   std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10910   assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
10911          "invalid tuple vector type!");
10912 
10913   EVT SplitVT =
10914       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10915                        VT.getVectorElementCount().divideCoefficientBy(N));
10916   assert(isTypeLegal(SplitVT));
10917 
10918   SmallVector<EVT, 5> VTs(N, SplitVT);
10919   VTs.push_back(MVT::Other); // Chain
10920   SDVTList NodeTys = DAG.getVTList(VTs);
10921 
10922   SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10923   SmallVector<SDValue, 4> PseudoLoadOps;
10924   for (unsigned I = 0; I < N; ++I)
10925     PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10926   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10927 }
10928 
getOptimalMemOpType(const MemOp & Op,const AttributeList & FuncAttributes) const10929 EVT AArch64TargetLowering::getOptimalMemOpType(
10930     const MemOp &Op, const AttributeList &FuncAttributes) const {
10931   bool CanImplicitFloat =
10932       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10933   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10934   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10935   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10936   // taken one instruction to materialize the v2i64 zero and one store (with
10937   // restrictive addressing mode). Just do i64 stores.
10938   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10939   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10940     if (Op.isAligned(AlignCheck))
10941       return true;
10942     bool Fast;
10943     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10944                                           &Fast) &&
10945            Fast;
10946   };
10947 
10948   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10949       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10950     return MVT::v2i64;
10951   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10952     return MVT::f128;
10953   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10954     return MVT::i64;
10955   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10956     return MVT::i32;
10957   return MVT::Other;
10958 }
10959 
getOptimalMemOpLLT(const MemOp & Op,const AttributeList & FuncAttributes) const10960 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10961     const MemOp &Op, const AttributeList &FuncAttributes) const {
10962   bool CanImplicitFloat =
10963       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10964   bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10965   bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10966   // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10967   // taken one instruction to materialize the v2i64 zero and one store (with
10968   // restrictive addressing mode). Just do i64 stores.
10969   bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10970   auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10971     if (Op.isAligned(AlignCheck))
10972       return true;
10973     bool Fast;
10974     return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10975                                           &Fast) &&
10976            Fast;
10977   };
10978 
10979   if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10980       AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10981     return LLT::vector(2, 64);
10982   if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10983     return LLT::scalar(128);
10984   if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10985     return LLT::scalar(64);
10986   if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10987     return LLT::scalar(32);
10988   return LLT();
10989 }
10990 
10991 // 12-bit optionally shifted immediates are legal for adds.
isLegalAddImmediate(int64_t Immed) const10992 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10993   if (Immed == std::numeric_limits<int64_t>::min()) {
10994     LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10995                       << ": avoid UB for INT64_MIN\n");
10996     return false;
10997   }
10998   // Same encoding for add/sub, just flip the sign.
10999   Immed = std::abs(Immed);
11000   bool IsLegal = ((Immed >> 12) == 0 ||
11001                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
11002   LLVM_DEBUG(dbgs() << "Is " << Immed
11003                     << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
11004   return IsLegal;
11005 }
11006 
11007 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
11008 // immediates is the same as for an add or a sub.
isLegalICmpImmediate(int64_t Immed) const11009 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
11010   return isLegalAddImmediate(Immed);
11011 }
11012 
11013 /// isLegalAddressingMode - Return true if the addressing mode represented
11014 /// by AM is legal for this target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const11015 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
11016                                                   const AddrMode &AM, Type *Ty,
11017                                                   unsigned AS, Instruction *I) const {
11018   // AArch64 has five basic addressing modes:
11019   //  reg
11020   //  reg + 9-bit signed offset
11021   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
11022   //  reg1 + reg2
11023   //  reg + SIZE_IN_BYTES * reg
11024 
11025   // No global is ever allowed as a base.
11026   if (AM.BaseGV)
11027     return false;
11028 
11029   // No reg+reg+imm addressing.
11030   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
11031     return false;
11032 
11033   // FIXME: Update this method to support scalable addressing modes.
11034   if (isa<ScalableVectorType>(Ty))
11035     return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
11036 
11037   // check reg + imm case:
11038   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
11039   uint64_t NumBytes = 0;
11040   if (Ty->isSized()) {
11041     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
11042     NumBytes = NumBits / 8;
11043     if (!isPowerOf2_64(NumBits))
11044       NumBytes = 0;
11045   }
11046 
11047   if (!AM.Scale) {
11048     int64_t Offset = AM.BaseOffs;
11049 
11050     // 9-bit signed offset
11051     if (isInt<9>(Offset))
11052       return true;
11053 
11054     // 12-bit unsigned offset
11055     unsigned shift = Log2_64(NumBytes);
11056     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
11057         // Must be a multiple of NumBytes (NumBytes is a power of 2)
11058         (Offset >> shift) << shift == Offset)
11059       return true;
11060     return false;
11061   }
11062 
11063   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
11064 
11065   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
11066 }
11067 
shouldConsiderGEPOffsetSplit() const11068 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
11069   // Consider splitting large offset of struct or array.
11070   return true;
11071 }
11072 
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const11073 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
11074                                                 const AddrMode &AM, Type *Ty,
11075                                                 unsigned AS) const {
11076   // Scaling factors are not free at all.
11077   // Operands                     | Rt Latency
11078   // -------------------------------------------
11079   // Rt, [Xn, Xm]                 | 4
11080   // -------------------------------------------
11081   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
11082   // Rt, [Xn, Wm, <extend> #imm]  |
11083   if (isLegalAddressingMode(DL, AM, Ty, AS))
11084     // Scale represents reg2 * scale, thus account for 1 if
11085     // it is not equal to 0 or 1.
11086     return AM.Scale != 0 && AM.Scale != 1;
11087   return -1;
11088 }
11089 
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const11090 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
11091     const MachineFunction &MF, EVT VT) const {
11092   VT = VT.getScalarType();
11093 
11094   if (!VT.isSimple())
11095     return false;
11096 
11097   switch (VT.getSimpleVT().SimpleTy) {
11098   case MVT::f32:
11099   case MVT::f64:
11100     return true;
11101   default:
11102     break;
11103   }
11104 
11105   return false;
11106 }
11107 
isFMAFasterThanFMulAndFAdd(const Function & F,Type * Ty) const11108 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
11109                                                        Type *Ty) const {
11110   switch (Ty->getScalarType()->getTypeID()) {
11111   case Type::FloatTyID:
11112   case Type::DoubleTyID:
11113     return true;
11114   default:
11115     return false;
11116   }
11117 }
11118 
11119 const MCPhysReg *
getScratchRegisters(CallingConv::ID) const11120 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
11121   // LR is a callee-save register, but we must treat it as clobbered by any call
11122   // site. Hence we include LR in the scratch registers, which are in turn added
11123   // as implicit-defs for stackmaps and patchpoints.
11124   static const MCPhysReg ScratchRegs[] = {
11125     AArch64::X16, AArch64::X17, AArch64::LR, 0
11126   };
11127   return ScratchRegs;
11128 }
11129 
11130 bool
isDesirableToCommuteWithShift(const SDNode * N,CombineLevel Level) const11131 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11132                                                      CombineLevel Level) const {
11133   N = N->getOperand(0).getNode();
11134   EVT VT = N->getValueType(0);
11135     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
11136     // it with shift to let it be lowered to UBFX.
11137   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
11138       isa<ConstantSDNode>(N->getOperand(1))) {
11139     uint64_t TruncMask = N->getConstantOperandVal(1);
11140     if (isMask_64(TruncMask) &&
11141       N->getOperand(0).getOpcode() == ISD::SRL &&
11142       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
11143       return false;
11144   }
11145   return true;
11146 }
11147 
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const11148 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11149                                                               Type *Ty) const {
11150   assert(Ty->isIntegerTy());
11151 
11152   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11153   if (BitSize == 0)
11154     return false;
11155 
11156   int64_t Val = Imm.getSExtValue();
11157   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
11158     return true;
11159 
11160   if ((int64_t)Val < 0)
11161     Val = ~Val;
11162   if (BitSize == 32)
11163     Val &= (1LL << 32) - 1;
11164 
11165   unsigned LZ = countLeadingZeros((uint64_t)Val);
11166   unsigned Shift = (63 - LZ) / 16;
11167   // MOVZ is free so return true for one or fewer MOVK.
11168   return Shift < 3;
11169 }
11170 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const11171 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
11172                                                     unsigned Index) const {
11173   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
11174     return false;
11175 
11176   return (Index == 0 || Index == ResVT.getVectorNumElements());
11177 }
11178 
11179 /// Turn vector tests of the signbit in the form of:
11180 ///   xor (sra X, elt_size(X)-1), -1
11181 /// into:
11182 ///   cmge X, X, #0
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)11183 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
11184                                          const AArch64Subtarget *Subtarget) {
11185   EVT VT = N->getValueType(0);
11186   if (!Subtarget->hasNEON() || !VT.isVector())
11187     return SDValue();
11188 
11189   // There must be a shift right algebraic before the xor, and the xor must be a
11190   // 'not' operation.
11191   SDValue Shift = N->getOperand(0);
11192   SDValue Ones = N->getOperand(1);
11193   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
11194       !ISD::isBuildVectorAllOnes(Ones.getNode()))
11195     return SDValue();
11196 
11197   // The shift should be smearing the sign bit across each vector element.
11198   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
11199   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
11200   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
11201     return SDValue();
11202 
11203   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
11204 }
11205 
11206 // Generate SUBS and CSEL for integer abs.
performIntegerAbsCombine(SDNode * N,SelectionDAG & DAG)11207 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
11208   EVT VT = N->getValueType(0);
11209 
11210   SDValue N0 = N->getOperand(0);
11211   SDValue N1 = N->getOperand(1);
11212   SDLoc DL(N);
11213 
11214   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
11215   // and change it to SUB and CSEL.
11216   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
11217       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
11218       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
11219     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
11220       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
11221         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
11222                                   N0.getOperand(0));
11223         // Generate SUBS & CSEL.
11224         SDValue Cmp =
11225             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
11226                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
11227         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
11228                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
11229                            SDValue(Cmp.getNode(), 1));
11230       }
11231   return SDValue();
11232 }
11233 
11234 // VECREDUCE_ADD( EXTEND(v16i8_type) ) to
11235 // VECREDUCE_ADD( DOTv16i8(v16i8_type) )
performVecReduceAddCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * ST)11236 static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
11237                                           const AArch64Subtarget *ST) {
11238   SDValue Op0 = N->getOperand(0);
11239   if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32)
11240     return SDValue();
11241 
11242   if (Op0.getValueType().getVectorElementType() != MVT::i32)
11243     return SDValue();
11244 
11245   unsigned ExtOpcode = Op0.getOpcode();
11246   if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
11247     return SDValue();
11248 
11249   EVT Op0VT = Op0.getOperand(0).getValueType();
11250   if (Op0VT != MVT::v16i8)
11251     return SDValue();
11252 
11253   SDLoc DL(Op0);
11254   SDValue Ones = DAG.getConstant(1, DL, Op0VT);
11255   SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
11256   auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND)
11257                          ? Intrinsic::aarch64_neon_udot
11258                          : Intrinsic::aarch64_neon_sdot;
11259   SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(),
11260                             DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros,
11261                             Ones, Op0.getOperand(0));
11262   return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
11263 }
11264 
11265 // Given a ABS node, detect the following pattern:
11266 // (ABS (SUB (EXTEND a), (EXTEND b))).
11267 // Generates UABD/SABD instruction.
performABSCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11268 static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG,
11269                                  TargetLowering::DAGCombinerInfo &DCI,
11270                                  const AArch64Subtarget *Subtarget) {
11271   SDValue AbsOp1 = N->getOperand(0);
11272   SDValue Op0, Op1;
11273 
11274   if (AbsOp1.getOpcode() != ISD::SUB)
11275     return SDValue();
11276 
11277   Op0 = AbsOp1.getOperand(0);
11278   Op1 = AbsOp1.getOperand(1);
11279 
11280   unsigned Opc0 = Op0.getOpcode();
11281   // Check if the operands of the sub are (zero|sign)-extended.
11282   if (Opc0 != Op1.getOpcode() ||
11283       (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
11284     return SDValue();
11285 
11286   EVT VectorT1 = Op0.getOperand(0).getValueType();
11287   EVT VectorT2 = Op1.getOperand(0).getValueType();
11288   // Check if vectors are of same type and valid size.
11289   uint64_t Size = VectorT1.getFixedSizeInBits();
11290   if (VectorT1 != VectorT2 || (Size != 64 && Size != 128))
11291     return SDValue();
11292 
11293   // Check if vector element types are valid.
11294   EVT VT1 = VectorT1.getVectorElementType();
11295   if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32)
11296     return SDValue();
11297 
11298   Op0 = Op0.getOperand(0);
11299   Op1 = Op1.getOperand(0);
11300   unsigned ABDOpcode =
11301       (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD;
11302   SDValue ABD =
11303       DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
11304   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
11305 }
11306 
performXorCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11307 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
11308                                  TargetLowering::DAGCombinerInfo &DCI,
11309                                  const AArch64Subtarget *Subtarget) {
11310   if (DCI.isBeforeLegalizeOps())
11311     return SDValue();
11312 
11313   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
11314     return Cmp;
11315 
11316   return performIntegerAbsCombine(N, DAG);
11317 }
11318 
11319 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const11320 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11321                                      SelectionDAG &DAG,
11322                                      SmallVectorImpl<SDNode *> &Created) const {
11323   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11324   if (isIntDivCheap(N->getValueType(0), Attr))
11325     return SDValue(N,0); // Lower SDIV as SDIV
11326 
11327   // fold (sdiv X, pow2)
11328   EVT VT = N->getValueType(0);
11329   if ((VT != MVT::i32 && VT != MVT::i64) ||
11330       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11331     return SDValue();
11332 
11333   SDLoc DL(N);
11334   SDValue N0 = N->getOperand(0);
11335   unsigned Lg2 = Divisor.countTrailingZeros();
11336   SDValue Zero = DAG.getConstant(0, DL, VT);
11337   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11338 
11339   // Add (N0 < 0) ? Pow2 - 1 : 0;
11340   SDValue CCVal;
11341   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
11342   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11343   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
11344 
11345   Created.push_back(Cmp.getNode());
11346   Created.push_back(Add.getNode());
11347   Created.push_back(CSel.getNode());
11348 
11349   // Divide by pow2.
11350   SDValue SRA =
11351       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
11352 
11353   // If we're dividing by a positive value, we're done.  Otherwise, we must
11354   // negate the result.
11355   if (Divisor.isNonNegative())
11356     return SRA;
11357 
11358   Created.push_back(SRA.getNode());
11359   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11360 }
11361 
IsSVECntIntrinsic(SDValue S)11362 static bool IsSVECntIntrinsic(SDValue S) {
11363   switch(getIntrinsicID(S.getNode())) {
11364   default:
11365     break;
11366   case Intrinsic::aarch64_sve_cntb:
11367   case Intrinsic::aarch64_sve_cnth:
11368   case Intrinsic::aarch64_sve_cntw:
11369   case Intrinsic::aarch64_sve_cntd:
11370     return true;
11371   }
11372   return false;
11373 }
11374 
performMulCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11375 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
11376                                  TargetLowering::DAGCombinerInfo &DCI,
11377                                  const AArch64Subtarget *Subtarget) {
11378   if (DCI.isBeforeLegalizeOps())
11379     return SDValue();
11380 
11381   // The below optimizations require a constant RHS.
11382   if (!isa<ConstantSDNode>(N->getOperand(1)))
11383     return SDValue();
11384 
11385   SDValue N0 = N->getOperand(0);
11386   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
11387   const APInt &ConstValue = C->getAPIntValue();
11388 
11389   // Allow the scaling to be folded into the `cnt` instruction by preventing
11390   // the scaling to be obscured here. This makes it easier to pattern match.
11391   if (IsSVECntIntrinsic(N0) ||
11392      (N0->getOpcode() == ISD::TRUNCATE &&
11393       (IsSVECntIntrinsic(N0->getOperand(0)))))
11394        if (ConstValue.sge(1) && ConstValue.sle(16))
11395          return SDValue();
11396 
11397   // Multiplication of a power of two plus/minus one can be done more
11398   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
11399   // future CPUs have a cheaper MADD instruction, this may need to be
11400   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
11401   // 64-bit is 5 cycles, so this is always a win.
11402   // More aggressively, some multiplications N0 * C can be lowered to
11403   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
11404   // e.g. 6=3*2=(2+1)*2.
11405   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
11406   // which equals to (1+2)*16-(1+2).
11407   // TrailingZeroes is used to test if the mul can be lowered to
11408   // shift+add+shift.
11409   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
11410   if (TrailingZeroes) {
11411     // Conservatively do not lower to shift+add+shift if the mul might be
11412     // folded into smul or umul.
11413     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
11414                             isZeroExtended(N0.getNode(), DAG)))
11415       return SDValue();
11416     // Conservatively do not lower to shift+add+shift if the mul might be
11417     // folded into madd or msub.
11418     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
11419                            N->use_begin()->getOpcode() == ISD::SUB))
11420       return SDValue();
11421   }
11422   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
11423   // and shift+add+shift.
11424   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
11425 
11426   unsigned ShiftAmt, AddSubOpc;
11427   // Is the shifted value the LHS operand of the add/sub?
11428   bool ShiftValUseIsN0 = true;
11429   // Do we need to negate the result?
11430   bool NegateResult = false;
11431 
11432   if (ConstValue.isNonNegative()) {
11433     // (mul x, 2^N + 1) => (add (shl x, N), x)
11434     // (mul x, 2^N - 1) => (sub (shl x, N), x)
11435     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
11436     APInt SCVMinus1 = ShiftedConstValue - 1;
11437     APInt CVPlus1 = ConstValue + 1;
11438     if (SCVMinus1.isPowerOf2()) {
11439       ShiftAmt = SCVMinus1.logBase2();
11440       AddSubOpc = ISD::ADD;
11441     } else if (CVPlus1.isPowerOf2()) {
11442       ShiftAmt = CVPlus1.logBase2();
11443       AddSubOpc = ISD::SUB;
11444     } else
11445       return SDValue();
11446   } else {
11447     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11448     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11449     APInt CVNegPlus1 = -ConstValue + 1;
11450     APInt CVNegMinus1 = -ConstValue - 1;
11451     if (CVNegPlus1.isPowerOf2()) {
11452       ShiftAmt = CVNegPlus1.logBase2();
11453       AddSubOpc = ISD::SUB;
11454       ShiftValUseIsN0 = false;
11455     } else if (CVNegMinus1.isPowerOf2()) {
11456       ShiftAmt = CVNegMinus1.logBase2();
11457       AddSubOpc = ISD::ADD;
11458       NegateResult = true;
11459     } else
11460       return SDValue();
11461   }
11462 
11463   SDLoc DL(N);
11464   EVT VT = N->getValueType(0);
11465   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
11466                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
11467 
11468   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
11469   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
11470   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
11471   assert(!(NegateResult && TrailingZeroes) &&
11472          "NegateResult and TrailingZeroes cannot both be true for now.");
11473   // Negate the result.
11474   if (NegateResult)
11475     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
11476   // Shift the result.
11477   if (TrailingZeroes)
11478     return DAG.getNode(ISD::SHL, DL, VT, Res,
11479                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
11480   return Res;
11481 }
11482 
performVectorCompareAndMaskUnaryOpCombine(SDNode * N,SelectionDAG & DAG)11483 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
11484                                                          SelectionDAG &DAG) {
11485   // Take advantage of vector comparisons producing 0 or -1 in each lane to
11486   // optimize away operation when it's from a constant.
11487   //
11488   // The general transformation is:
11489   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
11490   //       AND(VECTOR_CMP(x,y), constant2)
11491   //    constant2 = UNARYOP(constant)
11492 
11493   // Early exit if this isn't a vector operation, the operand of the
11494   // unary operation isn't a bitwise AND, or if the sizes of the operations
11495   // aren't the same.
11496   EVT VT = N->getValueType(0);
11497   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
11498       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
11499       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
11500     return SDValue();
11501 
11502   // Now check that the other operand of the AND is a constant. We could
11503   // make the transformation for non-constant splats as well, but it's unclear
11504   // that would be a benefit as it would not eliminate any operations, just
11505   // perform one more step in scalar code before moving to the vector unit.
11506   if (BuildVectorSDNode *BV =
11507           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
11508     // Bail out if the vector isn't a constant.
11509     if (!BV->isConstant())
11510       return SDValue();
11511 
11512     // Everything checks out. Build up the new and improved node.
11513     SDLoc DL(N);
11514     EVT IntVT = BV->getValueType(0);
11515     // Create a new constant of the appropriate type for the transformed
11516     // DAG.
11517     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
11518     // The AND node needs bitcasts to/from an integer vector type around it.
11519     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
11520     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
11521                                  N->getOperand(0)->getOperand(0), MaskConst);
11522     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
11523     return Res;
11524   }
11525 
11526   return SDValue();
11527 }
11528 
performIntToFpCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)11529 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
11530                                      const AArch64Subtarget *Subtarget) {
11531   // First try to optimize away the conversion when it's conditionally from
11532   // a constant. Vectors only.
11533   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
11534     return Res;
11535 
11536   EVT VT = N->getValueType(0);
11537   if (VT != MVT::f32 && VT != MVT::f64)
11538     return SDValue();
11539 
11540   // Only optimize when the source and destination types have the same width.
11541   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
11542     return SDValue();
11543 
11544   // If the result of an integer load is only used by an integer-to-float
11545   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
11546   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
11547   SDValue N0 = N->getOperand(0);
11548   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
11549       // Do not change the width of a volatile load.
11550       !cast<LoadSDNode>(N0)->isVolatile()) {
11551     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
11552     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
11553                                LN0->getPointerInfo(), LN0->getAlignment(),
11554                                LN0->getMemOperand()->getFlags());
11555 
11556     // Make sure successors of the original load stay after it by updating them
11557     // to use the new Chain.
11558     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
11559 
11560     unsigned Opcode =
11561         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
11562     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
11563   }
11564 
11565   return SDValue();
11566 }
11567 
11568 /// Fold a floating-point multiply by power of two into floating-point to
11569 /// fixed-point conversion.
performFpToIntCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11570 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
11571                                      TargetLowering::DAGCombinerInfo &DCI,
11572                                      const AArch64Subtarget *Subtarget) {
11573   if (!Subtarget->hasNEON())
11574     return SDValue();
11575 
11576   if (!N->getValueType(0).isSimple())
11577     return SDValue();
11578 
11579   SDValue Op = N->getOperand(0);
11580   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11581       Op.getOpcode() != ISD::FMUL)
11582     return SDValue();
11583 
11584   SDValue ConstVec = Op->getOperand(1);
11585   if (!isa<BuildVectorSDNode>(ConstVec))
11586     return SDValue();
11587 
11588   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11589   uint32_t FloatBits = FloatTy.getSizeInBits();
11590   if (FloatBits != 32 && FloatBits != 64)
11591     return SDValue();
11592 
11593   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11594   uint32_t IntBits = IntTy.getSizeInBits();
11595   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11596     return SDValue();
11597 
11598   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
11599   if (IntBits > FloatBits)
11600     return SDValue();
11601 
11602   BitVector UndefElements;
11603   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11604   int32_t Bits = IntBits == 64 ? 64 : 32;
11605   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
11606   if (C == -1 || C == 0 || C > Bits)
11607     return SDValue();
11608 
11609   MVT ResTy;
11610   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11611   switch (NumLanes) {
11612   default:
11613     return SDValue();
11614   case 2:
11615     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11616     break;
11617   case 4:
11618     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11619     break;
11620   }
11621 
11622   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11623     return SDValue();
11624 
11625   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
11626          "Illegal vector type after legalization");
11627 
11628   SDLoc DL(N);
11629   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11630   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
11631                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
11632   SDValue FixConv =
11633       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
11634                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
11635                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
11636   // We can handle smaller integers by generating an extra trunc.
11637   if (IntBits < FloatBits)
11638     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
11639 
11640   return FixConv;
11641 }
11642 
11643 /// Fold a floating-point divide by power of two into fixed-point to
11644 /// floating-point conversion.
performFDivCombine(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11645 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
11646                                   TargetLowering::DAGCombinerInfo &DCI,
11647                                   const AArch64Subtarget *Subtarget) {
11648   if (!Subtarget->hasNEON())
11649     return SDValue();
11650 
11651   SDValue Op = N->getOperand(0);
11652   unsigned Opc = Op->getOpcode();
11653   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11654       !Op.getOperand(0).getValueType().isSimple() ||
11655       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
11656     return SDValue();
11657 
11658   SDValue ConstVec = N->getOperand(1);
11659   if (!isa<BuildVectorSDNode>(ConstVec))
11660     return SDValue();
11661 
11662   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11663   int32_t IntBits = IntTy.getSizeInBits();
11664   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
11665     return SDValue();
11666 
11667   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11668   int32_t FloatBits = FloatTy.getSizeInBits();
11669   if (FloatBits != 32 && FloatBits != 64)
11670     return SDValue();
11671 
11672   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
11673   if (IntBits > FloatBits)
11674     return SDValue();
11675 
11676   BitVector UndefElements;
11677   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11678   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
11679   if (C == -1 || C == 0 || C > FloatBits)
11680     return SDValue();
11681 
11682   MVT ResTy;
11683   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11684   switch (NumLanes) {
11685   default:
11686     return SDValue();
11687   case 2:
11688     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
11689     break;
11690   case 4:
11691     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
11692     break;
11693   }
11694 
11695   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
11696     return SDValue();
11697 
11698   SDLoc DL(N);
11699   SDValue ConvInput = Op.getOperand(0);
11700   bool IsSigned = Opc == ISD::SINT_TO_FP;
11701   if (IntBits < FloatBits)
11702     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
11703                             ResTy, ConvInput);
11704 
11705   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
11706                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
11707   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
11708                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
11709                      DAG.getConstant(C, DL, MVT::i32));
11710 }
11711 
11712 /// An EXTR instruction is made up of two shifts, ORed together. This helper
11713 /// searches for and classifies those shifts.
findEXTRHalf(SDValue N,SDValue & Src,uint32_t & ShiftAmount,bool & FromHi)11714 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
11715                          bool &FromHi) {
11716   if (N.getOpcode() == ISD::SHL)
11717     FromHi = false;
11718   else if (N.getOpcode() == ISD::SRL)
11719     FromHi = true;
11720   else
11721     return false;
11722 
11723   if (!isa<ConstantSDNode>(N.getOperand(1)))
11724     return false;
11725 
11726   ShiftAmount = N->getConstantOperandVal(1);
11727   Src = N->getOperand(0);
11728   return true;
11729 }
11730 
11731 /// EXTR instruction extracts a contiguous chunk of bits from two existing
11732 /// registers viewed as a high/low pair. This function looks for the pattern:
11733 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
11734 /// with an EXTR. Can't quite be done in TableGen because the two immediates
11735 /// aren't independent.
tryCombineToEXTR(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)11736 static SDValue tryCombineToEXTR(SDNode *N,
11737                                 TargetLowering::DAGCombinerInfo &DCI) {
11738   SelectionDAG &DAG = DCI.DAG;
11739   SDLoc DL(N);
11740   EVT VT = N->getValueType(0);
11741 
11742   assert(N->getOpcode() == ISD::OR && "Unexpected root");
11743 
11744   if (VT != MVT::i32 && VT != MVT::i64)
11745     return SDValue();
11746 
11747   SDValue LHS;
11748   uint32_t ShiftLHS = 0;
11749   bool LHSFromHi = false;
11750   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
11751     return SDValue();
11752 
11753   SDValue RHS;
11754   uint32_t ShiftRHS = 0;
11755   bool RHSFromHi = false;
11756   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
11757     return SDValue();
11758 
11759   // If they're both trying to come from the high part of the register, they're
11760   // not really an EXTR.
11761   if (LHSFromHi == RHSFromHi)
11762     return SDValue();
11763 
11764   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
11765     return SDValue();
11766 
11767   if (LHSFromHi) {
11768     std::swap(LHS, RHS);
11769     std::swap(ShiftLHS, ShiftRHS);
11770   }
11771 
11772   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
11773                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
11774 }
11775 
tryCombineToBSL(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)11776 static SDValue tryCombineToBSL(SDNode *N,
11777                                 TargetLowering::DAGCombinerInfo &DCI) {
11778   EVT VT = N->getValueType(0);
11779   SelectionDAG &DAG = DCI.DAG;
11780   SDLoc DL(N);
11781 
11782   if (!VT.isVector())
11783     return SDValue();
11784 
11785   SDValue N0 = N->getOperand(0);
11786   if (N0.getOpcode() != ISD::AND)
11787     return SDValue();
11788 
11789   SDValue N1 = N->getOperand(1);
11790   if (N1.getOpcode() != ISD::AND)
11791     return SDValue();
11792 
11793   // We only have to look for constant vectors here since the general, variable
11794   // case can be handled in TableGen.
11795   unsigned Bits = VT.getScalarSizeInBits();
11796   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
11797   for (int i = 1; i >= 0; --i)
11798     for (int j = 1; j >= 0; --j) {
11799       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
11800       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
11801       if (!BVN0 || !BVN1)
11802         continue;
11803 
11804       bool FoundMatch = true;
11805       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
11806         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
11807         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
11808         if (!CN0 || !CN1 ||
11809             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
11810           FoundMatch = false;
11811           break;
11812         }
11813       }
11814 
11815       if (FoundMatch)
11816         return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
11817                            N0->getOperand(1 - i), N1->getOperand(1 - j));
11818     }
11819 
11820   return SDValue();
11821 }
11822 
performORCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)11823 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11824                                 const AArch64Subtarget *Subtarget) {
11825   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
11826   SelectionDAG &DAG = DCI.DAG;
11827   EVT VT = N->getValueType(0);
11828 
11829   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11830     return SDValue();
11831 
11832   if (SDValue Res = tryCombineToEXTR(N, DCI))
11833     return Res;
11834 
11835   if (SDValue Res = tryCombineToBSL(N, DCI))
11836     return Res;
11837 
11838   return SDValue();
11839 }
11840 
isConstantSplatVectorMaskForType(SDNode * N,EVT MemVT)11841 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
11842   if (!MemVT.getVectorElementType().isSimple())
11843     return false;
11844 
11845   uint64_t MaskForTy = 0ull;
11846   switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
11847   case MVT::i8:
11848     MaskForTy = 0xffull;
11849     break;
11850   case MVT::i16:
11851     MaskForTy = 0xffffull;
11852     break;
11853   case MVT::i32:
11854     MaskForTy = 0xffffffffull;
11855     break;
11856   default:
11857     return false;
11858     break;
11859   }
11860 
11861   if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
11862     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
11863       return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
11864 
11865   return false;
11866 }
11867 
performSVEAndCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)11868 static SDValue performSVEAndCombine(SDNode *N,
11869                                     TargetLowering::DAGCombinerInfo &DCI) {
11870   if (DCI.isBeforeLegalizeOps())
11871     return SDValue();
11872 
11873   SelectionDAG &DAG = DCI.DAG;
11874   SDValue Src = N->getOperand(0);
11875   unsigned Opc = Src->getOpcode();
11876 
11877   // Zero/any extend of an unsigned unpack
11878   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
11879     SDValue UnpkOp = Src->getOperand(0);
11880     SDValue Dup = N->getOperand(1);
11881 
11882     if (Dup.getOpcode() != AArch64ISD::DUP)
11883       return SDValue();
11884 
11885     SDLoc DL(N);
11886     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11887     uint64_t ExtVal = C->getZExtValue();
11888 
11889     // If the mask is fully covered by the unpack, we don't need to push
11890     // a new AND onto the operand
11891     EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11892     if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11893         (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11894         (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11895       return Src;
11896 
11897     // Truncate to prevent a DUP with an over wide constant
11898     APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11899 
11900     // Otherwise, make sure we propagate the AND to the operand
11901     // of the unpack
11902     Dup = DAG.getNode(AArch64ISD::DUP, DL,
11903                       UnpkOp->getValueType(0),
11904                       DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11905 
11906     SDValue And = DAG.getNode(ISD::AND, DL,
11907                               UnpkOp->getValueType(0), UnpkOp, Dup);
11908 
11909     return DAG.getNode(Opc, DL, N->getValueType(0), And);
11910   }
11911 
11912   SDValue Mask = N->getOperand(1);
11913 
11914   if (!Src.hasOneUse())
11915     return SDValue();
11916 
11917   EVT MemVT;
11918 
11919   // SVE load instructions perform an implicit zero-extend, which makes them
11920   // perfect candidates for combining.
11921   switch (Opc) {
11922   case AArch64ISD::LD1_MERGE_ZERO:
11923   case AArch64ISD::LDNF1_MERGE_ZERO:
11924   case AArch64ISD::LDFF1_MERGE_ZERO:
11925     MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11926     break;
11927   case AArch64ISD::GLD1_MERGE_ZERO:
11928   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11929   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11930   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11931   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11932   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11933   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11934   case AArch64ISD::GLDFF1_MERGE_ZERO:
11935   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11936   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11937   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11938   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11939   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11940   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11941   case AArch64ISD::GLDNT1_MERGE_ZERO:
11942     MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11943     break;
11944   default:
11945     return SDValue();
11946   }
11947 
11948   if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11949     return Src;
11950 
11951   return SDValue();
11952 }
11953 
performANDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)11954 static SDValue performANDCombine(SDNode *N,
11955                                  TargetLowering::DAGCombinerInfo &DCI) {
11956   SelectionDAG &DAG = DCI.DAG;
11957   SDValue LHS = N->getOperand(0);
11958   EVT VT = N->getValueType(0);
11959   if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11960     return SDValue();
11961 
11962   if (VT.isScalableVector())
11963     return performSVEAndCombine(N, DCI);
11964 
11965   // The combining code below works only for NEON vectors. In particular, it
11966   // does not work for SVE when dealing with vectors wider than 128 bits.
11967   if (!(VT.is64BitVector() || VT.is128BitVector()))
11968     return SDValue();
11969 
11970   BuildVectorSDNode *BVN =
11971       dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11972   if (!BVN)
11973     return SDValue();
11974 
11975   // AND does not accept an immediate, so check if we can use a BIC immediate
11976   // instruction instead. We do this here instead of using a (and x, (mvni imm))
11977   // pattern in isel, because some immediates may be lowered to the preferred
11978   // (and x, (movi imm)) form, even though an mvni representation also exists.
11979   APInt DefBits(VT.getSizeInBits(), 0);
11980   APInt UndefBits(VT.getSizeInBits(), 0);
11981   if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11982     SDValue NewOp;
11983 
11984     DefBits = ~DefBits;
11985     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11986                                     DefBits, &LHS)) ||
11987         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11988                                     DefBits, &LHS)))
11989       return NewOp;
11990 
11991     UndefBits = ~UndefBits;
11992     if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11993                                     UndefBits, &LHS)) ||
11994         (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11995                                     UndefBits, &LHS)))
11996       return NewOp;
11997   }
11998 
11999   return SDValue();
12000 }
12001 
performSRLCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)12002 static SDValue performSRLCombine(SDNode *N,
12003                                  TargetLowering::DAGCombinerInfo &DCI) {
12004   SelectionDAG &DAG = DCI.DAG;
12005   EVT VT = N->getValueType(0);
12006   if (VT != MVT::i32 && VT != MVT::i64)
12007     return SDValue();
12008 
12009   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
12010   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
12011   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
12012   SDValue N0 = N->getOperand(0);
12013   if (N0.getOpcode() == ISD::BSWAP) {
12014     SDLoc DL(N);
12015     SDValue N1 = N->getOperand(1);
12016     SDValue N00 = N0.getOperand(0);
12017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12018       uint64_t ShiftAmt = C->getZExtValue();
12019       if (VT == MVT::i32 && ShiftAmt == 16 &&
12020           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
12021         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
12022       if (VT == MVT::i64 && ShiftAmt == 32 &&
12023           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
12024         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
12025     }
12026   }
12027   return SDValue();
12028 }
12029 
12030 // Attempt to form urhadd(OpA, OpB) from
12031 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
12032 // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
12033 // The original form of the first expression is
12034 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
12035 // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
12036 // Before this function is called the srl will have been lowered to
12037 // AArch64ISD::VLSHR.
12038 // This pass can also recognize signed variants of the patterns that use sign
12039 // extension instead of zero extension and form a srhadd(OpA, OpB) or a
12040 // shadd(OpA, OpB) from them.
12041 static SDValue
performVectorTruncateCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12042 performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12043                              SelectionDAG &DAG) {
12044   EVT VT = N->getValueType(0);
12045 
12046   // Since we are looking for a right shift by a constant value of 1 and we are
12047   // operating on types at least 16 bits in length (sign/zero extended OpA and
12048   // OpB, which are at least 8 bits), it follows that the truncate will always
12049   // discard the shifted-in bit and therefore the right shift will be logical
12050   // regardless of the signedness of OpA and OpB.
12051   SDValue Shift = N->getOperand(0);
12052   if (Shift.getOpcode() != AArch64ISD::VLSHR)
12053     return SDValue();
12054 
12055   // Is the right shift using an immediate value of 1?
12056   uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
12057   if (ShiftAmount != 1)
12058     return SDValue();
12059 
12060   SDValue ExtendOpA, ExtendOpB;
12061   SDValue ShiftOp0 = Shift.getOperand(0);
12062   unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
12063   if (ShiftOp0Opc == ISD::SUB) {
12064 
12065     SDValue Xor = ShiftOp0.getOperand(1);
12066     if (Xor.getOpcode() != ISD::XOR)
12067       return SDValue();
12068 
12069     // Is the XOR using a constant amount of all ones in the right hand side?
12070     uint64_t C;
12071     if (!isAllConstantBuildVector(Xor.getOperand(1), C))
12072       return SDValue();
12073 
12074     unsigned ElemSizeInBits = VT.getScalarSizeInBits();
12075     APInt CAsAPInt(ElemSizeInBits, C);
12076     if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
12077       return SDValue();
12078 
12079     ExtendOpA = Xor.getOperand(0);
12080     ExtendOpB = ShiftOp0.getOperand(0);
12081   } else if (ShiftOp0Opc == ISD::ADD) {
12082     ExtendOpA = ShiftOp0.getOperand(0);
12083     ExtendOpB = ShiftOp0.getOperand(1);
12084   } else
12085     return SDValue();
12086 
12087   unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
12088   unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
12089   if (!(ExtendOpAOpc == ExtendOpBOpc &&
12090         (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
12091     return SDValue();
12092 
12093   // Is the result of the right shift being truncated to the same value type as
12094   // the original operands, OpA and OpB?
12095   SDValue OpA = ExtendOpA.getOperand(0);
12096   SDValue OpB = ExtendOpB.getOperand(0);
12097   EVT OpAVT = OpA.getValueType();
12098   assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
12099   if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
12100     return SDValue();
12101 
12102   SDLoc DL(N);
12103   bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
12104   bool IsRHADD = ShiftOp0Opc == ISD::SUB;
12105   unsigned HADDOpc = IsSignExtend
12106                          ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
12107                          : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
12108   SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
12109 
12110   return ResultHADD;
12111 }
12112 
hasPairwiseAdd(unsigned Opcode,EVT VT,bool FullFP16)12113 static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
12114   switch (Opcode) {
12115   case ISD::FADD:
12116     return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
12117   case ISD::ADD:
12118     return VT == MVT::i64;
12119   default:
12120     return false;
12121   }
12122 }
12123 
performExtractVectorEltCombine(SDNode * N,SelectionDAG & DAG)12124 static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
12125   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
12126   ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
12127 
12128   EVT VT = N->getValueType(0);
12129   const bool FullFP16 =
12130       static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
12131 
12132   // Rewrite for pairwise fadd pattern
12133   //   (f32 (extract_vector_elt
12134   //           (fadd (vXf32 Other)
12135   //                 (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
12136   // ->
12137   //   (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
12138   //              (extract_vector_elt (vXf32 Other) 1))
12139   if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
12140       hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
12141     SDLoc DL(N0);
12142     SDValue N00 = N0->getOperand(0);
12143     SDValue N01 = N0->getOperand(1);
12144 
12145     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
12146     SDValue Other = N00;
12147 
12148     // And handle the commutative case.
12149     if (!Shuffle) {
12150       Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
12151       Other = N01;
12152     }
12153 
12154     if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
12155         Other == Shuffle->getOperand(0)) {
12156       return DAG.getNode(N0->getOpcode(), DL, VT,
12157                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
12158                                      DAG.getConstant(0, DL, MVT::i64)),
12159                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
12160                                      DAG.getConstant(1, DL, MVT::i64)));
12161     }
12162   }
12163 
12164   return SDValue();
12165 }
12166 
performConcatVectorsCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12167 static SDValue performConcatVectorsCombine(SDNode *N,
12168                                            TargetLowering::DAGCombinerInfo &DCI,
12169                                            SelectionDAG &DAG) {
12170   SDLoc dl(N);
12171   EVT VT = N->getValueType(0);
12172   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
12173   unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
12174 
12175   // Optimize concat_vectors of truncated vectors, where the intermediate
12176   // type is illegal, to avoid said illegality,  e.g.,
12177   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
12178   //                          (v2i16 (truncate (v2i64)))))
12179   // ->
12180   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
12181   //                                    (v4i32 (bitcast (v2i64))),
12182   //                                    <0, 2, 4, 6>)))
12183   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
12184   // on both input and result type, so we might generate worse code.
12185   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
12186   if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
12187       N1Opc == ISD::TRUNCATE) {
12188     SDValue N00 = N0->getOperand(0);
12189     SDValue N10 = N1->getOperand(0);
12190     EVT N00VT = N00.getValueType();
12191 
12192     if (N00VT == N10.getValueType() &&
12193         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
12194         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
12195       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
12196       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
12197       for (size_t i = 0; i < Mask.size(); ++i)
12198         Mask[i] = i * 2;
12199       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12200                          DAG.getVectorShuffle(
12201                              MidVT, dl,
12202                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
12203                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
12204     }
12205   }
12206 
12207   // Wait 'til after everything is legalized to try this. That way we have
12208   // legal vector types and such.
12209   if (DCI.isBeforeLegalizeOps())
12210     return SDValue();
12211 
12212   // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
12213   // subvectors from the same original vectors. Combine these into a single
12214   // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
12215   //  (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
12216   //                                        extract_subvector (v16i8 OpB,
12217   //                                        <0>))),
12218   //                         (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
12219   //                                        extract_subvector (v16i8 OpB,
12220   //                                        <8>)))))
12221   // ->
12222   //  (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
12223   if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
12224       (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
12225        N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
12226     SDValue N00 = N0->getOperand(0);
12227     SDValue N01 = N0->getOperand(1);
12228     SDValue N10 = N1->getOperand(0);
12229     SDValue N11 = N1->getOperand(1);
12230 
12231     EVT N00VT = N00.getValueType();
12232     EVT N10VT = N10.getValueType();
12233 
12234     if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12235         N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12236         N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
12237         N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
12238       SDValue N00Source = N00->getOperand(0);
12239       SDValue N01Source = N01->getOperand(0);
12240       SDValue N10Source = N10->getOperand(0);
12241       SDValue N11Source = N11->getOperand(0);
12242 
12243       if (N00Source == N10Source && N01Source == N11Source &&
12244           N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
12245         assert(N0.getValueType() == N1.getValueType());
12246 
12247         uint64_t N00Index = N00.getConstantOperandVal(1);
12248         uint64_t N01Index = N01.getConstantOperandVal(1);
12249         uint64_t N10Index = N10.getConstantOperandVal(1);
12250         uint64_t N11Index = N11.getConstantOperandVal(1);
12251 
12252         if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
12253             N10Index == N00VT.getVectorNumElements())
12254           return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
12255       }
12256     }
12257   }
12258 
12259   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
12260   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
12261   // canonicalise to that.
12262   if (N0 == N1 && VT.getVectorNumElements() == 2) {
12263     assert(VT.getScalarSizeInBits() == 64);
12264     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
12265                        DAG.getConstant(0, dl, MVT::i64));
12266   }
12267 
12268   // Canonicalise concat_vectors so that the right-hand vector has as few
12269   // bit-casts as possible before its real operation. The primary matching
12270   // destination for these operations will be the narrowing "2" instructions,
12271   // which depend on the operation being performed on this right-hand vector.
12272   // For example,
12273   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
12274   // becomes
12275   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
12276 
12277   if (N1Opc != ISD::BITCAST)
12278     return SDValue();
12279   SDValue RHS = N1->getOperand(0);
12280   MVT RHSTy = RHS.getValueType().getSimpleVT();
12281   // If the RHS is not a vector, this is not the pattern we're looking for.
12282   if (!RHSTy.isVector())
12283     return SDValue();
12284 
12285   LLVM_DEBUG(
12286       dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
12287 
12288   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
12289                                   RHSTy.getVectorNumElements() * 2);
12290   return DAG.getNode(ISD::BITCAST, dl, VT,
12291                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
12292                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
12293                                  RHS));
12294 }
12295 
tryCombineFixedPointConvert(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12296 static SDValue tryCombineFixedPointConvert(SDNode *N,
12297                                            TargetLowering::DAGCombinerInfo &DCI,
12298                                            SelectionDAG &DAG) {
12299   // Wait until after everything is legalized to try this. That way we have
12300   // legal vector types and such.
12301   if (DCI.isBeforeLegalizeOps())
12302     return SDValue();
12303   // Transform a scalar conversion of a value from a lane extract into a
12304   // lane extract of a vector conversion. E.g., from foo1 to foo2:
12305   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
12306   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
12307   //
12308   // The second form interacts better with instruction selection and the
12309   // register allocator to avoid cross-class register copies that aren't
12310   // coalescable due to a lane reference.
12311 
12312   // Check the operand and see if it originates from a lane extract.
12313   SDValue Op1 = N->getOperand(1);
12314   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12315     // Yep, no additional predication needed. Perform the transform.
12316     SDValue IID = N->getOperand(0);
12317     SDValue Shift = N->getOperand(2);
12318     SDValue Vec = Op1.getOperand(0);
12319     SDValue Lane = Op1.getOperand(1);
12320     EVT ResTy = N->getValueType(0);
12321     EVT VecResTy;
12322     SDLoc DL(N);
12323 
12324     // The vector width should be 128 bits by the time we get here, even
12325     // if it started as 64 bits (the extract_vector handling will have
12326     // done so).
12327     assert(Vec.getValueSizeInBits() == 128 &&
12328            "unexpected vector size on extract_vector_elt!");
12329     if (Vec.getValueType() == MVT::v4i32)
12330       VecResTy = MVT::v4f32;
12331     else if (Vec.getValueType() == MVT::v2i64)
12332       VecResTy = MVT::v2f64;
12333     else
12334       llvm_unreachable("unexpected vector type!");
12335 
12336     SDValue Convert =
12337         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
12338     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
12339   }
12340   return SDValue();
12341 }
12342 
12343 // AArch64 high-vector "long" operations are formed by performing the non-high
12344 // version on an extract_subvector of each operand which gets the high half:
12345 //
12346 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
12347 //
12348 // However, there are cases which don't have an extract_high explicitly, but
12349 // have another operation that can be made compatible with one for free. For
12350 // example:
12351 //
12352 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
12353 //
12354 // This routine does the actual conversion of such DUPs, once outer routines
12355 // have determined that everything else is in order.
12356 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
12357 // similarly here.
tryExtendDUPToExtractHigh(SDValue N,SelectionDAG & DAG)12358 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
12359   switch (N.getOpcode()) {
12360   case AArch64ISD::DUP:
12361   case AArch64ISD::DUPLANE8:
12362   case AArch64ISD::DUPLANE16:
12363   case AArch64ISD::DUPLANE32:
12364   case AArch64ISD::DUPLANE64:
12365   case AArch64ISD::MOVI:
12366   case AArch64ISD::MOVIshift:
12367   case AArch64ISD::MOVIedit:
12368   case AArch64ISD::MOVImsl:
12369   case AArch64ISD::MVNIshift:
12370   case AArch64ISD::MVNImsl:
12371     break;
12372   default:
12373     // FMOV could be supported, but isn't very useful, as it would only occur
12374     // if you passed a bitcast' floating point immediate to an eligible long
12375     // integer op (addl, smull, ...).
12376     return SDValue();
12377   }
12378 
12379   MVT NarrowTy = N.getSimpleValueType();
12380   if (!NarrowTy.is64BitVector())
12381     return SDValue();
12382 
12383   MVT ElementTy = NarrowTy.getVectorElementType();
12384   unsigned NumElems = NarrowTy.getVectorNumElements();
12385   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
12386 
12387   SDLoc dl(N);
12388   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
12389                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
12390                      DAG.getConstant(NumElems, dl, MVT::i64));
12391 }
12392 
isEssentiallyExtractHighSubvector(SDValue N)12393 static bool isEssentiallyExtractHighSubvector(SDValue N) {
12394   if (N.getOpcode() == ISD::BITCAST)
12395     N = N.getOperand(0);
12396   if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12397     return false;
12398   return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
12399          N.getOperand(0).getValueType().getVectorNumElements() / 2;
12400 }
12401 
12402 /// Helper structure to keep track of ISD::SET_CC operands.
12403 struct GenericSetCCInfo {
12404   const SDValue *Opnd0;
12405   const SDValue *Opnd1;
12406   ISD::CondCode CC;
12407 };
12408 
12409 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
12410 struct AArch64SetCCInfo {
12411   const SDValue *Cmp;
12412   AArch64CC::CondCode CC;
12413 };
12414 
12415 /// Helper structure to keep track of SetCC information.
12416 union SetCCInfo {
12417   GenericSetCCInfo Generic;
12418   AArch64SetCCInfo AArch64;
12419 };
12420 
12421 /// Helper structure to be able to read SetCC information.  If set to
12422 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
12423 /// GenericSetCCInfo.
12424 struct SetCCInfoAndKind {
12425   SetCCInfo Info;
12426   bool IsAArch64;
12427 };
12428 
12429 /// Check whether or not \p Op is a SET_CC operation, either a generic or
12430 /// an
12431 /// AArch64 lowered one.
12432 /// \p SetCCInfo is filled accordingly.
12433 /// \post SetCCInfo is meanginfull only when this function returns true.
12434 /// \return True when Op is a kind of SET_CC operation.
isSetCC(SDValue Op,SetCCInfoAndKind & SetCCInfo)12435 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
12436   // If this is a setcc, this is straight forward.
12437   if (Op.getOpcode() == ISD::SETCC) {
12438     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
12439     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
12440     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12441     SetCCInfo.IsAArch64 = false;
12442     return true;
12443   }
12444   // Otherwise, check if this is a matching csel instruction.
12445   // In other words:
12446   // - csel 1, 0, cc
12447   // - csel 0, 1, !cc
12448   if (Op.getOpcode() != AArch64ISD::CSEL)
12449     return false;
12450   // Set the information about the operands.
12451   // TODO: we want the operands of the Cmp not the csel
12452   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
12453   SetCCInfo.IsAArch64 = true;
12454   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
12455       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12456 
12457   // Check that the operands matches the constraints:
12458   // (1) Both operands must be constants.
12459   // (2) One must be 1 and the other must be 0.
12460   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
12461   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12462 
12463   // Check (1).
12464   if (!TValue || !FValue)
12465     return false;
12466 
12467   // Check (2).
12468   if (!TValue->isOne()) {
12469     // Update the comparison when we are interested in !cc.
12470     std::swap(TValue, FValue);
12471     SetCCInfo.Info.AArch64.CC =
12472         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
12473   }
12474   return TValue->isOne() && FValue->isNullValue();
12475 }
12476 
12477 // Returns true if Op is setcc or zext of setcc.
isSetCCOrZExtSetCC(const SDValue & Op,SetCCInfoAndKind & Info)12478 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
12479   if (isSetCC(Op, Info))
12480     return true;
12481   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
12482     isSetCC(Op->getOperand(0), Info));
12483 }
12484 
12485 // The folding we want to perform is:
12486 // (add x, [zext] (setcc cc ...) )
12487 //   -->
12488 // (csel x, (add x, 1), !cc ...)
12489 //
12490 // The latter will get matched to a CSINC instruction.
performSetccAddFolding(SDNode * Op,SelectionDAG & DAG)12491 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
12492   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
12493   SDValue LHS = Op->getOperand(0);
12494   SDValue RHS = Op->getOperand(1);
12495   SetCCInfoAndKind InfoAndKind;
12496 
12497   // If neither operand is a SET_CC, give up.
12498   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
12499     std::swap(LHS, RHS);
12500     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
12501       return SDValue();
12502   }
12503 
12504   // FIXME: This could be generatized to work for FP comparisons.
12505   EVT CmpVT = InfoAndKind.IsAArch64
12506                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
12507                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
12508   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
12509     return SDValue();
12510 
12511   SDValue CCVal;
12512   SDValue Cmp;
12513   SDLoc dl(Op);
12514   if (InfoAndKind.IsAArch64) {
12515     CCVal = DAG.getConstant(
12516         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
12517         MVT::i32);
12518     Cmp = *InfoAndKind.Info.AArch64.Cmp;
12519   } else
12520     Cmp = getAArch64Cmp(
12521         *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
12522         ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
12523         dl);
12524 
12525   EVT VT = Op->getValueType(0);
12526   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
12527   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
12528 }
12529 
12530 // ADD(UADDV a, UADDV b) -->  UADDV(ADD a, b)
performUADDVCombine(SDNode * N,SelectionDAG & DAG)12531 static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
12532   EVT VT = N->getValueType(0);
12533   // Only scalar integer and vector types.
12534   if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
12535     return SDValue();
12536 
12537   SDValue LHS = N->getOperand(0);
12538   SDValue RHS = N->getOperand(1);
12539   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12540       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
12541     return SDValue();
12542 
12543   auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12544   auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
12545   if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue())
12546     return SDValue();
12547 
12548   SDValue Op1 = LHS->getOperand(0);
12549   SDValue Op2 = RHS->getOperand(0);
12550   EVT OpVT1 = Op1.getValueType();
12551   EVT OpVT2 = Op2.getValueType();
12552   if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
12553       Op2.getOpcode() != AArch64ISD::UADDV ||
12554       OpVT1.getVectorElementType() != VT)
12555     return SDValue();
12556 
12557   SDValue Val1 = Op1.getOperand(0);
12558   SDValue Val2 = Op2.getOperand(0);
12559   EVT ValVT = Val1->getValueType(0);
12560   SDLoc DL(N);
12561   SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
12562   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
12563                      DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
12564                      DAG.getConstant(0, DL, MVT::i64));
12565 }
12566 
12567 // The basic add/sub long vector instructions have variants with "2" on the end
12568 // which act on the high-half of their inputs. They are normally matched by
12569 // patterns like:
12570 //
12571 // (add (zeroext (extract_high LHS)),
12572 //      (zeroext (extract_high RHS)))
12573 // -> uaddl2 vD, vN, vM
12574 //
12575 // However, if one of the extracts is something like a duplicate, this
12576 // instruction can still be used profitably. This function puts the DAG into a
12577 // more appropriate form for those patterns to trigger.
performAddSubLongCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12578 static SDValue performAddSubLongCombine(SDNode *N,
12579                                         TargetLowering::DAGCombinerInfo &DCI,
12580                                         SelectionDAG &DAG) {
12581   if (DCI.isBeforeLegalizeOps())
12582     return SDValue();
12583 
12584   MVT VT = N->getSimpleValueType(0);
12585   if (!VT.is128BitVector()) {
12586     if (N->getOpcode() == ISD::ADD)
12587       return performSetccAddFolding(N, DAG);
12588     return SDValue();
12589   }
12590 
12591   // Make sure both branches are extended in the same way.
12592   SDValue LHS = N->getOperand(0);
12593   SDValue RHS = N->getOperand(1);
12594   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
12595        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
12596       LHS.getOpcode() != RHS.getOpcode())
12597     return SDValue();
12598 
12599   unsigned ExtType = LHS.getOpcode();
12600 
12601   // It's not worth doing if at least one of the inputs isn't already an
12602   // extract, but we don't know which it'll be so we have to try both.
12603   if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
12604     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
12605     if (!RHS.getNode())
12606       return SDValue();
12607 
12608     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
12609   } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
12610     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
12611     if (!LHS.getNode())
12612       return SDValue();
12613 
12614     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
12615   }
12616 
12617   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
12618 }
12619 
performAddSubCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12620 static SDValue performAddSubCombine(SDNode *N,
12621                                     TargetLowering::DAGCombinerInfo &DCI,
12622                                     SelectionDAG &DAG) {
12623   // Try to change sum of two reductions.
12624   if (SDValue Val = performUADDVCombine(N, DAG))
12625     return Val;
12626 
12627   return performAddSubLongCombine(N, DCI, DAG);
12628 }
12629 
12630 // Massage DAGs which we can use the high-half "long" operations on into
12631 // something isel will recognize better. E.g.
12632 //
12633 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
12634 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
12635 //                     (extract_high (v2i64 (dup128 scalar)))))
12636 //
tryCombineLongOpWithDup(unsigned IID,SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12637 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
12638                                        TargetLowering::DAGCombinerInfo &DCI,
12639                                        SelectionDAG &DAG) {
12640   if (DCI.isBeforeLegalizeOps())
12641     return SDValue();
12642 
12643   SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
12644   SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
12645   assert(LHS.getValueType().is64BitVector() &&
12646          RHS.getValueType().is64BitVector() &&
12647          "unexpected shape for long operation");
12648 
12649   // Either node could be a DUP, but it's not worth doing both of them (you'd
12650   // just as well use the non-high version) so look for a corresponding extract
12651   // operation on the other "wing".
12652   if (isEssentiallyExtractHighSubvector(LHS)) {
12653     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
12654     if (!RHS.getNode())
12655       return SDValue();
12656   } else if (isEssentiallyExtractHighSubvector(RHS)) {
12657     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
12658     if (!LHS.getNode())
12659       return SDValue();
12660   }
12661 
12662   if (IID == Intrinsic::not_intrinsic)
12663     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
12664 
12665   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
12666                      N->getOperand(0), LHS, RHS);
12667 }
12668 
tryCombineShiftImm(unsigned IID,SDNode * N,SelectionDAG & DAG)12669 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
12670   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
12671   unsigned ElemBits = ElemTy.getSizeInBits();
12672 
12673   int64_t ShiftAmount;
12674   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
12675     APInt SplatValue, SplatUndef;
12676     unsigned SplatBitSize;
12677     bool HasAnyUndefs;
12678     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12679                               HasAnyUndefs, ElemBits) ||
12680         SplatBitSize != ElemBits)
12681       return SDValue();
12682 
12683     ShiftAmount = SplatValue.getSExtValue();
12684   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
12685     ShiftAmount = CVN->getSExtValue();
12686   } else
12687     return SDValue();
12688 
12689   unsigned Opcode;
12690   bool IsRightShift;
12691   switch (IID) {
12692   default:
12693     llvm_unreachable("Unknown shift intrinsic");
12694   case Intrinsic::aarch64_neon_sqshl:
12695     Opcode = AArch64ISD::SQSHL_I;
12696     IsRightShift = false;
12697     break;
12698   case Intrinsic::aarch64_neon_uqshl:
12699     Opcode = AArch64ISD::UQSHL_I;
12700     IsRightShift = false;
12701     break;
12702   case Intrinsic::aarch64_neon_srshl:
12703     Opcode = AArch64ISD::SRSHR_I;
12704     IsRightShift = true;
12705     break;
12706   case Intrinsic::aarch64_neon_urshl:
12707     Opcode = AArch64ISD::URSHR_I;
12708     IsRightShift = true;
12709     break;
12710   case Intrinsic::aarch64_neon_sqshlu:
12711     Opcode = AArch64ISD::SQSHLU_I;
12712     IsRightShift = false;
12713     break;
12714   case Intrinsic::aarch64_neon_sshl:
12715   case Intrinsic::aarch64_neon_ushl:
12716     // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
12717     // left shift for positive shift amounts. Below, we only replace the current
12718     // node with VSHL, if this condition is met.
12719     Opcode = AArch64ISD::VSHL;
12720     IsRightShift = false;
12721     break;
12722   }
12723 
12724   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
12725     SDLoc dl(N);
12726     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12727                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
12728   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
12729     SDLoc dl(N);
12730     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
12731                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
12732   }
12733 
12734   return SDValue();
12735 }
12736 
12737 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
12738 // the intrinsics must be legal and take an i32, this means there's almost
12739 // certainly going to be a zext in the DAG which we can eliminate.
tryCombineCRC32(unsigned Mask,SDNode * N,SelectionDAG & DAG)12740 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
12741   SDValue AndN = N->getOperand(2);
12742   if (AndN.getOpcode() != ISD::AND)
12743     return SDValue();
12744 
12745   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
12746   if (!CMask || CMask->getZExtValue() != Mask)
12747     return SDValue();
12748 
12749   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
12750                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
12751 }
12752 
combineAcrossLanesIntrinsic(unsigned Opc,SDNode * N,SelectionDAG & DAG)12753 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
12754                                            SelectionDAG &DAG) {
12755   SDLoc dl(N);
12756   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
12757                      DAG.getNode(Opc, dl,
12758                                  N->getOperand(1).getSimpleValueType(),
12759                                  N->getOperand(1)),
12760                      DAG.getConstant(0, dl, MVT::i64));
12761 }
12762 
LowerSVEIntrinsicIndex(SDNode * N,SelectionDAG & DAG)12763 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
12764   SDLoc DL(N);
12765   SDValue Op1 = N->getOperand(1);
12766   SDValue Op2 = N->getOperand(2);
12767   EVT ScalarTy = Op1.getValueType();
12768 
12769   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
12770     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
12771     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
12772   }
12773 
12774   return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
12775                      Op1, Op2);
12776 }
12777 
LowerSVEIntrinsicDUP(SDNode * N,SelectionDAG & DAG)12778 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
12779   SDLoc dl(N);
12780   SDValue Scalar = N->getOperand(3);
12781   EVT ScalarTy = Scalar.getValueType();
12782 
12783   if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
12784     Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
12785 
12786   SDValue Passthru = N->getOperand(1);
12787   SDValue Pred = N->getOperand(2);
12788   return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
12789                      Pred, Scalar, Passthru);
12790 }
12791 
LowerSVEIntrinsicEXT(SDNode * N,SelectionDAG & DAG)12792 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
12793   SDLoc dl(N);
12794   LLVMContext &Ctx = *DAG.getContext();
12795   EVT VT = N->getValueType(0);
12796 
12797   assert(VT.isScalableVector() && "Expected a scalable vector.");
12798 
12799   // Current lowering only supports the SVE-ACLE types.
12800   if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
12801     return SDValue();
12802 
12803   unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
12804   unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
12805   EVT ByteVT =
12806       EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
12807 
12808   // Convert everything to the domain of EXT (i.e bytes).
12809   SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
12810   SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
12811   SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
12812                             DAG.getConstant(ElemSize, dl, MVT::i32));
12813 
12814   SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
12815   return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
12816 }
12817 
tryConvertSVEWideCompare(SDNode * N,ISD::CondCode CC,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)12818 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
12819                                         TargetLowering::DAGCombinerInfo &DCI,
12820                                         SelectionDAG &DAG) {
12821   if (DCI.isBeforeLegalize())
12822     return SDValue();
12823 
12824   SDValue Comparator = N->getOperand(3);
12825   if (Comparator.getOpcode() == AArch64ISD::DUP ||
12826       Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
12827     unsigned IID = getIntrinsicID(N);
12828     EVT VT = N->getValueType(0);
12829     EVT CmpVT = N->getOperand(2).getValueType();
12830     SDValue Pred = N->getOperand(1);
12831     SDValue Imm;
12832     SDLoc DL(N);
12833 
12834     switch (IID) {
12835     default:
12836       llvm_unreachable("Called with wrong intrinsic!");
12837       break;
12838 
12839     // Signed comparisons
12840     case Intrinsic::aarch64_sve_cmpeq_wide:
12841     case Intrinsic::aarch64_sve_cmpne_wide:
12842     case Intrinsic::aarch64_sve_cmpge_wide:
12843     case Intrinsic::aarch64_sve_cmpgt_wide:
12844     case Intrinsic::aarch64_sve_cmplt_wide:
12845     case Intrinsic::aarch64_sve_cmple_wide: {
12846       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12847         int64_t ImmVal = CN->getSExtValue();
12848         if (ImmVal >= -16 && ImmVal <= 15)
12849           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12850         else
12851           return SDValue();
12852       }
12853       break;
12854     }
12855     // Unsigned comparisons
12856     case Intrinsic::aarch64_sve_cmphs_wide:
12857     case Intrinsic::aarch64_sve_cmphi_wide:
12858     case Intrinsic::aarch64_sve_cmplo_wide:
12859     case Intrinsic::aarch64_sve_cmpls_wide:  {
12860       if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
12861         uint64_t ImmVal = CN->getZExtValue();
12862         if (ImmVal <= 127)
12863           Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
12864         else
12865           return SDValue();
12866       }
12867       break;
12868     }
12869     }
12870 
12871     if (!Imm)
12872       return SDValue();
12873 
12874     SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
12875     return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
12876                        N->getOperand(2), Splat, DAG.getCondCode(CC));
12877   }
12878 
12879   return SDValue();
12880 }
12881 
getPTest(SelectionDAG & DAG,EVT VT,SDValue Pg,SDValue Op,AArch64CC::CondCode Cond)12882 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
12883                         AArch64CC::CondCode Cond) {
12884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12885 
12886   SDLoc DL(Op);
12887   assert(Op.getValueType().isScalableVector() &&
12888          TLI.isTypeLegal(Op.getValueType()) &&
12889          "Expected legal scalable vector type!");
12890 
12891   // Ensure target specific opcodes are using legal type.
12892   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
12893   SDValue TVal = DAG.getConstant(1, DL, OutVT);
12894   SDValue FVal = DAG.getConstant(0, DL, OutVT);
12895 
12896   // Set condition code (CC) flags.
12897   SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
12898 
12899   // Convert CC to integer based on requested condition.
12900   // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
12901   SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
12902   SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
12903   return DAG.getZExtOrTrunc(Res, DL, VT);
12904 }
12905 
combineSVEReductionInt(SDNode * N,unsigned Opc,SelectionDAG & DAG)12906 static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
12907                                       SelectionDAG &DAG) {
12908   SDLoc DL(N);
12909 
12910   SDValue Pred = N->getOperand(1);
12911   SDValue VecToReduce = N->getOperand(2);
12912 
12913   // NOTE: The integer reduction's result type is not always linked to the
12914   // operand's element type so we construct it from the intrinsic's result type.
12915   EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
12916   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12917 
12918   // SVE reductions set the whole vector register with the first element
12919   // containing the reduction result, which we'll now extract.
12920   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12921   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12922                      Zero);
12923 }
12924 
combineSVEReductionFP(SDNode * N,unsigned Opc,SelectionDAG & DAG)12925 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
12926                                      SelectionDAG &DAG) {
12927   SDLoc DL(N);
12928 
12929   SDValue Pred = N->getOperand(1);
12930   SDValue VecToReduce = N->getOperand(2);
12931 
12932   EVT ReduceVT = VecToReduce.getValueType();
12933   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
12934 
12935   // SVE reductions set the whole vector register with the first element
12936   // containing the reduction result, which we'll now extract.
12937   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12938   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12939                      Zero);
12940 }
12941 
combineSVEReductionOrderedFP(SDNode * N,unsigned Opc,SelectionDAG & DAG)12942 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
12943                                             SelectionDAG &DAG) {
12944   SDLoc DL(N);
12945 
12946   SDValue Pred = N->getOperand(1);
12947   SDValue InitVal = N->getOperand(2);
12948   SDValue VecToReduce = N->getOperand(3);
12949   EVT ReduceVT = VecToReduce.getValueType();
12950 
12951   // Ordered reductions use the first lane of the result vector as the
12952   // reduction's initial value.
12953   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
12954   InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
12955                         DAG.getUNDEF(ReduceVT), InitVal, Zero);
12956 
12957   SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
12958 
12959   // SVE reductions set the whole vector register with the first element
12960   // containing the reduction result, which we'll now extract.
12961   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
12962                      Zero);
12963 }
12964 
12965 // If a merged operation has no inactive lanes we can relax it to a predicated
12966 // or unpredicated operation, which potentially allows better isel (perhaps
12967 // using immediate forms) or relaxing register reuse requirements.
convertMergedOpToPredOp(SDNode * N,unsigned PredOpc,SelectionDAG & DAG)12968 static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
12969                                        SelectionDAG &DAG) {
12970   assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
12971   assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
12972   SDValue Pg = N->getOperand(1);
12973 
12974   // ISD way to specify an all active predicate.
12975   if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
12976       (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
12977     return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
12978                        N->getOperand(2), N->getOperand(3));
12979 
12980   // FUTURE: SplatVector(true)
12981   return SDValue();
12982 }
12983 
performIntrinsicCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,const AArch64Subtarget * Subtarget)12984 static SDValue performIntrinsicCombine(SDNode *N,
12985                                        TargetLowering::DAGCombinerInfo &DCI,
12986                                        const AArch64Subtarget *Subtarget) {
12987   SelectionDAG &DAG = DCI.DAG;
12988   unsigned IID = getIntrinsicID(N);
12989   switch (IID) {
12990   default:
12991     break;
12992   case Intrinsic::aarch64_neon_vcvtfxs2fp:
12993   case Intrinsic::aarch64_neon_vcvtfxu2fp:
12994     return tryCombineFixedPointConvert(N, DCI, DAG);
12995   case Intrinsic::aarch64_neon_saddv:
12996     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
12997   case Intrinsic::aarch64_neon_uaddv:
12998     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
12999   case Intrinsic::aarch64_neon_sminv:
13000     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
13001   case Intrinsic::aarch64_neon_uminv:
13002     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
13003   case Intrinsic::aarch64_neon_smaxv:
13004     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
13005   case Intrinsic::aarch64_neon_umaxv:
13006     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
13007   case Intrinsic::aarch64_neon_fmax:
13008     return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
13009                        N->getOperand(1), N->getOperand(2));
13010   case Intrinsic::aarch64_neon_fmin:
13011     return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
13012                        N->getOperand(1), N->getOperand(2));
13013   case Intrinsic::aarch64_neon_fmaxnm:
13014     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
13015                        N->getOperand(1), N->getOperand(2));
13016   case Intrinsic::aarch64_neon_fminnm:
13017     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
13018                        N->getOperand(1), N->getOperand(2));
13019   case Intrinsic::aarch64_neon_smull:
13020   case Intrinsic::aarch64_neon_umull:
13021   case Intrinsic::aarch64_neon_pmull:
13022   case Intrinsic::aarch64_neon_sqdmull:
13023     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
13024   case Intrinsic::aarch64_neon_sqshl:
13025   case Intrinsic::aarch64_neon_uqshl:
13026   case Intrinsic::aarch64_neon_sqshlu:
13027   case Intrinsic::aarch64_neon_srshl:
13028   case Intrinsic::aarch64_neon_urshl:
13029   case Intrinsic::aarch64_neon_sshl:
13030   case Intrinsic::aarch64_neon_ushl:
13031     return tryCombineShiftImm(IID, N, DAG);
13032   case Intrinsic::aarch64_crc32b:
13033   case Intrinsic::aarch64_crc32cb:
13034     return tryCombineCRC32(0xff, N, DAG);
13035   case Intrinsic::aarch64_crc32h:
13036   case Intrinsic::aarch64_crc32ch:
13037     return tryCombineCRC32(0xffff, N, DAG);
13038   case Intrinsic::aarch64_sve_saddv:
13039     // There is no i64 version of SADDV because the sign is irrelevant.
13040     if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
13041       return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
13042     else
13043       return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
13044   case Intrinsic::aarch64_sve_uaddv:
13045     return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
13046   case Intrinsic::aarch64_sve_smaxv:
13047     return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
13048   case Intrinsic::aarch64_sve_umaxv:
13049     return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
13050   case Intrinsic::aarch64_sve_sminv:
13051     return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
13052   case Intrinsic::aarch64_sve_uminv:
13053     return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
13054   case Intrinsic::aarch64_sve_orv:
13055     return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
13056   case Intrinsic::aarch64_sve_eorv:
13057     return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
13058   case Intrinsic::aarch64_sve_andv:
13059     return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
13060   case Intrinsic::aarch64_sve_index:
13061     return LowerSVEIntrinsicIndex(N, DAG);
13062   case Intrinsic::aarch64_sve_dup:
13063     return LowerSVEIntrinsicDUP(N, DAG);
13064   case Intrinsic::aarch64_sve_dup_x:
13065     return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
13066                        N->getOperand(1));
13067   case Intrinsic::aarch64_sve_ext:
13068     return LowerSVEIntrinsicEXT(N, DAG);
13069   case Intrinsic::aarch64_sve_smin:
13070     return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
13071   case Intrinsic::aarch64_sve_umin:
13072     return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
13073   case Intrinsic::aarch64_sve_smax:
13074     return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
13075   case Intrinsic::aarch64_sve_umax:
13076     return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
13077   case Intrinsic::aarch64_sve_lsl:
13078     return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
13079   case Intrinsic::aarch64_sve_lsr:
13080     return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
13081   case Intrinsic::aarch64_sve_asr:
13082     return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
13083   case Intrinsic::aarch64_sve_cmphs:
13084     if (!N->getOperand(2).getValueType().isFloatingPoint())
13085       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13086                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13087                          N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
13088     break;
13089   case Intrinsic::aarch64_sve_cmphi:
13090     if (!N->getOperand(2).getValueType().isFloatingPoint())
13091       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13092                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13093                          N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
13094     break;
13095   case Intrinsic::aarch64_sve_cmpge:
13096     if (!N->getOperand(2).getValueType().isFloatingPoint())
13097       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13098                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13099                          N->getOperand(3), DAG.getCondCode(ISD::SETGE));
13100     break;
13101   case Intrinsic::aarch64_sve_cmpgt:
13102     if (!N->getOperand(2).getValueType().isFloatingPoint())
13103       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13104                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13105                          N->getOperand(3), DAG.getCondCode(ISD::SETGT));
13106     break;
13107   case Intrinsic::aarch64_sve_cmpeq:
13108     if (!N->getOperand(2).getValueType().isFloatingPoint())
13109       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13110                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13111                          N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
13112     break;
13113   case Intrinsic::aarch64_sve_cmpne:
13114     if (!N->getOperand(2).getValueType().isFloatingPoint())
13115       return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
13116                          N->getValueType(0), N->getOperand(1), N->getOperand(2),
13117                          N->getOperand(3), DAG.getCondCode(ISD::SETNE));
13118     break;
13119   case Intrinsic::aarch64_sve_fadda:
13120     return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
13121   case Intrinsic::aarch64_sve_faddv:
13122     return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
13123   case Intrinsic::aarch64_sve_fmaxnmv:
13124     return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
13125   case Intrinsic::aarch64_sve_fmaxv:
13126     return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
13127   case Intrinsic::aarch64_sve_fminnmv:
13128     return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
13129   case Intrinsic::aarch64_sve_fminv:
13130     return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
13131   case Intrinsic::aarch64_sve_sel:
13132     return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
13133                        N->getOperand(1), N->getOperand(2), N->getOperand(3));
13134   case Intrinsic::aarch64_sve_cmpeq_wide:
13135     return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
13136   case Intrinsic::aarch64_sve_cmpne_wide:
13137     return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
13138   case Intrinsic::aarch64_sve_cmpge_wide:
13139     return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
13140   case Intrinsic::aarch64_sve_cmpgt_wide:
13141     return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
13142   case Intrinsic::aarch64_sve_cmplt_wide:
13143     return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
13144   case Intrinsic::aarch64_sve_cmple_wide:
13145     return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
13146   case Intrinsic::aarch64_sve_cmphs_wide:
13147     return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
13148   case Intrinsic::aarch64_sve_cmphi_wide:
13149     return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
13150   case Intrinsic::aarch64_sve_cmplo_wide:
13151     return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
13152   case Intrinsic::aarch64_sve_cmpls_wide:
13153     return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
13154   case Intrinsic::aarch64_sve_ptest_any:
13155     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13156                     AArch64CC::ANY_ACTIVE);
13157   case Intrinsic::aarch64_sve_ptest_first:
13158     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13159                     AArch64CC::FIRST_ACTIVE);
13160   case Intrinsic::aarch64_sve_ptest_last:
13161     return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
13162                     AArch64CC::LAST_ACTIVE);
13163   }
13164   return SDValue();
13165 }
13166 
performExtendCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13167 static SDValue performExtendCombine(SDNode *N,
13168                                     TargetLowering::DAGCombinerInfo &DCI,
13169                                     SelectionDAG &DAG) {
13170   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
13171   // we can convert that DUP into another extract_high (of a bigger DUP), which
13172   // helps the backend to decide that an sabdl2 would be useful, saving a real
13173   // extract_high operation.
13174   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
13175       (N->getOperand(0).getOpcode() == AArch64ISD::UABD ||
13176        N->getOperand(0).getOpcode() == AArch64ISD::SABD)) {
13177     SDNode *ABDNode = N->getOperand(0).getNode();
13178     SDValue NewABD =
13179         tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
13180     if (!NewABD.getNode())
13181       return SDValue();
13182 
13183     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
13184   }
13185 
13186   // This is effectively a custom type legalization for AArch64.
13187   //
13188   // Type legalization will split an extend of a small, legal, type to a larger
13189   // illegal type by first splitting the destination type, often creating
13190   // illegal source types, which then get legalized in isel-confusing ways,
13191   // leading to really terrible codegen. E.g.,
13192   //   %result = v8i32 sext v8i8 %value
13193   // becomes
13194   //   %losrc = extract_subreg %value, ...
13195   //   %hisrc = extract_subreg %value, ...
13196   //   %lo = v4i32 sext v4i8 %losrc
13197   //   %hi = v4i32 sext v4i8 %hisrc
13198   // Things go rapidly downhill from there.
13199   //
13200   // For AArch64, the [sz]ext vector instructions can only go up one element
13201   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
13202   // take two instructions.
13203   //
13204   // This implies that the most efficient way to do the extend from v8i8
13205   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
13206   // the normal splitting to happen for the v8i16->v8i32.
13207 
13208   // This is pre-legalization to catch some cases where the default
13209   // type legalization will create ill-tempered code.
13210   if (!DCI.isBeforeLegalizeOps())
13211     return SDValue();
13212 
13213   // We're only interested in cleaning things up for non-legal vector types
13214   // here. If both the source and destination are legal, things will just
13215   // work naturally without any fiddling.
13216   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13217   EVT ResVT = N->getValueType(0);
13218   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
13219     return SDValue();
13220   // If the vector type isn't a simple VT, it's beyond the scope of what
13221   // we're  worried about here. Let legalization do its thing and hope for
13222   // the best.
13223   SDValue Src = N->getOperand(0);
13224   EVT SrcVT = Src->getValueType(0);
13225   if (!ResVT.isSimple() || !SrcVT.isSimple())
13226     return SDValue();
13227 
13228   // If the source VT is a 64-bit fixed or scalable vector, we can play games
13229   // and get the better results we want.
13230   if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
13231     return SDValue();
13232 
13233   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
13234   ElementCount SrcEC = SrcVT.getVectorElementCount();
13235   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
13236   SDLoc DL(N);
13237   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
13238 
13239   // Now split the rest of the operation into two halves, each with a 64
13240   // bit source.
13241   EVT LoVT, HiVT;
13242   SDValue Lo, Hi;
13243   LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
13244 
13245   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
13246                                LoVT.getVectorElementCount());
13247   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13248                    DAG.getConstant(0, DL, MVT::i64));
13249   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
13250                    DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
13251   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
13252   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
13253 
13254   // Now combine the parts back together so we still have a single result
13255   // like the combiner expects.
13256   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
13257 }
13258 
splitStoreSplat(SelectionDAG & DAG,StoreSDNode & St,SDValue SplatVal,unsigned NumVecElts)13259 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
13260                                SDValue SplatVal, unsigned NumVecElts) {
13261   assert(!St.isTruncatingStore() && "cannot split truncating vector store");
13262   unsigned OrigAlignment = St.getAlignment();
13263   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
13264 
13265   // Create scalar stores. This is at least as good as the code sequence for a
13266   // split unaligned store which is a dup.s, ext.b, and two stores.
13267   // Most of the time the three stores should be replaced by store pair
13268   // instructions (stp).
13269   SDLoc DL(&St);
13270   SDValue BasePtr = St.getBasePtr();
13271   uint64_t BaseOffset = 0;
13272 
13273   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
13274   SDValue NewST1 =
13275       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
13276                    OrigAlignment, St.getMemOperand()->getFlags());
13277 
13278   // As this in ISel, we will not merge this add which may degrade results.
13279   if (BasePtr->getOpcode() == ISD::ADD &&
13280       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
13281     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
13282     BasePtr = BasePtr->getOperand(0);
13283   }
13284 
13285   unsigned Offset = EltOffset;
13286   while (--NumVecElts) {
13287     unsigned Alignment = MinAlign(OrigAlignment, Offset);
13288     SDValue OffsetPtr =
13289         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13290                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
13291     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
13292                           PtrInfo.getWithOffset(Offset), Alignment,
13293                           St.getMemOperand()->getFlags());
13294     Offset += EltOffset;
13295   }
13296   return NewST1;
13297 }
13298 
13299 // Returns an SVE type that ContentTy can be trivially sign or zero extended
13300 // into.
getSVEContainerType(EVT ContentTy)13301 static MVT getSVEContainerType(EVT ContentTy) {
13302   assert(ContentTy.isSimple() && "No SVE containers for extended types");
13303 
13304   switch (ContentTy.getSimpleVT().SimpleTy) {
13305   default:
13306     llvm_unreachable("No known SVE container for this MVT type");
13307   case MVT::nxv2i8:
13308   case MVT::nxv2i16:
13309   case MVT::nxv2i32:
13310   case MVT::nxv2i64:
13311   case MVT::nxv2f32:
13312   case MVT::nxv2f64:
13313     return MVT::nxv2i64;
13314   case MVT::nxv4i8:
13315   case MVT::nxv4i16:
13316   case MVT::nxv4i32:
13317   case MVT::nxv4f32:
13318     return MVT::nxv4i32;
13319   case MVT::nxv8i8:
13320   case MVT::nxv8i16:
13321   case MVT::nxv8f16:
13322   case MVT::nxv8bf16:
13323     return MVT::nxv8i16;
13324   case MVT::nxv16i8:
13325     return MVT::nxv16i8;
13326   }
13327 }
13328 
performLD1Combine(SDNode * N,SelectionDAG & DAG,unsigned Opc)13329 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
13330   SDLoc DL(N);
13331   EVT VT = N->getValueType(0);
13332 
13333   if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13334     return SDValue();
13335 
13336   EVT ContainerVT = VT;
13337   if (ContainerVT.isInteger())
13338     ContainerVT = getSVEContainerType(ContainerVT);
13339 
13340   SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
13341   SDValue Ops[] = { N->getOperand(0), // Chain
13342                     N->getOperand(2), // Pg
13343                     N->getOperand(3), // Base
13344                     DAG.getValueType(VT) };
13345 
13346   SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
13347   SDValue LoadChain = SDValue(Load.getNode(), 1);
13348 
13349   if (ContainerVT.isInteger() && (VT != ContainerVT))
13350     Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
13351 
13352   return DAG.getMergeValues({ Load, LoadChain }, DL);
13353 }
13354 
performLDNT1Combine(SDNode * N,SelectionDAG & DAG)13355 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
13356   SDLoc DL(N);
13357   EVT VT = N->getValueType(0);
13358   EVT PtrTy = N->getOperand(3).getValueType();
13359 
13360   if (VT == MVT::nxv8bf16 &&
13361       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13362     return SDValue();
13363 
13364   EVT LoadVT = VT;
13365   if (VT.isFloatingPoint())
13366     LoadVT = VT.changeTypeToInteger();
13367 
13368   auto *MINode = cast<MemIntrinsicSDNode>(N);
13369   SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
13370   SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
13371                                 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
13372                                 MINode->getOperand(2), PassThru,
13373                                 MINode->getMemoryVT(), MINode->getMemOperand(),
13374                                 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
13375 
13376    if (VT.isFloatingPoint()) {
13377      SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
13378      return DAG.getMergeValues(Ops, DL);
13379    }
13380 
13381   return L;
13382 }
13383 
13384 template <unsigned Opcode>
performLD1ReplicateCombine(SDNode * N,SelectionDAG & DAG)13385 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
13386   static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
13387                     Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
13388                 "Unsupported opcode.");
13389   SDLoc DL(N);
13390   EVT VT = N->getValueType(0);
13391   if (VT == MVT::nxv8bf16 &&
13392       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13393     return SDValue();
13394 
13395   EVT LoadVT = VT;
13396   if (VT.isFloatingPoint())
13397     LoadVT = VT.changeTypeToInteger();
13398 
13399   SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
13400   SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
13401   SDValue LoadChain = SDValue(Load.getNode(), 1);
13402 
13403   if (VT.isFloatingPoint())
13404     Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
13405 
13406   return DAG.getMergeValues({Load, LoadChain}, DL);
13407 }
13408 
performST1Combine(SDNode * N,SelectionDAG & DAG)13409 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
13410   SDLoc DL(N);
13411   SDValue Data = N->getOperand(2);
13412   EVT DataVT = Data.getValueType();
13413   EVT HwSrcVt = getSVEContainerType(DataVT);
13414   SDValue InputVT = DAG.getValueType(DataVT);
13415 
13416   if (DataVT == MVT::nxv8bf16 &&
13417       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13418     return SDValue();
13419 
13420   if (DataVT.isFloatingPoint())
13421     InputVT = DAG.getValueType(HwSrcVt);
13422 
13423   SDValue SrcNew;
13424   if (Data.getValueType().isFloatingPoint())
13425     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
13426   else
13427     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
13428 
13429   SDValue Ops[] = { N->getOperand(0), // Chain
13430                     SrcNew,
13431                     N->getOperand(4), // Base
13432                     N->getOperand(3), // Pg
13433                     InputVT
13434                   };
13435 
13436   return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
13437 }
13438 
performSTNT1Combine(SDNode * N,SelectionDAG & DAG)13439 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
13440   SDLoc DL(N);
13441 
13442   SDValue Data = N->getOperand(2);
13443   EVT DataVT = Data.getValueType();
13444   EVT PtrTy = N->getOperand(4).getValueType();
13445 
13446   if (DataVT == MVT::nxv8bf16 &&
13447       !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
13448     return SDValue();
13449 
13450   if (DataVT.isFloatingPoint())
13451     Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
13452 
13453   auto *MINode = cast<MemIntrinsicSDNode>(N);
13454   return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
13455                             DAG.getUNDEF(PtrTy), MINode->getOperand(3),
13456                             MINode->getMemoryVT(), MINode->getMemOperand(),
13457                             ISD::UNINDEXED, false, false);
13458 }
13459 
13460 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
13461 /// load store optimizer pass will merge them to store pair stores.  This should
13462 /// be better than a movi to create the vector zero followed by a vector store
13463 /// if the zero constant is not re-used, since one instructions and one register
13464 /// live range will be removed.
13465 ///
13466 /// For example, the final generated code should be:
13467 ///
13468 ///   stp xzr, xzr, [x0]
13469 ///
13470 /// instead of:
13471 ///
13472 ///   movi v0.2d, #0
13473 ///   str q0, [x0]
13474 ///
replaceZeroVectorStore(SelectionDAG & DAG,StoreSDNode & St)13475 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13476   SDValue StVal = St.getValue();
13477   EVT VT = StVal.getValueType();
13478 
13479   // Avoid scalarizing zero splat stores for scalable vectors.
13480   if (VT.isScalableVector())
13481     return SDValue();
13482 
13483   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
13484   // 2, 3 or 4 i32 elements.
13485   int NumVecElts = VT.getVectorNumElements();
13486   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
13487          VT.getVectorElementType().getSizeInBits() == 64) ||
13488         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
13489          VT.getVectorElementType().getSizeInBits() == 32)))
13490     return SDValue();
13491 
13492   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
13493     return SDValue();
13494 
13495   // If the zero constant has more than one use then the vector store could be
13496   // better since the constant mov will be amortized and stp q instructions
13497   // should be able to be formed.
13498   if (!StVal.hasOneUse())
13499     return SDValue();
13500 
13501   // If the store is truncating then it's going down to i16 or smaller, which
13502   // means it can be implemented in a single store anyway.
13503   if (St.isTruncatingStore())
13504     return SDValue();
13505 
13506   // If the immediate offset of the address operand is too large for the stp
13507   // instruction, then bail out.
13508   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
13509     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
13510     if (Offset < -512 || Offset > 504)
13511       return SDValue();
13512   }
13513 
13514   for (int I = 0; I < NumVecElts; ++I) {
13515     SDValue EltVal = StVal.getOperand(I);
13516     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
13517       return SDValue();
13518   }
13519 
13520   // Use a CopyFromReg WZR/XZR here to prevent
13521   // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
13522   SDLoc DL(&St);
13523   unsigned ZeroReg;
13524   EVT ZeroVT;
13525   if (VT.getVectorElementType().getSizeInBits() == 32) {
13526     ZeroReg = AArch64::WZR;
13527     ZeroVT = MVT::i32;
13528   } else {
13529     ZeroReg = AArch64::XZR;
13530     ZeroVT = MVT::i64;
13531   }
13532   SDValue SplatVal =
13533       DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
13534   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13535 }
13536 
13537 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
13538 /// value. The load store optimizer pass will merge them to store pair stores.
13539 /// This has better performance than a splat of the scalar followed by a split
13540 /// vector store. Even if the stores are not merged it is four stores vs a dup,
13541 /// followed by an ext.b and two stores.
replaceSplatVectorStore(SelectionDAG & DAG,StoreSDNode & St)13542 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
13543   SDValue StVal = St.getValue();
13544   EVT VT = StVal.getValueType();
13545 
13546   // Don't replace floating point stores, they possibly won't be transformed to
13547   // stp because of the store pair suppress pass.
13548   if (VT.isFloatingPoint())
13549     return SDValue();
13550 
13551   // We can express a splat as store pair(s) for 2 or 4 elements.
13552   unsigned NumVecElts = VT.getVectorNumElements();
13553   if (NumVecElts != 4 && NumVecElts != 2)
13554     return SDValue();
13555 
13556   // If the store is truncating then it's going down to i16 or smaller, which
13557   // means it can be implemented in a single store anyway.
13558   if (St.isTruncatingStore())
13559     return SDValue();
13560 
13561   // Check that this is a splat.
13562   // Make sure that each of the relevant vector element locations are inserted
13563   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
13564   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
13565   SDValue SplatVal;
13566   for (unsigned I = 0; I < NumVecElts; ++I) {
13567     // Check for insert vector elements.
13568     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
13569       return SDValue();
13570 
13571     // Check that same value is inserted at each vector element.
13572     if (I == 0)
13573       SplatVal = StVal.getOperand(1);
13574     else if (StVal.getOperand(1) != SplatVal)
13575       return SDValue();
13576 
13577     // Check insert element index.
13578     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
13579     if (!CIndex)
13580       return SDValue();
13581     uint64_t IndexVal = CIndex->getZExtValue();
13582     if (IndexVal >= NumVecElts)
13583       return SDValue();
13584     IndexNotInserted.reset(IndexVal);
13585 
13586     StVal = StVal.getOperand(0);
13587   }
13588   // Check that all vector element locations were inserted to.
13589   if (IndexNotInserted.any())
13590       return SDValue();
13591 
13592   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
13593 }
13594 
splitStores(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)13595 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13596                            SelectionDAG &DAG,
13597                            const AArch64Subtarget *Subtarget) {
13598 
13599   StoreSDNode *S = cast<StoreSDNode>(N);
13600   if (S->isVolatile() || S->isIndexed())
13601     return SDValue();
13602 
13603   SDValue StVal = S->getValue();
13604   EVT VT = StVal.getValueType();
13605 
13606   if (!VT.isFixedLengthVector())
13607     return SDValue();
13608 
13609   // If we get a splat of zeros, convert this vector store to a store of
13610   // scalars. They will be merged into store pairs of xzr thereby removing one
13611   // instruction and one register.
13612   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
13613     return ReplacedZeroSplat;
13614 
13615   // FIXME: The logic for deciding if an unaligned store should be split should
13616   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
13617   // a call to that function here.
13618 
13619   if (!Subtarget->isMisaligned128StoreSlow())
13620     return SDValue();
13621 
13622   // Don't split at -Oz.
13623   if (DAG.getMachineFunction().getFunction().hasMinSize())
13624     return SDValue();
13625 
13626   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
13627   // those up regresses performance on micro-benchmarks and olden/bh.
13628   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
13629     return SDValue();
13630 
13631   // Split unaligned 16B stores. They are terrible for performance.
13632   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
13633   // extensions can use this to mark that it does not want splitting to happen
13634   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
13635   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
13636   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
13637       S->getAlignment() <= 2)
13638     return SDValue();
13639 
13640   // If we get a splat of a scalar convert this vector store to a store of
13641   // scalars. They will be merged into store pairs thereby removing two
13642   // instructions.
13643   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
13644     return ReplacedSplat;
13645 
13646   SDLoc DL(S);
13647 
13648   // Split VT into two.
13649   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
13650   unsigned NumElts = HalfVT.getVectorNumElements();
13651   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13652                                    DAG.getConstant(0, DL, MVT::i64));
13653   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
13654                                    DAG.getConstant(NumElts, DL, MVT::i64));
13655   SDValue BasePtr = S->getBasePtr();
13656   SDValue NewST1 =
13657       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
13658                    S->getAlignment(), S->getMemOperand()->getFlags());
13659   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
13660                                   DAG.getConstant(8, DL, MVT::i64));
13661   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
13662                       S->getPointerInfo(), S->getAlignment(),
13663                       S->getMemOperand()->getFlags());
13664 }
13665 
performUzpCombine(SDNode * N,SelectionDAG & DAG)13666 static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
13667   SDLoc DL(N);
13668   SDValue Op0 = N->getOperand(0);
13669   SDValue Op1 = N->getOperand(1);
13670   EVT ResVT = N->getValueType(0);
13671 
13672   // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
13673   if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
13674     if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13675       SDValue X = Op0.getOperand(0).getOperand(0);
13676       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
13677     }
13678   }
13679 
13680   // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
13681   if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
13682     if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
13683       SDValue Z = Op1.getOperand(0).getOperand(1);
13684       return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
13685     }
13686   }
13687 
13688   return SDValue();
13689 }
13690 
13691 /// Target-specific DAG combine function for post-increment LD1 (lane) and
13692 /// post-increment LD1R.
performPostLD1Combine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,bool IsLaneOp)13693 static SDValue performPostLD1Combine(SDNode *N,
13694                                      TargetLowering::DAGCombinerInfo &DCI,
13695                                      bool IsLaneOp) {
13696   if (DCI.isBeforeLegalizeOps())
13697     return SDValue();
13698 
13699   SelectionDAG &DAG = DCI.DAG;
13700   EVT VT = N->getValueType(0);
13701 
13702   if (VT.isScalableVector())
13703     return SDValue();
13704 
13705   unsigned LoadIdx = IsLaneOp ? 1 : 0;
13706   SDNode *LD = N->getOperand(LoadIdx).getNode();
13707   // If it is not LOAD, can not do such combine.
13708   if (LD->getOpcode() != ISD::LOAD)
13709     return SDValue();
13710 
13711   // The vector lane must be a constant in the LD1LANE opcode.
13712   SDValue Lane;
13713   if (IsLaneOp) {
13714     Lane = N->getOperand(2);
13715     auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
13716     if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
13717       return SDValue();
13718   }
13719 
13720   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
13721   EVT MemVT = LoadSDN->getMemoryVT();
13722   // Check if memory operand is the same type as the vector element.
13723   if (MemVT != VT.getVectorElementType())
13724     return SDValue();
13725 
13726   // Check if there are other uses. If so, do not combine as it will introduce
13727   // an extra load.
13728   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
13729        ++UI) {
13730     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
13731       continue;
13732     if (*UI != N)
13733       return SDValue();
13734   }
13735 
13736   SDValue Addr = LD->getOperand(1);
13737   SDValue Vector = N->getOperand(0);
13738   // Search for a use of the address operand that is an increment.
13739   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
13740        Addr.getNode()->use_end(); UI != UE; ++UI) {
13741     SDNode *User = *UI;
13742     if (User->getOpcode() != ISD::ADD
13743         || UI.getUse().getResNo() != Addr.getResNo())
13744       continue;
13745 
13746     // If the increment is a constant, it must match the memory ref size.
13747     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13748     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13749       uint32_t IncVal = CInc->getZExtValue();
13750       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
13751       if (IncVal != NumBytes)
13752         continue;
13753       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13754     }
13755 
13756     // To avoid cycle construction make sure that neither the load nor the add
13757     // are predecessors to each other or the Vector.
13758     SmallPtrSet<const SDNode *, 32> Visited;
13759     SmallVector<const SDNode *, 16> Worklist;
13760     Visited.insert(Addr.getNode());
13761     Worklist.push_back(User);
13762     Worklist.push_back(LD);
13763     Worklist.push_back(Vector.getNode());
13764     if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
13765         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13766       continue;
13767 
13768     SmallVector<SDValue, 8> Ops;
13769     Ops.push_back(LD->getOperand(0));  // Chain
13770     if (IsLaneOp) {
13771       Ops.push_back(Vector);           // The vector to be inserted
13772       Ops.push_back(Lane);             // The lane to be inserted in the vector
13773     }
13774     Ops.push_back(Addr);
13775     Ops.push_back(Inc);
13776 
13777     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
13778     SDVTList SDTys = DAG.getVTList(Tys);
13779     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
13780     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
13781                                            MemVT,
13782                                            LoadSDN->getMemOperand());
13783 
13784     // Update the uses.
13785     SDValue NewResults[] = {
13786         SDValue(LD, 0),            // The result of load
13787         SDValue(UpdN.getNode(), 2) // Chain
13788     };
13789     DCI.CombineTo(LD, NewResults);
13790     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
13791     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
13792 
13793     break;
13794   }
13795   return SDValue();
13796 }
13797 
13798 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
13799 /// address translation.
performTBISimplification(SDValue Addr,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13800 static bool performTBISimplification(SDValue Addr,
13801                                      TargetLowering::DAGCombinerInfo &DCI,
13802                                      SelectionDAG &DAG) {
13803   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
13804   KnownBits Known;
13805   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13806                                         !DCI.isBeforeLegalizeOps());
13807   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13808   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
13809     DCI.CommitTargetLoweringOpt(TLO);
13810     return true;
13811   }
13812   return false;
13813 }
13814 
performSTORECombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)13815 static SDValue performSTORECombine(SDNode *N,
13816                                    TargetLowering::DAGCombinerInfo &DCI,
13817                                    SelectionDAG &DAG,
13818                                    const AArch64Subtarget *Subtarget) {
13819   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
13820     return Split;
13821 
13822   if (Subtarget->supportsAddressTopByteIgnored() &&
13823       performTBISimplification(N->getOperand(2), DCI, DAG))
13824     return SDValue(N, 0);
13825 
13826   return SDValue();
13827 }
13828 
13829 
13830 /// Target-specific DAG combine function for NEON load/store intrinsics
13831 /// to merge base address updates.
performNEONPostLDSTCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)13832 static SDValue performNEONPostLDSTCombine(SDNode *N,
13833                                           TargetLowering::DAGCombinerInfo &DCI,
13834                                           SelectionDAG &DAG) {
13835   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13836     return SDValue();
13837 
13838   unsigned AddrOpIdx = N->getNumOperands() - 1;
13839   SDValue Addr = N->getOperand(AddrOpIdx);
13840 
13841   // Search for a use of the address operand that is an increment.
13842   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13843        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13844     SDNode *User = *UI;
13845     if (User->getOpcode() != ISD::ADD ||
13846         UI.getUse().getResNo() != Addr.getResNo())
13847       continue;
13848 
13849     // Check that the add is independent of the load/store.  Otherwise, folding
13850     // it would create a cycle.
13851     SmallPtrSet<const SDNode *, 32> Visited;
13852     SmallVector<const SDNode *, 16> Worklist;
13853     Visited.insert(Addr.getNode());
13854     Worklist.push_back(N);
13855     Worklist.push_back(User);
13856     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13857         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13858       continue;
13859 
13860     // Find the new opcode for the updating load/store.
13861     bool IsStore = false;
13862     bool IsLaneOp = false;
13863     bool IsDupOp = false;
13864     unsigned NewOpc = 0;
13865     unsigned NumVecs = 0;
13866     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13867     switch (IntNo) {
13868     default: llvm_unreachable("unexpected intrinsic for Neon base update");
13869     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
13870       NumVecs = 2; break;
13871     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
13872       NumVecs = 3; break;
13873     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
13874       NumVecs = 4; break;
13875     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
13876       NumVecs = 2; IsStore = true; break;
13877     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
13878       NumVecs = 3; IsStore = true; break;
13879     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
13880       NumVecs = 4; IsStore = true; break;
13881     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
13882       NumVecs = 2; break;
13883     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
13884       NumVecs = 3; break;
13885     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
13886       NumVecs = 4; break;
13887     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
13888       NumVecs = 2; IsStore = true; break;
13889     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
13890       NumVecs = 3; IsStore = true; break;
13891     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
13892       NumVecs = 4; IsStore = true; break;
13893     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
13894       NumVecs = 2; IsDupOp = true; break;
13895     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
13896       NumVecs = 3; IsDupOp = true; break;
13897     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
13898       NumVecs = 4; IsDupOp = true; break;
13899     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
13900       NumVecs = 2; IsLaneOp = true; break;
13901     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
13902       NumVecs = 3; IsLaneOp = true; break;
13903     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
13904       NumVecs = 4; IsLaneOp = true; break;
13905     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
13906       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
13907     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
13908       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
13909     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
13910       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
13911     }
13912 
13913     EVT VecTy;
13914     if (IsStore)
13915       VecTy = N->getOperand(2).getValueType();
13916     else
13917       VecTy = N->getValueType(0);
13918 
13919     // If the increment is a constant, it must match the memory ref size.
13920     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13921     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
13922       uint32_t IncVal = CInc->getZExtValue();
13923       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13924       if (IsLaneOp || IsDupOp)
13925         NumBytes /= VecTy.getVectorNumElements();
13926       if (IncVal != NumBytes)
13927         continue;
13928       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
13929     }
13930     SmallVector<SDValue, 8> Ops;
13931     Ops.push_back(N->getOperand(0)); // Incoming chain
13932     // Load lane and store have vector list as input.
13933     if (IsLaneOp || IsStore)
13934       for (unsigned i = 2; i < AddrOpIdx; ++i)
13935         Ops.push_back(N->getOperand(i));
13936     Ops.push_back(Addr); // Base register
13937     Ops.push_back(Inc);
13938 
13939     // Return Types.
13940     EVT Tys[6];
13941     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
13942     unsigned n;
13943     for (n = 0; n < NumResultVecs; ++n)
13944       Tys[n] = VecTy;
13945     Tys[n++] = MVT::i64;  // Type of write back register
13946     Tys[n] = MVT::Other;  // Type of the chain
13947     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13948 
13949     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
13950     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
13951                                            MemInt->getMemoryVT(),
13952                                            MemInt->getMemOperand());
13953 
13954     // Update the uses.
13955     std::vector<SDValue> NewResults;
13956     for (unsigned i = 0; i < NumResultVecs; ++i) {
13957       NewResults.push_back(SDValue(UpdN.getNode(), i));
13958     }
13959     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
13960     DCI.CombineTo(N, NewResults);
13961     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13962 
13963     break;
13964   }
13965   return SDValue();
13966 }
13967 
13968 // Checks to see if the value is the prescribed width and returns information
13969 // about its extension mode.
13970 static
checkValueWidth(SDValue V,unsigned width,ISD::LoadExtType & ExtType)13971 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
13972   ExtType = ISD::NON_EXTLOAD;
13973   switch(V.getNode()->getOpcode()) {
13974   default:
13975     return false;
13976   case ISD::LOAD: {
13977     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
13978     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
13979        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
13980       ExtType = LoadNode->getExtensionType();
13981       return true;
13982     }
13983     return false;
13984   }
13985   case ISD::AssertSext: {
13986     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13987     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13988        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13989       ExtType = ISD::SEXTLOAD;
13990       return true;
13991     }
13992     return false;
13993   }
13994   case ISD::AssertZext: {
13995     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
13996     if ((TypeNode->getVT() == MVT::i8 && width == 8)
13997        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
13998       ExtType = ISD::ZEXTLOAD;
13999       return true;
14000     }
14001     return false;
14002   }
14003   case ISD::Constant:
14004   case ISD::TargetConstant: {
14005     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
14006            1LL << (width - 1);
14007   }
14008   }
14009 
14010   return true;
14011 }
14012 
14013 // This function does a whole lot of voodoo to determine if the tests are
14014 // equivalent without and with a mask. Essentially what happens is that given a
14015 // DAG resembling:
14016 //
14017 //  +-------------+ +-------------+ +-------------+ +-------------+
14018 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
14019 //  +-------------+ +-------------+ +-------------+ +-------------+
14020 //           |           |           |               |
14021 //           V           V           |    +----------+
14022 //          +-------------+  +----+  |    |
14023 //          |     ADD     |  |0xff|  |    |
14024 //          +-------------+  +----+  |    |
14025 //                  |           |    |    |
14026 //                  V           V    |    |
14027 //                 +-------------+   |    |
14028 //                 |     AND     |   |    |
14029 //                 +-------------+   |    |
14030 //                      |            |    |
14031 //                      +-----+      |    |
14032 //                            |      |    |
14033 //                            V      V    V
14034 //                           +-------------+
14035 //                           |     CMP     |
14036 //                           +-------------+
14037 //
14038 // The AND node may be safely removed for some combinations of inputs. In
14039 // particular we need to take into account the extension type of the Input,
14040 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
14041 // width of the input (this can work for any width inputs, the above graph is
14042 // specific to 8 bits.
14043 //
14044 // The specific equations were worked out by generating output tables for each
14045 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
14046 // problem was simplified by working with 4 bit inputs, which means we only
14047 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
14048 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
14049 // patterns present in both extensions (0,7). For every distinct set of
14050 // AddConstant and CompConstants bit patterns we can consider the masked and
14051 // unmasked versions to be equivalent if the result of this function is true for
14052 // all 16 distinct bit patterns of for the current extension type of Input (w0).
14053 //
14054 //   sub      w8, w0, w1
14055 //   and      w10, w8, #0x0f
14056 //   cmp      w8, w2
14057 //   cset     w9, AArch64CC
14058 //   cmp      w10, w2
14059 //   cset     w11, AArch64CC
14060 //   cmp      w9, w11
14061 //   cset     w0, eq
14062 //   ret
14063 //
14064 // Since the above function shows when the outputs are equivalent it defines
14065 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
14066 // would be expensive to run during compiles. The equations below were written
14067 // in a test harness that confirmed they gave equivalent outputs to the above
14068 // for all inputs function, so they can be used determine if the removal is
14069 // legal instead.
14070 //
14071 // isEquivalentMaskless() is the code for testing if the AND can be removed
14072 // factored out of the DAG recognition as the DAG can take several forms.
14073 
isEquivalentMaskless(unsigned CC,unsigned width,ISD::LoadExtType ExtType,int AddConstant,int CompConstant)14074 static bool isEquivalentMaskless(unsigned CC, unsigned width,
14075                                  ISD::LoadExtType ExtType, int AddConstant,
14076                                  int CompConstant) {
14077   // By being careful about our equations and only writing the in term
14078   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
14079   // make them generally applicable to all bit widths.
14080   int MaxUInt = (1 << width);
14081 
14082   // For the purposes of these comparisons sign extending the type is
14083   // equivalent to zero extending the add and displacing it by half the integer
14084   // width. Provided we are careful and make sure our equations are valid over
14085   // the whole range we can just adjust the input and avoid writing equations
14086   // for sign extended inputs.
14087   if (ExtType == ISD::SEXTLOAD)
14088     AddConstant -= (1 << (width-1));
14089 
14090   switch(CC) {
14091   case AArch64CC::LE:
14092   case AArch64CC::GT:
14093     if ((AddConstant == 0) ||
14094         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
14095         (AddConstant >= 0 && CompConstant < 0) ||
14096         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
14097       return true;
14098     break;
14099   case AArch64CC::LT:
14100   case AArch64CC::GE:
14101     if ((AddConstant == 0) ||
14102         (AddConstant >= 0 && CompConstant <= 0) ||
14103         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
14104       return true;
14105     break;
14106   case AArch64CC::HI:
14107   case AArch64CC::LS:
14108     if ((AddConstant >= 0 && CompConstant < 0) ||
14109        (AddConstant <= 0 && CompConstant >= -1 &&
14110         CompConstant < AddConstant + MaxUInt))
14111       return true;
14112    break;
14113   case AArch64CC::PL:
14114   case AArch64CC::MI:
14115     if ((AddConstant == 0) ||
14116         (AddConstant > 0 && CompConstant <= 0) ||
14117         (AddConstant < 0 && CompConstant <= AddConstant))
14118       return true;
14119     break;
14120   case AArch64CC::LO:
14121   case AArch64CC::HS:
14122     if ((AddConstant >= 0 && CompConstant <= 0) ||
14123         (AddConstant <= 0 && CompConstant >= 0 &&
14124          CompConstant <= AddConstant + MaxUInt))
14125       return true;
14126     break;
14127   case AArch64CC::EQ:
14128   case AArch64CC::NE:
14129     if ((AddConstant > 0 && CompConstant < 0) ||
14130         (AddConstant < 0 && CompConstant >= 0 &&
14131          CompConstant < AddConstant + MaxUInt) ||
14132         (AddConstant >= 0 && CompConstant >= 0 &&
14133          CompConstant >= AddConstant) ||
14134         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
14135       return true;
14136     break;
14137   case AArch64CC::VS:
14138   case AArch64CC::VC:
14139   case AArch64CC::AL:
14140   case AArch64CC::NV:
14141     return true;
14142   case AArch64CC::Invalid:
14143     break;
14144   }
14145 
14146   return false;
14147 }
14148 
14149 static
performCONDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG,unsigned CCIndex,unsigned CmpIndex)14150 SDValue performCONDCombine(SDNode *N,
14151                            TargetLowering::DAGCombinerInfo &DCI,
14152                            SelectionDAG &DAG, unsigned CCIndex,
14153                            unsigned CmpIndex) {
14154   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
14155   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
14156   unsigned CondOpcode = SubsNode->getOpcode();
14157 
14158   if (CondOpcode != AArch64ISD::SUBS)
14159     return SDValue();
14160 
14161   // There is a SUBS feeding this condition. Is it fed by a mask we can
14162   // use?
14163 
14164   SDNode *AndNode = SubsNode->getOperand(0).getNode();
14165   unsigned MaskBits = 0;
14166 
14167   if (AndNode->getOpcode() != ISD::AND)
14168     return SDValue();
14169 
14170   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
14171     uint32_t CNV = CN->getZExtValue();
14172     if (CNV == 255)
14173       MaskBits = 8;
14174     else if (CNV == 65535)
14175       MaskBits = 16;
14176   }
14177 
14178   if (!MaskBits)
14179     return SDValue();
14180 
14181   SDValue AddValue = AndNode->getOperand(0);
14182 
14183   if (AddValue.getOpcode() != ISD::ADD)
14184     return SDValue();
14185 
14186   // The basic dag structure is correct, grab the inputs and validate them.
14187 
14188   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
14189   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
14190   SDValue SubsInputValue = SubsNode->getOperand(1);
14191 
14192   // The mask is present and the provenance of all the values is a smaller type,
14193   // lets see if the mask is superfluous.
14194 
14195   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
14196       !isa<ConstantSDNode>(SubsInputValue.getNode()))
14197     return SDValue();
14198 
14199   ISD::LoadExtType ExtType;
14200 
14201   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
14202       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
14203       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
14204     return SDValue();
14205 
14206   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
14207                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
14208                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
14209     return SDValue();
14210 
14211   // The AND is not necessary, remove it.
14212 
14213   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
14214                                SubsNode->getValueType(1));
14215   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
14216 
14217   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
14218   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
14219 
14220   return SDValue(N, 0);
14221 }
14222 
14223 // Optimize compare with zero and branch.
performBRCONDCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14224 static SDValue performBRCONDCombine(SDNode *N,
14225                                     TargetLowering::DAGCombinerInfo &DCI,
14226                                     SelectionDAG &DAG) {
14227   MachineFunction &MF = DAG.getMachineFunction();
14228   // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
14229   // will not be produced, as they are conditional branch instructions that do
14230   // not set flags.
14231   if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
14232     return SDValue();
14233 
14234   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
14235     N = NV.getNode();
14236   SDValue Chain = N->getOperand(0);
14237   SDValue Dest = N->getOperand(1);
14238   SDValue CCVal = N->getOperand(2);
14239   SDValue Cmp = N->getOperand(3);
14240 
14241   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
14242   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
14243   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
14244     return SDValue();
14245 
14246   unsigned CmpOpc = Cmp.getOpcode();
14247   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
14248     return SDValue();
14249 
14250   // Only attempt folding if there is only one use of the flag and no use of the
14251   // value.
14252   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
14253     return SDValue();
14254 
14255   SDValue LHS = Cmp.getOperand(0);
14256   SDValue RHS = Cmp.getOperand(1);
14257 
14258   assert(LHS.getValueType() == RHS.getValueType() &&
14259          "Expected the value type to be the same for both operands!");
14260   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
14261     return SDValue();
14262 
14263   if (isNullConstant(LHS))
14264     std::swap(LHS, RHS);
14265 
14266   if (!isNullConstant(RHS))
14267     return SDValue();
14268 
14269   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
14270       LHS.getOpcode() == ISD::SRL)
14271     return SDValue();
14272 
14273   // Fold the compare into the branch instruction.
14274   SDValue BR;
14275   if (CC == AArch64CC::EQ)
14276     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14277   else
14278     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
14279 
14280   // Do not add new nodes to DAG combiner worklist.
14281   DCI.CombineTo(N, BR, false);
14282 
14283   return SDValue();
14284 }
14285 
14286 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
14287 // as well as whether the test should be inverted.  This code is required to
14288 // catch these cases (as opposed to standard dag combines) because
14289 // AArch64ISD::TBZ is matched during legalization.
getTestBitOperand(SDValue Op,unsigned & Bit,bool & Invert,SelectionDAG & DAG)14290 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
14291                                  SelectionDAG &DAG) {
14292 
14293   if (!Op->hasOneUse())
14294     return Op;
14295 
14296   // We don't handle undef/constant-fold cases below, as they should have
14297   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
14298   // etc.)
14299 
14300   // (tbz (trunc x), b) -> (tbz x, b)
14301   // This case is just here to enable more of the below cases to be caught.
14302   if (Op->getOpcode() == ISD::TRUNCATE &&
14303       Bit < Op->getValueType(0).getSizeInBits()) {
14304     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14305   }
14306 
14307   // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
14308   if (Op->getOpcode() == ISD::ANY_EXTEND &&
14309       Bit < Op->getOperand(0).getValueSizeInBits()) {
14310     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14311   }
14312 
14313   if (Op->getNumOperands() != 2)
14314     return Op;
14315 
14316   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
14317   if (!C)
14318     return Op;
14319 
14320   switch (Op->getOpcode()) {
14321   default:
14322     return Op;
14323 
14324   // (tbz (and x, m), b) -> (tbz x, b)
14325   case ISD::AND:
14326     if ((C->getZExtValue() >> Bit) & 1)
14327       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14328     return Op;
14329 
14330   // (tbz (shl x, c), b) -> (tbz x, b-c)
14331   case ISD::SHL:
14332     if (C->getZExtValue() <= Bit &&
14333         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14334       Bit = Bit - C->getZExtValue();
14335       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14336     }
14337     return Op;
14338 
14339   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
14340   case ISD::SRA:
14341     Bit = Bit + C->getZExtValue();
14342     if (Bit >= Op->getValueType(0).getSizeInBits())
14343       Bit = Op->getValueType(0).getSizeInBits() - 1;
14344     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14345 
14346   // (tbz (srl x, c), b) -> (tbz x, b+c)
14347   case ISD::SRL:
14348     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
14349       Bit = Bit + C->getZExtValue();
14350       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14351     }
14352     return Op;
14353 
14354   // (tbz (xor x, -1), b) -> (tbnz x, b)
14355   case ISD::XOR:
14356     if ((C->getZExtValue() >> Bit) & 1)
14357       Invert = !Invert;
14358     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
14359   }
14360 }
14361 
14362 // Optimize test single bit zero/non-zero and branch.
performTBZCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14363 static SDValue performTBZCombine(SDNode *N,
14364                                  TargetLowering::DAGCombinerInfo &DCI,
14365                                  SelectionDAG &DAG) {
14366   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14367   bool Invert = false;
14368   SDValue TestSrc = N->getOperand(1);
14369   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
14370 
14371   if (TestSrc == NewTestSrc)
14372     return SDValue();
14373 
14374   unsigned NewOpc = N->getOpcode();
14375   if (Invert) {
14376     if (NewOpc == AArch64ISD::TBZ)
14377       NewOpc = AArch64ISD::TBNZ;
14378     else {
14379       assert(NewOpc == AArch64ISD::TBNZ);
14380       NewOpc = AArch64ISD::TBZ;
14381     }
14382   }
14383 
14384   SDLoc DL(N);
14385   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
14386                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
14387 }
14388 
14389 // vselect (v1i1 setcc) ->
14390 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
14391 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
14392 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
14393 // such VSELECT.
performVSelectCombine(SDNode * N,SelectionDAG & DAG)14394 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
14395   SDValue N0 = N->getOperand(0);
14396   EVT CCVT = N0.getValueType();
14397 
14398   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
14399       CCVT.getVectorElementType() != MVT::i1)
14400     return SDValue();
14401 
14402   EVT ResVT = N->getValueType(0);
14403   EVT CmpVT = N0.getOperand(0).getValueType();
14404   // Only combine when the result type is of the same size as the compared
14405   // operands.
14406   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
14407     return SDValue();
14408 
14409   SDValue IfTrue = N->getOperand(1);
14410   SDValue IfFalse = N->getOperand(2);
14411   SDValue SetCC =
14412       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
14413                    N0.getOperand(0), N0.getOperand(1),
14414                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
14415   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
14416                      IfTrue, IfFalse);
14417 }
14418 
14419 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
14420 /// the compare-mask instructions rather than going via NZCV, even if LHS and
14421 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
14422 /// with a vector one followed by a DUP shuffle on the result.
performSelectCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI)14423 static SDValue performSelectCombine(SDNode *N,
14424                                     TargetLowering::DAGCombinerInfo &DCI) {
14425   SelectionDAG &DAG = DCI.DAG;
14426   SDValue N0 = N->getOperand(0);
14427   EVT ResVT = N->getValueType(0);
14428 
14429   if (N0.getOpcode() != ISD::SETCC)
14430     return SDValue();
14431 
14432   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
14433   // scalar SetCCResultType. We also don't expect vectors, because we assume
14434   // that selects fed by vector SETCCs are canonicalized to VSELECT.
14435   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
14436          "Scalar-SETCC feeding SELECT has unexpected result type!");
14437 
14438   // If NumMaskElts == 0, the comparison is larger than select result. The
14439   // largest real NEON comparison is 64-bits per lane, which means the result is
14440   // at most 32-bits and an illegal vector. Just bail out for now.
14441   EVT SrcVT = N0.getOperand(0).getValueType();
14442 
14443   // Don't try to do this optimization when the setcc itself has i1 operands.
14444   // There are no legal vectors of i1, so this would be pointless.
14445   if (SrcVT == MVT::i1)
14446     return SDValue();
14447 
14448   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
14449   if (!ResVT.isVector() || NumMaskElts == 0)
14450     return SDValue();
14451 
14452   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
14453   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
14454 
14455   // Also bail out if the vector CCVT isn't the same size as ResVT.
14456   // This can happen if the SETCC operand size doesn't divide the ResVT size
14457   // (e.g., f64 vs v3f32).
14458   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
14459     return SDValue();
14460 
14461   // Make sure we didn't create illegal types, if we're not supposed to.
14462   assert(DCI.isBeforeLegalize() ||
14463          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
14464 
14465   // First perform a vector comparison, where lane 0 is the one we're interested
14466   // in.
14467   SDLoc DL(N0);
14468   SDValue LHS =
14469       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
14470   SDValue RHS =
14471       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
14472   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
14473 
14474   // Now duplicate the comparison mask we want across all other lanes.
14475   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
14476   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
14477   Mask = DAG.getNode(ISD::BITCAST, DL,
14478                      ResVT.changeVectorElementTypeToInteger(), Mask);
14479 
14480   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
14481 }
14482 
14483 /// Get rid of unnecessary NVCASTs (that don't change the type).
performNVCASTCombine(SDNode * N)14484 static SDValue performNVCASTCombine(SDNode *N) {
14485   if (N->getValueType(0) == N->getOperand(0).getValueType())
14486     return N->getOperand(0);
14487 
14488   return SDValue();
14489 }
14490 
14491 // If all users of the globaladdr are of the form (globaladdr + constant), find
14492 // the smallest constant, fold it into the globaladdr's offset and rewrite the
14493 // globaladdr as (globaladdr + constant) - constant.
performGlobalAddressCombine(SDNode * N,SelectionDAG & DAG,const AArch64Subtarget * Subtarget,const TargetMachine & TM)14494 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
14495                                            const AArch64Subtarget *Subtarget,
14496                                            const TargetMachine &TM) {
14497   auto *GN = cast<GlobalAddressSDNode>(N);
14498   if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
14499       AArch64II::MO_NO_FLAG)
14500     return SDValue();
14501 
14502   uint64_t MinOffset = -1ull;
14503   for (SDNode *N : GN->uses()) {
14504     if (N->getOpcode() != ISD::ADD)
14505       return SDValue();
14506     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
14507     if (!C)
14508       C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14509     if (!C)
14510       return SDValue();
14511     MinOffset = std::min(MinOffset, C->getZExtValue());
14512   }
14513   uint64_t Offset = MinOffset + GN->getOffset();
14514 
14515   // Require that the new offset is larger than the existing one. Otherwise, we
14516   // can end up oscillating between two possible DAGs, for example,
14517   // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
14518   if (Offset <= uint64_t(GN->getOffset()))
14519     return SDValue();
14520 
14521   // Check whether folding this offset is legal. It must not go out of bounds of
14522   // the referenced object to avoid violating the code model, and must be
14523   // smaller than 2^21 because this is the largest offset expressible in all
14524   // object formats.
14525   //
14526   // This check also prevents us from folding negative offsets, which will end
14527   // up being treated in the same way as large positive ones. They could also
14528   // cause code model violations, and aren't really common enough to matter.
14529   if (Offset >= (1 << 21))
14530     return SDValue();
14531 
14532   const GlobalValue *GV = GN->getGlobal();
14533   Type *T = GV->getValueType();
14534   if (!T->isSized() ||
14535       Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
14536     return SDValue();
14537 
14538   SDLoc DL(GN);
14539   SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
14540   return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
14541                      DAG.getConstant(MinOffset, DL, MVT::i64));
14542 }
14543 
14544 // Turns the vector of indices into a vector of byte offstes by scaling Offset
14545 // by (BitWidth / 8).
getScaledOffsetForBitWidth(SelectionDAG & DAG,SDValue Offset,SDLoc DL,unsigned BitWidth)14546 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
14547                                           SDLoc DL, unsigned BitWidth) {
14548   assert(Offset.getValueType().isScalableVector() &&
14549          "This method is only for scalable vectors of offsets");
14550 
14551   SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
14552   SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
14553 
14554   return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
14555 }
14556 
14557 /// Check if the value of \p OffsetInBytes can be used as an immediate for
14558 /// the gather load/prefetch and scatter store instructions with vector base and
14559 /// immediate offset addressing mode:
14560 ///
14561 ///      [<Zn>.[S|D]{, #<imm>}]
14562 ///
14563 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
14564 
isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,unsigned ScalarSizeInBytes)14565 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
14566                                                   unsigned ScalarSizeInBytes) {
14567   // The immediate is not a multiple of the scalar size.
14568   if (OffsetInBytes % ScalarSizeInBytes)
14569     return false;
14570 
14571   // The immediate is out of range.
14572   if (OffsetInBytes / ScalarSizeInBytes > 31)
14573     return false;
14574 
14575   return true;
14576 }
14577 
14578 /// Check if the value of \p Offset represents a valid immediate for the SVE
14579 /// gather load/prefetch and scatter store instructiona with vector base and
14580 /// immediate offset addressing mode:
14581 ///
14582 ///      [<Zn>.[S|D]{, #<imm>}]
14583 ///
14584 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
isValidImmForSVEVecImmAddrMode(SDValue Offset,unsigned ScalarSizeInBytes)14585 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
14586                                            unsigned ScalarSizeInBytes) {
14587   ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
14588   return OffsetConst && isValidImmForSVEVecImmAddrMode(
14589                             OffsetConst->getZExtValue(), ScalarSizeInBytes);
14590 }
14591 
performScatterStoreCombine(SDNode * N,SelectionDAG & DAG,unsigned Opcode,bool OnlyPackedOffsets=true)14592 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
14593                                           unsigned Opcode,
14594                                           bool OnlyPackedOffsets = true) {
14595   const SDValue Src = N->getOperand(2);
14596   const EVT SrcVT = Src->getValueType(0);
14597   assert(SrcVT.isScalableVector() &&
14598          "Scatter stores are only possible for SVE vectors");
14599 
14600   SDLoc DL(N);
14601   MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
14602 
14603   // Make sure that source data will fit into an SVE register
14604   if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14605     return SDValue();
14606 
14607   // For FPs, ACLE only supports _packed_ single and double precision types.
14608   if (SrcElVT.isFloatingPoint())
14609     if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
14610       return SDValue();
14611 
14612   // Depending on the addressing mode, this is either a pointer or a vector of
14613   // pointers (that fits into one register)
14614   SDValue Base = N->getOperand(4);
14615   // Depending on the addressing mode, this is either a single offset or a
14616   // vector of offsets  (that fits into one register)
14617   SDValue Offset = N->getOperand(5);
14618 
14619   // For "scalar + vector of indices", just scale the indices. This only
14620   // applies to non-temporal scatters because there's no instruction that takes
14621   // indicies.
14622   if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
14623     Offset =
14624         getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
14625     Opcode = AArch64ISD::SSTNT1_PRED;
14626   }
14627 
14628   // In the case of non-temporal gather loads there's only one SVE instruction
14629   // per data-size: "scalar + vector", i.e.
14630   //    * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14631   // Since we do have intrinsics that allow the arguments to be in a different
14632   // order, we may need to swap them to match the spec.
14633   if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
14634     std::swap(Base, Offset);
14635 
14636   // SST1_IMM requires that the offset is an immediate that is:
14637   //    * a multiple of #SizeInBytes,
14638   //    * in the range [0, 31 x #SizeInBytes],
14639   // where #SizeInBytes is the size in bytes of the stored items. For
14640   // immediates outside that range and non-immediate scalar offsets use SST1 or
14641   // SST1_UXTW instead.
14642   if (Opcode == AArch64ISD::SST1_IMM_PRED) {
14643     if (!isValidImmForSVEVecImmAddrMode(Offset,
14644                                         SrcVT.getScalarSizeInBits() / 8)) {
14645       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14646         Opcode = AArch64ISD::SST1_UXTW_PRED;
14647       else
14648         Opcode = AArch64ISD::SST1_PRED;
14649 
14650       std::swap(Base, Offset);
14651     }
14652   }
14653 
14654   auto &TLI = DAG.getTargetLoweringInfo();
14655   if (!TLI.isTypeLegal(Base.getValueType()))
14656     return SDValue();
14657 
14658   // Some scatter store variants allow unpacked offsets, but only as nxv2i32
14659   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14660   // nxv2i64. Legalize accordingly.
14661   if (!OnlyPackedOffsets &&
14662       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14663     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14664 
14665   if (!TLI.isTypeLegal(Offset.getValueType()))
14666     return SDValue();
14667 
14668   // Source value type that is representable in hardware
14669   EVT HwSrcVt = getSVEContainerType(SrcVT);
14670 
14671   // Keep the original type of the input data to store - this is needed to be
14672   // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
14673   // FP values we want the integer equivalent, so just use HwSrcVt.
14674   SDValue InputVT = DAG.getValueType(SrcVT);
14675   if (SrcVT.isFloatingPoint())
14676     InputVT = DAG.getValueType(HwSrcVt);
14677 
14678   SDVTList VTs = DAG.getVTList(MVT::Other);
14679   SDValue SrcNew;
14680 
14681   if (Src.getValueType().isFloatingPoint())
14682     SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
14683   else
14684     SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
14685 
14686   SDValue Ops[] = {N->getOperand(0), // Chain
14687                    SrcNew,
14688                    N->getOperand(3), // Pg
14689                    Base,
14690                    Offset,
14691                    InputVT};
14692 
14693   return DAG.getNode(Opcode, DL, VTs, Ops);
14694 }
14695 
performGatherLoadCombine(SDNode * N,SelectionDAG & DAG,unsigned Opcode,bool OnlyPackedOffsets=true)14696 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
14697                                         unsigned Opcode,
14698                                         bool OnlyPackedOffsets = true) {
14699   const EVT RetVT = N->getValueType(0);
14700   assert(RetVT.isScalableVector() &&
14701          "Gather loads are only possible for SVE vectors");
14702 
14703   SDLoc DL(N);
14704 
14705   // Make sure that the loaded data will fit into an SVE register
14706   if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
14707     return SDValue();
14708 
14709   // Depending on the addressing mode, this is either a pointer or a vector of
14710   // pointers (that fits into one register)
14711   SDValue Base = N->getOperand(3);
14712   // Depending on the addressing mode, this is either a single offset or a
14713   // vector of offsets  (that fits into one register)
14714   SDValue Offset = N->getOperand(4);
14715 
14716   // For "scalar + vector of indices", just scale the indices. This only
14717   // applies to non-temporal gathers because there's no instruction that takes
14718   // indicies.
14719   if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
14720     Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
14721                                         RetVT.getScalarSizeInBits());
14722     Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
14723   }
14724 
14725   // In the case of non-temporal gather loads there's only one SVE instruction
14726   // per data-size: "scalar + vector", i.e.
14727   //    * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
14728   // Since we do have intrinsics that allow the arguments to be in a different
14729   // order, we may need to swap them to match the spec.
14730   if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
14731       Offset.getValueType().isVector())
14732     std::swap(Base, Offset);
14733 
14734   // GLD{FF}1_IMM requires that the offset is an immediate that is:
14735   //    * a multiple of #SizeInBytes,
14736   //    * in the range [0, 31 x #SizeInBytes],
14737   // where #SizeInBytes is the size in bytes of the loaded items. For
14738   // immediates outside that range and non-immediate scalar offsets use
14739   // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
14740   if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
14741       Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
14742     if (!isValidImmForSVEVecImmAddrMode(Offset,
14743                                         RetVT.getScalarSizeInBits() / 8)) {
14744       if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
14745         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14746                      ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
14747                      : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
14748       else
14749         Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
14750                      ? AArch64ISD::GLD1_MERGE_ZERO
14751                      : AArch64ISD::GLDFF1_MERGE_ZERO;
14752 
14753       std::swap(Base, Offset);
14754     }
14755   }
14756 
14757   auto &TLI = DAG.getTargetLoweringInfo();
14758   if (!TLI.isTypeLegal(Base.getValueType()))
14759     return SDValue();
14760 
14761   // Some gather load variants allow unpacked offsets, but only as nxv2i32
14762   // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
14763   // nxv2i64. Legalize accordingly.
14764   if (!OnlyPackedOffsets &&
14765       Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
14766     Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
14767 
14768   // Return value type that is representable in hardware
14769   EVT HwRetVt = getSVEContainerType(RetVT);
14770 
14771   // Keep the original output value type around - this is needed to be able to
14772   // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
14773   // values we want the integer equivalent, so just use HwRetVT.
14774   SDValue OutVT = DAG.getValueType(RetVT);
14775   if (RetVT.isFloatingPoint())
14776     OutVT = DAG.getValueType(HwRetVt);
14777 
14778   SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
14779   SDValue Ops[] = {N->getOperand(0), // Chain
14780                    N->getOperand(2), // Pg
14781                    Base, Offset, OutVT};
14782 
14783   SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
14784   SDValue LoadChain = SDValue(Load.getNode(), 1);
14785 
14786   if (RetVT.isInteger() && (RetVT != HwRetVt))
14787     Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
14788 
14789   // If the original return value was FP, bitcast accordingly. Doing it here
14790   // means that we can avoid adding TableGen patterns for FPs.
14791   if (RetVT.isFloatingPoint())
14792     Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
14793 
14794   return DAG.getMergeValues({Load, LoadChain}, DL);
14795 }
14796 
14797 static SDValue
performSignExtendInRegCombine(SDNode * N,TargetLowering::DAGCombinerInfo & DCI,SelectionDAG & DAG)14798 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
14799                               SelectionDAG &DAG) {
14800   if (DCI.isBeforeLegalizeOps())
14801     return SDValue();
14802 
14803   SDLoc DL(N);
14804   SDValue Src = N->getOperand(0);
14805   unsigned Opc = Src->getOpcode();
14806 
14807   // Sign extend of an unsigned unpack -> signed unpack
14808   if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
14809 
14810     unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
14811                                                : AArch64ISD::SUNPKLO;
14812 
14813     // Push the sign extend to the operand of the unpack
14814     // This is necessary where, for example, the operand of the unpack
14815     // is another unpack:
14816     // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
14817     // ->
14818     // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
14819     // ->
14820     // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
14821     SDValue ExtOp = Src->getOperand(0);
14822     auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
14823     EVT EltTy = VT.getVectorElementType();
14824     (void)EltTy;
14825 
14826     assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
14827            "Sign extending from an invalid type");
14828 
14829     EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
14830 
14831     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
14832                               ExtOp, DAG.getValueType(ExtVT));
14833 
14834     return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
14835   }
14836 
14837   // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
14838   // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
14839   unsigned NewOpc;
14840   unsigned MemVTOpNum = 4;
14841   switch (Opc) {
14842   case AArch64ISD::LD1_MERGE_ZERO:
14843     NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
14844     MemVTOpNum = 3;
14845     break;
14846   case AArch64ISD::LDNF1_MERGE_ZERO:
14847     NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
14848     MemVTOpNum = 3;
14849     break;
14850   case AArch64ISD::LDFF1_MERGE_ZERO:
14851     NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
14852     MemVTOpNum = 3;
14853     break;
14854   case AArch64ISD::GLD1_MERGE_ZERO:
14855     NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
14856     break;
14857   case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
14858     NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
14859     break;
14860   case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
14861     NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
14862     break;
14863   case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
14864     NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
14865     break;
14866   case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
14867     NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
14868     break;
14869   case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
14870     NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
14871     break;
14872   case AArch64ISD::GLD1_IMM_MERGE_ZERO:
14873     NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
14874     break;
14875   case AArch64ISD::GLDFF1_MERGE_ZERO:
14876     NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
14877     break;
14878   case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
14879     NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
14880     break;
14881   case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
14882     NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
14883     break;
14884   case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
14885     NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
14886     break;
14887   case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
14888     NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
14889     break;
14890   case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
14891     NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
14892     break;
14893   case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
14894     NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
14895     break;
14896   case AArch64ISD::GLDNT1_MERGE_ZERO:
14897     NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
14898     break;
14899   default:
14900     return SDValue();
14901   }
14902 
14903   EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
14904   EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
14905 
14906   if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
14907     return SDValue();
14908 
14909   EVT DstVT = N->getValueType(0);
14910   SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
14911 
14912   SmallVector<SDValue, 5> Ops;
14913   for (unsigned I = 0; I < Src->getNumOperands(); ++I)
14914     Ops.push_back(Src->getOperand(I));
14915 
14916   SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
14917   DCI.CombineTo(N, ExtLoad);
14918   DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
14919 
14920   // Return N so it doesn't get rechecked
14921   return SDValue(N, 0);
14922 }
14923 
14924 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
14925 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
14926 /// != nxv2i32) do not need legalization.
legalizeSVEGatherPrefetchOffsVec(SDNode * N,SelectionDAG & DAG)14927 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
14928   const unsigned OffsetPos = 4;
14929   SDValue Offset = N->getOperand(OffsetPos);
14930 
14931   // Not an unpacked vector, bail out.
14932   if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
14933     return SDValue();
14934 
14935   // Extend the unpacked offset vector to 64-bit lanes.
14936   SDLoc DL(N);
14937   Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
14938   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14939   // Replace the offset operand with the 64-bit one.
14940   Ops[OffsetPos] = Offset;
14941 
14942   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14943 }
14944 
14945 /// Combines a node carrying the intrinsic
14946 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
14947 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
14948 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
14949 /// sve gather prefetch instruction with vector plus immediate addressing mode.
combineSVEPrefetchVecBaseImmOff(SDNode * N,SelectionDAG & DAG,unsigned ScalarSizeInBytes)14950 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
14951                                                unsigned ScalarSizeInBytes) {
14952   const unsigned ImmPos = 4, OffsetPos = 3;
14953   // No need to combine the node if the immediate is valid...
14954   if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
14955     return SDValue();
14956 
14957   // ...otherwise swap the offset base with the offset...
14958   SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
14959   std::swap(Ops[ImmPos], Ops[OffsetPos]);
14960   // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
14961   // `aarch64_sve_prfb_gather_uxtw_index`.
14962   SDLoc DL(N);
14963   Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
14964                            MVT::i64);
14965 
14966   return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
14967 }
14968 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const14969 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
14970                                                  DAGCombinerInfo &DCI) const {
14971   SelectionDAG &DAG = DCI.DAG;
14972   switch (N->getOpcode()) {
14973   default:
14974     LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
14975     break;
14976   case ISD::ABS:
14977     return performABSCombine(N, DAG, DCI, Subtarget);
14978   case ISD::ADD:
14979   case ISD::SUB:
14980     return performAddSubCombine(N, DCI, DAG);
14981   case ISD::XOR:
14982     return performXorCombine(N, DAG, DCI, Subtarget);
14983   case ISD::MUL:
14984     return performMulCombine(N, DAG, DCI, Subtarget);
14985   case ISD::SINT_TO_FP:
14986   case ISD::UINT_TO_FP:
14987     return performIntToFpCombine(N, DAG, Subtarget);
14988   case ISD::FP_TO_SINT:
14989   case ISD::FP_TO_UINT:
14990     return performFpToIntCombine(N, DAG, DCI, Subtarget);
14991   case ISD::FDIV:
14992     return performFDivCombine(N, DAG, DCI, Subtarget);
14993   case ISD::OR:
14994     return performORCombine(N, DCI, Subtarget);
14995   case ISD::AND:
14996     return performANDCombine(N, DCI);
14997   case ISD::SRL:
14998     return performSRLCombine(N, DCI);
14999   case ISD::INTRINSIC_WO_CHAIN:
15000     return performIntrinsicCombine(N, DCI, Subtarget);
15001   case ISD::ANY_EXTEND:
15002   case ISD::ZERO_EXTEND:
15003   case ISD::SIGN_EXTEND:
15004     return performExtendCombine(N, DCI, DAG);
15005   case ISD::SIGN_EXTEND_INREG:
15006     return performSignExtendInRegCombine(N, DCI, DAG);
15007   case ISD::TRUNCATE:
15008     return performVectorTruncateCombine(N, DCI, DAG);
15009   case ISD::CONCAT_VECTORS:
15010     return performConcatVectorsCombine(N, DCI, DAG);
15011   case ISD::SELECT:
15012     return performSelectCombine(N, DCI);
15013   case ISD::VSELECT:
15014     return performVSelectCombine(N, DCI.DAG);
15015   case ISD::LOAD:
15016     if (performTBISimplification(N->getOperand(1), DCI, DAG))
15017       return SDValue(N, 0);
15018     break;
15019   case ISD::STORE:
15020     return performSTORECombine(N, DCI, DAG, Subtarget);
15021   case AArch64ISD::BRCOND:
15022     return performBRCONDCombine(N, DCI, DAG);
15023   case AArch64ISD::TBNZ:
15024   case AArch64ISD::TBZ:
15025     return performTBZCombine(N, DCI, DAG);
15026   case AArch64ISD::CSEL:
15027     return performCONDCombine(N, DCI, DAG, 2, 3);
15028   case AArch64ISD::DUP:
15029     return performPostLD1Combine(N, DCI, false);
15030   case AArch64ISD::NVCAST:
15031     return performNVCASTCombine(N);
15032   case AArch64ISD::UZP1:
15033     return performUzpCombine(N, DAG);
15034   case ISD::INSERT_VECTOR_ELT:
15035     return performPostLD1Combine(N, DCI, true);
15036   case ISD::EXTRACT_VECTOR_ELT:
15037     return performExtractVectorEltCombine(N, DAG);
15038   case ISD::VECREDUCE_ADD:
15039     return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
15040   case ISD::INTRINSIC_VOID:
15041   case ISD::INTRINSIC_W_CHAIN:
15042     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15043     case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
15044       return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
15045     case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
15046       return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
15047     case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
15048       return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
15049     case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
15050       return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
15051     case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
15052     case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
15053     case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
15054     case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
15055     case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
15056     case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
15057     case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
15058     case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
15059       return legalizeSVEGatherPrefetchOffsVec(N, DAG);
15060     case Intrinsic::aarch64_neon_ld2:
15061     case Intrinsic::aarch64_neon_ld3:
15062     case Intrinsic::aarch64_neon_ld4:
15063     case Intrinsic::aarch64_neon_ld1x2:
15064     case Intrinsic::aarch64_neon_ld1x3:
15065     case Intrinsic::aarch64_neon_ld1x4:
15066     case Intrinsic::aarch64_neon_ld2lane:
15067     case Intrinsic::aarch64_neon_ld3lane:
15068     case Intrinsic::aarch64_neon_ld4lane:
15069     case Intrinsic::aarch64_neon_ld2r:
15070     case Intrinsic::aarch64_neon_ld3r:
15071     case Intrinsic::aarch64_neon_ld4r:
15072     case Intrinsic::aarch64_neon_st2:
15073     case Intrinsic::aarch64_neon_st3:
15074     case Intrinsic::aarch64_neon_st4:
15075     case Intrinsic::aarch64_neon_st1x2:
15076     case Intrinsic::aarch64_neon_st1x3:
15077     case Intrinsic::aarch64_neon_st1x4:
15078     case Intrinsic::aarch64_neon_st2lane:
15079     case Intrinsic::aarch64_neon_st3lane:
15080     case Intrinsic::aarch64_neon_st4lane:
15081       return performNEONPostLDSTCombine(N, DCI, DAG);
15082     case Intrinsic::aarch64_sve_ldnt1:
15083       return performLDNT1Combine(N, DAG);
15084     case Intrinsic::aarch64_sve_ld1rq:
15085       return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
15086     case Intrinsic::aarch64_sve_ld1ro:
15087       return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
15088     case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
15089       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15090     case Intrinsic::aarch64_sve_ldnt1_gather:
15091       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15092     case Intrinsic::aarch64_sve_ldnt1_gather_index:
15093       return performGatherLoadCombine(N, DAG,
15094                                       AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
15095     case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
15096       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
15097     case Intrinsic::aarch64_sve_ld1:
15098       return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
15099     case Intrinsic::aarch64_sve_ldnf1:
15100       return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
15101     case Intrinsic::aarch64_sve_ldff1:
15102       return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
15103     case Intrinsic::aarch64_sve_st1:
15104       return performST1Combine(N, DAG);
15105     case Intrinsic::aarch64_sve_stnt1:
15106       return performSTNT1Combine(N, DAG);
15107     case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
15108       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15109     case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
15110       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15111     case Intrinsic::aarch64_sve_stnt1_scatter:
15112       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
15113     case Intrinsic::aarch64_sve_stnt1_scatter_index:
15114       return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
15115     case Intrinsic::aarch64_sve_ld1_gather:
15116       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
15117     case Intrinsic::aarch64_sve_ld1_gather_index:
15118       return performGatherLoadCombine(N, DAG,
15119                                       AArch64ISD::GLD1_SCALED_MERGE_ZERO);
15120     case Intrinsic::aarch64_sve_ld1_gather_sxtw:
15121       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
15122                                       /*OnlyPackedOffsets=*/false);
15123     case Intrinsic::aarch64_sve_ld1_gather_uxtw:
15124       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
15125                                       /*OnlyPackedOffsets=*/false);
15126     case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
15127       return performGatherLoadCombine(N, DAG,
15128                                       AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
15129                                       /*OnlyPackedOffsets=*/false);
15130     case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
15131       return performGatherLoadCombine(N, DAG,
15132                                       AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
15133                                       /*OnlyPackedOffsets=*/false);
15134     case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
15135       return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
15136     case Intrinsic::aarch64_sve_ldff1_gather:
15137       return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
15138     case Intrinsic::aarch64_sve_ldff1_gather_index:
15139       return performGatherLoadCombine(N, DAG,
15140                                       AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
15141     case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
15142       return performGatherLoadCombine(N, DAG,
15143                                       AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
15144                                       /*OnlyPackedOffsets=*/false);
15145     case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
15146       return performGatherLoadCombine(N, DAG,
15147                                       AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
15148                                       /*OnlyPackedOffsets=*/false);
15149     case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
15150       return performGatherLoadCombine(N, DAG,
15151                                       AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
15152                                       /*OnlyPackedOffsets=*/false);
15153     case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
15154       return performGatherLoadCombine(N, DAG,
15155                                       AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
15156                                       /*OnlyPackedOffsets=*/false);
15157     case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
15158       return performGatherLoadCombine(N, DAG,
15159                                       AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
15160     case Intrinsic::aarch64_sve_st1_scatter:
15161       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
15162     case Intrinsic::aarch64_sve_st1_scatter_index:
15163       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
15164     case Intrinsic::aarch64_sve_st1_scatter_sxtw:
15165       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
15166                                         /*OnlyPackedOffsets=*/false);
15167     case Intrinsic::aarch64_sve_st1_scatter_uxtw:
15168       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
15169                                         /*OnlyPackedOffsets=*/false);
15170     case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
15171       return performScatterStoreCombine(N, DAG,
15172                                         AArch64ISD::SST1_SXTW_SCALED_PRED,
15173                                         /*OnlyPackedOffsets=*/false);
15174     case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
15175       return performScatterStoreCombine(N, DAG,
15176                                         AArch64ISD::SST1_UXTW_SCALED_PRED,
15177                                         /*OnlyPackedOffsets=*/false);
15178     case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
15179       return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
15180     case Intrinsic::aarch64_sve_tuple_get: {
15181       SDLoc DL(N);
15182       SDValue Chain = N->getOperand(0);
15183       SDValue Src1 = N->getOperand(2);
15184       SDValue Idx = N->getOperand(3);
15185 
15186       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15187       EVT ResVT = N->getValueType(0);
15188       uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
15189       SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
15190       SDValue Val =
15191           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
15192       return DAG.getMergeValues({Val, Chain}, DL);
15193     }
15194     case Intrinsic::aarch64_sve_tuple_set: {
15195       SDLoc DL(N);
15196       SDValue Chain = N->getOperand(0);
15197       SDValue Tuple = N->getOperand(2);
15198       SDValue Idx = N->getOperand(3);
15199       SDValue Vec = N->getOperand(4);
15200 
15201       EVT TupleVT = Tuple.getValueType();
15202       uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
15203 
15204       uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
15205       uint64_t NumLanes =
15206           Vec.getValueType().getVectorElementCount().getKnownMinValue();
15207 
15208       if ((TupleLanes % NumLanes) != 0)
15209         report_fatal_error("invalid tuple vector!");
15210 
15211       uint64_t NumVecs = TupleLanes / NumLanes;
15212 
15213       SmallVector<SDValue, 4> Opnds;
15214       for (unsigned I = 0; I < NumVecs; ++I) {
15215         if (I == IdxConst)
15216           Opnds.push_back(Vec);
15217         else {
15218           SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
15219           Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
15220                                       Vec.getValueType(), Tuple, ExtIdx));
15221         }
15222       }
15223       SDValue Concat =
15224           DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
15225       return DAG.getMergeValues({Concat, Chain}, DL);
15226     }
15227     case Intrinsic::aarch64_sve_tuple_create2:
15228     case Intrinsic::aarch64_sve_tuple_create3:
15229     case Intrinsic::aarch64_sve_tuple_create4: {
15230       SDLoc DL(N);
15231       SDValue Chain = N->getOperand(0);
15232 
15233       SmallVector<SDValue, 4> Opnds;
15234       for (unsigned I = 2; I < N->getNumOperands(); ++I)
15235         Opnds.push_back(N->getOperand(I));
15236 
15237       EVT VT = Opnds[0].getValueType();
15238       EVT EltVT = VT.getVectorElementType();
15239       EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
15240                                     VT.getVectorElementCount() *
15241                                         (N->getNumOperands() - 2));
15242       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
15243       return DAG.getMergeValues({Concat, Chain}, DL);
15244     }
15245     case Intrinsic::aarch64_sve_ld2:
15246     case Intrinsic::aarch64_sve_ld3:
15247     case Intrinsic::aarch64_sve_ld4: {
15248       SDLoc DL(N);
15249       SDValue Chain = N->getOperand(0);
15250       SDValue Mask = N->getOperand(2);
15251       SDValue BasePtr = N->getOperand(3);
15252       SDValue LoadOps[] = {Chain, Mask, BasePtr};
15253       unsigned IntrinsicID =
15254           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15255       SDValue Result =
15256           LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
15257       return DAG.getMergeValues({Result, Chain}, DL);
15258     }
15259     default:
15260       break;
15261     }
15262     break;
15263   case ISD::GlobalAddress:
15264     return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
15265   }
15266   return SDValue();
15267 }
15268 
15269 // Check if the return value is used as only a return value, as otherwise
15270 // we can't perform a tail-call. In particular, we need to check for
15271 // target ISD nodes that are returns and any other "odd" constructs
15272 // that the generic analysis code won't necessarily catch.
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const15273 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
15274                                                SDValue &Chain) const {
15275   if (N->getNumValues() != 1)
15276     return false;
15277   if (!N->hasNUsesOfValue(1, 0))
15278     return false;
15279 
15280   SDValue TCChain = Chain;
15281   SDNode *Copy = *N->use_begin();
15282   if (Copy->getOpcode() == ISD::CopyToReg) {
15283     // If the copy has a glue operand, we conservatively assume it isn't safe to
15284     // perform a tail call.
15285     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
15286         MVT::Glue)
15287       return false;
15288     TCChain = Copy->getOperand(0);
15289   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
15290     return false;
15291 
15292   bool HasRet = false;
15293   for (SDNode *Node : Copy->uses()) {
15294     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
15295       return false;
15296     HasRet = true;
15297   }
15298 
15299   if (!HasRet)
15300     return false;
15301 
15302   Chain = TCChain;
15303   return true;
15304 }
15305 
15306 // Return whether the an instruction can potentially be optimized to a tail
15307 // call. This will cause the optimizers to attempt to move, or duplicate,
15308 // return instructions to help enable tail call optimizations for this
15309 // instruction.
mayBeEmittedAsTailCall(const CallInst * CI) const15310 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15311   return CI->isTailCall();
15312 }
15313 
getIndexedAddressParts(SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,bool & IsInc,SelectionDAG & DAG) const15314 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
15315                                                    SDValue &Offset,
15316                                                    ISD::MemIndexedMode &AM,
15317                                                    bool &IsInc,
15318                                                    SelectionDAG &DAG) const {
15319   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
15320     return false;
15321 
15322   Base = Op->getOperand(0);
15323   // All of the indexed addressing mode instructions take a signed
15324   // 9 bit immediate offset.
15325   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
15326     int64_t RHSC = RHS->getSExtValue();
15327     if (Op->getOpcode() == ISD::SUB)
15328       RHSC = -(uint64_t)RHSC;
15329     if (!isInt<9>(RHSC))
15330       return false;
15331     IsInc = (Op->getOpcode() == ISD::ADD);
15332     Offset = Op->getOperand(1);
15333     return true;
15334   }
15335   return false;
15336 }
15337 
getPreIndexedAddressParts(SDNode * N,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const15338 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15339                                                       SDValue &Offset,
15340                                                       ISD::MemIndexedMode &AM,
15341                                                       SelectionDAG &DAG) const {
15342   EVT VT;
15343   SDValue Ptr;
15344   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15345     VT = LD->getMemoryVT();
15346     Ptr = LD->getBasePtr();
15347   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15348     VT = ST->getMemoryVT();
15349     Ptr = ST->getBasePtr();
15350   } else
15351     return false;
15352 
15353   bool IsInc;
15354   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
15355     return false;
15356   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
15357   return true;
15358 }
15359 
getPostIndexedAddressParts(SDNode * N,SDNode * Op,SDValue & Base,SDValue & Offset,ISD::MemIndexedMode & AM,SelectionDAG & DAG) const15360 bool AArch64TargetLowering::getPostIndexedAddressParts(
15361     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
15362     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
15363   EVT VT;
15364   SDValue Ptr;
15365   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15366     VT = LD->getMemoryVT();
15367     Ptr = LD->getBasePtr();
15368   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15369     VT = ST->getMemoryVT();
15370     Ptr = ST->getBasePtr();
15371   } else
15372     return false;
15373 
15374   bool IsInc;
15375   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
15376     return false;
15377   // Post-indexing updates the base, so it's not a valid transform
15378   // if that's not the same as the load's pointer.
15379   if (Ptr != Base)
15380     return false;
15381   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
15382   return true;
15383 }
15384 
ReplaceBITCASTResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG)15385 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
15386                                   SelectionDAG &DAG) {
15387   SDLoc DL(N);
15388   SDValue Op = N->getOperand(0);
15389 
15390   if (N->getValueType(0) != MVT::i16 ||
15391       (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
15392     return;
15393 
15394   Op = SDValue(
15395       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
15396                          DAG.getUNDEF(MVT::i32), Op,
15397                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
15398       0);
15399   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
15400   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
15401 }
15402 
ReplaceReductionResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,unsigned InterOp,unsigned AcrossOp)15403 static void ReplaceReductionResults(SDNode *N,
15404                                     SmallVectorImpl<SDValue> &Results,
15405                                     SelectionDAG &DAG, unsigned InterOp,
15406                                     unsigned AcrossOp) {
15407   EVT LoVT, HiVT;
15408   SDValue Lo, Hi;
15409   SDLoc dl(N);
15410   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
15411   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
15412   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
15413   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
15414   Results.push_back(SplitVal);
15415 }
15416 
splitInt128(SDValue N,SelectionDAG & DAG)15417 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
15418   SDLoc DL(N);
15419   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
15420   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
15421                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
15422                                        DAG.getConstant(64, DL, MVT::i64)));
15423   return std::make_pair(Lo, Hi);
15424 }
15425 
ReplaceExtractSubVectorResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const15426 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
15427     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15428   SDValue In = N->getOperand(0);
15429   EVT InVT = In.getValueType();
15430 
15431   // Common code will handle these just fine.
15432   if (!InVT.isScalableVector() || !InVT.isInteger())
15433     return;
15434 
15435   SDLoc DL(N);
15436   EVT VT = N->getValueType(0);
15437 
15438   // The following checks bail if this is not a halving operation.
15439 
15440   ElementCount ResEC = VT.getVectorElementCount();
15441 
15442   if (InVT.getVectorElementCount() != (ResEC * 2))
15443     return;
15444 
15445   auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
15446   if (!CIndex)
15447     return;
15448 
15449   unsigned Index = CIndex->getZExtValue();
15450   if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
15451     return;
15452 
15453   unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
15454   EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
15455 
15456   SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
15457   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
15458 }
15459 
15460 // Create an even/odd pair of X registers holding integer value V.
createGPRPairNode(SelectionDAG & DAG,SDValue V)15461 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
15462   SDLoc dl(V.getNode());
15463   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
15464   SDValue VHi = DAG.getAnyExtOrTrunc(
15465       DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
15466       dl, MVT::i64);
15467   if (DAG.getDataLayout().isBigEndian())
15468     std::swap (VLo, VHi);
15469   SDValue RegClass =
15470       DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
15471   SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
15472   SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
15473   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
15474   return SDValue(
15475       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
15476 }
15477 
ReplaceCMP_SWAP_128Results(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG,const AArch64Subtarget * Subtarget)15478 static void ReplaceCMP_SWAP_128Results(SDNode *N,
15479                                        SmallVectorImpl<SDValue> &Results,
15480                                        SelectionDAG &DAG,
15481                                        const AArch64Subtarget *Subtarget) {
15482   assert(N->getValueType(0) == MVT::i128 &&
15483          "AtomicCmpSwap on types less than 128 should be legal");
15484 
15485   if (Subtarget->hasLSE()) {
15486     // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
15487     // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
15488     SDValue Ops[] = {
15489         createGPRPairNode(DAG, N->getOperand(2)), // Compare value
15490         createGPRPairNode(DAG, N->getOperand(3)), // Store value
15491         N->getOperand(1), // Ptr
15492         N->getOperand(0), // Chain in
15493     };
15494 
15495     MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15496 
15497     unsigned Opcode;
15498     switch (MemOp->getOrdering()) {
15499     case AtomicOrdering::Monotonic:
15500       Opcode = AArch64::CASPX;
15501       break;
15502     case AtomicOrdering::Acquire:
15503       Opcode = AArch64::CASPAX;
15504       break;
15505     case AtomicOrdering::Release:
15506       Opcode = AArch64::CASPLX;
15507       break;
15508     case AtomicOrdering::AcquireRelease:
15509     case AtomicOrdering::SequentiallyConsistent:
15510       Opcode = AArch64::CASPALX;
15511       break;
15512     default:
15513       llvm_unreachable("Unexpected ordering!");
15514     }
15515 
15516     MachineSDNode *CmpSwap = DAG.getMachineNode(
15517         Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
15518     DAG.setNodeMemRefs(CmpSwap, {MemOp});
15519 
15520     unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
15521     if (DAG.getDataLayout().isBigEndian())
15522       std::swap(SubReg1, SubReg2);
15523     SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
15524                                             SDValue(CmpSwap, 0));
15525     SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
15526                                             SDValue(CmpSwap, 0));
15527     Results.push_back(
15528         DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
15529     Results.push_back(SDValue(CmpSwap, 1)); // Chain out
15530     return;
15531   }
15532 
15533   auto Desired = splitInt128(N->getOperand(2), DAG);
15534   auto New = splitInt128(N->getOperand(3), DAG);
15535   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
15536                    New.first,        New.second,    N->getOperand(0)};
15537   SDNode *CmpSwap = DAG.getMachineNode(
15538       AArch64::CMP_SWAP_128, SDLoc(N),
15539       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
15540 
15541   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
15542   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
15543 
15544   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15545                                 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
15546   Results.push_back(SDValue(CmpSwap, 3));
15547 }
15548 
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const15549 void AArch64TargetLowering::ReplaceNodeResults(
15550     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
15551   switch (N->getOpcode()) {
15552   default:
15553     llvm_unreachable("Don't know how to custom expand this");
15554   case ISD::BITCAST:
15555     ReplaceBITCASTResults(N, Results, DAG);
15556     return;
15557   case ISD::VECREDUCE_ADD:
15558   case ISD::VECREDUCE_SMAX:
15559   case ISD::VECREDUCE_SMIN:
15560   case ISD::VECREDUCE_UMAX:
15561   case ISD::VECREDUCE_UMIN:
15562     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
15563     return;
15564 
15565   case ISD::CTPOP:
15566     Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
15567     return;
15568   case AArch64ISD::SADDV:
15569     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
15570     return;
15571   case AArch64ISD::UADDV:
15572     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
15573     return;
15574   case AArch64ISD::SMINV:
15575     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
15576     return;
15577   case AArch64ISD::UMINV:
15578     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
15579     return;
15580   case AArch64ISD::SMAXV:
15581     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
15582     return;
15583   case AArch64ISD::UMAXV:
15584     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
15585     return;
15586   case ISD::FP_TO_UINT:
15587   case ISD::FP_TO_SINT:
15588     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
15589     // Let normal code take care of it by not adding anything to Results.
15590     return;
15591   case ISD::ATOMIC_CMP_SWAP:
15592     ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
15593     return;
15594   case ISD::LOAD: {
15595     assert(SDValue(N, 0).getValueType() == MVT::i128 &&
15596            "unexpected load's value type");
15597     LoadSDNode *LoadNode = cast<LoadSDNode>(N);
15598     if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
15599       // Non-volatile loads are optimized later in AArch64's load/store
15600       // optimizer.
15601       return;
15602     }
15603 
15604     SDValue Result = DAG.getMemIntrinsicNode(
15605         AArch64ISD::LDP, SDLoc(N),
15606         DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
15607         {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
15608         LoadNode->getMemOperand());
15609 
15610     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
15611                                Result.getValue(0), Result.getValue(1));
15612     Results.append({Pair, Result.getValue(2) /* Chain */});
15613     return;
15614   }
15615   case ISD::EXTRACT_SUBVECTOR:
15616     ReplaceExtractSubVectorResults(N, Results, DAG);
15617     return;
15618   case ISD::INTRINSIC_WO_CHAIN: {
15619     EVT VT = N->getValueType(0);
15620     assert((VT == MVT::i8 || VT == MVT::i16) &&
15621            "custom lowering for unexpected type");
15622 
15623     ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
15624     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15625     switch (IntID) {
15626     default:
15627       return;
15628     case Intrinsic::aarch64_sve_clasta_n: {
15629       SDLoc DL(N);
15630       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15631       auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
15632                            N->getOperand(1), Op2, N->getOperand(3));
15633       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15634       return;
15635     }
15636     case Intrinsic::aarch64_sve_clastb_n: {
15637       SDLoc DL(N);
15638       auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
15639       auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
15640                            N->getOperand(1), Op2, N->getOperand(3));
15641       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15642       return;
15643     }
15644     case Intrinsic::aarch64_sve_lasta: {
15645       SDLoc DL(N);
15646       auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
15647                            N->getOperand(1), N->getOperand(2));
15648       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15649       return;
15650     }
15651     case Intrinsic::aarch64_sve_lastb: {
15652       SDLoc DL(N);
15653       auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
15654                            N->getOperand(1), N->getOperand(2));
15655       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
15656       return;
15657     }
15658     }
15659   }
15660   }
15661 }
15662 
useLoadStackGuardNode() const15663 bool AArch64TargetLowering::useLoadStackGuardNode() const {
15664   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
15665     return TargetLowering::useLoadStackGuardNode();
15666   return true;
15667 }
15668 
combineRepeatedFPDivisors() const15669 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
15670   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15671   // reciprocal if there are three or more FDIVs.
15672   return 3;
15673 }
15674 
15675 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const15676 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
15677   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
15678   // v4i16, v2i32 instead of to promote.
15679   if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
15680       VT == MVT::v1f32)
15681     return TypeWidenVector;
15682 
15683   return TargetLoweringBase::getPreferredVectorAction(VT);
15684 }
15685 
15686 // Loads and stores less than 128-bits are already atomic; ones above that
15687 // are doomed anyway, so defer to the default libcall and blame the OS when
15688 // things go wrong.
shouldExpandAtomicStoreInIR(StoreInst * SI) const15689 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15690   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
15691   return Size == 128;
15692 }
15693 
15694 // Loads and stores less than 128-bits are already atomic; ones above that
15695 // are doomed anyway, so defer to the default libcall and blame the OS when
15696 // things go wrong.
15697 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const15698 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15699   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
15700   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
15701 }
15702 
15703 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
15704 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const15705 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
15706   if (AI->isFloatingPointOperation())
15707     return AtomicExpansionKind::CmpXChg;
15708 
15709   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
15710   if (Size > 128) return AtomicExpansionKind::None;
15711   // Nand not supported in LSE.
15712   if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
15713   // Leave 128 bits to LLSC.
15714   return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
15715 }
15716 
15717 TargetLowering::AtomicExpansionKind
shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst * AI) const15718 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
15719     AtomicCmpXchgInst *AI) const {
15720   // If subtarget has LSE, leave cmpxchg intact for codegen.
15721   if (Subtarget->hasLSE())
15722     return AtomicExpansionKind::None;
15723   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
15724   // implement cmpxchg without spilling. If the address being exchanged is also
15725   // on the stack and close enough to the spill slot, this can lead to a
15726   // situation where the monitor always gets cleared and the atomic operation
15727   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
15728   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
15729     return AtomicExpansionKind::None;
15730   return AtomicExpansionKind::LLSC;
15731 }
15732 
emitLoadLinked(IRBuilder<> & Builder,Value * Addr,AtomicOrdering Ord) const15733 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
15734                                              AtomicOrdering Ord) const {
15735   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15736   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
15737   bool IsAcquire = isAcquireOrStronger(Ord);
15738 
15739   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
15740   // intrinsic must return {i64, i64} and we have to recombine them into a
15741   // single i128 here.
15742   if (ValTy->getPrimitiveSizeInBits() == 128) {
15743     Intrinsic::ID Int =
15744         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
15745     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
15746 
15747     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15748     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
15749 
15750     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
15751     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
15752     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
15753     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
15754     return Builder.CreateOr(
15755         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
15756   }
15757 
15758   Type *Tys[] = { Addr->getType() };
15759   Intrinsic::ID Int =
15760       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
15761   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
15762 
15763   Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
15764 
15765   const DataLayout &DL = M->getDataLayout();
15766   IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
15767   Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
15768 
15769   return Builder.CreateBitCast(Trunc, EltTy);
15770 }
15771 
emitAtomicCmpXchgNoStoreLLBalance(IRBuilder<> & Builder) const15772 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
15773     IRBuilder<> &Builder) const {
15774   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15775   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
15776 }
15777 
emitStoreConditional(IRBuilder<> & Builder,Value * Val,Value * Addr,AtomicOrdering Ord) const15778 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
15779                                                    Value *Val, Value *Addr,
15780                                                    AtomicOrdering Ord) const {
15781   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
15782   bool IsRelease = isReleaseOrStronger(Ord);
15783 
15784   // Since the intrinsics must have legal type, the i128 intrinsics take two
15785   // parameters: "i64, i64". We must marshal Val into the appropriate form
15786   // before the call.
15787   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
15788     Intrinsic::ID Int =
15789         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
15790     Function *Stxr = Intrinsic::getDeclaration(M, Int);
15791     Type *Int64Ty = Type::getInt64Ty(M->getContext());
15792 
15793     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
15794     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
15795     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
15796     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
15797   }
15798 
15799   Intrinsic::ID Int =
15800       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
15801   Type *Tys[] = { Addr->getType() };
15802   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
15803 
15804   const DataLayout &DL = M->getDataLayout();
15805   IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
15806   Val = Builder.CreateBitCast(Val, IntValTy);
15807 
15808   return Builder.CreateCall(Stxr,
15809                             {Builder.CreateZExtOrBitCast(
15810                                  Val, Stxr->getFunctionType()->getParamType(0)),
15811                              Addr});
15812 }
15813 
functionArgumentNeedsConsecutiveRegisters(Type * Ty,CallingConv::ID CallConv,bool isVarArg) const15814 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
15815     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15816   if (Ty->isArrayTy())
15817     return true;
15818 
15819   const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
15820   if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
15821     return true;
15822 
15823   return false;
15824 }
15825 
shouldNormalizeToSelectSequence(LLVMContext &,EVT) const15826 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
15827                                                             EVT) const {
15828   return false;
15829 }
15830 
UseTlsOffset(IRBuilder<> & IRB,unsigned Offset)15831 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
15832   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
15833   Function *ThreadPointerFunc =
15834       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
15835   return IRB.CreatePointerCast(
15836       IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
15837                              Offset),
15838       IRB.getInt8PtrTy()->getPointerTo(0));
15839 }
15840 
getIRStackGuard(IRBuilder<> & IRB) const15841 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
15842   // Android provides a fixed TLS slot for the stack cookie. See the definition
15843   // of TLS_SLOT_STACK_GUARD in
15844   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15845   if (Subtarget->isTargetAndroid())
15846     return UseTlsOffset(IRB, 0x28);
15847 
15848   // Fuchsia is similar.
15849   // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
15850   if (Subtarget->isTargetFuchsia())
15851     return UseTlsOffset(IRB, -0x10);
15852 
15853   return TargetLowering::getIRStackGuard(IRB);
15854 }
15855 
insertSSPDeclarations(Module & M) const15856 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
15857   // MSVC CRT provides functionalities for stack protection.
15858   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
15859     // MSVC CRT has a global variable holding security cookie.
15860     M.getOrInsertGlobal("__security_cookie",
15861                         Type::getInt8PtrTy(M.getContext()));
15862 
15863     // MSVC CRT has a function to validate security cookie.
15864     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
15865         "__security_check_cookie", Type::getVoidTy(M.getContext()),
15866         Type::getInt8PtrTy(M.getContext()));
15867     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
15868       F->setCallingConv(CallingConv::Win64);
15869       F->addAttribute(1, Attribute::AttrKind::InReg);
15870     }
15871     return;
15872   }
15873   TargetLowering::insertSSPDeclarations(M);
15874 }
15875 
getSDagStackGuard(const Module & M) const15876 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
15877   // MSVC CRT has a global variable holding security cookie.
15878   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15879     return M.getGlobalVariable("__security_cookie");
15880   return TargetLowering::getSDagStackGuard(M);
15881 }
15882 
getSSPStackGuardCheck(const Module & M) const15883 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
15884   // MSVC CRT has a function to validate security cookie.
15885   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
15886     return M.getFunction("__security_check_cookie");
15887   return TargetLowering::getSSPStackGuardCheck(M);
15888 }
15889 
getSafeStackPointerLocation(IRBuilder<> & IRB) const15890 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
15891   // Android provides a fixed TLS slot for the SafeStack pointer. See the
15892   // definition of TLS_SLOT_SAFESTACK in
15893   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
15894   if (Subtarget->isTargetAndroid())
15895     return UseTlsOffset(IRB, 0x48);
15896 
15897   // Fuchsia is similar.
15898   // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
15899   if (Subtarget->isTargetFuchsia())
15900     return UseTlsOffset(IRB, -0x8);
15901 
15902   return TargetLowering::getSafeStackPointerLocation(IRB);
15903 }
15904 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const15905 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
15906     const Instruction &AndI) const {
15907   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
15908   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
15909   // may be beneficial to sink in other cases, but we would have to check that
15910   // the cmp would not get folded into the br to form a cbz for these to be
15911   // beneficial.
15912   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
15913   if (!Mask)
15914     return false;
15915   return Mask->getValue().isPowerOf2();
15916 }
15917 
15918 bool AArch64TargetLowering::
shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X,ConstantSDNode * XC,ConstantSDNode * CC,SDValue Y,unsigned OldShiftOpcode,unsigned NewShiftOpcode,SelectionDAG & DAG) const15919     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15920         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
15921         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
15922         SelectionDAG &DAG) const {
15923   // Does baseline recommend not to perform the fold by default?
15924   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
15925           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
15926     return false;
15927   // Else, if this is a vector shift, prefer 'shl'.
15928   return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
15929 }
15930 
shouldExpandShift(SelectionDAG & DAG,SDNode * N) const15931 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
15932                                               SDNode *N) const {
15933   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15934       !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
15935     return false;
15936   return true;
15937 }
15938 
initializeSplitCSR(MachineBasicBlock * Entry) const15939 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15940   // Update IsSplitCSR in AArch64unctionInfo.
15941   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
15942   AFI->setIsSplitCSR(true);
15943 }
15944 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const15945 void AArch64TargetLowering::insertCopiesSplitCSR(
15946     MachineBasicBlock *Entry,
15947     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15948   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
15949   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15950   if (!IStart)
15951     return;
15952 
15953   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15954   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15955   MachineBasicBlock::iterator MBBI = Entry->begin();
15956   for (const MCPhysReg *I = IStart; *I; ++I) {
15957     const TargetRegisterClass *RC = nullptr;
15958     if (AArch64::GPR64RegClass.contains(*I))
15959       RC = &AArch64::GPR64RegClass;
15960     else if (AArch64::FPR64RegClass.contains(*I))
15961       RC = &AArch64::FPR64RegClass;
15962     else
15963       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15964 
15965     Register NewVR = MRI->createVirtualRegister(RC);
15966     // Create copy from CSR to a virtual register.
15967     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15968     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15969     // nounwind. If we want to generalize this later, we may need to emit
15970     // CFI pseudo-instructions.
15971     assert(Entry->getParent()->getFunction().hasFnAttribute(
15972                Attribute::NoUnwind) &&
15973            "Function should be nounwind in insertCopiesSplitCSR!");
15974     Entry->addLiveIn(*I);
15975     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15976         .addReg(*I);
15977 
15978     // Insert the copy-back instructions right before the terminator.
15979     for (auto *Exit : Exits)
15980       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15981               TII->get(TargetOpcode::COPY), *I)
15982           .addReg(NewVR);
15983   }
15984 }
15985 
isIntDivCheap(EVT VT,AttributeList Attr) const15986 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
15987   // Integer division on AArch64 is expensive. However, when aggressively
15988   // optimizing for code size, we prefer to use a div instruction, as it is
15989   // usually smaller than the alternative sequence.
15990   // The exception to this is vector division. Since AArch64 doesn't have vector
15991   // integer division, leaving the division as-is is a loss even in terms of
15992   // size, because it will have to be scalarized, while the alternative code
15993   // sequence can be performed in vector form.
15994   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
15995   return OptSize && !VT.isVector();
15996 }
15997 
preferIncOfAddToSubOfNot(EVT VT) const15998 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
15999   // We want inc-of-add for scalars and sub-of-not for vectors.
16000   return VT.isScalarInteger();
16001 }
16002 
enableAggressiveFMAFusion(EVT VT) const16003 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
16004   return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
16005 }
16006 
16007 unsigned
getVaListSizeInBits(const DataLayout & DL) const16008 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
16009   if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
16010     return getPointerTy(DL).getSizeInBits();
16011 
16012   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
16013 }
16014 
finalizeLowering(MachineFunction & MF) const16015 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
16016   MF.getFrameInfo().computeMaxCallFrameSize(MF);
16017   TargetLoweringBase::finalizeLowering(MF);
16018 }
16019 
16020 // Unlike X86, we let frame lowering assign offsets to all catch objects.
needsFixedCatchObjects() const16021 bool AArch64TargetLowering::needsFixedCatchObjects() const {
16022   return false;
16023 }
16024 
shouldLocalize(const MachineInstr & MI,const TargetTransformInfo * TTI) const16025 bool AArch64TargetLowering::shouldLocalize(
16026     const MachineInstr &MI, const TargetTransformInfo *TTI) const {
16027   switch (MI.getOpcode()) {
16028   case TargetOpcode::G_GLOBAL_VALUE: {
16029     // On Darwin, TLS global vars get selected into function calls, which
16030     // we don't want localized, as they can get moved into the middle of a
16031     // another call sequence.
16032     const GlobalValue &GV = *MI.getOperand(1).getGlobal();
16033     if (GV.isThreadLocal() && Subtarget->isTargetMachO())
16034       return false;
16035     break;
16036   }
16037   // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
16038   // localizable.
16039   case AArch64::ADRP:
16040   case AArch64::G_ADD_LOW:
16041     return true;
16042   default:
16043     break;
16044   }
16045   return TargetLoweringBase::shouldLocalize(MI, TTI);
16046 }
16047 
fallBackToDAGISel(const Instruction & Inst) const16048 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
16049   if (isa<ScalableVectorType>(Inst.getType()))
16050     return true;
16051 
16052   for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
16053     if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
16054       return true;
16055 
16056   if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
16057     if (isa<ScalableVectorType>(AI->getAllocatedType()))
16058       return true;
16059   }
16060 
16061   return false;
16062 }
16063 
16064 // Return the largest legal scalable vector type that matches VT's element type.
getContainerForFixedLengthVector(SelectionDAG & DAG,EVT VT)16065 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
16066   assert(VT.isFixedLengthVector() &&
16067          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16068          "Expected legal fixed length vector!");
16069   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
16070   default:
16071     llvm_unreachable("unexpected element type for SVE container");
16072   case MVT::i8:
16073     return EVT(MVT::nxv16i8);
16074   case MVT::i16:
16075     return EVT(MVT::nxv8i16);
16076   case MVT::i32:
16077     return EVT(MVT::nxv4i32);
16078   case MVT::i64:
16079     return EVT(MVT::nxv2i64);
16080   case MVT::f16:
16081     return EVT(MVT::nxv8f16);
16082   case MVT::f32:
16083     return EVT(MVT::nxv4f32);
16084   case MVT::f64:
16085     return EVT(MVT::nxv2f64);
16086   }
16087 }
16088 
16089 // Return a PTRUE with active lanes corresponding to the extent of VT.
getPredicateForFixedLengthVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)16090 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
16091                                                 EVT VT) {
16092   assert(VT.isFixedLengthVector() &&
16093          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16094          "Expected legal fixed length vector!");
16095 
16096   int PgPattern;
16097   switch (VT.getVectorNumElements()) {
16098   default:
16099     llvm_unreachable("unexpected element count for SVE predicate");
16100   case 1:
16101     PgPattern = AArch64SVEPredPattern::vl1;
16102     break;
16103   case 2:
16104     PgPattern = AArch64SVEPredPattern::vl2;
16105     break;
16106   case 4:
16107     PgPattern = AArch64SVEPredPattern::vl4;
16108     break;
16109   case 8:
16110     PgPattern = AArch64SVEPredPattern::vl8;
16111     break;
16112   case 16:
16113     PgPattern = AArch64SVEPredPattern::vl16;
16114     break;
16115   case 32:
16116     PgPattern = AArch64SVEPredPattern::vl32;
16117     break;
16118   case 64:
16119     PgPattern = AArch64SVEPredPattern::vl64;
16120     break;
16121   case 128:
16122     PgPattern = AArch64SVEPredPattern::vl128;
16123     break;
16124   case 256:
16125     PgPattern = AArch64SVEPredPattern::vl256;
16126     break;
16127   }
16128 
16129   // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
16130   // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
16131   // variants of instructions when available.
16132 
16133   MVT MaskVT;
16134   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
16135   default:
16136     llvm_unreachable("unexpected element type for SVE predicate");
16137   case MVT::i8:
16138     MaskVT = MVT::nxv16i1;
16139     break;
16140   case MVT::i16:
16141   case MVT::f16:
16142     MaskVT = MVT::nxv8i1;
16143     break;
16144   case MVT::i32:
16145   case MVT::f32:
16146     MaskVT = MVT::nxv4i1;
16147     break;
16148   case MVT::i64:
16149   case MVT::f64:
16150     MaskVT = MVT::nxv2i1;
16151     break;
16152   }
16153 
16154   return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
16155                      DAG.getTargetConstant(PgPattern, DL, MVT::i64));
16156 }
16157 
getPredicateForScalableVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)16158 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
16159                                              EVT VT) {
16160   assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16161          "Expected legal scalable vector!");
16162   auto PredTy = VT.changeVectorElementType(MVT::i1);
16163   return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
16164 }
16165 
getPredicateForVector(SelectionDAG & DAG,SDLoc & DL,EVT VT)16166 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
16167   if (VT.isFixedLengthVector())
16168     return getPredicateForFixedLengthVector(DAG, DL, VT);
16169 
16170   return getPredicateForScalableVector(DAG, DL, VT);
16171 }
16172 
16173 // Grow V to consume an entire SVE register.
convertToScalableVector(SelectionDAG & DAG,EVT VT,SDValue V)16174 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
16175   assert(VT.isScalableVector() &&
16176          "Expected to convert into a scalable vector!");
16177   assert(V.getValueType().isFixedLengthVector() &&
16178          "Expected a fixed length vector operand!");
16179   SDLoc DL(V);
16180   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16181   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
16182 }
16183 
16184 // Shrink V so it's just big enough to maintain a VT's worth of data.
convertFromScalableVector(SelectionDAG & DAG,EVT VT,SDValue V)16185 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
16186   assert(VT.isFixedLengthVector() &&
16187          "Expected to convert into a fixed length vector!");
16188   assert(V.getValueType().isScalableVector() &&
16189          "Expected a scalable vector operand!");
16190   SDLoc DL(V);
16191   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16192   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
16193 }
16194 
16195 // Convert all fixed length vector loads larger than NEON to masked_loads.
LowerFixedLengthVectorLoadToSVE(SDValue Op,SelectionDAG & DAG) const16196 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
16197     SDValue Op, SelectionDAG &DAG) const {
16198   auto Load = cast<LoadSDNode>(Op);
16199 
16200   SDLoc DL(Op);
16201   EVT VT = Op.getValueType();
16202   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16203 
16204   auto NewLoad = DAG.getMaskedLoad(
16205       ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
16206       getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
16207       Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
16208       Load->getExtensionType());
16209 
16210   auto Result = convertFromScalableVector(DAG, VT, NewLoad);
16211   SDValue MergedValues[2] = {Result, Load->getChain()};
16212   return DAG.getMergeValues(MergedValues, DL);
16213 }
16214 
16215 // Convert all fixed length vector stores larger than NEON to masked_stores.
LowerFixedLengthVectorStoreToSVE(SDValue Op,SelectionDAG & DAG) const16216 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
16217     SDValue Op, SelectionDAG &DAG) const {
16218   auto Store = cast<StoreSDNode>(Op);
16219 
16220   SDLoc DL(Op);
16221   EVT VT = Store->getValue().getValueType();
16222   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16223 
16224   auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
16225   return DAG.getMaskedStore(
16226       Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
16227       getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
16228       Store->getMemOperand(), Store->getAddressingMode(),
16229       Store->isTruncatingStore());
16230 }
16231 
LowerFixedLengthVectorIntDivideToSVE(SDValue Op,SelectionDAG & DAG) const16232 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
16233     SDValue Op, SelectionDAG &DAG) const {
16234   SDLoc dl(Op);
16235   EVT VT = Op.getValueType();
16236   EVT EltVT = VT.getVectorElementType();
16237 
16238   bool Signed = Op.getOpcode() == ISD::SDIV;
16239   unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
16240 
16241   // Scalable vector i32/i64 DIV is supported.
16242   if (EltVT == MVT::i32 || EltVT == MVT::i64)
16243     return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
16244 
16245   // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
16246   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16247   EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
16248   EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
16249   EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
16250 
16251   // Convert the operands to scalable vectors.
16252   SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16253   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16254 
16255   // Extend the scalable operands.
16256   unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16257   unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
16258   SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
16259   SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
16260   SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
16261   SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
16262 
16263   // Convert back to fixed vectors so the DIV can be further lowered.
16264   Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
16265   Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
16266   Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
16267   Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
16268   SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16269                                  Op0Lo, Op1Lo);
16270   SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
16271                                  Op0Hi, Op1Hi);
16272 
16273   // Convert again to scalable vectors to truncate.
16274   ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
16275   ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
16276   SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
16277                                        ResultLo, ResultHi);
16278 
16279   return convertFromScalableVector(DAG, VT, ScalableResult);
16280 }
16281 
LowerFixedLengthVectorIntExtendToSVE(SDValue Op,SelectionDAG & DAG) const16282 SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
16283     SDValue Op, SelectionDAG &DAG) const {
16284   EVT VT = Op.getValueType();
16285   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16286 
16287   SDLoc DL(Op);
16288   SDValue Val = Op.getOperand(0);
16289   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16290   Val = convertToScalableVector(DAG, ContainerVT, Val);
16291 
16292   bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
16293   unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
16294 
16295   // Repeatedly unpack Val until the result is of the desired element type.
16296   switch (ContainerVT.getSimpleVT().SimpleTy) {
16297   default:
16298     llvm_unreachable("unimplemented container type");
16299   case MVT::nxv16i8:
16300     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
16301     if (VT.getVectorElementType() == MVT::i16)
16302       break;
16303     LLVM_FALLTHROUGH;
16304   case MVT::nxv8i16:
16305     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
16306     if (VT.getVectorElementType() == MVT::i32)
16307       break;
16308     LLVM_FALLTHROUGH;
16309   case MVT::nxv4i32:
16310     Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
16311     assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
16312     break;
16313   }
16314 
16315   return convertFromScalableVector(DAG, VT, Val);
16316 }
16317 
LowerFixedLengthVectorTruncateToSVE(SDValue Op,SelectionDAG & DAG) const16318 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
16319     SDValue Op, SelectionDAG &DAG) const {
16320   EVT VT = Op.getValueType();
16321   assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
16322 
16323   SDLoc DL(Op);
16324   SDValue Val = Op.getOperand(0);
16325   EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
16326   Val = convertToScalableVector(DAG, ContainerVT, Val);
16327 
16328   // Repeatedly truncate Val until the result is of the desired element type.
16329   switch (ContainerVT.getSimpleVT().SimpleTy) {
16330   default:
16331     llvm_unreachable("unimplemented container type");
16332   case MVT::nxv2i64:
16333     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
16334     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
16335     if (VT.getVectorElementType() == MVT::i32)
16336       break;
16337     LLVM_FALLTHROUGH;
16338   case MVT::nxv4i32:
16339     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
16340     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
16341     if (VT.getVectorElementType() == MVT::i16)
16342       break;
16343     LLVM_FALLTHROUGH;
16344   case MVT::nxv8i16:
16345     Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
16346     Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
16347     assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
16348     break;
16349   }
16350 
16351   return convertFromScalableVector(DAG, VT, Val);
16352 }
16353 
16354 // Convert vector operation 'Op' to an equivalent predicated operation whereby
16355 // the original operation's type is used to construct a suitable predicate.
16356 // NOTE: The results for inactive lanes are undefined.
LowerToPredicatedOp(SDValue Op,SelectionDAG & DAG,unsigned NewOp,bool OverrideNEON) const16357 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
16358                                                    SelectionDAG &DAG,
16359                                                    unsigned NewOp,
16360                                                    bool OverrideNEON) const {
16361   EVT VT = Op.getValueType();
16362   SDLoc DL(Op);
16363   auto Pg = getPredicateForVector(DAG, DL, VT);
16364 
16365   if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
16366     EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16367 
16368     // Create list of operands by converting existing ones to scalable types.
16369     SmallVector<SDValue, 4> Operands = {Pg};
16370     for (const SDValue &V : Op->op_values()) {
16371       if (isa<CondCodeSDNode>(V)) {
16372         Operands.push_back(V);
16373         continue;
16374       }
16375 
16376       if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
16377         EVT VTArg = VTNode->getVT().getVectorElementType();
16378         EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
16379         Operands.push_back(DAG.getValueType(NewVTArg));
16380         continue;
16381       }
16382 
16383       assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
16384              "Only fixed length vectors are supported!");
16385       Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
16386     }
16387 
16388     if (isMergePassthruOpcode(NewOp))
16389       Operands.push_back(DAG.getUNDEF(ContainerVT));
16390 
16391     auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
16392     return convertFromScalableVector(DAG, VT, ScalableRes);
16393   }
16394 
16395   assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
16396 
16397   SmallVector<SDValue, 4> Operands = {Pg};
16398   for (const SDValue &V : Op->op_values()) {
16399     assert((!V.getValueType().isVector() ||
16400             V.getValueType().isScalableVector()) &&
16401            "Only scalable vectors are supported!");
16402     Operands.push_back(V);
16403   }
16404 
16405   if (isMergePassthruOpcode(NewOp))
16406     Operands.push_back(DAG.getUNDEF(VT));
16407 
16408   return DAG.getNode(NewOp, DL, VT, Operands);
16409 }
16410 
16411 // If a fixed length vector operation has no side effects when applied to
16412 // undefined elements, we can safely use scalable vectors to perform the same
16413 // operation without needing to worry about predication.
LowerToScalableOp(SDValue Op,SelectionDAG & DAG) const16414 SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
16415                                                  SelectionDAG &DAG) const {
16416   EVT VT = Op.getValueType();
16417   assert(useSVEForFixedLengthVectorVT(VT) &&
16418          "Only expected to lower fixed length vector operation!");
16419   EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
16420 
16421   // Create list of operands by converting existing ones to scalable types.
16422   SmallVector<SDValue, 4> Ops;
16423   for (const SDValue &V : Op->op_values()) {
16424     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
16425 
16426     // Pass through non-vector operands.
16427     if (!V.getValueType().isVector()) {
16428       Ops.push_back(V);
16429       continue;
16430     }
16431 
16432     // "cast" fixed length vector to a scalable vector.
16433     assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
16434            "Only fixed length vectors are supported!");
16435     Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
16436   }
16437 
16438   auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
16439   return convertFromScalableVector(DAG, VT, ScalableRes);
16440 }
16441 
LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,SelectionDAG & DAG) const16442 SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
16443     SelectionDAG &DAG) const {
16444   SDLoc DL(ScalarOp);
16445   SDValue AccOp = ScalarOp.getOperand(0);
16446   SDValue VecOp = ScalarOp.getOperand(1);
16447   EVT SrcVT = VecOp.getValueType();
16448   EVT ResVT = SrcVT.getVectorElementType();
16449 
16450   // Only fixed length FADDA handled for now.
16451   if (!useSVEForFixedLengthVectorVT(SrcVT, /*OverrideNEON=*/true))
16452     return SDValue();
16453 
16454   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
16455   EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
16456   SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
16457 
16458   // Convert operands to Scalable.
16459   AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
16460                       DAG.getUNDEF(ContainerVT), AccOp, Zero);
16461   VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
16462 
16463   // Perform reduction.
16464   SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
16465                             Pg, AccOp, VecOp);
16466 
16467   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
16468 }
16469 
LowerPredReductionToSVE(SDValue ReduceOp,SelectionDAG & DAG) const16470 SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
16471                                                        SelectionDAG &DAG) const {
16472   SDLoc DL(ReduceOp);
16473   SDValue Op = ReduceOp.getOperand(0);
16474   EVT OpVT = Op.getValueType();
16475   EVT VT = ReduceOp.getValueType();
16476 
16477   if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
16478     return SDValue();
16479 
16480   SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
16481 
16482   switch (ReduceOp.getOpcode()) {
16483   default:
16484     return SDValue();
16485   case ISD::VECREDUCE_OR:
16486     return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
16487   case ISD::VECREDUCE_AND: {
16488     Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
16489     return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
16490   }
16491   case ISD::VECREDUCE_XOR: {
16492     SDValue ID =
16493         DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
16494     SDValue Cntp =
16495         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
16496     return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
16497   }
16498   }
16499 
16500   return SDValue();
16501 }
16502 
LowerReductionToSVE(unsigned Opcode,SDValue ScalarOp,SelectionDAG & DAG) const16503 SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
16504                                                    SDValue ScalarOp,
16505                                                    SelectionDAG &DAG) const {
16506   SDLoc DL(ScalarOp);
16507   SDValue VecOp = ScalarOp.getOperand(0);
16508   EVT SrcVT = VecOp.getValueType();
16509 
16510   if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
16511     EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
16512     VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
16513   }
16514 
16515   // UADDV always returns an i64 result.
16516   EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
16517                                                    SrcVT.getVectorElementType();
16518 
16519   SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
16520   SDValue Rdx = DAG.getNode(Opcode, DL, getPackedSVEVectorVT(ResVT), Pg, VecOp);
16521   SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
16522                             Rdx, DAG.getConstant(0, DL, MVT::i64));
16523 
16524   // The VEC_REDUCE nodes expect an element size result.
16525   if (ResVT != ScalarOp.getValueType())
16526     Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
16527 
16528   return Res;
16529 }
16530 
16531 SDValue
LowerFixedLengthVectorSelectToSVE(SDValue Op,SelectionDAG & DAG) const16532 AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
16533     SelectionDAG &DAG) const {
16534   EVT VT = Op.getValueType();
16535   SDLoc DL(Op);
16536 
16537   EVT InVT = Op.getOperand(1).getValueType();
16538   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16539   SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
16540   SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
16541 
16542   // Convert the mask to a predicated (NOTE: We don't need to worry about
16543   // inactive lanes since VSELECT is safe when given undefined elements).
16544   EVT MaskVT = Op.getOperand(0).getValueType();
16545   EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
16546   auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
16547   Mask = DAG.getNode(ISD::TRUNCATE, DL,
16548                      MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
16549 
16550   auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
16551                                 Mask, Op1, Op2);
16552 
16553   return convertFromScalableVector(DAG, VT, ScalableRes);
16554 }
16555 
LowerFixedLengthVectorSetccToSVE(SDValue Op,SelectionDAG & DAG) const16556 SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
16557     SDValue Op, SelectionDAG &DAG) const {
16558   SDLoc DL(Op);
16559   EVT InVT = Op.getOperand(0).getValueType();
16560   EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
16561 
16562   assert(useSVEForFixedLengthVectorVT(InVT) &&
16563          "Only expected to lower fixed length vector operation!");
16564   assert(Op.getValueType() == InVT.changeTypeToInteger() &&
16565          "Expected integer result of the same bit length as the inputs!");
16566 
16567   // Expand floating point vector comparisons.
16568   if (InVT.isFloatingPoint())
16569     return SDValue();
16570 
16571   auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
16572   auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
16573   auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
16574 
16575   EVT CmpVT = Pg.getValueType();
16576   auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
16577                          {Pg, Op1, Op2, Op.getOperand(2)});
16578 
16579   EVT PromoteVT = ContainerVT.changeTypeToInteger();
16580   auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
16581   return convertFromScalableVector(DAG, Op.getValueType(), Promote);
16582 }
16583