1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the AArch64TargetLowering class.
11 //===----------------------------------------------------------------------===//
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"
94 using namespace llvm::PatternMatch;
96 #define DEBUG_TYPE "aarch64-lower"
98 STATISTIC(NumTailCalls, "Number of tail calls");
99 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
100 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
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"),
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
119 /// Returns true if VT's elements occupy the lowest bit positions of its
120 /// associated register class without any intervening space.
122 /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
123 /// same register class, but only nxv8f16 can be treated as a packed vector.
124 static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
125 assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
126 "Expected legal vector type!");
127 return VT.isFixedLengthVector() ||
128 VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
131 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
132 const AArch64Subtarget &STI)
133 : TargetLowering(TM), Subtarget(&STI) {
134 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
135 // we have to make something up. Arbitrarily, choose ZeroOrOne.
136 setBooleanContents(ZeroOrOneBooleanContent);
137 // When comparing vectors the result sets the different elements in the
138 // vector to all-one or all-zero.
139 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
141 // Set up the register classes.
142 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
143 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
145 if (Subtarget->hasFPARMv8()) {
146 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
147 addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
148 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
149 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
150 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
153 if (Subtarget->hasNEON()) {
154 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
155 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
156 // Someone set us up the NEON.
157 addDRTypeForNEON(MVT::v2f32);
158 addDRTypeForNEON(MVT::v8i8);
159 addDRTypeForNEON(MVT::v4i16);
160 addDRTypeForNEON(MVT::v2i32);
161 addDRTypeForNEON(MVT::v1i64);
162 addDRTypeForNEON(MVT::v1f64);
163 addDRTypeForNEON(MVT::v4f16);
164 addDRTypeForNEON(MVT::v4bf16);
166 addQRTypeForNEON(MVT::v4f32);
167 addQRTypeForNEON(MVT::v2f64);
168 addQRTypeForNEON(MVT::v16i8);
169 addQRTypeForNEON(MVT::v8i16);
170 addQRTypeForNEON(MVT::v4i32);
171 addQRTypeForNEON(MVT::v2i64);
172 addQRTypeForNEON(MVT::v8f16);
173 addQRTypeForNEON(MVT::v8bf16);
176 if (Subtarget->hasSVE()) {
177 // Add legal sve predicate types
178 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
179 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
180 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
181 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
183 // Add legal sve data types
184 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
185 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
186 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
187 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
189 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
190 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
191 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
192 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
193 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
194 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
196 if (Subtarget->hasBF16()) {
197 addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
198 addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
199 addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
202 if (useSVEForFixedLengthVectors()) {
203 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
204 if (useSVEForFixedLengthVectorVT(VT))
205 addRegisterClass(VT, &AArch64::ZPRRegClass);
207 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
208 if (useSVEForFixedLengthVectorVT(VT))
209 addRegisterClass(VT, &AArch64::ZPRRegClass);
212 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
213 setOperationAction(ISD::SADDSAT, VT, Legal);
214 setOperationAction(ISD::UADDSAT, VT, Legal);
215 setOperationAction(ISD::SSUBSAT, VT, Legal);
216 setOperationAction(ISD::USUBSAT, VT, Legal);
217 setOperationAction(ISD::UREM, VT, Expand);
218 setOperationAction(ISD::SREM, VT, Expand);
219 setOperationAction(ISD::SDIVREM, VT, Expand);
220 setOperationAction(ISD::UDIVREM, VT, Expand);
224 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
225 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
226 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
229 { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
231 setCondCodeAction(ISD::SETO, VT, Expand);
232 setCondCodeAction(ISD::SETOLT, VT, Expand);
233 setCondCodeAction(ISD::SETOLE, VT, Expand);
234 setCondCodeAction(ISD::SETULT, VT, Expand);
235 setCondCodeAction(ISD::SETULE, VT, Expand);
236 setCondCodeAction(ISD::SETUGE, VT, Expand);
237 setCondCodeAction(ISD::SETUGT, VT, Expand);
238 setCondCodeAction(ISD::SETUEQ, VT, Expand);
239 setCondCodeAction(ISD::SETUNE, VT, Expand);
243 // Compute derived properties from the register classes
244 computeRegisterProperties(Subtarget->getRegisterInfo());
246 // Provide all sorts of operation actions
247 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
248 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
249 setOperationAction(ISD::SETCC, MVT::i32, Custom);
250 setOperationAction(ISD::SETCC, MVT::i64, Custom);
251 setOperationAction(ISD::SETCC, MVT::f16, Custom);
252 setOperationAction(ISD::SETCC, MVT::f32, Custom);
253 setOperationAction(ISD::SETCC, MVT::f64, Custom);
254 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
255 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
256 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
257 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
258 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
259 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
260 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
261 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
262 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
263 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
264 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
265 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
266 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
267 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
268 setOperationAction(ISD::SELECT, MVT::i32, Custom);
269 setOperationAction(ISD::SELECT, MVT::i64, Custom);
270 setOperationAction(ISD::SELECT, MVT::f16, Custom);
271 setOperationAction(ISD::SELECT, MVT::f32, Custom);
272 setOperationAction(ISD::SELECT, MVT::f64, Custom);
273 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
274 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
275 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
276 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
277 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
278 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
279 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
285 setOperationAction(ISD::FREM, MVT::f32, Expand);
286 setOperationAction(ISD::FREM, MVT::f64, Expand);
287 setOperationAction(ISD::FREM, MVT::f80, Expand);
289 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
291 // Custom lowering hooks are needed for XOR
292 // to fold it into CSINC/CSINV.
293 setOperationAction(ISD::XOR, MVT::i32, Custom);
294 setOperationAction(ISD::XOR, MVT::i64, Custom);
296 // Virtually no operation on f128 is legal, but LLVM can't expand them when
297 // there's a valid register class, so we need custom operations in most cases.
298 setOperationAction(ISD::FABS, MVT::f128, Expand);
299 setOperationAction(ISD::FADD, MVT::f128, Custom);
300 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
301 setOperationAction(ISD::FCOS, MVT::f128, Expand);
302 setOperationAction(ISD::FDIV, MVT::f128, Custom);
303 setOperationAction(ISD::FMA, MVT::f128, Expand);
304 setOperationAction(ISD::FMUL, MVT::f128, Custom);
305 setOperationAction(ISD::FNEG, MVT::f128, Expand);
306 setOperationAction(ISD::FPOW, MVT::f128, Expand);
307 setOperationAction(ISD::FREM, MVT::f128, Expand);
308 setOperationAction(ISD::FRINT, MVT::f128, Expand);
309 setOperationAction(ISD::FSIN, MVT::f128, Expand);
310 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
311 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
312 setOperationAction(ISD::FSUB, MVT::f128, Custom);
313 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
314 setOperationAction(ISD::SETCC, MVT::f128, Custom);
315 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
316 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
317 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
318 setOperationAction(ISD::SELECT, MVT::f128, Custom);
319 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
320 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
322 // Lowering for many of the conversions is actually specified by the non-f128
323 // type. The LowerXXX function will be trivial when f128 isn't involved.
324 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
325 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
326 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
327 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
328 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
329 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
330 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
331 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
332 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
333 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
334 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
335 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
336 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
337 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
338 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
339 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
340 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
341 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
342 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
343 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
344 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
345 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
346 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
347 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
348 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
349 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
350 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
351 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
353 // Variable arguments.
354 setOperationAction(ISD::VASTART, MVT::Other, Custom);
355 setOperationAction(ISD::VAARG, MVT::Other, Custom);
356 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
357 setOperationAction(ISD::VAEND, MVT::Other, Expand);
359 // Variable-sized objects.
360 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
361 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
363 if (Subtarget->isTargetWindows())
364 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
366 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
368 // Constant pool entries
369 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
372 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
374 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
375 setOperationAction(ISD::ADDC, MVT::i32, Custom);
376 setOperationAction(ISD::ADDE, MVT::i32, Custom);
377 setOperationAction(ISD::SUBC, MVT::i32, Custom);
378 setOperationAction(ISD::SUBE, MVT::i32, Custom);
379 setOperationAction(ISD::ADDC, MVT::i64, Custom);
380 setOperationAction(ISD::ADDE, MVT::i64, Custom);
381 setOperationAction(ISD::SUBC, MVT::i64, Custom);
382 setOperationAction(ISD::SUBE, MVT::i64, Custom);
384 // AArch64 lacks both left-rotate and popcount instructions.
385 setOperationAction(ISD::ROTL, MVT::i32, Expand);
386 setOperationAction(ISD::ROTL, MVT::i64, Expand);
387 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
388 setOperationAction(ISD::ROTL, VT, Expand);
389 setOperationAction(ISD::ROTR, VT, Expand);
392 // AArch64 doesn't have i32 MULH{S|U}.
393 setOperationAction(ISD::MULHU, MVT::i32, Expand);
394 setOperationAction(ISD::MULHS, MVT::i32, Expand);
396 // AArch64 doesn't have {U|S}MUL_LOHI.
397 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
398 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
400 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
401 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
402 setOperationAction(ISD::CTPOP, MVT::i128, Custom);
404 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
405 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
406 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
407 setOperationAction(ISD::SDIVREM, VT, Expand);
408 setOperationAction(ISD::UDIVREM, VT, Expand);
410 setOperationAction(ISD::SREM, MVT::i32, Expand);
411 setOperationAction(ISD::SREM, MVT::i64, Expand);
412 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
413 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
414 setOperationAction(ISD::UREM, MVT::i32, Expand);
415 setOperationAction(ISD::UREM, MVT::i64, Expand);
417 // Custom lower Add/Sub/Mul with overflow.
418 setOperationAction(ISD::SADDO, MVT::i32, Custom);
419 setOperationAction(ISD::SADDO, MVT::i64, Custom);
420 setOperationAction(ISD::UADDO, MVT::i32, Custom);
421 setOperationAction(ISD::UADDO, MVT::i64, Custom);
422 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
423 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
424 setOperationAction(ISD::USUBO, MVT::i32, Custom);
425 setOperationAction(ISD::USUBO, MVT::i64, Custom);
426 setOperationAction(ISD::SMULO, MVT::i32, Custom);
427 setOperationAction(ISD::SMULO, MVT::i64, Custom);
428 setOperationAction(ISD::UMULO, MVT::i32, Custom);
429 setOperationAction(ISD::UMULO, MVT::i64, Custom);
431 setOperationAction(ISD::FSIN, MVT::f32, Expand);
432 setOperationAction(ISD::FSIN, MVT::f64, Expand);
433 setOperationAction(ISD::FCOS, MVT::f32, Expand);
434 setOperationAction(ISD::FCOS, MVT::f64, Expand);
435 setOperationAction(ISD::FPOW, MVT::f32, Expand);
436 setOperationAction(ISD::FPOW, MVT::f64, Expand);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439 if (Subtarget->hasFullFP16())
440 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
442 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
444 setOperationAction(ISD::FREM, MVT::f16, Promote);
445 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
446 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
447 setOperationAction(ISD::FPOW, MVT::f16, Promote);
448 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
449 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
450 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
451 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
452 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
453 setOperationAction(ISD::FCOS, MVT::f16, Promote);
454 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
455 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
456 setOperationAction(ISD::FSIN, MVT::f16, Promote);
457 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
458 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
459 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
460 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
461 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
462 setOperationAction(ISD::FEXP, MVT::f16, Promote);
463 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
464 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
465 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
466 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
467 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
468 setOperationAction(ISD::FLOG, MVT::f16, Promote);
469 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
470 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
471 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
472 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
473 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
474 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
475 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
476 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
478 if (!Subtarget->hasFullFP16()) {
479 setOperationAction(ISD::SELECT, MVT::f16, Promote);
480 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
481 setOperationAction(ISD::SETCC, MVT::f16, Promote);
482 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
483 setOperationAction(ISD::FADD, MVT::f16, Promote);
484 setOperationAction(ISD::FSUB, MVT::f16, Promote);
485 setOperationAction(ISD::FMUL, MVT::f16, Promote);
486 setOperationAction(ISD::FDIV, MVT::f16, Promote);
487 setOperationAction(ISD::FMA, MVT::f16, Promote);
488 setOperationAction(ISD::FNEG, MVT::f16, Promote);
489 setOperationAction(ISD::FABS, MVT::f16, Promote);
490 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
491 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
492 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
493 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
494 setOperationAction(ISD::FRINT, MVT::f16, Promote);
495 setOperationAction(ISD::FROUND, MVT::f16, Promote);
496 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
497 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
498 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
499 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
500 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
502 // promote v4f16 to v4f32 when that is known to be safe.
503 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
504 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
505 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
506 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
507 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
508 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
509 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
510 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
512 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
513 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
514 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
515 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
516 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
517 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
518 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
519 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
520 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
521 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
522 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
523 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
526 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
528 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
529 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
530 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
531 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
532 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
533 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
534 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
535 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
536 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
537 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
538 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
539 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
540 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
541 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
542 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
543 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
544 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
545 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
546 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
547 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
550 // AArch64 has implementations of a lot of rounding-like FP operations.
551 for (MVT Ty : {MVT::f32, MVT::f64}) {
552 setOperationAction(ISD::FFLOOR, Ty, Legal);
553 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
554 setOperationAction(ISD::FCEIL, Ty, Legal);
555 setOperationAction(ISD::FRINT, Ty, Legal);
556 setOperationAction(ISD::FTRUNC, Ty, Legal);
557 setOperationAction(ISD::FROUND, Ty, Legal);
558 setOperationAction(ISD::FMINNUM, Ty, Legal);
559 setOperationAction(ISD::FMAXNUM, Ty, Legal);
560 setOperationAction(ISD::FMINIMUM, Ty, Legal);
561 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
562 setOperationAction(ISD::LROUND, Ty, Legal);
563 setOperationAction(ISD::LLROUND, Ty, Legal);
564 setOperationAction(ISD::LRINT, Ty, Legal);
565 setOperationAction(ISD::LLRINT, Ty, Legal);
568 if (Subtarget->hasFullFP16()) {
569 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
570 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
571 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
572 setOperationAction(ISD::FRINT, MVT::f16, Legal);
573 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
574 setOperationAction(ISD::FROUND, MVT::f16, Legal);
575 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
576 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
577 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
578 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
581 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
583 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
585 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
586 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
587 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
588 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
589 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
591 // 128-bit loads and stores can be done without expanding
592 setOperationAction(ISD::LOAD, MVT::i128, Custom);
593 setOperationAction(ISD::STORE, MVT::i128, Custom);
595 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
596 // custom lowering, as there are no un-paired non-temporal stores and
597 // legalization will break up 256 bit inputs.
598 setOperationAction(ISD::STORE, MVT::v32i8, Custom);
599 setOperationAction(ISD::STORE, MVT::v16i16, Custom);
600 setOperationAction(ISD::STORE, MVT::v16f16, Custom);
601 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
602 setOperationAction(ISD::STORE, MVT::v8f32, Custom);
603 setOperationAction(ISD::STORE, MVT::v4f64, Custom);
604 setOperationAction(ISD::STORE, MVT::v4i64, Custom);
606 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
607 // This requires the Performance Monitors extension.
608 if (Subtarget->hasPerfMon())
609 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
611 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
612 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
613 // Issue __sincos_stret if available.
614 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
615 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
617 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
618 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
621 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
622 // MSVCRT doesn't have powi; fall back to pow
623 setLibcallName(RTLIB::POWI_F32, nullptr);
624 setLibcallName(RTLIB::POWI_F64, nullptr);
627 // Make floating-point constants legal for the large code model, so they don't
628 // become loads from the constant pool.
629 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
630 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
631 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
634 // AArch64 does not have floating-point extending loads, i1 sign-extending
635 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
636 for (MVT VT : MVT::fp_valuetypes()) {
637 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
638 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
639 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
640 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
642 for (MVT VT : MVT::integer_valuetypes())
643 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
645 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
646 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
647 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
648 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
649 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
650 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
651 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
653 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
654 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
655 setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
657 // Indexed loads and stores are supported.
658 for (unsigned im = (unsigned)ISD::PRE_INC;
659 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
660 setIndexedLoadAction(im, MVT::i8, Legal);
661 setIndexedLoadAction(im, MVT::i16, Legal);
662 setIndexedLoadAction(im, MVT::i32, Legal);
663 setIndexedLoadAction(im, MVT::i64, Legal);
664 setIndexedLoadAction(im, MVT::f64, Legal);
665 setIndexedLoadAction(im, MVT::f32, Legal);
666 setIndexedLoadAction(im, MVT::f16, Legal);
667 setIndexedLoadAction(im, MVT::bf16, Legal);
668 setIndexedStoreAction(im, MVT::i8, Legal);
669 setIndexedStoreAction(im, MVT::i16, Legal);
670 setIndexedStoreAction(im, MVT::i32, Legal);
671 setIndexedStoreAction(im, MVT::i64, Legal);
672 setIndexedStoreAction(im, MVT::f64, Legal);
673 setIndexedStoreAction(im, MVT::f32, Legal);
674 setIndexedStoreAction(im, MVT::f16, Legal);
675 setIndexedStoreAction(im, MVT::bf16, Legal);
679 setOperationAction(ISD::TRAP, MVT::Other, Legal);
680 if (Subtarget->isTargetWindows())
681 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
683 // We combine OR nodes for bitfield operations.
684 setTargetDAGCombine(ISD::OR);
685 // Try to create BICs for vector ANDs.
686 setTargetDAGCombine(ISD::AND);
688 // Vector add and sub nodes may conceal a high-half opportunity.
689 // Also, try to fold ADD into CSINC/CSINV..
690 setTargetDAGCombine(ISD::ADD);
691 setTargetDAGCombine(ISD::SUB);
692 setTargetDAGCombine(ISD::SRL);
693 setTargetDAGCombine(ISD::XOR);
694 setTargetDAGCombine(ISD::SINT_TO_FP);
695 setTargetDAGCombine(ISD::UINT_TO_FP);
697 setTargetDAGCombine(ISD::FP_TO_SINT);
698 setTargetDAGCombine(ISD::FP_TO_UINT);
699 setTargetDAGCombine(ISD::FDIV);
701 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
703 setTargetDAGCombine(ISD::ANY_EXTEND);
704 setTargetDAGCombine(ISD::ZERO_EXTEND);
705 setTargetDAGCombine(ISD::SIGN_EXTEND);
706 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
707 setTargetDAGCombine(ISD::CONCAT_VECTORS);
708 setTargetDAGCombine(ISD::STORE);
709 if (Subtarget->supportsAddressTopByteIgnored())
710 setTargetDAGCombine(ISD::LOAD);
712 setTargetDAGCombine(ISD::MUL);
714 setTargetDAGCombine(ISD::SELECT);
715 setTargetDAGCombine(ISD::VSELECT);
717 setTargetDAGCombine(ISD::INTRINSIC_VOID);
718 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
719 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
721 setTargetDAGCombine(ISD::GlobalAddress);
723 // In case of strict alignment, avoid an excessive number of byte wide stores.
724 MaxStoresPerMemsetOptSize = 8;
725 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
726 ? MaxStoresPerMemsetOptSize : 32;
728 MaxGluedStoresPerMemcpy = 4;
729 MaxStoresPerMemcpyOptSize = 4;
730 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
731 ? MaxStoresPerMemcpyOptSize : 16;
733 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
735 MaxLoadsPerMemcmpOptSize = 4;
736 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
737 ? MaxLoadsPerMemcmpOptSize : 8;
739 setStackPointerRegisterToSaveRestore(AArch64::SP);
741 setSchedulingPreference(Sched::Hybrid);
743 EnableExtLdPromotion = true;
745 // Set required alignment.
746 setMinFunctionAlignment(Align(4));
747 // Set preferred alignments.
748 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
749 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
751 // Only change the limit for entries in a jump table if specified by
752 // the sub target, but not at the command line.
753 unsigned MaxJT = STI.getMaximumJumpTableSize();
754 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
755 setMaximumJumpTableSize(MaxJT);
757 setHasExtractBitsInsn(true);
759 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
761 if (Subtarget->hasNEON()) {
762 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
763 // silliness like this:
764 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
765 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
766 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
767 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
768 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
769 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
770 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
771 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
772 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
773 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
774 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
775 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
776 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
777 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
778 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
779 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
780 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
781 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
782 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
783 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
784 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
785 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
786 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
787 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
788 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
790 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
791 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
792 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
793 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
794 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
796 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
798 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
799 // elements smaller than i32, so promote the input to i32 first.
800 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
801 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
802 // i8 vector elements also need promotion to i32 for v8i8
803 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
804 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
805 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
806 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
807 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
808 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
809 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
810 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
811 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
812 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
813 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
815 if (Subtarget->hasFullFP16()) {
816 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
817 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
818 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
819 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
821 // when AArch64 doesn't have fullfp16 support, promote the input
823 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
824 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
825 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
826 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
829 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
830 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
832 // AArch64 doesn't have MUL.2d:
833 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
834 // Custom handling for some quad-vector types to detect MULL.
835 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
836 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
837 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
839 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
840 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
842 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
843 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
844 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
845 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
846 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
849 setOperationAction(ISD::SADDSAT, VT, Legal);
850 setOperationAction(ISD::UADDSAT, VT, Legal);
851 setOperationAction(ISD::SSUBSAT, VT, Legal);
852 setOperationAction(ISD::USUBSAT, VT, Legal);
854 setOperationAction(ISD::TRUNCATE, VT, Custom);
856 for (MVT VT : { MVT::v4f16, MVT::v2f32,
857 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
858 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
859 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
862 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
863 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
864 // Likewise, narrowing and extending vector loads/stores aren't handled
866 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
867 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
869 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
870 setOperationAction(ISD::MULHS, VT, Legal);
871 setOperationAction(ISD::MULHU, VT, Legal);
873 setOperationAction(ISD::MULHS, VT, Expand);
874 setOperationAction(ISD::MULHU, VT, Expand);
876 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
877 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
879 setOperationAction(ISD::BSWAP, VT, Expand);
880 setOperationAction(ISD::CTTZ, VT, Expand);
882 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
883 setTruncStoreAction(VT, InnerVT, Expand);
884 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
885 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
886 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
890 // AArch64 has implementations of a lot of rounding-like FP operations.
891 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
892 setOperationAction(ISD::FFLOOR, Ty, Legal);
893 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
894 setOperationAction(ISD::FCEIL, Ty, Legal);
895 setOperationAction(ISD::FRINT, Ty, Legal);
896 setOperationAction(ISD::FTRUNC, Ty, Legal);
897 setOperationAction(ISD::FROUND, Ty, Legal);
900 if (Subtarget->hasFullFP16()) {
901 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
902 setOperationAction(ISD::FFLOOR, Ty, Legal);
903 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
904 setOperationAction(ISD::FCEIL, Ty, Legal);
905 setOperationAction(ISD::FRINT, Ty, Legal);
906 setOperationAction(ISD::FTRUNC, Ty, Legal);
907 setOperationAction(ISD::FROUND, Ty, Legal);
911 if (Subtarget->hasSVE())
912 setOperationAction(ISD::VSCALE, MVT::i32, Custom);
914 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
917 if (Subtarget->hasSVE()) {
918 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
919 // splat of 0 or undef) once vector selects supported in SVE codegen. See
920 // D68877 for more details.
921 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
922 if (isTypeLegal(VT)) {
923 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
924 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
925 setOperationAction(ISD::SELECT, VT, Custom);
926 setOperationAction(ISD::SDIV, VT, Custom);
927 setOperationAction(ISD::UDIV, VT, Custom);
928 setOperationAction(ISD::SMIN, VT, Custom);
929 setOperationAction(ISD::UMIN, VT, Custom);
930 setOperationAction(ISD::SMAX, VT, Custom);
931 setOperationAction(ISD::UMAX, VT, Custom);
932 setOperationAction(ISD::SHL, VT, Custom);
933 setOperationAction(ISD::SRL, VT, Custom);
934 setOperationAction(ISD::SRA, VT, Custom);
935 if (VT.getScalarType() == MVT::i1) {
936 setOperationAction(ISD::SETCC, VT, Custom);
937 setOperationAction(ISD::TRUNCATE, VT, Custom);
938 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
943 for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32})
944 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
946 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
947 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
949 for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
950 if (isTypeLegal(VT)) {
951 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
952 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
953 setOperationAction(ISD::SELECT, VT, Custom);
954 setOperationAction(ISD::FMA, VT, Custom);
958 // NOTE: Currently this has to happen after computeRegisterProperties rather
959 // than the preferred option of combining it with the addRegisterClass call.
960 if (useSVEForFixedLengthVectors()) {
961 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
962 if (useSVEForFixedLengthVectorVT(VT))
963 addTypeForFixedLengthSVE(VT);
964 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
965 if (useSVEForFixedLengthVectorVT(VT))
966 addTypeForFixedLengthSVE(VT);
968 // 64bit results can mean a bigger than NEON input.
969 for (auto VT : {MVT::v8i8, MVT::v4i16})
970 setOperationAction(ISD::TRUNCATE, VT, Custom);
971 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
973 // 128bit results imply a bigger than NEON input.
974 for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
975 setOperationAction(ISD::TRUNCATE, VT, Custom);
976 for (auto VT : {MVT::v8f16, MVT::v4f32})
977 setOperationAction(ISD::FP_ROUND, VT, Expand);
981 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
984 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
985 assert(VT.isVector() && "VT should be a vector type");
987 if (VT.isFloatingPoint()) {
988 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
989 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
990 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
993 // Mark vector float intrinsics as expand.
994 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
995 setOperationAction(ISD::FSIN, VT, Expand);
996 setOperationAction(ISD::FCOS, VT, Expand);
997 setOperationAction(ISD::FPOW, VT, Expand);
998 setOperationAction(ISD::FLOG, VT, Expand);
999 setOperationAction(ISD::FLOG2, VT, Expand);
1000 setOperationAction(ISD::FLOG10, VT, Expand);
1001 setOperationAction(ISD::FEXP, VT, Expand);
1002 setOperationAction(ISD::FEXP2, VT, Expand);
1004 // But we do support custom-lowering for FCOPYSIGN.
1005 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1008 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1010 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1011 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1012 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1013 setOperationAction(ISD::SRA, VT, Custom);
1014 setOperationAction(ISD::SRL, VT, Custom);
1015 setOperationAction(ISD::SHL, VT, Custom);
1016 setOperationAction(ISD::OR, VT, Custom);
1017 setOperationAction(ISD::SETCC, VT, Custom);
1018 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
1020 setOperationAction(ISD::SELECT, VT, Expand);
1021 setOperationAction(ISD::SELECT_CC, VT, Expand);
1022 setOperationAction(ISD::VSELECT, VT, Expand);
1023 for (MVT InnerVT : MVT::all_valuetypes())
1024 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
1026 // CNT supports only B element sizes, then use UADDLP to widen.
1027 if (VT != MVT::v8i8 && VT != MVT::v16i8)
1028 setOperationAction(ISD::CTPOP, VT, Custom);
1030 setOperationAction(ISD::UDIV, VT, Expand);
1031 setOperationAction(ISD::SDIV, VT, Expand);
1032 setOperationAction(ISD::UREM, VT, Expand);
1033 setOperationAction(ISD::SREM, VT, Expand);
1034 setOperationAction(ISD::FREM, VT, Expand);
1036 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
1037 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
1039 if (!VT.isFloatingPoint())
1040 setOperationAction(ISD::ABS, VT, Legal);
1042 // [SU][MIN|MAX] are available for all NEON types apart from i64.
1043 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
1044 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
1045 setOperationAction(Opcode, VT, Legal);
1047 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
1048 if (VT.isFloatingPoint() &&
1049 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
1050 for (unsigned Opcode :
1051 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
1052 setOperationAction(Opcode, VT, Legal);
1054 if (Subtarget->isLittleEndian()) {
1055 for (unsigned im = (unsigned)ISD::PRE_INC;
1056 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1057 setIndexedLoadAction(im, VT, Legal);
1058 setIndexedStoreAction(im, VT, Legal);
1063 void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
1064 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
1066 // By default everything must be expanded.
1067 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
1068 setOperationAction(Op, VT, Expand);
1070 // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
1071 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1073 // Lower fixed length vector operations to scalable equivalents.
1074 setOperationAction(ISD::ADD, VT, Custom);
1075 setOperationAction(ISD::FADD, VT, Custom);
1076 setOperationAction(ISD::LOAD, VT, Custom);
1077 setOperationAction(ISD::STORE, VT, Custom);
1078 setOperationAction(ISD::TRUNCATE, VT, Custom);
1081 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
1082 addRegisterClass(VT, &AArch64::FPR64RegClass);
1083 addTypeForNEON(VT, MVT::v2i32);
1086 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
1087 addRegisterClass(VT, &AArch64::FPR128RegClass);
1088 addTypeForNEON(VT, MVT::v4i32);
1091 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
1092 LLVMContext &C, EVT VT) const {
1095 if (VT.isScalableVector())
1096 return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
1097 return VT.changeVectorElementTypeToInteger();
1100 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
1101 const APInt &Demanded,
1102 TargetLowering::TargetLoweringOpt &TLO,
1104 uint64_t OldImm = Imm, NewImm, Enc;
1105 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
1107 // Return if the immediate is already all zeros, all ones, a bimm32 or a
1109 if (Imm == 0 || Imm == Mask ||
1110 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
1113 unsigned EltSize = Size;
1114 uint64_t DemandedBits = Demanded.getZExtValue();
1116 // Clear bits that are not demanded.
1117 Imm &= DemandedBits;
1120 // The goal here is to set the non-demanded bits in a way that minimizes
1121 // the number of switching between 0 and 1. In order to achieve this goal,
1122 // we set the non-demanded bits to the value of the preceding demanded bits.
1123 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
1124 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
1125 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
1126 // The final result is 0b11000011.
1127 uint64_t NonDemandedBits = ~DemandedBits;
1128 uint64_t InvertedImm = ~Imm & DemandedBits;
1129 uint64_t RotatedImm =
1130 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
1132 uint64_t Sum = RotatedImm + NonDemandedBits;
1133 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
1134 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
1135 NewImm = (Imm | Ones) & Mask;
1137 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
1138 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
1139 // we halve the element size and continue the search.
1140 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
1143 // We cannot shrink the element size any further if it is 2-bits.
1149 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1151 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1152 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1155 // Merge the upper and lower halves of Imm and DemandedBits.
1157 DemandedBits |= DemandedBitsHi;
1162 // Replicate the element across the register width.
1163 while (EltSize < Size) {
1164 NewImm |= NewImm << EltSize;
1169 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1170 "demanded bits should never be altered");
1171 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1173 // Create the new constant immediate node.
1174 EVT VT = Op.getValueType();
1178 // If the new constant immediate is all-zeros or all-ones, let the target
1179 // independent DAG combine optimize this node.
1180 if (NewImm == 0 || NewImm == OrigMask) {
1181 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1182 TLO.DAG.getConstant(NewImm, DL, VT));
1183 // Otherwise, create a machine node so that target independent DAG combine
1184 // doesn't undo this optimization.
1186 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1187 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1189 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1192 return TLO.CombineTo(Op, New);
1195 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1196 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
1197 TargetLoweringOpt &TLO) const {
1198 // Delay this optimization to as late as possible.
1202 if (!EnableOptimizeLogicalImm)
1205 EVT VT = Op.getValueType();
1209 unsigned Size = VT.getSizeInBits();
1210 assert((Size == 32 || Size == 64) &&
1211 "i32 or i64 is expected after legalization.");
1213 // Exit early if we demand all bits.
1214 if (DemandedBits.countPopulation() == Size)
1218 switch (Op.getOpcode()) {
1222 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1225 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1228 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1234 uint64_t Imm = C->getZExtValue();
1235 return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
1238 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1239 /// Mask are known to be either zero or one and return them Known.
1240 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1241 const SDValue Op, KnownBits &Known,
1242 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1243 switch (Op.getOpcode()) {
1246 case AArch64ISD::CSEL: {
1248 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1249 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1250 Known.Zero &= Known2.Zero;
1251 Known.One &= Known2.One;
1254 case AArch64ISD::LOADgot:
1255 case AArch64ISD::ADDlow: {
1256 if (!Subtarget->isTargetILP32())
1258 // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1259 Known.Zero = APInt::getHighBitsSet(64, 32);
1262 case ISD::INTRINSIC_W_CHAIN: {
1263 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1264 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1267 case Intrinsic::aarch64_ldaxr:
1268 case Intrinsic::aarch64_ldxr: {
1269 unsigned BitWidth = Known.getBitWidth();
1270 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1271 unsigned MemBits = VT.getScalarSizeInBits();
1272 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1278 case ISD::INTRINSIC_WO_CHAIN:
1279 case ISD::INTRINSIC_VOID: {
1280 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1284 case Intrinsic::aarch64_neon_umaxv:
1285 case Intrinsic::aarch64_neon_uminv: {
1286 // Figure out the datatype of the vector operand. The UMINV instruction
1287 // will zero extend the result, so we can mark as known zero all the
1288 // bits larger than the element datatype. 32-bit or larget doesn't need
1289 // this as those are legal types and will be handled by isel directly.
1290 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1291 unsigned BitWidth = Known.getBitWidth();
1292 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1293 assert(BitWidth >= 8 && "Unexpected width!");
1294 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1296 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1297 assert(BitWidth >= 16 && "Unexpected width!");
1298 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1308 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1313 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1314 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1316 if (Subtarget->requiresStrictAlign())
1320 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1321 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1322 // See comments in performSTORECombine() for more details about
1323 // these conditions.
1325 // Code that uses clang vector extensions can mark that it
1326 // wants unaligned accesses to be treated as fast by
1327 // underspecifying alignment to be 1 or 2.
1330 // Disregard v2i64. Memcpy lowering produces those and splitting
1331 // them regresses performance on micro-benchmarks and olden/bh.
1337 // Same as above but handling LLTs instead.
1338 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1339 LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1341 if (Subtarget->requiresStrictAlign())
1345 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1346 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1347 Ty.getSizeInBytes() != 16 ||
1348 // See comments in performSTORECombine() for more details about
1349 // these conditions.
1351 // Code that uses clang vector extensions can mark that it
1352 // wants unaligned accesses to be treated as fast by
1353 // underspecifying alignment to be 1 or 2.
1356 // Disregard v2i64. Memcpy lowering produces those and splitting
1357 // them regresses performance on micro-benchmarks and olden/bh.
1358 Ty == LLT::vector(2, 64);
1364 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1365 const TargetLibraryInfo *libInfo) const {
1366 return AArch64::createFastISel(funcInfo, libInfo);
1369 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1370 #define MAKE_CASE(V) \
1373 switch ((AArch64ISD::NodeType)Opcode) {
1374 case AArch64ISD::FIRST_NUMBER:
1376 MAKE_CASE(AArch64ISD::CALL)
1377 MAKE_CASE(AArch64ISD::ADRP)
1378 MAKE_CASE(AArch64ISD::ADR)
1379 MAKE_CASE(AArch64ISD::ADDlow)
1380 MAKE_CASE(AArch64ISD::LOADgot)
1381 MAKE_CASE(AArch64ISD::RET_FLAG)
1382 MAKE_CASE(AArch64ISD::BRCOND)
1383 MAKE_CASE(AArch64ISD::CSEL)
1384 MAKE_CASE(AArch64ISD::FCSEL)
1385 MAKE_CASE(AArch64ISD::CSINV)
1386 MAKE_CASE(AArch64ISD::CSNEG)
1387 MAKE_CASE(AArch64ISD::CSINC)
1388 MAKE_CASE(AArch64ISD::THREAD_POINTER)
1389 MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
1390 MAKE_CASE(AArch64ISD::ADD_PRED)
1391 MAKE_CASE(AArch64ISD::SDIV_PRED)
1392 MAKE_CASE(AArch64ISD::UDIV_PRED)
1393 MAKE_CASE(AArch64ISD::SMIN_MERGE_OP1)
1394 MAKE_CASE(AArch64ISD::UMIN_MERGE_OP1)
1395 MAKE_CASE(AArch64ISD::SMAX_MERGE_OP1)
1396 MAKE_CASE(AArch64ISD::UMAX_MERGE_OP1)
1397 MAKE_CASE(AArch64ISD::SHL_MERGE_OP1)
1398 MAKE_CASE(AArch64ISD::SRL_MERGE_OP1)
1399 MAKE_CASE(AArch64ISD::SRA_MERGE_OP1)
1400 MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
1401 MAKE_CASE(AArch64ISD::ADC)
1402 MAKE_CASE(AArch64ISD::SBC)
1403 MAKE_CASE(AArch64ISD::ADDS)
1404 MAKE_CASE(AArch64ISD::SUBS)
1405 MAKE_CASE(AArch64ISD::ADCS)
1406 MAKE_CASE(AArch64ISD::SBCS)
1407 MAKE_CASE(AArch64ISD::ANDS)
1408 MAKE_CASE(AArch64ISD::CCMP)
1409 MAKE_CASE(AArch64ISD::CCMN)
1410 MAKE_CASE(AArch64ISD::FCCMP)
1411 MAKE_CASE(AArch64ISD::FCMP)
1412 MAKE_CASE(AArch64ISD::STRICT_FCMP)
1413 MAKE_CASE(AArch64ISD::STRICT_FCMPE)
1414 MAKE_CASE(AArch64ISD::DUP)
1415 MAKE_CASE(AArch64ISD::DUPLANE8)
1416 MAKE_CASE(AArch64ISD::DUPLANE16)
1417 MAKE_CASE(AArch64ISD::DUPLANE32)
1418 MAKE_CASE(AArch64ISD::DUPLANE64)
1419 MAKE_CASE(AArch64ISD::MOVI)
1420 MAKE_CASE(AArch64ISD::MOVIshift)
1421 MAKE_CASE(AArch64ISD::MOVIedit)
1422 MAKE_CASE(AArch64ISD::MOVImsl)
1423 MAKE_CASE(AArch64ISD::FMOV)
1424 MAKE_CASE(AArch64ISD::MVNIshift)
1425 MAKE_CASE(AArch64ISD::MVNImsl)
1426 MAKE_CASE(AArch64ISD::BICi)
1427 MAKE_CASE(AArch64ISD::ORRi)
1428 MAKE_CASE(AArch64ISD::BSP)
1429 MAKE_CASE(AArch64ISD::NEG)
1430 MAKE_CASE(AArch64ISD::EXTR)
1431 MAKE_CASE(AArch64ISD::ZIP1)
1432 MAKE_CASE(AArch64ISD::ZIP2)
1433 MAKE_CASE(AArch64ISD::UZP1)
1434 MAKE_CASE(AArch64ISD::UZP2)
1435 MAKE_CASE(AArch64ISD::TRN1)
1436 MAKE_CASE(AArch64ISD::TRN2)
1437 MAKE_CASE(AArch64ISD::REV16)
1438 MAKE_CASE(AArch64ISD::REV32)
1439 MAKE_CASE(AArch64ISD::REV64)
1440 MAKE_CASE(AArch64ISD::EXT)
1441 MAKE_CASE(AArch64ISD::VSHL)
1442 MAKE_CASE(AArch64ISD::VLSHR)
1443 MAKE_CASE(AArch64ISD::VASHR)
1444 MAKE_CASE(AArch64ISD::VSLI)
1445 MAKE_CASE(AArch64ISD::VSRI)
1446 MAKE_CASE(AArch64ISD::CMEQ)
1447 MAKE_CASE(AArch64ISD::CMGE)
1448 MAKE_CASE(AArch64ISD::CMGT)
1449 MAKE_CASE(AArch64ISD::CMHI)
1450 MAKE_CASE(AArch64ISD::CMHS)
1451 MAKE_CASE(AArch64ISD::FCMEQ)
1452 MAKE_CASE(AArch64ISD::FCMGE)
1453 MAKE_CASE(AArch64ISD::FCMGT)
1454 MAKE_CASE(AArch64ISD::CMEQz)
1455 MAKE_CASE(AArch64ISD::CMGEz)
1456 MAKE_CASE(AArch64ISD::CMGTz)
1457 MAKE_CASE(AArch64ISD::CMLEz)
1458 MAKE_CASE(AArch64ISD::CMLTz)
1459 MAKE_CASE(AArch64ISD::FCMEQz)
1460 MAKE_CASE(AArch64ISD::FCMGEz)
1461 MAKE_CASE(AArch64ISD::FCMGTz)
1462 MAKE_CASE(AArch64ISD::FCMLEz)
1463 MAKE_CASE(AArch64ISD::FCMLTz)
1464 MAKE_CASE(AArch64ISD::SADDV)
1465 MAKE_CASE(AArch64ISD::UADDV)
1466 MAKE_CASE(AArch64ISD::SRHADD)
1467 MAKE_CASE(AArch64ISD::URHADD)
1468 MAKE_CASE(AArch64ISD::SMINV)
1469 MAKE_CASE(AArch64ISD::UMINV)
1470 MAKE_CASE(AArch64ISD::SMAXV)
1471 MAKE_CASE(AArch64ISD::UMAXV)
1472 MAKE_CASE(AArch64ISD::SMAXV_PRED)
1473 MAKE_CASE(AArch64ISD::UMAXV_PRED)
1474 MAKE_CASE(AArch64ISD::SMINV_PRED)
1475 MAKE_CASE(AArch64ISD::UMINV_PRED)
1476 MAKE_CASE(AArch64ISD::ORV_PRED)
1477 MAKE_CASE(AArch64ISD::EORV_PRED)
1478 MAKE_CASE(AArch64ISD::ANDV_PRED)
1479 MAKE_CASE(AArch64ISD::CLASTA_N)
1480 MAKE_CASE(AArch64ISD::CLASTB_N)
1481 MAKE_CASE(AArch64ISD::LASTA)
1482 MAKE_CASE(AArch64ISD::LASTB)
1483 MAKE_CASE(AArch64ISD::REV)
1484 MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
1485 MAKE_CASE(AArch64ISD::TBL)
1486 MAKE_CASE(AArch64ISD::FADD_PRED)
1487 MAKE_CASE(AArch64ISD::FADDA_PRED)
1488 MAKE_CASE(AArch64ISD::FADDV_PRED)
1489 MAKE_CASE(AArch64ISD::FMA_PRED)
1490 MAKE_CASE(AArch64ISD::FMAXV_PRED)
1491 MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
1492 MAKE_CASE(AArch64ISD::FMINV_PRED)
1493 MAKE_CASE(AArch64ISD::FMINNMV_PRED)
1494 MAKE_CASE(AArch64ISD::NOT)
1495 MAKE_CASE(AArch64ISD::BIT)
1496 MAKE_CASE(AArch64ISD::CBZ)
1497 MAKE_CASE(AArch64ISD::CBNZ)
1498 MAKE_CASE(AArch64ISD::TBZ)
1499 MAKE_CASE(AArch64ISD::TBNZ)
1500 MAKE_CASE(AArch64ISD::TC_RETURN)
1501 MAKE_CASE(AArch64ISD::PREFETCH)
1502 MAKE_CASE(AArch64ISD::SITOF)
1503 MAKE_CASE(AArch64ISD::UITOF)
1504 MAKE_CASE(AArch64ISD::NVCAST)
1505 MAKE_CASE(AArch64ISD::SQSHL_I)
1506 MAKE_CASE(AArch64ISD::UQSHL_I)
1507 MAKE_CASE(AArch64ISD::SRSHR_I)
1508 MAKE_CASE(AArch64ISD::URSHR_I)
1509 MAKE_CASE(AArch64ISD::SQSHLU_I)
1510 MAKE_CASE(AArch64ISD::WrapperLarge)
1511 MAKE_CASE(AArch64ISD::LD2post)
1512 MAKE_CASE(AArch64ISD::LD3post)
1513 MAKE_CASE(AArch64ISD::LD4post)
1514 MAKE_CASE(AArch64ISD::ST2post)
1515 MAKE_CASE(AArch64ISD::ST3post)
1516 MAKE_CASE(AArch64ISD::ST4post)
1517 MAKE_CASE(AArch64ISD::LD1x2post)
1518 MAKE_CASE(AArch64ISD::LD1x3post)
1519 MAKE_CASE(AArch64ISD::LD1x4post)
1520 MAKE_CASE(AArch64ISD::ST1x2post)
1521 MAKE_CASE(AArch64ISD::ST1x3post)
1522 MAKE_CASE(AArch64ISD::ST1x4post)
1523 MAKE_CASE(AArch64ISD::LD1DUPpost)
1524 MAKE_CASE(AArch64ISD::LD2DUPpost)
1525 MAKE_CASE(AArch64ISD::LD3DUPpost)
1526 MAKE_CASE(AArch64ISD::LD4DUPpost)
1527 MAKE_CASE(AArch64ISD::LD1LANEpost)
1528 MAKE_CASE(AArch64ISD::LD2LANEpost)
1529 MAKE_CASE(AArch64ISD::LD3LANEpost)
1530 MAKE_CASE(AArch64ISD::LD4LANEpost)
1531 MAKE_CASE(AArch64ISD::ST2LANEpost)
1532 MAKE_CASE(AArch64ISD::ST3LANEpost)
1533 MAKE_CASE(AArch64ISD::ST4LANEpost)
1534 MAKE_CASE(AArch64ISD::SMULL)
1535 MAKE_CASE(AArch64ISD::UMULL)
1536 MAKE_CASE(AArch64ISD::FRECPE)
1537 MAKE_CASE(AArch64ISD::FRECPS)
1538 MAKE_CASE(AArch64ISD::FRSQRTE)
1539 MAKE_CASE(AArch64ISD::FRSQRTS)
1540 MAKE_CASE(AArch64ISD::STG)
1541 MAKE_CASE(AArch64ISD::STZG)
1542 MAKE_CASE(AArch64ISD::ST2G)
1543 MAKE_CASE(AArch64ISD::STZ2G)
1544 MAKE_CASE(AArch64ISD::SUNPKHI)
1545 MAKE_CASE(AArch64ISD::SUNPKLO)
1546 MAKE_CASE(AArch64ISD::UUNPKHI)
1547 MAKE_CASE(AArch64ISD::UUNPKLO)
1548 MAKE_CASE(AArch64ISD::INSR)
1549 MAKE_CASE(AArch64ISD::PTEST)
1550 MAKE_CASE(AArch64ISD::PTRUE)
1551 MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
1552 MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
1553 MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
1554 MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
1555 MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
1556 MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
1557 MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
1558 MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
1559 MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
1560 MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
1561 MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
1562 MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
1563 MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
1564 MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
1565 MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
1566 MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
1567 MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
1568 MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
1569 MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
1570 MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
1571 MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
1572 MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
1573 MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
1574 MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
1575 MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
1576 MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
1577 MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
1578 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
1579 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
1580 MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
1581 MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
1582 MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
1583 MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
1584 MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
1585 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
1586 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
1587 MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
1588 MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
1589 MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
1590 MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
1591 MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
1592 MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
1593 MAKE_CASE(AArch64ISD::ST1_PRED)
1594 MAKE_CASE(AArch64ISD::SST1_PRED)
1595 MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
1596 MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
1597 MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
1598 MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
1599 MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
1600 MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
1601 MAKE_CASE(AArch64ISD::SSTNT1_PRED)
1602 MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
1603 MAKE_CASE(AArch64ISD::LDP)
1604 MAKE_CASE(AArch64ISD::STP)
1605 MAKE_CASE(AArch64ISD::STNP)
1606 MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
1607 MAKE_CASE(AArch64ISD::INDEX_VECTOR)
1614 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1615 MachineBasicBlock *MBB) const {
1616 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1620 // [... previous instrs leading to comparison ...]
1626 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1628 MachineFunction *MF = MBB->getParent();
1629 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1630 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1631 DebugLoc DL = MI.getDebugLoc();
1632 MachineFunction::iterator It = ++MBB->getIterator();
1634 Register DestReg = MI.getOperand(0).getReg();
1635 Register IfTrueReg = MI.getOperand(1).getReg();
1636 Register IfFalseReg = MI.getOperand(2).getReg();
1637 unsigned CondCode = MI.getOperand(3).getImm();
1638 bool NZCVKilled = MI.getOperand(4).isKill();
1640 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1641 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1642 MF->insert(It, TrueBB);
1643 MF->insert(It, EndBB);
1645 // Transfer rest of current basic-block to EndBB
1646 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1648 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1650 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1651 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1652 MBB->addSuccessor(TrueBB);
1653 MBB->addSuccessor(EndBB);
1655 // TrueBB falls through to the end.
1656 TrueBB->addSuccessor(EndBB);
1659 TrueBB->addLiveIn(AArch64::NZCV);
1660 EndBB->addLiveIn(AArch64::NZCV);
1663 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1669 MI.eraseFromParent();
1673 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1674 MachineInstr &MI, MachineBasicBlock *BB) const {
1675 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1676 BB->getParent()->getFunction().getPersonalityFn())) &&
1677 "SEH does not use catchret!");
1681 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1682 MachineInstr &MI, MachineBasicBlock *BB) const {
1683 switch (MI.getOpcode()) {
1688 llvm_unreachable("Unexpected instruction for custom inserter!");
1690 case AArch64::F128CSEL:
1691 return EmitF128CSEL(MI, BB);
1693 case TargetOpcode::STACKMAP:
1694 case TargetOpcode::PATCHPOINT:
1695 return emitPatchPoint(MI, BB);
1697 case AArch64::CATCHRET:
1698 return EmitLoweredCatchRet(MI, BB);
1702 //===----------------------------------------------------------------------===//
1703 // AArch64 Lowering private implementation.
1704 //===----------------------------------------------------------------------===//
1706 //===----------------------------------------------------------------------===//
1708 //===----------------------------------------------------------------------===//
1710 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1712 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1715 llvm_unreachable("Unknown condition code!");
1717 return AArch64CC::NE;
1719 return AArch64CC::EQ;
1721 return AArch64CC::GT;
1723 return AArch64CC::GE;
1725 return AArch64CC::LT;
1727 return AArch64CC::LE;
1729 return AArch64CC::HI;
1731 return AArch64CC::HS;
1733 return AArch64CC::LO;
1735 return AArch64CC::LS;
1739 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1740 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1741 AArch64CC::CondCode &CondCode,
1742 AArch64CC::CondCode &CondCode2) {
1743 CondCode2 = AArch64CC::AL;
1746 llvm_unreachable("Unknown FP condition!");
1749 CondCode = AArch64CC::EQ;
1753 CondCode = AArch64CC::GT;
1757 CondCode = AArch64CC::GE;
1760 CondCode = AArch64CC::MI;
1763 CondCode = AArch64CC::LS;
1766 CondCode = AArch64CC::MI;
1767 CondCode2 = AArch64CC::GT;
1770 CondCode = AArch64CC::VC;
1773 CondCode = AArch64CC::VS;
1776 CondCode = AArch64CC::EQ;
1777 CondCode2 = AArch64CC::VS;
1780 CondCode = AArch64CC::HI;
1783 CondCode = AArch64CC::PL;
1787 CondCode = AArch64CC::LT;
1791 CondCode = AArch64CC::LE;
1795 CondCode = AArch64CC::NE;
1800 /// Convert a DAG fp condition code to an AArch64 CC.
1801 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1802 /// should be AND'ed instead of OR'ed.
1803 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1804 AArch64CC::CondCode &CondCode,
1805 AArch64CC::CondCode &CondCode2) {
1806 CondCode2 = AArch64CC::AL;
1809 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1810 assert(CondCode2 == AArch64CC::AL);
1814 // == ((a olt b) || (a ogt b))
1815 // == ((a ord b) && (a une b))
1816 CondCode = AArch64CC::VC;
1817 CondCode2 = AArch64CC::NE;
1821 // == ((a uno b) || (a oeq b))
1822 // == ((a ule b) && (a uge b))
1823 CondCode = AArch64CC::PL;
1824 CondCode2 = AArch64CC::LE;
1829 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1830 /// CC usable with the vector instructions. Fewer operations are available
1831 /// without a real NZCV register, so we have to use less efficient combinations
1832 /// to get the same effect.
1833 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1834 AArch64CC::CondCode &CondCode,
1835 AArch64CC::CondCode &CondCode2,
1840 // Mostly the scalar mappings work fine.
1841 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1847 CondCode = AArch64CC::MI;
1848 CondCode2 = AArch64CC::GE;
1855 // All of the compare-mask comparisons are ordered, but we can switch
1856 // between the two by a double inversion. E.g. ULE == !OGT.
1858 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1859 CondCode, CondCode2);
1864 static bool isLegalArithImmed(uint64_t C) {
1865 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1866 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1867 LLVM_DEBUG(dbgs() << "Is imm " << C
1868 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1872 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1873 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1874 // can be set differently by this operation. It comes down to whether
1875 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1876 // everything is fine. If not then the optimization is wrong. Thus general
1877 // comparisons are only valid if op2 != 0.
1879 // So, finally, the only LLVM-native comparisons that don't mention C and V
1880 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1881 // the absence of information about op2.
1882 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1883 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1884 (CC == ISD::SETEQ || CC == ISD::SETNE);
1887 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
1888 SelectionDAG &DAG, SDValue Chain,
1890 EVT VT = LHS.getValueType();
1891 assert(VT != MVT::f128);
1892 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
1894 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
1895 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
1898 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1899 const SDLoc &dl, SelectionDAG &DAG) {
1900 EVT VT = LHS.getValueType();
1901 const bool FullFP16 =
1902 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1904 if (VT.isFloatingPoint()) {
1905 assert(VT != MVT::f128);
1906 if (VT == MVT::f16 && !FullFP16) {
1907 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1908 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1911 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1914 // The CMP instruction is just an alias for SUBS, and representing it as
1915 // SUBS means that it's possible to get CSE with subtract operations.
1916 // A later phase can perform the optimization of setting the destination
1917 // register to WZR/XZR if it ends up being unused.
1918 unsigned Opcode = AArch64ISD::SUBS;
1920 if (isCMN(RHS, CC)) {
1921 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1922 Opcode = AArch64ISD::ADDS;
1923 RHS = RHS.getOperand(1);
1924 } else if (isCMN(LHS, CC)) {
1925 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1926 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1927 Opcode = AArch64ISD::ADDS;
1928 LHS = LHS.getOperand(1);
1929 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
1930 if (LHS.getOpcode() == ISD::AND) {
1931 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1932 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1933 // of the signed comparisons.
1934 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
1935 DAG.getVTList(VT, MVT_CC),
1938 // Replace all users of (and X, Y) with newly generated (ands X, Y)
1939 DAG.ReplaceAllUsesWith(LHS, ANDSNode);
1940 return ANDSNode.getValue(1);
1941 } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
1942 // Use result of ANDS
1943 return LHS.getValue(1);
1947 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1951 /// \defgroup AArch64CCMP CMP;CCMP matching
1953 /// These functions deal with the formation of CMP;CCMP;... sequences.
1954 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1955 /// a comparison. They set the NZCV flags to a predefined value if their
1956 /// predicate is false. This allows to express arbitrary conjunctions, for
1957 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1960 /// ccmp B, inv(CB), CA
1961 /// check for CB flags
1963 /// This naturally lets us implement chains of AND operations with SETCC
1964 /// operands. And we can even implement some other situations by transforming
1966 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1967 /// negating the flags used in a CCMP/FCCMP operations.
1968 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1969 /// by negating the flags we test for afterwards. i.e.
1970 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1971 /// - Note that we can only ever negate all previously processed results.
1972 /// What we can not implement by flipping the flags to test is a negation
1973 /// of two sub-trees (because the negation affects all sub-trees emitted so
1974 /// far, so the 2nd sub-tree we emit would also affect the first).
1975 /// With those tools we can implement some OR operations:
1976 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1977 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1978 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1979 /// elimination rules from earlier to implement the whole thing as a
1980 /// CCMP/FCCMP chain.
1982 /// As complete example:
1983 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1984 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1985 /// can be reassociated to:
1986 /// or (and (setCC (cmp C)) setCD (cmp D))
1987 // (or (setCA (cmp A)) (setCB (cmp B)))
1988 /// can be transformed to:
1989 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1990 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1991 /// which can be implemented as:
1993 /// ccmp D, inv(CD), CC
1994 /// ccmp A, CA, inv(CD)
1995 /// ccmp B, CB, inv(CA)
1996 /// check for CB flags
1998 /// A counterexample is "or (and A B) (and C D)" which translates to
1999 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
2000 /// can only implement 1 of the inner (not) operations, but not both!
2003 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
2004 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
2005 ISD::CondCode CC, SDValue CCOp,
2006 AArch64CC::CondCode Predicate,
2007 AArch64CC::CondCode OutCC,
2008 const SDLoc &DL, SelectionDAG &DAG) {
2009 unsigned Opcode = 0;
2010 const bool FullFP16 =
2011 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
2013 if (LHS.getValueType().isFloatingPoint()) {
2014 assert(LHS.getValueType() != MVT::f128);
2015 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
2016 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
2017 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
2019 Opcode = AArch64ISD::FCCMP;
2020 } else if (RHS.getOpcode() == ISD::SUB) {
2021 SDValue SubOp0 = RHS.getOperand(0);
2022 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2023 // See emitComparison() on why we can only do this for SETEQ and SETNE.
2024 Opcode = AArch64ISD::CCMN;
2025 RHS = RHS.getOperand(1);
2029 Opcode = AArch64ISD::CCMP;
2031 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
2032 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
2033 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
2034 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
2035 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
2038 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
2039 /// expressed as a conjunction. See \ref AArch64CCMP.
2040 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
2041 /// changing the conditions on the SETCC tests.
2042 /// (this means we can call emitConjunctionRec() with
2043 /// Negate==true on this sub-tree)
2044 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
2045 /// cannot do the negation naturally. We are required to
2046 /// emit the subtree first in this case.
2047 /// \param WillNegate Is true if are called when the result of this
2048 /// subexpression must be negated. This happens when the
2049 /// outer expression is an OR. We can use this fact to know
2050 /// that we have a double negation (or (or ...) ...) that
2051 /// can be implemented for free.
2052 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
2053 bool &MustBeFirst, bool WillNegate,
2054 unsigned Depth = 0) {
2055 if (!Val.hasOneUse())
2057 unsigned Opcode = Val->getOpcode();
2058 if (Opcode == ISD::SETCC) {
2059 if (Val->getOperand(0).getValueType() == MVT::f128)
2062 MustBeFirst = false;
2065 // Protect against exponential runtime and stack overflow.
2068 if (Opcode == ISD::AND || Opcode == ISD::OR) {
2069 bool IsOR = Opcode == ISD::OR;
2070 SDValue O0 = Val->getOperand(0);
2071 SDValue O1 = Val->getOperand(1);
2074 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
2078 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
2081 if (MustBeFirstL && MustBeFirstR)
2085 // For an OR expression we need to be able to naturally negate at least
2086 // one side or we cannot do the transformation at all.
2087 if (!CanNegateL && !CanNegateR)
2089 // If we the result of the OR will be negated and we can naturally negate
2090 // the leafs, then this sub-tree as a whole negates naturally.
2091 CanNegate = WillNegate && CanNegateL && CanNegateR;
2092 // If we cannot naturally negate the whole sub-tree, then this must be
2094 MustBeFirst = !CanNegate;
2096 assert(Opcode == ISD::AND && "Must be OR or AND");
2097 // We cannot naturally negate an AND operation.
2099 MustBeFirst = MustBeFirstL || MustBeFirstR;
2106 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
2107 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
2108 /// Tries to transform the given i1 producing node @p Val to a series compare
2109 /// and conditional compare operations. @returns an NZCV flags producing node
2110 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
2111 /// transformation was not possible.
2112 /// \p Negate is true if we want this sub-tree being negated just by changing
2113 /// SETCC conditions.
2114 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
2115 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
2116 AArch64CC::CondCode Predicate) {
2117 // We're at a tree leaf, produce a conditional comparison operation.
2118 unsigned Opcode = Val->getOpcode();
2119 if (Opcode == ISD::SETCC) {
2120 SDValue LHS = Val->getOperand(0);
2121 SDValue RHS = Val->getOperand(1);
2122 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
2123 bool isInteger = LHS.getValueType().isInteger();
2125 CC = getSetCCInverse(CC, LHS.getValueType());
2127 // Determine OutCC and handle FP special case.
2129 OutCC = changeIntCCToAArch64CC(CC);
2131 assert(LHS.getValueType().isFloatingPoint());
2132 AArch64CC::CondCode ExtraCC;
2133 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
2134 // Some floating point conditions can't be tested with a single condition
2135 // code. Construct an additional comparison in this case.
2136 if (ExtraCC != AArch64CC::AL) {
2138 if (!CCOp.getNode())
2139 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
2141 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
2144 Predicate = ExtraCC;
2148 // Produce a normal comparison if we are first in the chain
2150 return emitComparison(LHS, RHS, CC, DL, DAG);
2151 // Otherwise produce a ccmp.
2152 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
2155 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
2157 bool IsOR = Opcode == ISD::OR;
2159 SDValue LHS = Val->getOperand(0);
2162 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
2163 assert(ValidL && "Valid conjunction/disjunction tree");
2166 SDValue RHS = Val->getOperand(1);
2169 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
2170 assert(ValidR && "Valid conjunction/disjunction tree");
2173 // Swap sub-tree that must come first to the right side.
2175 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
2176 std::swap(LHS, RHS);
2177 std::swap(CanNegateL, CanNegateR);
2178 std::swap(MustBeFirstL, MustBeFirstR);
2184 bool NegateAfterAll;
2185 if (Opcode == ISD::OR) {
2186 // Swap the sub-tree that we can negate naturally to the left.
2188 assert(CanNegateR && "at least one side must be negatable");
2189 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
2191 std::swap(LHS, RHS);
2193 NegateAfterR = true;
2195 // Negate the left sub-tree if possible, otherwise negate the result.
2196 NegateR = CanNegateR;
2197 NegateAfterR = !CanNegateR;
2200 NegateAfterAll = !Negate;
2202 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
2203 assert(!Negate && "Valid conjunction/disjunction tree");
2207 NegateAfterR = false;
2208 NegateAfterAll = false;
2212 AArch64CC::CondCode RHSCC;
2213 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
2215 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
2216 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
2218 OutCC = AArch64CC::getInvertedCondCode(OutCC);
2222 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2223 /// In some cases this is even possible with OR operations in the expression.
2224 /// See \ref AArch64CCMP.
2225 /// \see emitConjunctionRec().
2226 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2227 AArch64CC::CondCode &OutCC) {
2228 bool DummyCanNegate;
2229 bool DummyMustBeFirst;
2230 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2233 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2238 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2239 /// extension operations.
2240 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2241 auto isSupportedExtend = [&](SDValue V) {
2242 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2245 if (V.getOpcode() == ISD::AND)
2246 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2247 uint64_t Mask = MaskCst->getZExtValue();
2248 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2254 if (!Op.hasOneUse())
2257 if (isSupportedExtend(Op))
2260 unsigned Opc = Op.getOpcode();
2261 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2262 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2263 uint64_t Shift = ShiftCst->getZExtValue();
2264 if (isSupportedExtend(Op.getOperand(0)))
2265 return (Shift <= 4) ? 2 : 1;
2266 EVT VT = Op.getValueType();
2267 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2274 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2275 SDValue &AArch64cc, SelectionDAG &DAG,
2277 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2278 EVT VT = RHS.getValueType();
2279 uint64_t C = RHSC->getZExtValue();
2280 if (!isLegalArithImmed(C)) {
2281 // Constant does not fit, try adjusting it by one?
2287 if ((VT == MVT::i32 && C != 0x80000000 &&
2288 isLegalArithImmed((uint32_t)(C - 1))) ||
2289 (VT == MVT::i64 && C != 0x80000000ULL &&
2290 isLegalArithImmed(C - 1ULL))) {
2291 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2292 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2293 RHS = DAG.getConstant(C, dl, VT);
2298 if ((VT == MVT::i32 && C != 0 &&
2299 isLegalArithImmed((uint32_t)(C - 1))) ||
2300 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2301 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2302 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2303 RHS = DAG.getConstant(C, dl, VT);
2308 if ((VT == MVT::i32 && C != INT32_MAX &&
2309 isLegalArithImmed((uint32_t)(C + 1))) ||
2310 (VT == MVT::i64 && C != INT64_MAX &&
2311 isLegalArithImmed(C + 1ULL))) {
2312 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2313 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2314 RHS = DAG.getConstant(C, dl, VT);
2319 if ((VT == MVT::i32 && C != UINT32_MAX &&
2320 isLegalArithImmed((uint32_t)(C + 1))) ||
2321 (VT == MVT::i64 && C != UINT64_MAX &&
2322 isLegalArithImmed(C + 1ULL))) {
2323 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2324 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2325 RHS = DAG.getConstant(C, dl, VT);
2332 // Comparisons are canonicalized so that the RHS operand is simpler than the
2333 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2334 // can fold some shift+extend operations on the RHS operand, so swap the
2335 // operands if that can be done.
2340 // can be turned into:
2341 // cmp w12, w11, lsl #1
2342 if (!isa<ConstantSDNode>(RHS) ||
2343 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2344 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2346 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2347 std::swap(LHS, RHS);
2348 CC = ISD::getSetCCSwappedOperands(CC);
2353 AArch64CC::CondCode AArch64CC;
2354 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2355 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2357 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2358 // For the i8 operand, the largest immediate is 255, so this can be easily
2359 // encoded in the compare instruction. For the i16 operand, however, the
2360 // largest immediate cannot be encoded in the compare.
2361 // Therefore, use a sign extending load and cmn to avoid materializing the
2362 // -1 constant. For example,
2364 // ldrh w0, [x0, #0]
2367 // ldrsh w0, [x0, #0]
2369 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2370 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2371 // ensure both the LHS and RHS are truly zero extended and to make sure the
2372 // transformation is profitable.
2373 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2374 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2375 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2376 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2377 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2378 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2380 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2381 DAG.getValueType(MVT::i16));
2382 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2383 RHS.getValueType()),
2385 AArch64CC = changeIntCCToAArch64CC(CC);
2389 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2390 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2391 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2392 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2398 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2399 AArch64CC = changeIntCCToAArch64CC(CC);
2401 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2405 static std::pair<SDValue, SDValue>
2406 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2407 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2408 "Unsupported value type");
2409 SDValue Value, Overflow;
2411 SDValue LHS = Op.getOperand(0);
2412 SDValue RHS = Op.getOperand(1);
2414 switch (Op.getOpcode()) {
2416 llvm_unreachable("Unknown overflow instruction!");
2418 Opc = AArch64ISD::ADDS;
2422 Opc = AArch64ISD::ADDS;
2426 Opc = AArch64ISD::SUBS;
2430 Opc = AArch64ISD::SUBS;
2433 // Multiply needs a little bit extra work.
2437 bool IsSigned = Op.getOpcode() == ISD::SMULO;
2438 if (Op.getValueType() == MVT::i32) {
2439 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2440 // For a 32 bit multiply with overflow check we want the instruction
2441 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2442 // need to generate the following pattern:
2443 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2444 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2445 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2446 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2447 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2448 DAG.getConstant(0, DL, MVT::i64));
2449 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2450 // operation. We need to clear out the upper 32 bits, because we used a
2451 // widening multiply that wrote all 64 bits. In the end this should be a
2453 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2455 // The signed overflow check requires more than just a simple check for
2456 // any bit set in the upper 32 bits of the result. These bits could be
2457 // just the sign bits of a negative number. To perform the overflow
2458 // check we have to arithmetic shift right the 32nd bit of the result by
2459 // 31 bits. Then we compare the result to the upper 32 bits.
2460 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2461 DAG.getConstant(32, DL, MVT::i64));
2462 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2463 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2464 DAG.getConstant(31, DL, MVT::i64));
2465 // It is important that LowerBits is last, otherwise the arithmetic
2466 // shift will not be folded into the compare (SUBS).
2467 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2468 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2471 // The overflow check for unsigned multiply is easy. We only need to
2472 // check if any of the upper 32 bits are set. This can be done with a
2473 // CMP (shifted register). For that we need to generate the following
2475 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2476 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2477 DAG.getConstant(32, DL, MVT::i64));
2478 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2480 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2481 DAG.getConstant(0, DL, MVT::i64),
2482 UpperBits).getValue(1);
2486 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2487 // For the 64 bit multiply
2488 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2490 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2491 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2492 DAG.getConstant(63, DL, MVT::i64));
2493 // It is important that LowerBits is last, otherwise the arithmetic
2494 // shift will not be folded into the compare (SUBS).
2495 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2496 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2499 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2500 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2502 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2503 DAG.getConstant(0, DL, MVT::i64),
2504 UpperBits).getValue(1);
2511 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2513 // Emit the AArch64 operation with overflow check.
2514 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2515 Overflow = Value.getValue(1);
2517 return std::make_pair(Value, Overflow);
2520 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2521 RTLIB::Libcall Call) const {
2522 bool IsStrict = Op->isStrictFPOpcode();
2523 unsigned Offset = IsStrict ? 1 : 0;
2524 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2525 SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
2526 MakeLibCallOptions CallOptions;
2529 std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops,
2530 CallOptions, dl, Chain);
2531 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2534 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2535 SDValue Sel = Op.getOperand(0);
2536 SDValue Other = Op.getOperand(1);
2539 // If the operand is an overflow checking operation, invert the condition
2540 // code and kill the Not operation. I.e., transform:
2541 // (xor (overflow_op_bool, 1))
2543 // (csel 1, 0, invert(cc), overflow_op_bool)
2544 // ... which later gets transformed to just a cset instruction with an
2545 // inverted condition code, rather than a cset + eor sequence.
2546 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
2547 // Only lower legal XALUO ops.
2548 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2551 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2552 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2553 AArch64CC::CondCode CC;
2554 SDValue Value, Overflow;
2555 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2556 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2557 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2560 // If neither operand is a SELECT_CC, give up.
2561 if (Sel.getOpcode() != ISD::SELECT_CC)
2562 std::swap(Sel, Other);
2563 if (Sel.getOpcode() != ISD::SELECT_CC)
2566 // The folding we want to perform is:
2567 // (xor x, (select_cc a, b, cc, 0, -1) )
2569 // (csel x, (xor x, -1), cc ...)
2571 // The latter will get matched to a CSINV instruction.
2573 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2574 SDValue LHS = Sel.getOperand(0);
2575 SDValue RHS = Sel.getOperand(1);
2576 SDValue TVal = Sel.getOperand(2);
2577 SDValue FVal = Sel.getOperand(3);
2579 // FIXME: This could be generalized to non-integer comparisons.
2580 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2583 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2584 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2586 // The values aren't constants, this isn't the pattern we're looking for.
2587 if (!CFVal || !CTVal)
2590 // We can commute the SELECT_CC by inverting the condition. This
2591 // might be needed to make this fit into a CSINV pattern.
2592 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2593 std::swap(TVal, FVal);
2594 std::swap(CTVal, CFVal);
2595 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2598 // If the constants line up, perform the transform!
2599 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2601 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2604 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2605 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2607 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2614 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2615 EVT VT = Op.getValueType();
2617 // Let legalize expand this if it isn't a legal type yet.
2618 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2621 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2624 bool ExtraOp = false;
2625 switch (Op.getOpcode()) {
2627 llvm_unreachable("Invalid code");
2629 Opc = AArch64ISD::ADDS;
2632 Opc = AArch64ISD::SUBS;
2635 Opc = AArch64ISD::ADCS;
2639 Opc = AArch64ISD::SBCS;
2645 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2646 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2650 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2651 // Let legalize expand this if it isn't a legal type yet.
2652 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2656 AArch64CC::CondCode CC;
2657 // The actual operation that sets the overflow or carry flag.
2658 SDValue Value, Overflow;
2659 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2661 // We use 0 and 1 as false and true values.
2662 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2663 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2665 // We use an inverted condition, because the conditional select is inverted
2666 // too. This will allow it to be selected to a single instruction:
2667 // CSINC Wd, WZR, WZR, invert(cond).
2668 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2669 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2672 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2673 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2676 // Prefetch operands are:
2677 // 1: Address to prefetch
2679 // 3: int locality (0 = no locality ... 3 = extreme locality)
2680 // 4: bool isDataCache
2681 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2683 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2684 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2685 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2687 bool IsStream = !Locality;
2688 // When the locality number is set
2690 // The front-end should have filtered out the out-of-range values
2691 assert(Locality <= 3 && "Prefetch locality out-of-range");
2692 // The locality degree is the opposite of the cache speed.
2693 // Put the number the other way around.
2694 // The encoding starts at 0 for level 1
2695 Locality = 3 - Locality;
2698 // built the mask value encoding the expected behavior.
2699 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2700 (!IsData << 3) | // IsDataCache bit
2701 (Locality << 1) | // Cache level bits
2702 (unsigned)IsStream; // Stream bit
2703 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2704 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2707 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2708 SelectionDAG &DAG) const {
2709 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2712 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2714 return LowerF128Call(Op, DAG, LC);
2717 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2718 SelectionDAG &DAG) const {
2719 bool IsStrict = Op->isStrictFPOpcode();
2720 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2721 EVT SrcVT = SrcVal.getValueType();
2723 if (SrcVT != MVT::f128) {
2724 // Expand cases where the input is a vector bigger than NEON.
2725 if (useSVEForFixedLengthVectorVT(SrcVT))
2728 // It's legal except when f128 is involved
2733 LC = RTLIB::getFPROUND(SrcVT, Op.getValueType());
2735 // FP_ROUND node has a second operand indicating whether it is known to be
2736 // precise. That doesn't take part in the LibCall so we can't directly use
2738 MakeLibCallOptions CallOptions;
2739 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
2742 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
2743 CallOptions, dl, Chain);
2744 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
2747 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2748 SelectionDAG &DAG) const {
2749 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2750 // Any additional optimization in this function should be recorded
2751 // in the cost tables.
2752 EVT InVT = Op.getOperand(0).getValueType();
2753 EVT VT = Op.getValueType();
2754 unsigned NumElts = InVT.getVectorNumElements();
2756 // f16 conversions are promoted to f32 when full fp16 is not supported.
2757 if (InVT.getVectorElementType() == MVT::f16 &&
2758 !Subtarget->hasFullFP16()) {
2759 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2762 Op.getOpcode(), dl, Op.getValueType(),
2763 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2766 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2769 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2771 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2774 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2777 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2778 VT.getVectorNumElements());
2779 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2780 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2783 // Type changing conversions are illegal.
2787 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2788 SelectionDAG &DAG) const {
2789 bool IsStrict = Op->isStrictFPOpcode();
2790 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2792 if (SrcVal.getValueType().isVector())
2793 return LowerVectorFP_TO_INT(Op, DAG);
2795 // f16 conversions are promoted to f32 when full fp16 is not supported.
2796 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
2797 assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2800 Op.getOpcode(), dl, Op.getValueType(),
2801 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
2804 if (SrcVal.getValueType() != MVT::f128) {
2805 // It's legal except when f128 is involved
2810 if (Op.getOpcode() == ISD::FP_TO_SINT ||
2811 Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
2812 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType());
2814 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType());
2816 return LowerF128Call(Op, DAG, LC);
2819 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2820 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2821 // Any additional optimization in this function should be recorded
2822 // in the cost tables.
2823 EVT VT = Op.getValueType();
2825 SDValue In = Op.getOperand(0);
2826 EVT InVT = In.getValueType();
2828 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2830 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2831 InVT.getVectorNumElements());
2832 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2833 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2836 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2838 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2839 EVT CastVT = VT.changeVectorElementTypeToInteger();
2840 In = DAG.getNode(CastOpc, dl, CastVT, In);
2841 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2847 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2848 SelectionDAG &DAG) const {
2849 if (Op.getValueType().isVector())
2850 return LowerVectorINT_TO_FP(Op, DAG);
2852 bool IsStrict = Op->isStrictFPOpcode();
2853 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
2855 // f16 conversions are promoted to f32 when full fp16 is not supported.
2856 if (Op.getValueType() == MVT::f16 &&
2857 !Subtarget->hasFullFP16()) {
2858 assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
2861 ISD::FP_ROUND, dl, MVT::f16,
2862 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
2863 DAG.getIntPtrConstant(0, dl));
2866 // i128 conversions are libcalls.
2867 if (SrcVal.getValueType() == MVT::i128)
2870 // Other conversions are legal, unless it's to the completely software-based
2872 if (Op.getValueType() != MVT::f128)
2876 if (Op.getOpcode() == ISD::SINT_TO_FP ||
2877 Op.getOpcode() == ISD::STRICT_SINT_TO_FP)
2878 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType());
2880 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType());
2882 return LowerF128Call(Op, DAG, LC);
2885 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2886 SelectionDAG &DAG) const {
2887 // For iOS, we want to call an alternative entry point: __sincos_stret,
2888 // which returns the values in two S / D registers.
2890 SDValue Arg = Op.getOperand(0);
2891 EVT ArgVT = Arg.getValueType();
2892 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2899 Entry.IsSExt = false;
2900 Entry.IsZExt = false;
2901 Args.push_back(Entry);
2903 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2904 : RTLIB::SINCOS_STRET_F32;
2905 const char *LibcallName = getLibcallName(LC);
2907 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2909 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2910 TargetLowering::CallLoweringInfo CLI(DAG);
2912 .setChain(DAG.getEntryNode())
2913 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2915 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2916 return CallResult.first;
2919 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2920 EVT OpVT = Op.getValueType();
2921 if (OpVT != MVT::f16 && OpVT != MVT::bf16)
2924 assert(Op.getOperand(0).getValueType() == MVT::i16);
2927 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2928 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2930 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
2931 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2935 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2936 if (OrigVT.getSizeInBits() >= 64)
2939 assert(OrigVT.isSimple() && "Expecting a simple value type");
2941 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2942 switch (OrigSimpleTy) {
2943 default: llvm_unreachable("Unexpected Vector Type");
2952 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2955 unsigned ExtOpcode) {
2956 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2957 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2958 // 64-bits we need to insert a new extension so that it will be 64-bits.
2959 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2960 if (OrigTy.getSizeInBits() >= 64)
2963 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2964 EVT NewVT = getExtensionTo64Bits(OrigTy);
2966 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2969 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2971 EVT VT = N->getValueType(0);
2973 if (N->getOpcode() != ISD::BUILD_VECTOR)
2976 for (const SDValue &Elt : N->op_values()) {
2977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2978 unsigned EltSize = VT.getScalarSizeInBits();
2979 unsigned HalfSize = EltSize / 2;
2981 if (!isIntN(HalfSize, C->getSExtValue()))
2984 if (!isUIntN(HalfSize, C->getZExtValue()))
2995 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2996 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2997 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2998 N->getOperand(0)->getValueType(0),
3002 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
3003 EVT VT = N->getValueType(0);
3005 unsigned EltSize = VT.getScalarSizeInBits() / 2;
3006 unsigned NumElts = VT.getVectorNumElements();
3007 MVT TruncVT = MVT::getIntegerVT(EltSize);
3008 SmallVector<SDValue, 8> Ops;
3009 for (unsigned i = 0; i != NumElts; ++i) {
3010 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
3011 const APInt &CInt = C->getAPIntValue();
3012 // Element types smaller than 32 bits are not legal, so use i32 elements.
3013 // The values are implicitly truncated so sext vs. zext doesn't matter.
3014 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
3016 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
3019 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
3020 return N->getOpcode() == ISD::SIGN_EXTEND ||
3021 isExtendedBUILD_VECTOR(N, DAG, true);
3024 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
3025 return N->getOpcode() == ISD::ZERO_EXTEND ||
3026 isExtendedBUILD_VECTOR(N, DAG, false);
3029 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
3030 unsigned Opcode = N->getOpcode();
3031 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3032 SDNode *N0 = N->getOperand(0).getNode();
3033 SDNode *N1 = N->getOperand(1).getNode();
3034 return N0->hasOneUse() && N1->hasOneUse() &&
3035 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
3040 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
3041 unsigned Opcode = N->getOpcode();
3042 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
3043 SDNode *N0 = N->getOperand(0).getNode();
3044 SDNode *N1 = N->getOperand(1).getNode();
3045 return N0->hasOneUse() && N1->hasOneUse() &&
3046 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
3051 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3052 SelectionDAG &DAG) const {
3053 // The rounding mode is in bits 23:22 of the FPSCR.
3054 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3055 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3056 // so that the shift + and get folded into a bitfield extract.
3059 SDValue Chain = Op.getOperand(0);
3060 SDValue FPCR_64 = DAG.getNode(
3061 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
3062 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
3063 Chain = FPCR_64.getValue(1);
3064 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
3065 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
3066 DAG.getConstant(1U << 22, dl, MVT::i32));
3067 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3068 DAG.getConstant(22, dl, MVT::i32));
3069 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3070 DAG.getConstant(3, dl, MVT::i32));
3071 return DAG.getMergeValues({AND, Chain}, dl);
3074 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
3075 // Multiplications are only custom-lowered for 128-bit vectors so that
3076 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
3077 EVT VT = Op.getValueType();
3078 assert(VT.is128BitVector() && VT.isInteger() &&
3079 "unexpected type for custom-lowering ISD::MUL");
3080 SDNode *N0 = Op.getOperand(0).getNode();
3081 SDNode *N1 = Op.getOperand(1).getNode();
3082 unsigned NewOpc = 0;
3084 bool isN0SExt = isSignExtended(N0, DAG);
3085 bool isN1SExt = isSignExtended(N1, DAG);
3086 if (isN0SExt && isN1SExt)
3087 NewOpc = AArch64ISD::SMULL;
3089 bool isN0ZExt = isZeroExtended(N0, DAG);
3090 bool isN1ZExt = isZeroExtended(N1, DAG);
3091 if (isN0ZExt && isN1ZExt)
3092 NewOpc = AArch64ISD::UMULL;
3093 else if (isN1SExt || isN1ZExt) {
3094 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
3095 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
3096 if (isN1SExt && isAddSubSExt(N0, DAG)) {
3097 NewOpc = AArch64ISD::SMULL;
3099 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
3100 NewOpc = AArch64ISD::UMULL;
3102 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
3104 NewOpc = AArch64ISD::UMULL;
3110 if (VT == MVT::v2i64)
3111 // Fall through to expand this. It is not legal.
3114 // Other vector multiplications are legal.
3119 // Legalize to a S/UMULL instruction
3122 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
3124 Op0 = skipExtensionForVectorMULL(N0, DAG);
3125 assert(Op0.getValueType().is64BitVector() &&
3126 Op1.getValueType().is64BitVector() &&
3127 "unexpected types for extended operands to VMULL");
3128 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
3130 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
3131 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
3132 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
3133 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
3134 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
3135 EVT Op1VT = Op1.getValueType();
3136 return DAG.getNode(N0->getOpcode(), DL, VT,
3137 DAG.getNode(NewOpc, DL, VT,
3138 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
3139 DAG.getNode(NewOpc, DL, VT,
3140 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
3143 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
3145 return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
3146 DAG.getTargetConstant(Pattern, DL, MVT::i32));
3149 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3150 SelectionDAG &DAG) const {
3151 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3154 default: return SDValue(); // Don't custom lower most intrinsics.
3155 case Intrinsic::thread_pointer: {
3156 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3157 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
3159 case Intrinsic::aarch64_neon_abs: {
3160 EVT Ty = Op.getValueType();
3161 if (Ty == MVT::i64) {
3162 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
3164 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
3165 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
3166 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
3167 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
3169 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
3172 case Intrinsic::aarch64_neon_smax:
3173 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
3174 Op.getOperand(1), Op.getOperand(2));
3175 case Intrinsic::aarch64_neon_umax:
3176 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
3177 Op.getOperand(1), Op.getOperand(2));
3178 case Intrinsic::aarch64_neon_smin:
3179 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
3180 Op.getOperand(1), Op.getOperand(2));
3181 case Intrinsic::aarch64_neon_umin:
3182 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
3183 Op.getOperand(1), Op.getOperand(2));
3185 case Intrinsic::aarch64_sve_sunpkhi:
3186 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
3188 case Intrinsic::aarch64_sve_sunpklo:
3189 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
3191 case Intrinsic::aarch64_sve_uunpkhi:
3192 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
3194 case Intrinsic::aarch64_sve_uunpklo:
3195 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
3197 case Intrinsic::aarch64_sve_clasta_n:
3198 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
3199 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3200 case Intrinsic::aarch64_sve_clastb_n:
3201 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
3202 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3203 case Intrinsic::aarch64_sve_lasta:
3204 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
3205 Op.getOperand(1), Op.getOperand(2));
3206 case Intrinsic::aarch64_sve_lastb:
3207 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
3208 Op.getOperand(1), Op.getOperand(2));
3209 case Intrinsic::aarch64_sve_rev:
3210 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
3212 case Intrinsic::aarch64_sve_tbl:
3213 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
3214 Op.getOperand(1), Op.getOperand(2));
3215 case Intrinsic::aarch64_sve_trn1:
3216 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
3217 Op.getOperand(1), Op.getOperand(2));
3218 case Intrinsic::aarch64_sve_trn2:
3219 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
3220 Op.getOperand(1), Op.getOperand(2));
3221 case Intrinsic::aarch64_sve_uzp1:
3222 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
3223 Op.getOperand(1), Op.getOperand(2));
3224 case Intrinsic::aarch64_sve_uzp2:
3225 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
3226 Op.getOperand(1), Op.getOperand(2));
3227 case Intrinsic::aarch64_sve_zip1:
3228 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
3229 Op.getOperand(1), Op.getOperand(2));
3230 case Intrinsic::aarch64_sve_zip2:
3231 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
3232 Op.getOperand(1), Op.getOperand(2));
3233 case Intrinsic::aarch64_sve_ptrue:
3234 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
3236 case Intrinsic::aarch64_sve_dupq_lane:
3237 return LowerDUPQLane(Op, DAG);
3238 case Intrinsic::aarch64_sve_convert_from_svbool:
3239 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
3241 case Intrinsic::aarch64_sve_convert_to_svbool: {
3242 EVT OutVT = Op.getValueType();
3243 EVT InVT = Op.getOperand(1).getValueType();
3244 // Return the operand if the cast isn't changing type,
3245 // i.e. <n x 16 x i1> -> <n x 16 x i1>
3247 return Op.getOperand(1);
3248 // Otherwise, zero the newly introduced lanes.
3249 SDValue Reinterpret =
3250 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
3251 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
3252 SDValue MaskReinterpret =
3253 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
3254 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
3257 case Intrinsic::aarch64_sve_insr: {
3258 SDValue Scalar = Op.getOperand(2);
3259 EVT ScalarTy = Scalar.getValueType();
3260 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
3261 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
3263 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3264 Op.getOperand(1), Scalar);
3267 case Intrinsic::localaddress: {
3268 const auto &MF = DAG.getMachineFunction();
3269 const auto *RegInfo = Subtarget->getRegisterInfo();
3270 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3271 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3272 Op.getSimpleValueType());
3275 case Intrinsic::eh_recoverfp: {
3276 // FIXME: This needs to be implemented to correctly handle highly aligned
3277 // stack objects. For now we simply return the incoming FP. Refer D53541
3278 // for more details.
3279 SDValue FnOp = Op.getOperand(1);
3280 SDValue IncomingFPOp = Op.getOperand(2);
3281 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3282 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3285 "llvm.eh.recoverfp must take a function as the first argument");
3286 return IncomingFPOp;
3289 case Intrinsic::aarch64_neon_vsri:
3290 case Intrinsic::aarch64_neon_vsli: {
3291 EVT Ty = Op.getValueType();
3294 report_fatal_error("Unexpected type for aarch64_neon_vsli");
3296 assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
3298 bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
3299 unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
3300 return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
3304 case Intrinsic::aarch64_neon_srhadd:
3305 case Intrinsic::aarch64_neon_urhadd: {
3306 bool IsSignedAdd = IntNo == Intrinsic::aarch64_neon_srhadd;
3307 unsigned Opcode = IsSignedAdd ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
3308 return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
3314 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3315 return ExtVal.getValueType().isScalableVector();
3318 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3319 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3321 SelectionDAG &DAG) {
3322 assert(VT.isVector() && "VT should be a vector type");
3323 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3325 SDValue Value = ST->getValue();
3327 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3328 // the word lane which represent the v4i8 subvector. It optimizes the store
3334 SDValue Undef = DAG.getUNDEF(MVT::i16);
3335 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3336 {Undef, Undef, Undef, Undef});
3338 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3340 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3342 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3343 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3344 Trunc, DAG.getConstant(0, DL, MVT::i64));
3346 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3347 ST->getBasePtr(), ST->getMemOperand());
3350 // Custom lowering for any store, vector or scalar and/or default or with
3351 // a truncate operations. Currently only custom lower truncate operation
3352 // from vector v4i16 to v4i8 or volatile stores of i128.
3353 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3354 SelectionDAG &DAG) const {
3356 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3357 assert (StoreNode && "Can only custom lower store nodes");
3359 SDValue Value = StoreNode->getValue();
3361 EVT VT = Value.getValueType();
3362 EVT MemVT = StoreNode->getMemoryVT();
3364 if (VT.isVector()) {
3365 if (useSVEForFixedLengthVectorVT(VT))
3366 return LowerFixedLengthVectorStoreToSVE(Op, DAG);
3368 unsigned AS = StoreNode->getAddressSpace();
3369 Align Alignment = StoreNode->getAlign();
3370 if (Alignment < MemVT.getStoreSize() &&
3371 !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
3372 StoreNode->getMemOperand()->getFlags(),
3374 return scalarizeVectorStore(StoreNode, DAG);
3377 if (StoreNode->isTruncatingStore()) {
3378 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3380 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3381 // the custom lowering, as there are no un-paired non-temporal stores and
3382 // legalization will break up 256 bit inputs.
3383 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3384 MemVT.getVectorElementCount().Min % 2u == 0 &&
3385 ((MemVT.getScalarSizeInBits() == 8u ||
3386 MemVT.getScalarSizeInBits() == 16u ||
3387 MemVT.getScalarSizeInBits() == 32u ||
3388 MemVT.getScalarSizeInBits() == 64u))) {
3390 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3391 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3392 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3393 SDValue Hi = DAG.getNode(
3394 ISD::EXTRACT_SUBVECTOR, Dl,
3395 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3396 StoreNode->getValue(),
3397 DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3398 SDValue Result = DAG.getMemIntrinsicNode(
3399 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3400 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3401 StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3404 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3405 assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3407 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3408 DAG.getConstant(0, Dl, MVT::i64));
3410 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3411 DAG.getConstant(1, Dl, MVT::i64));
3412 SDValue Result = DAG.getMemIntrinsicNode(
3413 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3414 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3415 StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3422 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3423 SelectionDAG &DAG) const {
3424 LLVM_DEBUG(dbgs() << "Custom lowering: ");
3425 LLVM_DEBUG(Op.dump());
3427 switch (Op.getOpcode()) {
3429 llvm_unreachable("unimplemented operand");
3432 return LowerBITCAST(Op, DAG);
3433 case ISD::GlobalAddress:
3434 return LowerGlobalAddress(Op, DAG);
3435 case ISD::GlobalTLSAddress:
3436 return LowerGlobalTLSAddress(Op, DAG);
3438 case ISD::STRICT_FSETCC:
3439 case ISD::STRICT_FSETCCS:
3440 return LowerSETCC(Op, DAG);
3442 return LowerBR_CC(Op, DAG);
3444 return LowerSELECT(Op, DAG);
3445 case ISD::SELECT_CC:
3446 return LowerSELECT_CC(Op, DAG);
3447 case ISD::JumpTable:
3448 return LowerJumpTable(Op, DAG);
3450 return LowerBR_JT(Op, DAG);
3451 case ISD::ConstantPool:
3452 return LowerConstantPool(Op, DAG);
3453 case ISD::BlockAddress:
3454 return LowerBlockAddress(Op, DAG);
3456 return LowerVASTART(Op, DAG);
3458 return LowerVACOPY(Op, DAG);
3460 return LowerVAARG(Op, DAG);
3465 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3472 return LowerXALUO(Op, DAG);
3474 if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3475 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
3476 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3478 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3480 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3482 return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
3484 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3486 case ISD::STRICT_FP_ROUND:
3487 return LowerFP_ROUND(Op, DAG);
3488 case ISD::FP_EXTEND:
3489 return LowerFP_EXTEND(Op, DAG);
3490 case ISD::FRAMEADDR:
3491 return LowerFRAMEADDR(Op, DAG);
3492 case ISD::SPONENTRY:
3493 return LowerSPONENTRY(Op, DAG);
3494 case ISD::RETURNADDR:
3495 return LowerRETURNADDR(Op, DAG);
3496 case ISD::ADDROFRETURNADDR:
3497 return LowerADDROFRETURNADDR(Op, DAG);
3498 case ISD::INSERT_VECTOR_ELT:
3499 return LowerINSERT_VECTOR_ELT(Op, DAG);
3500 case ISD::EXTRACT_VECTOR_ELT:
3501 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3502 case ISD::BUILD_VECTOR:
3503 return LowerBUILD_VECTOR(Op, DAG);
3504 case ISD::VECTOR_SHUFFLE:
3505 return LowerVECTOR_SHUFFLE(Op, DAG);
3506 case ISD::SPLAT_VECTOR:
3507 return LowerSPLAT_VECTOR(Op, DAG);
3508 case ISD::EXTRACT_SUBVECTOR:
3509 return LowerEXTRACT_SUBVECTOR(Op, DAG);
3510 case ISD::INSERT_SUBVECTOR:
3511 return LowerINSERT_SUBVECTOR(Op, DAG);
3513 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SDIV_PRED);
3515 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UDIV_PRED);
3517 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_MERGE_OP1);
3519 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_MERGE_OP1);
3521 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_MERGE_OP1);
3523 return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_MERGE_OP1);
3527 return LowerVectorSRA_SRL_SHL(Op, DAG);
3528 case ISD::SHL_PARTS:
3529 return LowerShiftLeftParts(Op, DAG);
3530 case ISD::SRL_PARTS:
3531 case ISD::SRA_PARTS:
3532 return LowerShiftRightParts(Op, DAG);
3534 return LowerCTPOP(Op, DAG);
3535 case ISD::FCOPYSIGN:
3536 return LowerFCOPYSIGN(Op, DAG);
3538 return LowerVectorOR(Op, DAG);
3540 return LowerXOR(Op, DAG);
3542 return LowerPREFETCH(Op, DAG);
3543 case ISD::SINT_TO_FP:
3544 case ISD::UINT_TO_FP:
3545 case ISD::STRICT_SINT_TO_FP:
3546 case ISD::STRICT_UINT_TO_FP:
3547 return LowerINT_TO_FP(Op, DAG);
3548 case ISD::FP_TO_SINT:
3549 case ISD::FP_TO_UINT:
3550 case ISD::STRICT_FP_TO_SINT:
3551 case ISD::STRICT_FP_TO_UINT:
3552 return LowerFP_TO_INT(Op, DAG);
3554 return LowerFSINCOS(Op, DAG);
3555 case ISD::FLT_ROUNDS_:
3556 return LowerFLT_ROUNDS_(Op, DAG);
3558 return LowerMUL(Op, DAG);
3559 case ISD::INTRINSIC_WO_CHAIN:
3560 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3562 return LowerSTORE(Op, DAG);
3563 case ISD::VECREDUCE_ADD:
3564 case ISD::VECREDUCE_SMAX:
3565 case ISD::VECREDUCE_SMIN:
3566 case ISD::VECREDUCE_UMAX:
3567 case ISD::VECREDUCE_UMIN:
3568 case ISD::VECREDUCE_FMAX:
3569 case ISD::VECREDUCE_FMIN:
3570 return LowerVECREDUCE(Op, DAG);
3571 case ISD::ATOMIC_LOAD_SUB:
3572 return LowerATOMIC_LOAD_SUB(Op, DAG);
3573 case ISD::ATOMIC_LOAD_AND:
3574 return LowerATOMIC_LOAD_AND(Op, DAG);
3575 case ISD::DYNAMIC_STACKALLOC:
3576 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3578 return LowerVSCALE(Op, DAG);
3580 return LowerTRUNCATE(Op, DAG);
3582 if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3583 return LowerFixedLengthVectorLoadToSVE(Op, DAG);
3584 llvm_unreachable("Unexpected request to lower ISD::LOAD");
3586 if (useSVEForFixedLengthVectorVT(Op.getValueType()))
3587 return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
3588 llvm_unreachable("Unexpected request to lower ISD::ADD");
3592 bool AArch64TargetLowering::useSVEForFixedLengthVectors() const {
3593 // Prefer NEON unless larger SVE registers are available.
3594 return Subtarget->hasSVE() && Subtarget->getMinSVEVectorSizeInBits() >= 256;
3597 bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(EVT VT) const {
3598 if (!useSVEForFixedLengthVectors())
3601 if (!VT.isFixedLengthVector())
3604 // Fixed length predicates should be promoted to i8.
3605 // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
3606 if (VT.getVectorElementType() == MVT::i1)
3609 // Don't use SVE for vectors we cannot scalarize if required.
3610 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
3623 // Ensure NEON MVTs only belong to a single register class.
3624 if (VT.getSizeInBits() <= 128)
3627 // Don't use SVE for types that don't fit.
3628 if (VT.getSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
3631 // TODO: Perhaps an artificial restriction, but worth having whilst getting
3632 // the base fixed length SVE support in place.
3633 if (!VT.isPow2VectorType())
3639 //===----------------------------------------------------------------------===//
3640 // Calling Convention Implementation
3641 //===----------------------------------------------------------------------===//
3643 /// Selects the correct CCAssignFn for a given CallingConvention value.
3644 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3645 bool IsVarArg) const {
3648 report_fatal_error("Unsupported calling convention.");
3649 case CallingConv::WebKit_JS:
3650 return CC_AArch64_WebKit_JS;
3651 case CallingConv::GHC:
3652 return CC_AArch64_GHC;
3653 case CallingConv::C:
3654 case CallingConv::Fast:
3655 case CallingConv::PreserveMost:
3656 case CallingConv::CXX_FAST_TLS:
3657 case CallingConv::Swift:
3658 if (Subtarget->isTargetWindows() && IsVarArg)
3659 return CC_AArch64_Win64_VarArg;
3660 if (!Subtarget->isTargetDarwin())
3661 return CC_AArch64_AAPCS;
3663 return CC_AArch64_DarwinPCS;
3664 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3665 : CC_AArch64_DarwinPCS_VarArg;
3666 case CallingConv::Win64:
3667 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3668 case CallingConv::CFGuard_Check:
3669 return CC_AArch64_Win64_CFGuard_Check;
3670 case CallingConv::AArch64_VectorCall:
3671 case CallingConv::AArch64_SVE_VectorCall:
3672 return CC_AArch64_AAPCS;
3677 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3678 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3679 : RetCC_AArch64_AAPCS;
3682 SDValue AArch64TargetLowering::LowerFormalArguments(
3683 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3684 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3685 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3686 MachineFunction &MF = DAG.getMachineFunction();
3687 MachineFrameInfo &MFI = MF.getFrameInfo();
3688 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3690 // Assign locations to all of the incoming arguments.
3691 SmallVector<CCValAssign, 16> ArgLocs;
3692 DenseMap<unsigned, SDValue> CopiedRegs;
3693 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3696 // At this point, Ins[].VT may already be promoted to i32. To correctly
3697 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3698 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3699 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3700 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3702 unsigned NumArgs = Ins.size();
3703 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3704 unsigned CurArgIdx = 0;
3705 for (unsigned i = 0; i != NumArgs; ++i) {
3706 MVT ValVT = Ins[i].VT;
3707 if (Ins[i].isOrigArg()) {
3708 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3709 CurArgIdx = Ins[i].getOrigArgIndex();
3711 // Get type of the original argument.
3712 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3713 /*AllowUnknown*/ true);
3714 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3715 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3716 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3718 else if (ActualMVT == MVT::i16)
3721 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3723 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3724 assert(!Res && "Call operand has unhandled type");
3727 assert(ArgLocs.size() == Ins.size());
3728 SmallVector<SDValue, 16> ArgValues;
3729 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3730 CCValAssign &VA = ArgLocs[i];
3732 if (Ins[i].Flags.isByVal()) {
3733 // Byval is used for HFAs in the PCS, but the system should work in a
3734 // non-compliant manner for larger structs.
3735 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3736 int Size = Ins[i].Flags.getByValSize();
3737 unsigned NumRegs = (Size + 7) / 8;
3739 // FIXME: This works on big-endian for composite byvals, which are the common
3740 // case. It should also work for fundamental types too.
3742 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3743 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3744 InVals.push_back(FrameIdxN);
3750 if (VA.isRegLoc()) {
3751 // Arguments stored in registers.
3752 EVT RegVT = VA.getLocVT();
3753 const TargetRegisterClass *RC;
3755 if (RegVT == MVT::i32)
3756 RC = &AArch64::GPR32RegClass;
3757 else if (RegVT == MVT::i64)
3758 RC = &AArch64::GPR64RegClass;
3759 else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
3760 RC = &AArch64::FPR16RegClass;
3761 else if (RegVT == MVT::f32)
3762 RC = &AArch64::FPR32RegClass;
3763 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3764 RC = &AArch64::FPR64RegClass;
3765 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3766 RC = &AArch64::FPR128RegClass;
3767 else if (RegVT.isScalableVector() &&
3768 RegVT.getVectorElementType() == MVT::i1)
3769 RC = &AArch64::PPRRegClass;
3770 else if (RegVT.isScalableVector())
3771 RC = &AArch64::ZPRRegClass;
3773 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3775 // Transform the arguments in physical registers into virtual ones.
3776 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3777 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3779 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3780 // to 64 bits. Insert an assert[sz]ext to capture this, then
3781 // truncate to the right size.
3782 switch (VA.getLocInfo()) {
3784 llvm_unreachable("Unknown loc info!");
3785 case CCValAssign::Full:
3787 case CCValAssign::Indirect:
3788 assert(VA.getValVT().isScalableVector() &&
3789 "Only scalable vectors can be passed indirectly");
3791 case CCValAssign::BCvt:
3792 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3794 case CCValAssign::AExt:
3795 case CCValAssign::SExt:
3796 case CCValAssign::ZExt:
3798 case CCValAssign::AExtUpper:
3799 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3800 DAG.getConstant(32, DL, RegVT));
3801 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3804 } else { // VA.isRegLoc()
3805 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3806 unsigned ArgOffset = VA.getLocMemOffset();
3807 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
3808 ? VA.getLocVT().getSizeInBits()
3809 : VA.getValVT().getSizeInBits()) / 8;
3811 uint32_t BEAlign = 0;
3812 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3813 !Ins[i].Flags.isInConsecutiveRegs())
3814 BEAlign = 8 - ArgSize;
3816 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3818 // Create load nodes to retrieve arguments from the stack.
3819 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3821 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3822 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3823 MVT MemVT = VA.getValVT();
3825 switch (VA.getLocInfo()) {
3828 case CCValAssign::Trunc:
3829 case CCValAssign::BCvt:
3830 MemVT = VA.getLocVT();
3832 case CCValAssign::Indirect:
3833 assert(VA.getValVT().isScalableVector() &&
3834 "Only scalable vectors can be passed indirectly");
3835 MemVT = VA.getLocVT();
3837 case CCValAssign::SExt:
3838 ExtType = ISD::SEXTLOAD;
3840 case CCValAssign::ZExt:
3841 ExtType = ISD::ZEXTLOAD;
3843 case CCValAssign::AExt:
3844 ExtType = ISD::EXTLOAD;
3848 ArgValue = DAG.getExtLoad(
3849 ExtType, DL, VA.getLocVT(), Chain, FIN,
3850 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3855 if (VA.getLocInfo() == CCValAssign::Indirect) {
3856 assert(VA.getValVT().isScalableVector() &&
3857 "Only scalable vectors can be passed indirectly");
3858 // If value is passed via pointer - do a load.
3860 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo());
3863 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3864 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3865 ArgValue, DAG.getValueType(MVT::i32));
3866 InVals.push_back(ArgValue);
3870 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3872 if (!Subtarget->isTargetDarwin() || IsWin64) {
3873 // The AAPCS variadic function ABI is identical to the non-variadic
3874 // one. As a result there may be more arguments in registers and we should
3875 // save them for future reference.
3876 // Win64 variadic functions also pass arguments in registers, but all float
3877 // arguments are passed in integer registers.
3878 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3881 // This will point to the next argument passed via stack.
3882 unsigned StackOffset = CCInfo.getNextStackOffset();
3883 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3884 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3885 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3887 if (MFI.hasMustTailInVarArgFunc()) {
3888 SmallVector<MVT, 2> RegParmTypes;
3889 RegParmTypes.push_back(MVT::i64);
3890 RegParmTypes.push_back(MVT::f128);
3891 // Compute the set of forwarded registers. The rest are scratch.
3892 SmallVectorImpl<ForwardedRegister> &Forwards =
3893 FuncInfo->getForwardedMustTailRegParms();
3894 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3897 // Conservatively forward X8, since it might be used for aggregate return.
3898 if (!CCInfo.isAllocated(AArch64::X8)) {
3899 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3900 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3905 // On Windows, InReg pointers must be returned, so record the pointer in a
3906 // virtual register at the start of the function so it can be returned in the
3909 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3910 if (Ins[I].Flags.isInReg()) {
3911 assert(!FuncInfo->getSRetReturnReg());
3913 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3915 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3916 FuncInfo->setSRetReturnReg(Reg);
3918 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3919 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3925 unsigned StackArgSize = CCInfo.getNextStackOffset();
3926 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3927 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3928 // This is a non-standard ABI so by fiat I say we're allowed to make full
3929 // use of the stack area to be popped, which must be aligned to 16 bytes in
3931 StackArgSize = alignTo(StackArgSize, 16);
3933 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3934 // a multiple of 16.
3935 FuncInfo->setArgumentStackToRestore(StackArgSize);
3937 // This realignment carries over to the available bytes below. Our own
3938 // callers will guarantee the space is free by giving an aligned value to
3941 // Even if we're not expected to free up the space, it's useful to know how
3942 // much is there while considering tail calls (because we can reuse it).
3943 FuncInfo->setBytesInStackArgArea(StackArgSize);
3945 if (Subtarget->hasCustomCallingConv())
3946 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3951 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3954 SDValue &Chain) const {
3955 MachineFunction &MF = DAG.getMachineFunction();
3956 MachineFrameInfo &MFI = MF.getFrameInfo();
3957 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3958 auto PtrVT = getPointerTy(DAG.getDataLayout());
3959 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3961 SmallVector<SDValue, 8> MemOps;
3963 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3964 AArch64::X3, AArch64::X4, AArch64::X5,
3965 AArch64::X6, AArch64::X7 };
3966 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3967 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3969 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3971 if (GPRSaveSize != 0) {
3973 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3974 if (GPRSaveSize & 15)
3975 // The extra size here, if triggered, will always be 8.
3976 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3978 GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
3980 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3982 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3983 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3984 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3985 SDValue Store = DAG.getStore(
3986 Val.getValue(1), DL, Val, FIN,
3988 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3990 (i - FirstVariadicGPR) * 8)
3991 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3992 MemOps.push_back(Store);
3994 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3997 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3998 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
4000 if (Subtarget->hasFPARMv8() && !IsWin64) {
4001 static const MCPhysReg FPRArgRegs[] = {
4002 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
4003 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
4004 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
4005 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
4007 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
4009 if (FPRSaveSize != 0) {
4010 FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
4012 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
4014 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
4015 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
4016 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
4018 SDValue Store = DAG.getStore(
4019 Val.getValue(1), DL, Val, FIN,
4020 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
4021 MemOps.push_back(Store);
4022 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
4023 DAG.getConstant(16, DL, PtrVT));
4026 FuncInfo->setVarArgsFPRIndex(FPRIdx);
4027 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
4030 if (!MemOps.empty()) {
4031 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4035 /// LowerCallResult - Lower the result values of a call into the
4036 /// appropriate copies out of appropriate physical registers.
4037 SDValue AArch64TargetLowering::LowerCallResult(
4038 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4039 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
4040 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
4041 SDValue ThisVal) const {
4042 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4043 ? RetCC_AArch64_WebKit_JS
4044 : RetCC_AArch64_AAPCS;
4045 // Assign locations to each value returned by this call.
4046 SmallVector<CCValAssign, 16> RVLocs;
4047 DenseMap<unsigned, SDValue> CopiedRegs;
4048 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4050 CCInfo.AnalyzeCallResult(Ins, RetCC);
4052 // Copy all of the result registers out of their specified physreg.
4053 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4054 CCValAssign VA = RVLocs[i];
4056 // Pass 'this' value directly from the argument to return value, to avoid
4057 // reg unit interference
4058 if (i == 0 && isThisReturn) {
4059 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
4060 "unexpected return calling convention register assignment");
4061 InVals.push_back(ThisVal);
4065 // Avoid copying a physreg twice since RegAllocFast is incompetent and only
4066 // allows one use of a physreg per block.
4067 SDValue Val = CopiedRegs.lookup(VA.getLocReg());
4070 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
4071 Chain = Val.getValue(1);
4072 InFlag = Val.getValue(2);
4073 CopiedRegs[VA.getLocReg()] = Val;
4076 switch (VA.getLocInfo()) {
4078 llvm_unreachable("Unknown loc info!");
4079 case CCValAssign::Full:
4081 case CCValAssign::BCvt:
4082 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
4084 case CCValAssign::AExtUpper:
4085 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
4086 DAG.getConstant(32, DL, VA.getLocVT()));
4088 case CCValAssign::AExt:
4090 case CCValAssign::ZExt:
4091 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
4095 InVals.push_back(Val);
4101 /// Return true if the calling convention is one that we can guarantee TCO for.
4102 static bool canGuaranteeTCO(CallingConv::ID CC) {
4103 return CC == CallingConv::Fast;
4106 /// Return true if we might ever do TCO for calls with this calling convention.
4107 static bool mayTailCallThisCC(CallingConv::ID CC) {
4109 case CallingConv::C:
4110 case CallingConv::PreserveMost:
4111 case CallingConv::Swift:
4114 return canGuaranteeTCO(CC);
4118 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
4119 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4120 const SmallVectorImpl<ISD::OutputArg> &Outs,
4121 const SmallVectorImpl<SDValue> &OutVals,
4122 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4123 if (!mayTailCallThisCC(CalleeCC))
4126 MachineFunction &MF = DAG.getMachineFunction();
4127 const Function &CallerF = MF.getFunction();
4128 CallingConv::ID CallerCC = CallerF.getCallingConv();
4129 bool CCMatch = CallerCC == CalleeCC;
4131 // When using the Windows calling convention on a non-windows OS, we want
4132 // to back up and restore X18 in such functions; we can't do a tail call
4133 // from those functions.
4134 if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
4135 CalleeCC != CallingConv::Win64)
4138 // Byval parameters hand the function a pointer directly into the stack area
4139 // we want to reuse during a tail call. Working around this *is* possible (see
4140 // X86) but less efficient and uglier in LowerCall.
4141 for (Function::const_arg_iterator i = CallerF.arg_begin(),
4142 e = CallerF.arg_end();
4144 if (i->hasByValAttr())
4147 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
4148 // In this case, it is necessary to save/restore X0 in the callee. Tail
4149 // call opt interferes with this. So we disable tail call opt when the
4150 // caller has an argument with "inreg" attribute.
4152 // FIXME: Check whether the callee also has an "inreg" argument.
4153 if (i->hasInRegAttr())
4157 if (getTargetMachine().Options.GuaranteedTailCallOpt)
4158 return canGuaranteeTCO(CalleeCC) && CCMatch;
4160 // Externally-defined functions with weak linkage should not be
4161 // tail-called on AArch64 when the OS does not support dynamic
4162 // pre-emption of symbols, as the AAELF spec requires normal calls
4163 // to undefined weak functions to be replaced with a NOP or jump to the
4164 // next instruction. The behaviour of branch instructions in this
4165 // situation (as used for tail calls) is implementation-defined, so we
4166 // cannot rely on the linker replacing the tail call with a return.
4167 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4168 const GlobalValue *GV = G->getGlobal();
4169 const Triple &TT = getTargetMachine().getTargetTriple();
4170 if (GV->hasExternalWeakLinkage() &&
4171 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
4175 // Now we search for cases where we can use a tail call without changing the
4176 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
4179 // I want anyone implementing a new calling convention to think long and hard
4180 // about this assert.
4181 assert((!isVarArg || CalleeCC == CallingConv::C) &&
4182 "Unexpected variadic calling convention");
4184 LLVMContext &C = *DAG.getContext();
4185 if (isVarArg && !Outs.empty()) {
4186 // At least two cases here: if caller is fastcc then we can't have any
4187 // memory arguments (we'd be expected to clean up the stack afterwards). If
4188 // caller is C then we could potentially use its argument area.
4190 // FIXME: for now we take the most conservative of these in both cases:
4191 // disallow all variadic memory operands.
4192 SmallVector<CCValAssign, 16> ArgLocs;
4193 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4195 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
4196 for (const CCValAssign &ArgLoc : ArgLocs)
4197 if (!ArgLoc.isRegLoc())
4201 // Check that the call results are passed in the same way.
4202 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4203 CCAssignFnForCall(CalleeCC, isVarArg),
4204 CCAssignFnForCall(CallerCC, isVarArg)))
4206 // The callee has to preserve all registers the caller needs to preserve.
4207 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4208 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4210 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4211 if (Subtarget->hasCustomCallingConv()) {
4212 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
4213 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
4215 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4219 // Nothing more to check if the callee is taking no arguments
4223 SmallVector<CCValAssign, 16> ArgLocs;
4224 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4226 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
4228 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4230 // If any of the arguments is passed indirectly, it must be SVE, so the
4231 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
4232 // allocate space on the stack. That is why we determine this explicitly here
4233 // the call cannot be a tailcall.
4234 if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
4235 assert((A.getLocInfo() != CCValAssign::Indirect ||
4236 A.getValVT().isScalableVector()) &&
4237 "Expected value to be scalable");
4238 return A.getLocInfo() == CCValAssign::Indirect;
4242 // If the stack arguments for this call do not fit into our own save area then
4243 // the call cannot be made tail.
4244 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
4247 const MachineRegisterInfo &MRI = MF.getRegInfo();
4248 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4254 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
4256 MachineFrameInfo &MFI,
4257 int ClobberedFI) const {
4258 SmallVector<SDValue, 8> ArgChains;
4259 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
4260 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
4262 // Include the original chain at the beginning of the list. When this is
4263 // used by target LowerCall hooks, this helps legalize find the
4264 // CALLSEQ_BEGIN node.
4265 ArgChains.push_back(Chain);
4267 // Add a chain value for each stack argument corresponding
4268 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
4269 UE = DAG.getEntryNode().getNode()->use_end();
4271 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4272 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4273 if (FI->getIndex() < 0) {
4274 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
4275 int64_t InLastByte = InFirstByte;
4276 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
4278 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
4279 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
4280 ArgChains.push_back(SDValue(L, 1));
4283 // Build a tokenfactor for all the chains.
4284 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4287 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
4288 bool TailCallOpt) const {
4289 return CallCC == CallingConv::Fast && TailCallOpt;
4292 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
4293 /// and add input and output parameter nodes.
4295 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
4296 SmallVectorImpl<SDValue> &InVals) const {
4297 SelectionDAG &DAG = CLI.DAG;
4299 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
4300 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
4301 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
4302 SDValue Chain = CLI.Chain;
4303 SDValue Callee = CLI.Callee;
4304 bool &IsTailCall = CLI.IsTailCall;
4305 CallingConv::ID CallConv = CLI.CallConv;
4306 bool IsVarArg = CLI.IsVarArg;
4308 MachineFunction &MF = DAG.getMachineFunction();
4309 MachineFunction::CallSiteInfo CSInfo;
4310 bool IsThisReturn = false;
4312 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4313 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
4314 bool IsSibCall = false;
4317 // Check if it's really possible to do a tail call.
4318 IsTailCall = isEligibleForTailCallOptimization(
4319 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
4320 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
4321 report_fatal_error("failed to perform tail call elimination on a call "
4322 "site marked musttail");
4324 // A sibling call is one where we're under the usual C ABI and not planning
4325 // to change that but can still do a tail call:
4326 if (!TailCallOpt && IsTailCall)
4333 // Analyze operands of the call, assigning locations to each operand.
4334 SmallVector<CCValAssign, 16> ArgLocs;
4335 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
4339 // Handle fixed and variable vector arguments differently.
4340 // Variable vector arguments always go into memory.
4341 unsigned NumArgs = Outs.size();
4343 for (unsigned i = 0; i != NumArgs; ++i) {
4344 MVT ArgVT = Outs[i].VT;
4345 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4346 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
4347 /*IsVarArg=*/ !Outs[i].IsFixed);
4348 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4349 assert(!Res && "Call operand has unhandled type");
4353 // At this point, Outs[].VT may already be promoted to i32. To correctly
4354 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
4355 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
4356 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
4357 // we use a special version of AnalyzeCallOperands to pass in ValVT and
4359 unsigned NumArgs = Outs.size();
4360 for (unsigned i = 0; i != NumArgs; ++i) {
4361 MVT ValVT = Outs[i].VT;
4362 // Get type of the original argument.
4363 EVT ActualVT = getValueType(DAG.getDataLayout(),
4364 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
4365 /*AllowUnknown*/ true);
4366 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
4367 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4368 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
4369 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
4371 else if (ActualMVT == MVT::i16)
4374 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
4375 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
4376 assert(!Res && "Call operand has unhandled type");
4381 // Get a count of how many bytes are to be pushed on the stack.
4382 unsigned NumBytes = CCInfo.getNextStackOffset();
4385 // Since we're not changing the ABI to make this a tail call, the memory
4386 // operands are already available in the caller's incoming argument space.
4390 // FPDiff is the byte offset of the call's argument area from the callee's.
4391 // Stores to callee stack arguments will be placed in FixedStackSlots offset
4392 // by this amount for a tail call. In a sibling call it must be 0 because the
4393 // caller will deallocate the entire stack and the callee still expects its
4394 // arguments to begin at SP+0. Completely unused for non-tail calls.
4397 if (IsTailCall && !IsSibCall) {
4398 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
4400 // Since callee will pop argument stack as a tail call, we must keep the
4401 // popped size 16-byte aligned.
4402 NumBytes = alignTo(NumBytes, 16);
4404 // FPDiff will be negative if this tail call requires more space than we
4405 // would automatically have in our incoming argument space. Positive if we
4406 // can actually shrink the stack.
4407 FPDiff = NumReusableBytes - NumBytes;
4409 // The stack pointer must be 16-byte aligned at all times it's used for a
4410 // memory operation, which in practice means at *all* times and in
4411 // particular across call boundaries. Therefore our own arguments started at
4412 // a 16-byte aligned SP and the delta applied for the tail call should
4413 // satisfy the same constraint.
4414 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4417 // Adjust the stack pointer for the new arguments...
4418 // These operations are automatically eliminated by the prolog/epilog pass
4420 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4422 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4423 getPointerTy(DAG.getDataLayout()));
4425 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4426 SmallSet<unsigned, 8> RegsUsed;
4427 SmallVector<SDValue, 8> MemOpChains;
4428 auto PtrVT = getPointerTy(DAG.getDataLayout());
4430 if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
4431 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4432 for (const auto &F : Forwards) {
4433 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4434 RegsToPass.emplace_back(F.PReg, Val);
4438 // Walk the register/memloc assignments, inserting copies/loads.
4439 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4440 CCValAssign &VA = ArgLocs[i];
4441 SDValue Arg = OutVals[i];
4442 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4444 // Promote the value if needed.
4445 switch (VA.getLocInfo()) {
4447 llvm_unreachable("Unknown loc info!");
4448 case CCValAssign::Full:
4450 case CCValAssign::SExt:
4451 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4453 case CCValAssign::ZExt:
4454 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4456 case CCValAssign::AExt:
4457 if (Outs[i].ArgVT == MVT::i1) {
4458 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4459 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4460 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4462 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4464 case CCValAssign::AExtUpper:
4465 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4466 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4467 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4468 DAG.getConstant(32, DL, VA.getLocVT()));
4470 case CCValAssign::BCvt:
4471 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4473 case CCValAssign::Trunc:
4474 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4476 case CCValAssign::FPExt:
4477 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4479 case CCValAssign::Indirect:
4480 assert(VA.getValVT().isScalableVector() &&
4481 "Only scalable vectors can be passed indirectly");
4482 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4483 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
4484 Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
4485 int FI = MFI.CreateStackObject(
4486 VA.getValVT().getStoreSize().getKnownMinSize(), Alignment, false);
4487 MFI.setStackID(FI, TargetStackID::SVEVector);
4489 SDValue SpillSlot = DAG.getFrameIndex(
4490 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
4491 Chain = DAG.getStore(
4492 Chain, DL, Arg, SpillSlot,
4493 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4498 if (VA.isRegLoc()) {
4499 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4500 Outs[0].VT == MVT::i64) {
4501 assert(VA.getLocVT() == MVT::i64 &&
4502 "unexpected calling convention register assignment");
4503 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4504 "unexpected use of 'returned'");
4505 IsThisReturn = true;
4507 if (RegsUsed.count(VA.getLocReg())) {
4508 // If this register has already been used then we're trying to pack
4509 // parts of an [N x i32] into an X-register. The extension type will
4510 // take care of putting the two halves in the right place but we have to
4513 std::find_if(RegsToPass.begin(), RegsToPass.end(),
4514 [=](const std::pair<unsigned, SDValue> &Elt) {
4515 return Elt.first == VA.getLocReg();
4518 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4519 // Call site info is used for function's parameter entry value
4520 // tracking. For now we track only simple cases when parameter
4521 // is transferred through whole register.
4522 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4523 [&VA](MachineFunction::ArgRegPair ArgReg) {
4524 return ArgReg.Reg == VA.getLocReg();
4528 RegsToPass.emplace_back(VA.getLocReg(), Arg);
4529 RegsUsed.insert(VA.getLocReg());
4530 const TargetOptions &Options = DAG.getTarget().Options;
4531 if (Options.EmitCallSiteInfo)
4532 CSInfo.emplace_back(VA.getLocReg(), i);
4535 assert(VA.isMemLoc());
4538 MachinePointerInfo DstInfo;
4540 // FIXME: This works on big-endian for composite byvals, which are the
4541 // common case. It should also work for fundamental types too.
4542 uint32_t BEAlign = 0;
4544 if (VA.getLocInfo() == CCValAssign::Indirect)
4545 OpSize = VA.getLocVT().getSizeInBits();
4547 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4548 : VA.getValVT().getSizeInBits();
4549 OpSize = (OpSize + 7) / 8;
4550 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4551 !Flags.isInConsecutiveRegs()) {
4553 BEAlign = 8 - OpSize;
4555 unsigned LocMemOffset = VA.getLocMemOffset();
4556 int32_t Offset = LocMemOffset + BEAlign;
4557 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4558 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4561 Offset = Offset + FPDiff;
4562 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4564 DstAddr = DAG.getFrameIndex(FI, PtrVT);
4566 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4568 // Make sure any stack arguments overlapping with where we're storing
4569 // are loaded before this eventual operation. Otherwise they'll be
4571 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4573 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4575 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4576 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4580 if (Outs[i].Flags.isByVal()) {
4582 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4583 SDValue Cpy = DAG.getMemcpy(
4584 Chain, DL, DstAddr, Arg, SizeNode,
4585 Outs[i].Flags.getNonZeroByValAlign(),
4586 /*isVol = */ false, /*AlwaysInline = */ false,
4587 /*isTailCall = */ false, DstInfo, MachinePointerInfo());
4589 MemOpChains.push_back(Cpy);
4591 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4592 // promoted to a legal register type i32, we should truncate Arg back to
4594 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4595 VA.getValVT() == MVT::i16)
4596 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4598 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4599 MemOpChains.push_back(Store);
4604 if (!MemOpChains.empty())
4605 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4607 // Build a sequence of copy-to-reg nodes chained together with token chain
4608 // and flag operands which copy the outgoing args into the appropriate regs.
4610 for (auto &RegToPass : RegsToPass) {
4611 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4612 RegToPass.second, InFlag);
4613 InFlag = Chain.getValue(1);
4616 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4617 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4618 // node so that legalize doesn't hack it.
4619 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4620 auto GV = G->getGlobal();
4622 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4623 if (OpFlags & AArch64II::MO_GOT) {
4624 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4625 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4627 const GlobalValue *GV = G->getGlobal();
4628 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4630 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4631 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4632 Subtarget->isTargetMachO()) {
4633 const char *Sym = S->getSymbol();
4634 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4635 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4637 const char *Sym = S->getSymbol();
4638 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4642 // We don't usually want to end the call-sequence here because we would tidy
4643 // the frame up *after* the call, however in the ABI-changing tail-call case
4644 // we've carefully laid out the parameters so that when sp is reset they'll be
4645 // in the correct location.
4646 if (IsTailCall && !IsSibCall) {
4647 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4648 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4649 InFlag = Chain.getValue(1);
4652 std::vector<SDValue> Ops;
4653 Ops.push_back(Chain);
4654 Ops.push_back(Callee);
4657 // Each tail call may have to adjust the stack by a different amount, so
4658 // this information must travel along with the operation for eventual
4659 // consumption by emitEpilogue.
4660 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4663 // Add argument registers to the end of the list so that they are known live
4665 for (auto &RegToPass : RegsToPass)
4666 Ops.push_back(DAG.getRegister(RegToPass.first,
4667 RegToPass.second.getValueType()));
4669 // Check callee args/returns for SVE registers and set calling convention
4671 if (CallConv == CallingConv::C) {
4672 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4673 return Out.VT.isScalableVector();
4675 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4676 return In.VT.isScalableVector();
4679 if (CalleeInSVE || CalleeOutSVE)
4680 CallConv = CallingConv::AArch64_SVE_VectorCall;
4683 // Add a register mask operand representing the call-preserved registers.
4684 const uint32_t *Mask;
4685 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4687 // For 'this' returns, use the X0-preserving mask if applicable
4688 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4690 IsThisReturn = false;
4691 Mask = TRI->getCallPreservedMask(MF, CallConv);
4694 Mask = TRI->getCallPreservedMask(MF, CallConv);
4696 if (Subtarget->hasCustomCallingConv())
4697 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4699 if (TRI->isAnyArgRegReserved(MF))
4700 TRI->emitReservedArgRegCallError(MF);
4702 assert(Mask && "Missing call preserved mask for calling convention");
4703 Ops.push_back(DAG.getRegisterMask(Mask));
4705 if (InFlag.getNode())
4706 Ops.push_back(InFlag);
4708 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4710 // If we're doing a tall call, use a TC_RETURN here rather than an
4711 // actual call instruction.
4713 MF.getFrameInfo().setHasTailCall();
4714 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4715 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4719 // Returns a chain and a flag for retval copy to use.
4720 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4721 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4722 InFlag = Chain.getValue(1);
4723 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4725 uint64_t CalleePopBytes =
4726 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4728 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4729 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4732 InFlag = Chain.getValue(1);
4734 // Handle result values, copying them out of physregs into vregs that we
4736 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4737 InVals, IsThisReturn,
4738 IsThisReturn ? OutVals[0] : SDValue());
4741 bool AArch64TargetLowering::CanLowerReturn(
4742 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4743 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4744 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4745 ? RetCC_AArch64_WebKit_JS
4746 : RetCC_AArch64_AAPCS;
4747 SmallVector<CCValAssign, 16> RVLocs;
4748 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4749 return CCInfo.CheckReturn(Outs, RetCC);
4753 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4755 const SmallVectorImpl<ISD::OutputArg> &Outs,
4756 const SmallVectorImpl<SDValue> &OutVals,
4757 const SDLoc &DL, SelectionDAG &DAG) const {
4758 auto &MF = DAG.getMachineFunction();
4759 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4761 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4762 ? RetCC_AArch64_WebKit_JS
4763 : RetCC_AArch64_AAPCS;
4764 SmallVector<CCValAssign, 16> RVLocs;
4765 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4767 CCInfo.AnalyzeReturn(Outs, RetCC);
4769 // Copy the result values into the output registers.
4771 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4772 SmallSet<unsigned, 4> RegsUsed;
4773 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4774 ++i, ++realRVLocIdx) {
4775 CCValAssign &VA = RVLocs[i];
4776 assert(VA.isRegLoc() && "Can only return in registers!");
4777 SDValue Arg = OutVals[realRVLocIdx];
4779 switch (VA.getLocInfo()) {
4781 llvm_unreachable("Unknown loc info!");
4782 case CCValAssign::Full:
4783 if (Outs[i].ArgVT == MVT::i1) {
4784 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4785 // value. This is strictly redundant on Darwin (which uses "zeroext
4786 // i1"), but will be optimised out before ISel.
4787 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4788 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4791 case CCValAssign::BCvt:
4792 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4794 case CCValAssign::AExt:
4795 case CCValAssign::ZExt:
4796 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4798 case CCValAssign::AExtUpper:
4799 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4800 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4801 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4802 DAG.getConstant(32, DL, VA.getLocVT()));
4806 if (RegsUsed.count(VA.getLocReg())) {
4808 std::find_if(RetVals.begin(), RetVals.end(),
4809 [=](const std::pair<unsigned, SDValue> &Elt) {
4810 return Elt.first == VA.getLocReg();
4813 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4815 RetVals.emplace_back(VA.getLocReg(), Arg);
4816 RegsUsed.insert(VA.getLocReg());
4820 SmallVector<SDValue, 4> RetOps(1, Chain);
4821 for (auto &RetVal : RetVals) {
4822 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4823 Flag = Chain.getValue(1);
4825 DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4828 // Windows AArch64 ABIs require that for returning structs by value we copy
4829 // the sret argument into X0 for the return.
4830 // We saved the argument into a virtual register in the entry block,
4831 // so now we copy the value out and into X0.
4832 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4833 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4834 getPointerTy(MF.getDataLayout()));
4836 unsigned RetValReg = AArch64::X0;
4837 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4838 Flag = Chain.getValue(1);
4841 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4844 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4845 const MCPhysReg *I =
4846 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4849 if (AArch64::GPR64RegClass.contains(*I))
4850 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4851 else if (AArch64::FPR64RegClass.contains(*I))
4852 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4854 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4858 RetOps[0] = Chain; // Update chain.
4860 // Add the flag if we have it.
4862 RetOps.push_back(Flag);
4864 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4867 //===----------------------------------------------------------------------===//
4868 // Other Lowering Code
4869 //===----------------------------------------------------------------------===//
4871 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4873 unsigned Flag) const {
4874 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4875 N->getOffset(), Flag);
4878 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4880 unsigned Flag) const {
4881 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4884 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4886 unsigned Flag) const {
4887 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
4888 N->getOffset(), Flag);
4891 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4893 unsigned Flag) const {
4894 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4898 template <class NodeTy>
4899 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4900 unsigned Flags) const {
4901 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4903 EVT Ty = getPointerTy(DAG.getDataLayout());
4904 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4905 // FIXME: Once remat is capable of dealing with instructions with register
4906 // operands, expand this into two nodes instead of using a wrapper node.
4907 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4910 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4911 template <class NodeTy>
4912 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4913 unsigned Flags) const {
4914 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4916 EVT Ty = getPointerTy(DAG.getDataLayout());
4917 const unsigned char MO_NC = AArch64II::MO_NC;
4919 AArch64ISD::WrapperLarge, DL, Ty,
4920 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4921 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4922 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4923 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4926 // (addlow (adrp %hi(sym)) %lo(sym))
4927 template <class NodeTy>
4928 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4929 unsigned Flags) const {
4930 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4932 EVT Ty = getPointerTy(DAG.getDataLayout());
4933 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4934 SDValue Lo = getTargetNode(N, Ty, DAG,
4935 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4936 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4937 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4941 template <class NodeTy>
4942 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4943 unsigned Flags) const {
4944 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4946 EVT Ty = getPointerTy(DAG.getDataLayout());
4947 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4948 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4951 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4952 SelectionDAG &DAG) const {
4953 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4954 const GlobalValue *GV = GN->getGlobal();
4955 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4957 if (OpFlags != AArch64II::MO_NO_FLAG)
4958 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4959 "unexpected offset in global node");
4961 // This also catches the large code model case for Darwin, and tiny code
4962 // model with got relocations.
4963 if ((OpFlags & AArch64II::MO_GOT) != 0) {
4964 return getGOT(GN, DAG, OpFlags);
4968 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4969 Result = getAddrLarge(GN, DAG, OpFlags);
4970 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4971 Result = getAddrTiny(GN, DAG, OpFlags);
4973 Result = getAddr(GN, DAG, OpFlags);
4975 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4977 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4978 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4979 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4983 /// Convert a TLS address reference into the correct sequence of loads
4984 /// and calls to compute the variable's address (for Darwin, currently) and
4985 /// return an SDValue containing the final node.
4987 /// Darwin only has one TLS scheme which must be capable of dealing with the
4988 /// fully general situation, in the worst case. This means:
4989 /// + "extern __thread" declaration.
4990 /// + Defined in a possibly unknown dynamic library.
4992 /// The general system is that each __thread variable has a [3 x i64] descriptor
4993 /// which contains information used by the runtime to calculate the address. The
4994 /// only part of this the compiler needs to know about is the first xword, which
4995 /// contains a function pointer that must be called with the address of the
4996 /// entire descriptor in "x0".
4998 /// Since this descriptor may be in a different unit, in general even the
4999 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
5001 /// adrp x0, _var@TLVPPAGE
5002 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
5003 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
5004 /// ; the function pointer
5005 /// blr x1 ; Uses descriptor address in x0
5006 /// ; Address of _var is now in x0.
5008 /// If the address of _var's descriptor *is* known to the linker, then it can
5009 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
5010 /// a slight efficiency gain.
5012 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
5013 SelectionDAG &DAG) const {
5014 assert(Subtarget->isTargetDarwin() &&
5015 "This function expects a Darwin target");
5018 MVT PtrVT = getPointerTy(DAG.getDataLayout());
5019 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5020 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5023 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5024 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
5026 // The first entry in the descriptor is a function pointer that we must call
5027 // to obtain the address of the variable.
5028 SDValue Chain = DAG.getEntryNode();
5029 SDValue FuncTLVGet = DAG.getLoad(
5030 PtrMemVT, DL, Chain, DescAddr,
5031 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
5032 /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
5033 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5034 Chain = FuncTLVGet.getValue(1);
5036 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
5037 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
5039 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5040 MFI.setAdjustsStack(true);
5042 // TLS calls preserve all registers except those that absolutely must be
5043 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
5045 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
5046 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
5047 if (Subtarget->hasCustomCallingConv())
5048 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
5050 // Finally, we can make the call. This is just a degenerate version of a
5051 // normal AArch64 call node: x0 takes the address of the descriptor, and
5052 // returns the address of the variable in this thread.
5053 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
5055 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
5056 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
5057 DAG.getRegisterMask(Mask), Chain.getValue(1));
5058 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
5061 /// Convert a thread-local variable reference into a sequence of instructions to
5062 /// compute the variable's address for the local exec TLS model of ELF targets.
5063 /// The sequence depends on the maximum TLS area size.
5064 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
5067 SelectionDAG &DAG) const {
5068 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5069 SDValue TPOff, Addr;
5071 switch (DAG.getTarget().Options.TLSSize) {
5073 llvm_unreachable("Unexpected TLS size");
5076 // mrs x0, TPIDR_EL0
5077 // add x0, x0, :tprel_lo12:a
5078 SDValue Var = DAG.getTargetGlobalAddress(
5079 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
5080 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5082 DAG.getTargetConstant(0, DL, MVT::i32)),
5087 // mrs x0, TPIDR_EL0
5088 // add x0, x0, :tprel_hi12:a
5089 // add x0, x0, :tprel_lo12_nc:a
5090 SDValue HiVar = DAG.getTargetGlobalAddress(
5091 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5092 SDValue LoVar = DAG.getTargetGlobalAddress(
5094 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5095 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
5097 DAG.getTargetConstant(0, DL, MVT::i32)),
5099 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
5101 DAG.getTargetConstant(0, DL, MVT::i32)),
5106 // mrs x1, TPIDR_EL0
5107 // movz x0, #:tprel_g1:a
5108 // movk x0, #:tprel_g0_nc:a
5110 SDValue HiVar = DAG.getTargetGlobalAddress(
5111 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
5112 SDValue LoVar = DAG.getTargetGlobalAddress(
5114 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5115 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5116 DAG.getTargetConstant(16, DL, MVT::i32)),
5118 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5119 DAG.getTargetConstant(0, DL, MVT::i32)),
5121 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5125 // mrs x1, TPIDR_EL0
5126 // movz x0, #:tprel_g2:a
5127 // movk x0, #:tprel_g1_nc:a
5128 // movk x0, #:tprel_g0_nc:a
5130 SDValue HiVar = DAG.getTargetGlobalAddress(
5131 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
5132 SDValue MiVar = DAG.getTargetGlobalAddress(
5134 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
5135 SDValue LoVar = DAG.getTargetGlobalAddress(
5137 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
5138 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
5139 DAG.getTargetConstant(32, DL, MVT::i32)),
5141 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
5142 DAG.getTargetConstant(16, DL, MVT::i32)),
5144 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
5145 DAG.getTargetConstant(0, DL, MVT::i32)),
5147 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5152 /// When accessing thread-local variables under either the general-dynamic or
5153 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
5154 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
5155 /// is a function pointer to carry out the resolution.
5157 /// The sequence is:
5158 /// adrp x0, :tlsdesc:var
5159 /// ldr x1, [x0, #:tlsdesc_lo12:var]
5160 /// add x0, x0, #:tlsdesc_lo12:var
5161 /// .tlsdesccall var
5163 /// (TPIDR_EL0 offset now in x0)
5165 /// The above sequence must be produced unscheduled, to enable the linker to
5166 /// optimize/relax this sequence.
5167 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
5168 /// above sequence, and expanded really late in the compilation flow, to ensure
5169 /// the sequence is produced as per above.
5170 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
5172 SelectionDAG &DAG) const {
5173 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5175 SDValue Chain = DAG.getEntryNode();
5176 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
5179 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
5180 SDValue Glue = Chain.getValue(1);
5182 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
5186 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
5187 SelectionDAG &DAG) const {
5188 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
5190 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5192 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
5194 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
5195 if (Model == TLSModel::LocalDynamic)
5196 Model = TLSModel::GeneralDynamic;
5199 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5200 Model != TLSModel::LocalExec)
5201 report_fatal_error("ELF TLS only supported in small memory model or "
5202 "in local exec TLS model");
5203 // Different choices can be made for the maximum size of the TLS area for a
5204 // module. For the small address model, the default TLS size is 16MiB and the
5205 // maximum TLS size is 4GiB.
5206 // FIXME: add tiny and large code model support for TLS access models other
5207 // than local exec. We currently generate the same code as small for tiny,
5208 // which may be larger than needed.
5211 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5213 const GlobalValue *GV = GA->getGlobal();
5215 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
5217 if (Model == TLSModel::LocalExec) {
5218 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
5219 } else if (Model == TLSModel::InitialExec) {
5220 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5221 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
5222 } else if (Model == TLSModel::LocalDynamic) {
5223 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
5224 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
5225 // the beginning of the module's TLS region, followed by a DTPREL offset
5228 // These accesses will need deduplicating if there's more than one.
5229 AArch64FunctionInfo *MFI =
5230 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5231 MFI->incNumLocalDynamicTLSAccesses();
5233 // The call needs a relocation too for linker relaxation. It doesn't make
5234 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5236 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
5239 // Now we can calculate the offset from TPIDR_EL0 to this module's
5240 // thread-local area.
5241 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5243 // Now use :dtprel_whatever: operations to calculate this variable's offset
5244 // in its thread-storage area.
5245 SDValue HiVar = DAG.getTargetGlobalAddress(
5246 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5247 SDValue LoVar = DAG.getTargetGlobalAddress(
5248 GV, DL, MVT::i64, 0,
5249 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5251 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
5252 DAG.getTargetConstant(0, DL, MVT::i32)),
5254 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
5255 DAG.getTargetConstant(0, DL, MVT::i32)),
5257 } else if (Model == TLSModel::GeneralDynamic) {
5258 // The call needs a relocation too for linker relaxation. It doesn't make
5259 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
5262 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
5264 // Finally we can make a call to calculate the offset from tpidr_el0.
5265 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
5267 llvm_unreachable("Unsupported ELF TLS access model");
5269 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
5273 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
5274 SelectionDAG &DAG) const {
5275 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
5277 SDValue Chain = DAG.getEntryNode();
5278 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5281 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
5283 // Load the ThreadLocalStoragePointer from the TEB
5284 // A pointer to the TLS array is located at offset 0x58 from the TEB.
5286 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
5287 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
5288 Chain = TLSArray.getValue(1);
5290 // Load the TLS index from the C runtime;
5291 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
5292 // This also does the same as LOADgot, but using a generic i32 load,
5293 // while LOADgot only loads i64.
5294 SDValue TLSIndexHi =
5295 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
5296 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
5297 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5298 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
5300 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
5301 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
5302 Chain = TLSIndex.getValue(1);
5304 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
5305 // offset into the TLSArray.
5306 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
5307 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
5308 DAG.getConstant(3, DL, PtrVT));
5309 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
5310 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
5311 MachinePointerInfo());
5312 Chain = TLS.getValue(1);
5314 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5315 const GlobalValue *GV = GA->getGlobal();
5316 SDValue TGAHi = DAG.getTargetGlobalAddress(
5317 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
5318 SDValue TGALo = DAG.getTargetGlobalAddress(
5320 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
5322 // Add the offset from the start of the .tls section (section base).
5324 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
5325 DAG.getTargetConstant(0, DL, MVT::i32)),
5327 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
5331 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
5332 SelectionDAG &DAG) const {
5333 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5334 if (DAG.getTarget().useEmulatedTLS())
5335 return LowerToTLSEmulatedModel(GA, DAG);
5337 if (Subtarget->isTargetDarwin())
5338 return LowerDarwinGlobalTLSAddress(Op, DAG);
5339 if (Subtarget->isTargetELF())
5340 return LowerELFGlobalTLSAddress(Op, DAG);
5341 if (Subtarget->isTargetWindows())
5342 return LowerWindowsGlobalTLSAddress(Op, DAG);
5344 llvm_unreachable("Unexpected platform trying to use TLS");
5347 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5348 SDValue Chain = Op.getOperand(0);
5349 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5350 SDValue LHS = Op.getOperand(2);
5351 SDValue RHS = Op.getOperand(3);
5352 SDValue Dest = Op.getOperand(4);
5355 MachineFunction &MF = DAG.getMachineFunction();
5356 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
5357 // will not be produced, as they are conditional branch instructions that do
5359 bool ProduceNonFlagSettingCondBr =
5360 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
5362 // Handle f128 first, since lowering it will result in comparing the return
5363 // value of a libcall against zero, which is just what the rest of LowerBR_CC
5364 // is expecting to deal with.
5365 if (LHS.getValueType() == MVT::f128) {
5366 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5368 // If softenSetCCOperands returned a scalar, we need to compare the result
5369 // against zero to select between true and false values.
5370 if (!RHS.getNode()) {
5371 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5376 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5378 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
5379 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5380 // Only lower legal XALUO ops.
5381 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5384 // The actual operation with overflow check.
5385 AArch64CC::CondCode OFCC;
5386 SDValue Value, Overflow;
5387 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
5389 if (CC == ISD::SETNE)
5390 OFCC = getInvertedCondCode(OFCC);
5391 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
5393 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5397 if (LHS.getValueType().isInteger()) {
5398 assert((LHS.getValueType() == RHS.getValueType()) &&
5399 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5401 // If the RHS of the comparison is zero, we can potentially fold this
5402 // to a specialized branch.
5403 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
5404 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
5405 if (CC == ISD::SETEQ) {
5406 // See if we can use a TBZ to fold in an AND as well.
5407 // TBZ has a smaller branch displacement than CBZ. If the offset is
5408 // out of bounds, a late MI-layer pass rewrites branches.
5409 // 403.gcc is an example that hits this case.
5410 if (LHS.getOpcode() == ISD::AND &&
5411 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5412 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5413 SDValue Test = LHS.getOperand(0);
5414 uint64_t Mask = LHS.getConstantOperandVal(1);
5415 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
5416 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5420 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5421 } else if (CC == ISD::SETNE) {
5422 // See if we can use a TBZ to fold in an AND as well.
5423 // TBZ has a smaller branch displacement than CBZ. If the offset is
5424 // out of bounds, a late MI-layer pass rewrites branches.
5425 // 403.gcc is an example that hits this case.
5426 if (LHS.getOpcode() == ISD::AND &&
5427 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5428 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5429 SDValue Test = LHS.getOperand(0);
5430 uint64_t Mask = LHS.getConstantOperandVal(1);
5431 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5432 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5436 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5437 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5438 // Don't combine AND since emitComparison converts the AND to an ANDS
5439 // (a.k.a. TST) and the test in the test bit and branch instruction
5440 // becomes redundant. This would also increase register pressure.
5441 uint64_t Mask = LHS.getValueSizeInBits() - 1;
5442 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5443 DAG.getConstant(Mask, dl, MVT::i64), Dest);
5446 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5447 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5448 // Don't combine AND since emitComparison converts the AND to an ANDS
5449 // (a.k.a. TST) and the test in the test bit and branch instruction
5450 // becomes redundant. This would also increase register pressure.
5451 uint64_t Mask = LHS.getValueSizeInBits() - 1;
5452 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5453 DAG.getConstant(Mask, dl, MVT::i64), Dest);
5457 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5458 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5462 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
5463 LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
5465 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5466 // clean. Some of them require two branches to implement.
5467 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5468 AArch64CC::CondCode CC1, CC2;
5469 changeFPCCToAArch64CC(CC, CC1, CC2);
5470 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5472 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5473 if (CC2 != AArch64CC::AL) {
5474 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5475 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5482 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5483 SelectionDAG &DAG) const {
5484 EVT VT = Op.getValueType();
5487 SDValue In1 = Op.getOperand(0);
5488 SDValue In2 = Op.getOperand(1);
5489 EVT SrcVT = In2.getValueType();
5491 if (SrcVT.bitsLT(VT))
5492 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5493 else if (SrcVT.bitsGT(VT))
5494 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5498 SDValue VecVal1, VecVal2;
5500 auto setVecVal = [&] (int Idx) {
5501 if (!VT.isVector()) {
5502 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5503 DAG.getUNDEF(VecVT), In1);
5504 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5505 DAG.getUNDEF(VecVT), In2);
5507 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5508 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5512 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5513 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5514 EltMask = 0x80000000ULL;
5515 setVecVal(AArch64::ssub);
5516 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5519 // We want to materialize a mask with the high bit set, but the AdvSIMD
5520 // immediate moves cannot materialize that in a single instruction for
5521 // 64-bit elements. Instead, materialize zero and then negate it.
5524 setVecVal(AArch64::dsub);
5525 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5526 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5527 EltMask = 0x8000ULL;
5528 setVecVal(AArch64::hsub);
5530 llvm_unreachable("Invalid type for copysign!");
5533 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5535 // If we couldn't materialize the mask above, then the mask vector will be
5536 // the zero vector, and we need to negate it here.
5537 if (VT == MVT::f64 || VT == MVT::v2f64) {
5538 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5539 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5540 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5544 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5547 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5549 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5550 else if (VT == MVT::f64)
5551 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5553 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5556 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5557 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5558 Attribute::NoImplicitFloat))
5561 if (!Subtarget->hasNEON())
5564 // While there is no integer popcount instruction, it can
5565 // be more efficiently lowered to the following sequence that uses
5566 // AdvSIMD registers/instructions as long as the copies to/from
5567 // the AdvSIMD registers are cheap.
5568 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
5569 // CNT V0.8B, V0.8B // 8xbyte pop-counts
5570 // ADDV B0, V0.8B // sum 8xbyte pop-counts
5571 // UMOV X0, V0.B[0] // copy byte result back to integer reg
5572 SDValue Val = Op.getOperand(0);
5574 EVT VT = Op.getValueType();
5576 if (VT == MVT::i32 || VT == MVT::i64) {
5578 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5579 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5581 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5582 SDValue UaddLV = DAG.getNode(
5583 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5584 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5587 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5589 } else if (VT == MVT::i128) {
5590 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
5592 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
5593 SDValue UaddLV = DAG.getNode(
5594 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5595 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5597 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
5600 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5601 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5602 "Unexpected type for custom ctpop lowering");
5604 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5605 Val = DAG.getBitcast(VT8Bit, Val);
5606 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5608 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5609 unsigned EltSize = 8;
5610 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5611 while (EltSize != VT.getScalarSizeInBits()) {
5614 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5616 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5617 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5623 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5625 if (Op.getValueType().isVector())
5626 return LowerVSETCC(Op, DAG);
5628 bool IsStrict = Op->isStrictFPOpcode();
5629 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
5630 unsigned OpNo = IsStrict ? 1 : 0;
5633 Chain = Op.getOperand(0);
5634 SDValue LHS = Op.getOperand(OpNo + 0);
5635 SDValue RHS = Op.getOperand(OpNo + 1);
5636 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
5639 // We chose ZeroOrOneBooleanContents, so use zero and one.
5640 EVT VT = Op.getValueType();
5641 SDValue TVal = DAG.getConstant(1, dl, VT);
5642 SDValue FVal = DAG.getConstant(0, dl, VT);
5644 // Handle f128 first, since one possible outcome is a normal integer
5645 // comparison which gets picked up by the next if statement.
5646 if (LHS.getValueType() == MVT::f128) {
5647 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
5650 // If softenSetCCOperands returned a scalar, use it.
5651 if (!RHS.getNode()) {
5652 assert(LHS.getValueType() == Op.getValueType() &&
5653 "Unexpected setcc expansion!");
5654 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
5658 if (LHS.getValueType().isInteger()) {
5660 SDValue Cmp = getAArch64Cmp(
5661 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5663 // Note that we inverted the condition above, so we reverse the order of
5664 // the true and false operands here. This will allow the setcc to be
5665 // matched to a single CSINC instruction.
5666 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5667 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
5670 // Now we know we're dealing with FP values.
5671 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5672 LHS.getValueType() == MVT::f64);
5674 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
5675 // and do the comparison.
5678 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
5680 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5682 AArch64CC::CondCode CC1, CC2;
5683 changeFPCCToAArch64CC(CC, CC1, CC2);
5685 if (CC2 == AArch64CC::AL) {
5686 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5688 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5690 // Note that we inverted the condition above, so we reverse the order of
5691 // the true and false operands here. This will allow the setcc to be
5692 // matched to a single CSINC instruction.
5693 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5695 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5696 // totally clean. Some of them require two CSELs to implement. As is in
5697 // this case, we emit the first CSEL and then emit a second using the output
5698 // of the first as the RHS. We're effectively OR'ing the two CC's together.
5700 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5701 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5703 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5705 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5706 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5708 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
5711 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5712 SDValue RHS, SDValue TVal,
5713 SDValue FVal, const SDLoc &dl,
5714 SelectionDAG &DAG) const {
5715 // Handle f128 first, because it will result in a comparison of some RTLIB
5716 // call result against zero.
5717 if (LHS.getValueType() == MVT::f128) {
5718 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5720 // If softenSetCCOperands returned a scalar, we need to compare the result
5721 // against zero to select between true and false values.
5722 if (!RHS.getNode()) {
5723 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5728 // Also handle f16, for which we need to do a f32 comparison.
5729 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5730 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5731 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5734 // Next, handle integers.
5735 if (LHS.getValueType().isInteger()) {
5736 assert((LHS.getValueType() == RHS.getValueType()) &&
5737 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5739 unsigned Opcode = AArch64ISD::CSEL;
5741 // If both the TVal and the FVal are constants, see if we can swap them in
5742 // order to for a CSINV or CSINC out of them.
5743 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5744 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5746 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5747 std::swap(TVal, FVal);
5748 std::swap(CTVal, CFVal);
5749 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5750 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5751 std::swap(TVal, FVal);
5752 std::swap(CTVal, CFVal);
5753 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5754 } else if (TVal.getOpcode() == ISD::XOR) {
5755 // If TVal is a NOT we want to swap TVal and FVal so that we can match
5756 // with a CSINV rather than a CSEL.
5757 if (isAllOnesConstant(TVal.getOperand(1))) {
5758 std::swap(TVal, FVal);
5759 std::swap(CTVal, CFVal);
5760 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5762 } else if (TVal.getOpcode() == ISD::SUB) {
5763 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5764 // that we can match with a CSNEG rather than a CSEL.
5765 if (isNullConstant(TVal.getOperand(0))) {
5766 std::swap(TVal, FVal);
5767 std::swap(CTVal, CFVal);
5768 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5770 } else if (CTVal && CFVal) {
5771 const int64_t TrueVal = CTVal->getSExtValue();
5772 const int64_t FalseVal = CFVal->getSExtValue();
5775 // If both TVal and FVal are constants, see if FVal is the
5776 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5777 // instead of a CSEL in that case.
5778 if (TrueVal == ~FalseVal) {
5779 Opcode = AArch64ISD::CSINV;
5780 } else if (TrueVal == -FalseVal) {
5781 Opcode = AArch64ISD::CSNEG;
5782 } else if (TVal.getValueType() == MVT::i32) {
5783 // If our operands are only 32-bit wide, make sure we use 32-bit
5784 // arithmetic for the check whether we can use CSINC. This ensures that
5785 // the addition in the check will wrap around properly in case there is
5786 // an overflow (which would not be the case if we do the check with
5787 // 64-bit arithmetic).
5788 const uint32_t TrueVal32 = CTVal->getZExtValue();
5789 const uint32_t FalseVal32 = CFVal->getZExtValue();
5791 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5792 Opcode = AArch64ISD::CSINC;
5794 if (TrueVal32 > FalseVal32) {
5798 // 64-bit check whether we can use CSINC.
5799 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5800 Opcode = AArch64ISD::CSINC;
5802 if (TrueVal > FalseVal) {
5807 // Swap TVal and FVal if necessary.
5809 std::swap(TVal, FVal);
5810 std::swap(CTVal, CFVal);
5811 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5814 if (Opcode != AArch64ISD::CSEL) {
5815 // Drop FVal since we can get its value by simply inverting/negating
5821 // Avoid materializing a constant when possible by reusing a known value in
5822 // a register. However, don't perform this optimization if the known value
5823 // is one, zero or negative one in the case of a CSEL. We can always
5824 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5825 // FVal, respectively.
5826 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5827 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5828 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5829 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5830 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5831 // "a != C ? x : a" to avoid materializing C.
5832 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5834 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5836 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5837 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5838 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5839 // avoid materializing C.
5840 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5841 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5842 Opcode = AArch64ISD::CSINV;
5844 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5849 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5850 EVT VT = TVal.getValueType();
5851 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5854 // Now we know we're dealing with FP values.
5855 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5856 LHS.getValueType() == MVT::f64);
5857 assert(LHS.getValueType() == RHS.getValueType());
5858 EVT VT = TVal.getValueType();
5859 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5861 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5862 // clean. Some of them require two CSELs to implement.
5863 AArch64CC::CondCode CC1, CC2;
5864 changeFPCCToAArch64CC(CC, CC1, CC2);
5866 if (DAG.getTarget().Options.UnsafeFPMath) {
5867 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5868 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5869 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5870 if (RHSVal && RHSVal->isZero()) {
5871 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5872 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5874 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5875 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5877 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5878 CFVal && CFVal->isZero() &&
5879 FVal.getValueType() == LHS.getValueType())
5884 // Emit first, and possibly only, CSEL.
5885 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5886 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5888 // If we need a second CSEL, emit it, using the output of the first as the
5889 // RHS. We're effectively OR'ing the two CC's together.
5890 if (CC2 != AArch64CC::AL) {
5891 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5892 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5895 // Otherwise, return the output of the first CSEL.
5899 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5900 SelectionDAG &DAG) const {
5901 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5902 SDValue LHS = Op.getOperand(0);
5903 SDValue RHS = Op.getOperand(1);
5904 SDValue TVal = Op.getOperand(2);
5905 SDValue FVal = Op.getOperand(3);
5907 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5910 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5911 SelectionDAG &DAG) const {
5912 SDValue CCVal = Op->getOperand(0);
5913 SDValue TVal = Op->getOperand(1);
5914 SDValue FVal = Op->getOperand(2);
5917 EVT Ty = Op.getValueType();
5918 if (Ty.isScalableVector()) {
5919 SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
5920 MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
5921 SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
5922 return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
5925 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5927 if (ISD::isOverflowIntrOpRes(CCVal)) {
5928 // Only lower legal XALUO ops.
5929 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5932 AArch64CC::CondCode OFCC;
5933 SDValue Value, Overflow;
5934 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5935 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5937 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5941 // Lower it the same way as we would lower a SELECT_CC node.
5944 if (CCVal.getOpcode() == ISD::SETCC) {
5945 LHS = CCVal.getOperand(0);
5946 RHS = CCVal.getOperand(1);
5947 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5950 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5953 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5956 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5957 SelectionDAG &DAG) const {
5958 // Jump table entries as PC relative offsets. No additional tweaking
5959 // is necessary here. Just get the address of the jump table.
5960 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5962 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5963 !Subtarget->isTargetMachO()) {
5964 return getAddrLarge(JT, DAG);
5965 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5966 return getAddrTiny(JT, DAG);
5968 return getAddr(JT, DAG);
5971 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5972 SelectionDAG &DAG) const {
5973 // Jump table entries as PC relative offsets. No additional tweaking
5974 // is necessary here. Just get the address of the jump table.
5976 SDValue JT = Op.getOperand(1);
5977 SDValue Entry = Op.getOperand(2);
5978 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5981 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5982 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5983 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5987 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5988 SelectionDAG &DAG) const {
5989 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5991 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5992 // Use the GOT for the large code model on iOS.
5993 if (Subtarget->isTargetMachO()) {
5994 return getGOT(CP, DAG);
5996 return getAddrLarge(CP, DAG);
5997 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5998 return getAddrTiny(CP, DAG);
6000 return getAddr(CP, DAG);
6004 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
6005 SelectionDAG &DAG) const {
6006 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
6007 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
6008 !Subtarget->isTargetMachO()) {
6009 return getAddrLarge(BA, DAG);
6010 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
6011 return getAddrTiny(BA, DAG);
6013 return getAddr(BA, DAG);
6016 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
6017 SelectionDAG &DAG) const {
6018 AArch64FunctionInfo *FuncInfo =
6019 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6022 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
6023 getPointerTy(DAG.getDataLayout()));
6024 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
6025 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6026 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6027 MachinePointerInfo(SV));
6030 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
6031 SelectionDAG &DAG) const {
6032 AArch64FunctionInfo *FuncInfo =
6033 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
6036 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
6037 ? FuncInfo->getVarArgsGPRIndex()
6038 : FuncInfo->getVarArgsStackIndex(),
6039 getPointerTy(DAG.getDataLayout()));
6040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6041 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
6042 MachinePointerInfo(SV));
6045 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
6046 SelectionDAG &DAG) const {
6047 // The layout of the va_list struct is specified in the AArch64 Procedure Call
6048 // Standard, section B.3.
6049 MachineFunction &MF = DAG.getMachineFunction();
6050 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
6051 auto PtrVT = getPointerTy(DAG.getDataLayout());
6054 SDValue Chain = Op.getOperand(0);
6055 SDValue VAList = Op.getOperand(1);
6056 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6057 SmallVector<SDValue, 4> MemOps;
6059 // void *__stack at offset 0
6060 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
6061 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
6062 MachinePointerInfo(SV), /* Alignment = */ 8));
6064 // void *__gr_top at offset 8
6065 int GPRSize = FuncInfo->getVarArgsGPRSize();
6067 SDValue GRTop, GRTopAddr;
6070 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
6072 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
6073 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
6074 DAG.getConstant(GPRSize, DL, PtrVT));
6076 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
6077 MachinePointerInfo(SV, 8),
6078 /* Alignment = */ 8));
6081 // void *__vr_top at offset 16
6082 int FPRSize = FuncInfo->getVarArgsFPRSize();
6084 SDValue VRTop, VRTopAddr;
6085 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6086 DAG.getConstant(16, DL, PtrVT));
6088 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
6089 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
6090 DAG.getConstant(FPRSize, DL, PtrVT));
6092 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
6093 MachinePointerInfo(SV, 16),
6094 /* Alignment = */ 8));
6097 // int __gr_offs at offset 24
6098 SDValue GROffsAddr =
6099 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
6100 MemOps.push_back(DAG.getStore(
6101 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
6102 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
6104 // int __vr_offs at offset 28
6105 SDValue VROffsAddr =
6106 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
6107 MemOps.push_back(DAG.getStore(
6108 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
6109 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
6111 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
6114 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
6115 SelectionDAG &DAG) const {
6116 MachineFunction &MF = DAG.getMachineFunction();
6118 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
6119 return LowerWin64_VASTART(Op, DAG);
6120 else if (Subtarget->isTargetDarwin())
6121 return LowerDarwin_VASTART(Op, DAG);
6123 return LowerAAPCS_VASTART(Op, DAG);
6126 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
6127 SelectionDAG &DAG) const {
6128 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
6131 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
6132 unsigned VaListSize = (Subtarget->isTargetDarwin() ||
6133 Subtarget->isTargetWindows()) ? PtrSize : 32;
6134 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6135 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6137 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
6138 DAG.getConstant(VaListSize, DL, MVT::i32),
6139 Align(PtrSize), false, false, false,
6140 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
6143 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6144 assert(Subtarget->isTargetDarwin() &&
6145 "automatic va_arg instruction only works on Darwin");
6147 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6148 EVT VT = Op.getValueType();
6150 SDValue Chain = Op.getOperand(0);
6151 SDValue Addr = Op.getOperand(1);
6152 MaybeAlign Align(Op.getConstantOperandVal(3));
6153 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
6154 auto PtrVT = getPointerTy(DAG.getDataLayout());
6155 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
6157 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
6158 Chain = VAList.getValue(1);
6159 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
6161 if (Align && *Align > MinSlotSize) {
6162 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6163 DAG.getConstant(Align->value() - 1, DL, PtrVT));
6164 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
6165 DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
6168 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6169 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
6171 // Scalar integer and FP values smaller than 64 bits are implicitly extended
6172 // up to 64 bits. At the very least, we have to increase the striding of the
6173 // vaargs list to match this, and for FP values we need to introduce
6174 // FP_ROUND nodes as well.
6175 if (VT.isInteger() && !VT.isVector())
6176 ArgSize = std::max(ArgSize, MinSlotSize);
6177 bool NeedFPTrunc = false;
6178 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
6183 // Increment the pointer, VAList, to the next vaarg
6184 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
6185 DAG.getConstant(ArgSize, DL, PtrVT));
6186 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
6188 // Store the incremented VAList to the legalized pointer
6190 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
6192 // Load the actual argument out of the pointer VAList
6194 // Load the value as an f64.
6196 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
6197 // Round the value down to an f32.
6198 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
6199 DAG.getIntPtrConstant(1, DL));
6200 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
6201 // Merge the rounded value with the chain output of the load.
6202 return DAG.getMergeValues(Ops, DL);
6205 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
6208 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
6209 SelectionDAG &DAG) const {
6210 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6211 MFI.setFrameAddressIsTaken(true);
6213 EVT VT = Op.getValueType();
6215 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6217 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
6219 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
6220 MachinePointerInfo());
6222 if (Subtarget->isTargetILP32())
6223 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
6224 DAG.getValueType(VT));
6229 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
6230 SelectionDAG &DAG) const {
6231 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6233 EVT VT = getPointerTy(DAG.getDataLayout());
6235 int FI = MFI.CreateFixedObject(4, 0, false);
6236 return DAG.getFrameIndex(FI, VT);
6239 #define GET_REGISTER_MATCHER
6240 #include "AArch64GenAsmMatcher.inc"
6242 // FIXME? Maybe this could be a TableGen attribute on some registers and
6243 // this table could be generated automatically from RegInfo.
6244 Register AArch64TargetLowering::
6245 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
6246 Register Reg = MatchRegisterName(RegName);
6247 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
6248 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
6249 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
6250 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
6255 report_fatal_error(Twine("Invalid register name \""
6256 + StringRef(RegName) + "\"."));
6259 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
6260 SelectionDAG &DAG) const {
6261 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
6263 EVT VT = Op.getValueType();
6267 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
6268 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6270 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
6273 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
6274 SelectionDAG &DAG) const {
6275 MachineFunction &MF = DAG.getMachineFunction();
6276 MachineFrameInfo &MFI = MF.getFrameInfo();
6277 MFI.setReturnAddressIsTaken(true);
6279 EVT VT = Op.getValueType();
6281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6283 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6284 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
6285 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
6286 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
6287 MachinePointerInfo());
6290 // Return LR, which contains the return address. Mark it an implicit live-in.
6291 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
6292 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6295 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6296 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6297 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
6298 SelectionDAG &DAG) const {
6299 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6300 EVT VT = Op.getValueType();
6301 unsigned VTBits = VT.getSizeInBits();
6303 SDValue ShOpLo = Op.getOperand(0);
6304 SDValue ShOpHi = Op.getOperand(1);
6305 SDValue ShAmt = Op.getOperand(2);
6306 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6308 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6310 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6311 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6312 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6314 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
6315 // is "undef". We wanted 0, so CSEL it directly.
6316 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6317 ISD::SETEQ, dl, DAG);
6318 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6320 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6321 HiBitsForLo, CCVal, Cmp);
6323 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6324 DAG.getConstant(VTBits, dl, MVT::i64));
6326 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6327 SDValue LoForNormalShift =
6328 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
6330 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6332 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6333 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6334 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6335 LoForNormalShift, CCVal, Cmp);
6337 // AArch64 shifts larger than the register width are wrapped rather than
6338 // clamped, so we can't just emit "hi >> x".
6339 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6340 SDValue HiForBigShift =
6342 ? DAG.getNode(Opc, dl, VT, ShOpHi,
6343 DAG.getConstant(VTBits - 1, dl, MVT::i64))
6344 : DAG.getConstant(0, dl, VT);
6345 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6346 HiForNormalShift, CCVal, Cmp);
6348 SDValue Ops[2] = { Lo, Hi };
6349 return DAG.getMergeValues(Ops, dl);
6352 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6353 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
6354 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
6355 SelectionDAG &DAG) const {
6356 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6357 EVT VT = Op.getValueType();
6358 unsigned VTBits = VT.getSizeInBits();
6360 SDValue ShOpLo = Op.getOperand(0);
6361 SDValue ShOpHi = Op.getOperand(1);
6362 SDValue ShAmt = Op.getOperand(2);
6364 assert(Op.getOpcode() == ISD::SHL_PARTS);
6365 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
6366 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
6367 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6369 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
6370 // is "undef". We wanted 0, so CSEL it directly.
6371 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
6372 ISD::SETEQ, dl, DAG);
6373 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
6375 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
6376 LoBitsForHi, CCVal, Cmp);
6378 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
6379 DAG.getConstant(VTBits, dl, MVT::i64));
6380 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6381 SDValue HiForNormalShift =
6382 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
6384 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6386 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
6388 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
6389 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
6390 HiForNormalShift, CCVal, Cmp);
6392 // AArch64 shifts of larger than register sizes are wrapped rather than
6393 // clamped, so we can't just emit "lo << a" if a is too big.
6394 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
6395 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6396 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
6397 LoForNormalShift, CCVal, Cmp);
6399 SDValue Ops[2] = { Lo, Hi };
6400 return DAG.getMergeValues(Ops, dl);
6403 bool AArch64TargetLowering::isOffsetFoldingLegal(
6404 const GlobalAddressSDNode *GA) const {
6405 // Offsets are folded in the DAG combine rather than here so that we can
6406 // intelligently choose an offset based on the uses.
6410 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
6411 bool OptForSize) const {
6412 bool IsLegal = false;
6413 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
6414 // 16-bit case when target has full fp16 support.
6415 // FIXME: We should be able to handle f128 as well with a clever lowering.
6416 const APInt ImmInt = Imm.bitcastToAPInt();
6418 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
6419 else if (VT == MVT::f32)
6420 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
6421 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
6422 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
6423 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
6424 // generate that fmov.
6426 // If we can not materialize in immediate field for fmov, check if the
6427 // value can be encoded as the immediate operand of a logical instruction.
6428 // The immediate value will be created with either MOVZ, MOVN, or ORR.
6429 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
6430 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
6431 // however the mov+fmov sequence is always better because of the reduced
6432 // cache pressure. The timings are still the same if you consider
6433 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
6434 // movw+movk is fused). So we limit up to 2 instrdduction at most.
6435 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
6436 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
6438 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
6439 IsLegal = Insn.size() <= Limit;
6442 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
6443 << " imm value: "; Imm.dump(););
6447 //===----------------------------------------------------------------------===//
6448 // AArch64 Optimization Hooks
6449 //===----------------------------------------------------------------------===//
6451 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6452 SDValue Operand, SelectionDAG &DAG,
6454 EVT VT = Operand.getValueType();
6455 if (ST->hasNEON() &&
6456 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6457 VT == MVT::f32 || VT == MVT::v1f32 ||
6458 VT == MVT::v2f32 || VT == MVT::v4f32)) {
6459 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6460 // For the reciprocal estimates, convergence is quadratic, so the number
6461 // of digits is doubled after each iteration. In ARMv8, the accuracy of
6462 // the initial estimate is 2^-8. Thus the number of extra steps to refine
6463 // the result for float (23 mantissa bits) is 2 and for double (52
6464 // mantissa bits) is 3.
6465 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6467 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6473 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6474 SelectionDAG &DAG, int Enabled,
6477 bool Reciprocal) const {
6478 if (Enabled == ReciprocalEstimate::Enabled ||
6479 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6480 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6483 EVT VT = Operand.getValueType();
6486 Flags.setAllowReassociation(true);
6488 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6489 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6490 for (int i = ExtraSteps; i > 0; --i) {
6491 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6493 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6494 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6497 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6499 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6500 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6502 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6503 // Correct the result if the operand is 0.0.
6504 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6505 VT, Eq, Operand, Estimate);
6515 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6516 SelectionDAG &DAG, int Enabled,
6517 int &ExtraSteps) const {
6518 if (Enabled == ReciprocalEstimate::Enabled)
6519 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6522 EVT VT = Operand.getValueType();
6525 Flags.setAllowReassociation(true);
6527 // Newton reciprocal iteration: E * (2 - X * E)
6528 // AArch64 reciprocal iteration instruction: (2 - M * N)
6529 for (int i = ExtraSteps; i > 0; --i) {
6530 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6532 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6542 //===----------------------------------------------------------------------===//
6543 // AArch64 Inline Assembly Support
6544 //===----------------------------------------------------------------------===//
6546 // Table of Constraints
6547 // TODO: This is the current set of constraints supported by ARM for the
6548 // compiler, not all of them may make sense.
6550 // r - A general register
6551 // w - An FP/SIMD register of some size in the range v0-v31
6552 // x - An FP/SIMD register of some size in the range v0-v15
6553 // I - Constant that can be used with an ADD instruction
6554 // J - Constant that can be used with a SUB instruction
6555 // K - Constant that can be used with a 32-bit logical instruction
6556 // L - Constant that can be used with a 64-bit logical instruction
6557 // M - Constant that can be used as a 32-bit MOV immediate
6558 // N - Constant that can be used as a 64-bit MOV immediate
6559 // Q - A memory reference with base register and no offset
6560 // S - A symbolic address
6561 // Y - Floating point constant zero
6562 // Z - Integer constant zero
6564 // Note that general register operands will be output using their 64-bit x
6565 // register name, whatever the size of the variable, unless the asm operand
6566 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6567 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6569 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6570 // At this point, we have to lower this constraint to something else, so we
6571 // lower it to an "r" or "w". However, by doing this we will force the result
6572 // to be in register, while the X constraint is much more permissive.
6574 // Although we are correct (we are free to emit anything, without
6575 // constraints), we might break use cases that would expect us to be more
6576 // efficient and emit something else.
6577 if (!Subtarget->hasFPARMv8())
6580 if (ConstraintVT.isFloatingPoint())
6583 if (ConstraintVT.isVector() &&
6584 (ConstraintVT.getSizeInBits() == 64 ||
6585 ConstraintVT.getSizeInBits() == 128))
6591 enum PredicateConstraint {
6597 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6598 PredicateConstraint P = PredicateConstraint::Invalid;
6599 if (Constraint == "Upa")
6600 P = PredicateConstraint::Upa;
6601 if (Constraint == "Upl")
6602 P = PredicateConstraint::Upl;
6606 /// getConstraintType - Given a constraint letter, return the type of
6607 /// constraint it is for this target.
6608 AArch64TargetLowering::ConstraintType
6609 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6610 if (Constraint.size() == 1) {
6611 switch (Constraint[0]) {
6617 return C_RegisterClass;
6618 // An address with a single base register. Due to the way we
6619 // currently handle addresses it is the same as 'r'.
6632 case 'S': // A symbolic address
6635 } else if (parsePredicateConstraint(Constraint) !=
6636 PredicateConstraint::Invalid)
6637 return C_RegisterClass;
6638 return TargetLowering::getConstraintType(Constraint);
6641 /// Examine constraint type and operand type and determine a weight value.
6642 /// This object must already have been set up with the operand type
6643 /// and the current alternative constraint selected.
6644 TargetLowering::ConstraintWeight
6645 AArch64TargetLowering::getSingleConstraintMatchWeight(
6646 AsmOperandInfo &info, const char *constraint) const {
6647 ConstraintWeight weight = CW_Invalid;
6648 Value *CallOperandVal = info.CallOperandVal;
6649 // If we don't have a value, we can't do a match,
6650 // but allow it at the lowest weight.
6651 if (!CallOperandVal)
6653 Type *type = CallOperandVal->getType();
6654 // Look at the constraint type.
6655 switch (*constraint) {
6657 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6662 if (type->isFloatingPointTy() || type->isVectorTy())
6663 weight = CW_Register;
6666 weight = CW_Constant;
6669 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6670 weight = CW_Register;
6676 std::pair<unsigned, const TargetRegisterClass *>
6677 AArch64TargetLowering::getRegForInlineAsmConstraint(
6678 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6679 if (Constraint.size() == 1) {
6680 switch (Constraint[0]) {
6682 if (VT.getSizeInBits() == 64)
6683 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6684 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6686 if (!Subtarget->hasFPARMv8())
6688 if (VT.isScalableVector())
6689 return std::make_pair(0U, &AArch64::ZPRRegClass);
6690 if (VT.getSizeInBits() == 16)
6691 return std::make_pair(0U, &AArch64::FPR16RegClass);
6692 if (VT.getSizeInBits() == 32)
6693 return std::make_pair(0U, &AArch64::FPR32RegClass);
6694 if (VT.getSizeInBits() == 64)
6695 return std::make_pair(0U, &AArch64::FPR64RegClass);
6696 if (VT.getSizeInBits() == 128)
6697 return std::make_pair(0U, &AArch64::FPR128RegClass);
6699 // The instructions that this constraint is designed for can
6700 // only take 128-bit registers so just use that regclass.
6702 if (!Subtarget->hasFPARMv8())
6704 if (VT.isScalableVector())
6705 return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6706 if (VT.getSizeInBits() == 128)
6707 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6710 if (!Subtarget->hasFPARMv8())
6712 if (VT.isScalableVector())
6713 return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6717 PredicateConstraint PC = parsePredicateConstraint(Constraint);
6718 if (PC != PredicateConstraint::Invalid) {
6719 assert(VT.isScalableVector());
6720 bool restricted = (PC == PredicateConstraint::Upl);
6721 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6722 : std::make_pair(0U, &AArch64::PPRRegClass);
6725 if (StringRef("{cc}").equals_lower(Constraint))
6726 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6728 // Use the default implementation in TargetLowering to convert the register
6729 // constraint into a member of a register class.
6730 std::pair<unsigned, const TargetRegisterClass *> Res;
6731 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6733 // Not found as a standard register?
6735 unsigned Size = Constraint.size();
6736 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6737 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6739 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6740 if (!Failed && RegNo >= 0 && RegNo <= 31) {
6741 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6742 // By default we'll emit v0-v31 for this unless there's a modifier where
6743 // we'll emit the correct register as well.
6744 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6745 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6746 Res.second = &AArch64::FPR64RegClass;
6748 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6749 Res.second = &AArch64::FPR128RegClass;
6755 if (Res.second && !Subtarget->hasFPARMv8() &&
6756 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6757 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6758 return std::make_pair(0U, nullptr);
6763 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6764 /// vector. If it is invalid, don't add anything to Ops.
6765 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6766 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6767 SelectionDAG &DAG) const {
6770 // Currently only support length 1 constraints.
6771 if (Constraint.length() != 1)
6774 char ConstraintLetter = Constraint[0];
6775 switch (ConstraintLetter) {
6779 // This set of constraints deal with valid constants for various instructions.
6780 // Validate and return a target constant for them if we can.
6782 // 'z' maps to xzr or wzr so it needs an input of 0.
6783 if (!isNullConstant(Op))
6786 if (Op.getValueType() == MVT::i64)
6787 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6789 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6793 // An absolute symbolic address or label reference.
6794 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6795 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6796 GA->getValueType(0));
6797 } else if (const BlockAddressSDNode *BA =
6798 dyn_cast<BlockAddressSDNode>(Op)) {
6800 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6801 } else if (const ExternalSymbolSDNode *ES =
6802 dyn_cast<ExternalSymbolSDNode>(Op)) {
6804 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6816 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6820 // Grab the value and do some validation.
6821 uint64_t CVal = C->getZExtValue();
6822 switch (ConstraintLetter) {
6823 // The I constraint applies only to simple ADD or SUB immediate operands:
6824 // i.e. 0 to 4095 with optional shift by 12
6825 // The J constraint applies only to ADD or SUB immediates that would be
6826 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6827 // instruction [or vice versa], in other words -1 to -4095 with optional
6828 // left shift by 12.
6830 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6834 uint64_t NVal = -C->getSExtValue();
6835 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6836 CVal = C->getSExtValue();
6841 // The K and L constraints apply *only* to logical immediates, including
6842 // what used to be the MOVI alias for ORR (though the MOVI alias has now
6843 // been removed and MOV should be used). So these constraints have to
6844 // distinguish between bit patterns that are valid 32-bit or 64-bit
6845 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6846 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6849 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6853 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6856 // The M and N constraints are a superset of K and L respectively, for use
6857 // with the MOV (immediate) alias. As well as the logical immediates they
6858 // also match 32 or 64-bit immediates that can be loaded either using a
6859 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6860 // (M) or 64-bit 0x1234000000000000 (N) etc.
6861 // As a note some of this code is liberally stolen from the asm parser.
6863 if (!isUInt<32>(CVal))
6865 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6867 if ((CVal & 0xFFFF) == CVal)
6869 if ((CVal & 0xFFFF0000ULL) == CVal)
6871 uint64_t NCVal = ~(uint32_t)CVal;
6872 if ((NCVal & 0xFFFFULL) == NCVal)
6874 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6879 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6881 if ((CVal & 0xFFFFULL) == CVal)
6883 if ((CVal & 0xFFFF0000ULL) == CVal)
6885 if ((CVal & 0xFFFF00000000ULL) == CVal)
6887 if ((CVal & 0xFFFF000000000000ULL) == CVal)
6889 uint64_t NCVal = ~CVal;
6890 if ((NCVal & 0xFFFFULL) == NCVal)
6892 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6894 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6896 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6904 // All assembler immediates are 64-bit integers.
6905 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6909 if (Result.getNode()) {
6910 Ops.push_back(Result);
6914 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6917 //===----------------------------------------------------------------------===//
6918 // AArch64 Advanced SIMD Support
6919 //===----------------------------------------------------------------------===//
6921 /// WidenVector - Given a value in the V64 register class, produce the
6922 /// equivalent value in the V128 register class.
6923 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6924 EVT VT = V64Reg.getValueType();
6925 unsigned NarrowSize = VT.getVectorNumElements();
6926 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6927 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6930 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6931 V64Reg, DAG.getConstant(0, DL, MVT::i32));
6934 /// getExtFactor - Determine the adjustment factor for the position when
6935 /// generating an "extract from vector registers" instruction.
6936 static unsigned getExtFactor(SDValue &V) {
6937 EVT EltType = V.getValueType().getVectorElementType();
6938 return EltType.getSizeInBits() / 8;
6941 /// NarrowVector - Given a value in the V128 register class, produce the
6942 /// equivalent value in the V64 register class.
6943 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6944 EVT VT = V128Reg.getValueType();
6945 unsigned WideSize = VT.getVectorNumElements();
6946 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6947 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6950 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6953 // Gather data to see if the operation can be modelled as a
6954 // shuffle in combination with VEXTs.
6955 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6956 SelectionDAG &DAG) const {
6957 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6958 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6960 EVT VT = Op.getValueType();
6961 unsigned NumElts = VT.getVectorNumElements();
6963 struct ShuffleSourceInfo {
6968 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6969 // be compatible with the shuffle we intend to construct. As a result
6970 // ShuffleVec will be some sliding window into the original Vec.
6973 // Code should guarantee that element i in Vec starts at element "WindowBase
6974 // + i * WindowScale in ShuffleVec".
6978 ShuffleSourceInfo(SDValue Vec)
6979 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6980 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6982 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6985 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6987 SmallVector<ShuffleSourceInfo, 2> Sources;
6988 for (unsigned i = 0; i < NumElts; ++i) {
6989 SDValue V = Op.getOperand(i);
6992 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6993 !isa<ConstantSDNode>(V.getOperand(1))) {
6995 dbgs() << "Reshuffle failed: "
6996 "a shuffle can only come from building a vector from "
6997 "various elements of other vectors, provided their "
6998 "indices are constant\n");
7002 // Add this element source to the list if it's not already there.
7003 SDValue SourceVec = V.getOperand(0);
7004 auto Source = find(Sources, SourceVec);
7005 if (Source == Sources.end())
7006 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7008 // Update the minimum and maximum lane number seen.
7009 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7010 Source->MinElt = std::min(Source->MinElt, EltNo);
7011 Source->MaxElt = std::max(Source->MaxElt, EltNo);
7014 if (Sources.size() > 2) {
7016 dbgs() << "Reshuffle failed: currently only do something sane when at "
7017 "most two source vectors are involved\n");
7021 // Find out the smallest element size among result and two sources, and use
7022 // it as element size to build the shuffle_vector.
7023 EVT SmallestEltTy = VT.getVectorElementType();
7024 for (auto &Source : Sources) {
7025 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7026 if (SrcEltTy.bitsLT(SmallestEltTy)) {
7027 SmallestEltTy = SrcEltTy;
7030 unsigned ResMultiplier =
7031 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7032 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7033 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7035 // If the source vector is too wide or too narrow, we may nevertheless be able
7036 // to construct a compatible shuffle either by concatenating it with UNDEF or
7037 // extracting a suitable range of elements.
7038 for (auto &Src : Sources) {
7039 EVT SrcVT = Src.ShuffleVec.getValueType();
7041 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7044 // This stage of the search produces a source with the same element type as
7045 // the original, but with a total width matching the BUILD_VECTOR output.
7046 EVT EltVT = SrcVT.getVectorElementType();
7047 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7048 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7050 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7051 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
7052 // We can pad out the smaller vector for free, so if it's part of a
7055 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7056 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7060 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
7062 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7064 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
7068 if (Src.MinElt >= NumSrcElts) {
7069 // The extraction can just take the second half
7071 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7072 DAG.getConstant(NumSrcElts, dl, MVT::i64));
7073 Src.WindowBase = -NumSrcElts;
7074 } else if (Src.MaxElt < NumSrcElts) {
7075 // The extraction can just take the first half
7077 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7078 DAG.getConstant(0, dl, MVT::i64));
7080 // An actual VEXT is needed
7082 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7083 DAG.getConstant(0, dl, MVT::i64));
7085 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7086 DAG.getConstant(NumSrcElts, dl, MVT::i64));
7087 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
7089 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
7091 DAG.getConstant(Imm, dl, MVT::i32));
7092 Src.WindowBase = -Src.MinElt;
7096 // Another possible incompatibility occurs from the vector element types. We
7097 // can fix this by bitcasting the source vectors to the same type we intend
7099 for (auto &Src : Sources) {
7100 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7101 if (SrcEltTy == SmallestEltTy)
7103 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7104 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7105 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7106 Src.WindowBase *= Src.WindowScale;
7109 // Final sanity check before we try to actually produce a shuffle.
7110 LLVM_DEBUG(for (auto Src
7112 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7114 // The stars all align, our next step is to produce the mask for the shuffle.
7115 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7116 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7117 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7118 SDValue Entry = Op.getOperand(i);
7119 if (Entry.isUndef())
7122 auto Src = find(Sources, Entry.getOperand(0));
7123 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7125 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7126 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7128 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7130 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
7131 int LanesDefined = BitsDefined / BitsPerShuffleLane;
7133 // This source is expected to fill ResMultiplier lanes of the final shuffle,
7134 // starting at the appropriate offset.
7135 int *LaneMask = &Mask[i * ResMultiplier];
7137 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7138 ExtractBase += NumElts * (Src - Sources.begin());
7139 for (int j = 0; j < LanesDefined; ++j)
7140 LaneMask[j] = ExtractBase + j;
7143 // Final check before we try to produce nonsense...
7144 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
7145 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
7149 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7150 for (unsigned i = 0; i < Sources.size(); ++i)
7151 ShuffleOps[i] = Sources[i].ShuffleVec;
7153 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7154 ShuffleOps[1], Mask);
7155 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7157 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
7158 dbgs() << "Reshuffle, creating node: "; V.dump(););
7163 // check if an EXT instruction can handle the shuffle mask when the
7164 // vector sources of the shuffle are the same.
7165 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
7166 unsigned NumElts = VT.getVectorNumElements();
7168 // Assume that the first shuffle index is not UNDEF. Fail if it is.
7174 // If this is a VEXT shuffle, the immediate value is the index of the first
7175 // element. The other shuffle indices must be the successive elements after
7177 unsigned ExpectedElt = Imm;
7178 for (unsigned i = 1; i < NumElts; ++i) {
7179 // Increment the expected index. If it wraps around, just follow it
7180 // back to index zero and keep going.
7182 if (ExpectedElt == NumElts)
7186 continue; // ignore UNDEF indices
7187 if (ExpectedElt != static_cast<unsigned>(M[i]))
7194 // check if an EXT instruction can handle the shuffle mask when the
7195 // vector sources of the shuffle are different.
7196 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
7198 // Look for the first non-undef element.
7199 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
7201 // Benefit form APInt to handle overflow when calculating expected element.
7202 unsigned NumElts = VT.getVectorNumElements();
7203 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
7204 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
7205 // The following shuffle indices must be the successive elements after the
7206 // first real element.
7207 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
7208 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
7209 if (FirstWrongElt != M.end())
7212 // The index of an EXT is the first element if it is not UNDEF.
7213 // Watch out for the beginning UNDEFs. The EXT index should be the expected
7214 // value of the first element. E.g.
7215 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
7216 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
7217 // ExpectedElt is the last mask index plus 1.
7218 Imm = ExpectedElt.getZExtValue();
7220 // There are two difference cases requiring to reverse input vectors.
7221 // For example, for vector <4 x i32> we have the following cases,
7222 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
7223 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
7224 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
7225 // to reverse two input vectors.
7234 /// isREVMask - Check if a vector shuffle corresponds to a REV
7235 /// instruction with the specified blocksize. (The order of the elements
7236 /// within each block of the vector is reversed.)
7237 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
7238 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
7239 "Only possible block sizes for REV are: 16, 32, 64");
7241 unsigned EltSz = VT.getScalarSizeInBits();
7245 unsigned NumElts = VT.getVectorNumElements();
7246 unsigned BlockElts = M[0] + 1;
7247 // If the first shuffle index is UNDEF, be optimistic.
7249 BlockElts = BlockSize / EltSz;
7251 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
7254 for (unsigned i = 0; i < NumElts; ++i) {
7256 continue; // ignore UNDEF indices
7257 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
7264 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7265 unsigned NumElts = VT.getVectorNumElements();
7266 if (NumElts % 2 != 0)
7268 WhichResult = (M[0] == 0 ? 0 : 1);
7269 unsigned Idx = WhichResult * NumElts / 2;
7270 for (unsigned i = 0; i != NumElts; i += 2) {
7271 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7272 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
7280 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7281 unsigned NumElts = VT.getVectorNumElements();
7282 WhichResult = (M[0] == 0 ? 0 : 1);
7283 for (unsigned i = 0; i != NumElts; ++i) {
7285 continue; // ignore UNDEF indices
7286 if ((unsigned)M[i] != 2 * i + WhichResult)
7293 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7294 unsigned NumElts = VT.getVectorNumElements();
7295 if (NumElts % 2 != 0)
7297 WhichResult = (M[0] == 0 ? 0 : 1);
7298 for (unsigned i = 0; i < NumElts; i += 2) {
7299 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7300 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
7306 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
7307 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7308 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7309 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7310 unsigned NumElts = VT.getVectorNumElements();
7311 if (NumElts % 2 != 0)
7313 WhichResult = (M[0] == 0 ? 0 : 1);
7314 unsigned Idx = WhichResult * NumElts / 2;
7315 for (unsigned i = 0; i != NumElts; i += 2) {
7316 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
7317 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
7325 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
7326 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7327 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7328 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7329 unsigned Half = VT.getVectorNumElements() / 2;
7330 WhichResult = (M[0] == 0 ? 0 : 1);
7331 for (unsigned j = 0; j != 2; ++j) {
7332 unsigned Idx = WhichResult;
7333 for (unsigned i = 0; i != Half; ++i) {
7334 int MIdx = M[i + j * Half];
7335 if (MIdx >= 0 && (unsigned)MIdx != Idx)
7344 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
7345 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7346 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7347 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7348 unsigned NumElts = VT.getVectorNumElements();
7349 if (NumElts % 2 != 0)
7351 WhichResult = (M[0] == 0 ? 0 : 1);
7352 for (unsigned i = 0; i < NumElts; i += 2) {
7353 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
7354 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
7360 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
7361 bool &DstIsLeft, int &Anomaly) {
7362 if (M.size() != static_cast<size_t>(NumInputElements))
7365 int NumLHSMatch = 0, NumRHSMatch = 0;
7366 int LastLHSMismatch = -1, LastRHSMismatch = -1;
7368 for (int i = 0; i < NumInputElements; ++i) {
7378 LastLHSMismatch = i;
7380 if (M[i] == i + NumInputElements)
7383 LastRHSMismatch = i;
7386 if (NumLHSMatch == NumInputElements - 1) {
7388 Anomaly = LastLHSMismatch;
7390 } else if (NumRHSMatch == NumInputElements - 1) {
7392 Anomaly = LastRHSMismatch;
7399 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
7400 if (VT.getSizeInBits() != 128)
7403 unsigned NumElts = VT.getVectorNumElements();
7405 for (int I = 0, E = NumElts / 2; I != E; I++) {
7410 int Offset = NumElts / 2;
7411 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
7412 if (Mask[I] != I + SplitLHS * Offset)
7419 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
7421 EVT VT = Op.getValueType();
7422 SDValue V0 = Op.getOperand(0);
7423 SDValue V1 = Op.getOperand(1);
7424 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
7426 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
7427 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
7430 bool SplitV0 = V0.getValueSizeInBits() == 128;
7432 if (!isConcatMask(Mask, VT, SplitV0))
7435 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7437 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
7438 DAG.getConstant(0, DL, MVT::i64));
7440 if (V1.getValueSizeInBits() == 128) {
7441 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
7442 DAG.getConstant(0, DL, MVT::i64));
7444 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
7447 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7448 /// the specified operations to build the shuffle.
7449 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7450 SDValue RHS, SelectionDAG &DAG,
7452 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7453 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7454 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7457 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7466 OP_VUZPL, // VUZP, left result
7467 OP_VUZPR, // VUZP, right result
7468 OP_VZIPL, // VZIP, left result
7469 OP_VZIPR, // VZIP, right result
7470 OP_VTRNL, // VTRN, left result
7471 OP_VTRNR // VTRN, right result
7474 if (OpNum == OP_COPY) {
7475 if (LHSID == (1 * 9 + 2) * 9 + 3)
7477 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7481 SDValue OpLHS, OpRHS;
7482 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7483 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7484 EVT VT = OpLHS.getValueType();
7488 llvm_unreachable("Unknown shuffle opcode!");
7490 // VREV divides the vector in half and swaps within the half.
7491 if (VT.getVectorElementType() == MVT::i32 ||
7492 VT.getVectorElementType() == MVT::f32)
7493 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7494 // vrev <4 x i16> -> REV32
7495 if (VT.getVectorElementType() == MVT::i16 ||
7496 VT.getVectorElementType() == MVT::f16 ||
7497 VT.getVectorElementType() == MVT::bf16)
7498 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7499 // vrev <4 x i8> -> REV16
7500 assert(VT.getVectorElementType() == MVT::i8);
7501 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7506 EVT EltTy = VT.getVectorElementType();
7508 if (EltTy == MVT::i8)
7509 Opcode = AArch64ISD::DUPLANE8;
7510 else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
7511 Opcode = AArch64ISD::DUPLANE16;
7512 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7513 Opcode = AArch64ISD::DUPLANE32;
7514 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7515 Opcode = AArch64ISD::DUPLANE64;
7517 llvm_unreachable("Invalid vector element type?");
7519 if (VT.getSizeInBits() == 64)
7520 OpLHS = WidenVector(OpLHS, DAG);
7521 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7522 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7527 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7528 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7529 DAG.getConstant(Imm, dl, MVT::i32));
7532 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7535 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7538 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7541 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7544 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7547 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7552 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7553 SelectionDAG &DAG) {
7554 // Check to see if we can use the TBL instruction.
7555 SDValue V1 = Op.getOperand(0);
7556 SDValue V2 = Op.getOperand(1);
7559 EVT EltVT = Op.getValueType().getVectorElementType();
7560 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7562 SmallVector<SDValue, 8> TBLMask;
7563 for (int Val : ShuffleMask) {
7564 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7565 unsigned Offset = Byte + Val * BytesPerElt;
7566 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7570 MVT IndexVT = MVT::v8i8;
7571 unsigned IndexLen = 8;
7572 if (Op.getValueSizeInBits() == 128) {
7573 IndexVT = MVT::v16i8;
7577 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7578 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7581 if (V2.getNode()->isUndef()) {
7583 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7584 Shuffle = DAG.getNode(
7585 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7586 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7587 DAG.getBuildVector(IndexVT, DL,
7588 makeArrayRef(TBLMask.data(), IndexLen)));
7590 if (IndexLen == 8) {
7591 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7592 Shuffle = DAG.getNode(
7593 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7594 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7595 DAG.getBuildVector(IndexVT, DL,
7596 makeArrayRef(TBLMask.data(), IndexLen)));
7598 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7599 // cannot currently represent the register constraints on the input
7601 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7602 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7604 Shuffle = DAG.getNode(
7605 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7606 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7607 V2Cst, DAG.getBuildVector(IndexVT, DL,
7608 makeArrayRef(TBLMask.data(), IndexLen)));
7611 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7614 static unsigned getDUPLANEOp(EVT EltType) {
7615 if (EltType == MVT::i8)
7616 return AArch64ISD::DUPLANE8;
7617 if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
7618 return AArch64ISD::DUPLANE16;
7619 if (EltType == MVT::i32 || EltType == MVT::f32)
7620 return AArch64ISD::DUPLANE32;
7621 if (EltType == MVT::i64 || EltType == MVT::f64)
7622 return AArch64ISD::DUPLANE64;
7624 llvm_unreachable("Invalid vector element type?");
7627 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7628 SelectionDAG &DAG) const {
7630 EVT VT = Op.getValueType();
7632 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7634 // Convert shuffles that are directly supported on NEON to target-specific
7635 // DAG nodes, instead of keeping them as shuffles and matching them again
7636 // during code selection. This is more efficient and avoids the possibility
7637 // of inconsistencies between legalization and selection.
7638 ArrayRef<int> ShuffleMask = SVN->getMask();
7640 SDValue V1 = Op.getOperand(0);
7641 SDValue V2 = Op.getOperand(1);
7643 if (SVN->isSplat()) {
7644 int Lane = SVN->getSplatIndex();
7645 // If this is undef splat, generate it via "just" vdup, if possible.
7649 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7650 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7652 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7653 // constant. If so, we can just reference the lane's definition directly.
7654 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7655 !isa<ConstantSDNode>(V1.getOperand(Lane)))
7656 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7658 // Otherwise, duplicate from the lane of the input vector.
7659 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7661 // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7662 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7663 // Match: dup (bitcast (extract_subv X, C)), LaneC
7664 if (BitCast.getOpcode() != ISD::BITCAST ||
7665 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7668 // The extract index must align in the destination type. That may not
7669 // happen if the bitcast is from narrow to wide type.
7670 SDValue Extract = BitCast.getOperand(0);
7671 unsigned ExtIdx = Extract.getConstantOperandVal(1);
7672 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7673 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7674 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7675 if (ExtIdxInBits % CastedEltBitWidth != 0)
7678 // Update the lane value by offsetting with the scaled extract index.
7679 LaneC += ExtIdxInBits / CastedEltBitWidth;
7681 // Determine the casted vector type of the wide vector input.
7682 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7684 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7685 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7686 unsigned SrcVecNumElts =
7687 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7688 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7693 if (getScaledOffsetDup(V1, Lane, CastVT)) {
7694 V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7695 } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7696 // The lane is incremented by the index of the extract.
7697 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7698 Lane += V1.getConstantOperandVal(1);
7699 V1 = V1.getOperand(0);
7700 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7701 // The lane is decremented if we are splatting from the 2nd operand.
7702 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7703 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7704 Lane -= Idx * VT.getVectorNumElements() / 2;
7705 V1 = WidenVector(V1.getOperand(Idx), DAG);
7706 } else if (VT.getSizeInBits() == 64) {
7707 // Widen the operand to 128-bit register with undef.
7708 V1 = WidenVector(V1, DAG);
7710 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7713 if (isREVMask(ShuffleMask, VT, 64))
7714 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7715 if (isREVMask(ShuffleMask, VT, 32))
7716 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7717 if (isREVMask(ShuffleMask, VT, 16))
7718 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7720 bool ReverseEXT = false;
7722 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7725 Imm *= getExtFactor(V1);
7726 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7727 DAG.getConstant(Imm, dl, MVT::i32));
7728 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7729 Imm *= getExtFactor(V1);
7730 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7731 DAG.getConstant(Imm, dl, MVT::i32));
7734 unsigned WhichResult;
7735 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7736 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7737 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7739 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7740 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7741 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7743 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7744 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7745 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7748 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7749 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7750 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7752 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7753 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7754 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7756 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7757 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7758 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7761 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7766 int NumInputElements = V1.getValueType().getVectorNumElements();
7767 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7768 SDValue DstVec = DstIsLeft ? V1 : V2;
7769 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7771 SDValue SrcVec = V1;
7772 int SrcLane = ShuffleMask[Anomaly];
7773 if (SrcLane >= NumInputElements) {
7775 SrcLane -= VT.getVectorNumElements();
7777 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7779 EVT ScalarVT = VT.getVectorElementType();
7781 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7782 ScalarVT = MVT::i32;
7785 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7786 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7790 // If the shuffle is not directly supported and it has 4 elements, use
7791 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7792 unsigned NumElts = VT.getVectorNumElements();
7794 unsigned PFIndexes[4];
7795 for (unsigned i = 0; i != 4; ++i) {
7796 if (ShuffleMask[i] < 0)
7799 PFIndexes[i] = ShuffleMask[i];
7802 // Compute the index in the perfect shuffle table.
7803 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7804 PFIndexes[2] * 9 + PFIndexes[3];
7805 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7806 unsigned Cost = (PFEntry >> 30);
7809 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7812 return GenerateTBL(Op, ShuffleMask, DAG);
7815 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7816 SelectionDAG &DAG) const {
7818 EVT VT = Op.getValueType();
7819 EVT ElemVT = VT.getScalarType();
7821 SDValue SplatVal = Op.getOperand(0);
7823 // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7824 // FPRs don't have this restriction.
7825 switch (ElemVT.getSimpleVT().SimpleTy) {
7827 // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
7829 if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
7830 if (ConstVal->isOne())
7831 return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
7832 // TODO: Add special case for constant false
7834 // The general case of i1. There isn't any natural way to do this,
7835 // so we use some trickery with whilelo.
7836 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7837 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7838 DAG.getValueType(MVT::i1));
7839 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7841 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7842 DAG.getConstant(0, dl, MVT::i64), SplatVal);
7847 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7850 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7859 report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7862 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7865 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
7866 SelectionDAG &DAG) const {
7869 EVT VT = Op.getValueType();
7870 if (!isTypeLegal(VT) || !VT.isScalableVector())
7873 // Current lowering only supports the SVE-ACLE types.
7874 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
7877 // The DUPQ operation is indepedent of element type so normalise to i64s.
7878 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
7879 SDValue Idx128 = Op.getOperand(2);
7881 // DUPQ can be used when idx is in range.
7882 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
7883 if (CIdx && (CIdx->getZExtValue() <= 3)) {
7884 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
7886 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
7887 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
7890 // The ACLE says this must produce the same result as:
7891 // svtbl(data, svadd_x(svptrue_b64(),
7892 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
7894 SDValue One = DAG.getConstant(1, DL, MVT::i64);
7895 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
7897 // create the vector 0,1,0,1,...
7898 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
7899 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
7900 DL, MVT::nxv2i64, Zero, One);
7901 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
7903 // create the vector idx64,idx64+1,idx64,idx64+1,...
7904 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
7905 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
7906 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
7908 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
7909 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
7910 return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
7914 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7916 EVT VT = BVN->getValueType(0);
7917 APInt SplatBits, SplatUndef;
7918 unsigned SplatBitSize;
7920 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7921 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7923 for (unsigned i = 0; i < NumSplats; ++i) {
7924 CnstBits <<= SplatBitSize;
7925 UndefBits <<= SplatBitSize;
7926 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7927 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7936 // Try 64-bit splatted SIMD immediate.
7937 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7938 const APInt &Bits) {
7939 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7940 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7941 EVT VT = Op.getValueType();
7942 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7944 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7945 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7948 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7949 DAG.getConstant(Value, dl, MVT::i32));
7950 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7957 // Try 32-bit splatted SIMD immediate.
7958 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7960 const SDValue *LHS = nullptr) {
7961 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7962 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7963 EVT VT = Op.getValueType();
7964 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7965 bool isAdvSIMDModImm = false;
7968 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7969 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7972 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7973 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7976 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7977 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7980 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7981 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7985 if (isAdvSIMDModImm) {
7990 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7991 DAG.getConstant(Value, dl, MVT::i32),
7992 DAG.getConstant(Shift, dl, MVT::i32));
7994 Mov = DAG.getNode(NewOp, dl, MovTy,
7995 DAG.getConstant(Value, dl, MVT::i32),
7996 DAG.getConstant(Shift, dl, MVT::i32));
7998 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8005 // Try 16-bit splatted SIMD immediate.
8006 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8008 const SDValue *LHS = nullptr) {
8009 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8010 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8011 EVT VT = Op.getValueType();
8012 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
8013 bool isAdvSIMDModImm = false;
8016 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
8017 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
8020 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
8021 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
8025 if (isAdvSIMDModImm) {
8030 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
8031 DAG.getConstant(Value, dl, MVT::i32),
8032 DAG.getConstant(Shift, dl, MVT::i32));
8034 Mov = DAG.getNode(NewOp, dl, MovTy,
8035 DAG.getConstant(Value, dl, MVT::i32),
8036 DAG.getConstant(Shift, dl, MVT::i32));
8038 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8045 // Try 32-bit splatted SIMD immediate with shifted ones.
8046 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
8047 SelectionDAG &DAG, const APInt &Bits) {
8048 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8049 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8050 EVT VT = Op.getValueType();
8051 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
8052 bool isAdvSIMDModImm = false;
8055 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
8056 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
8059 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
8060 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
8064 if (isAdvSIMDModImm) {
8066 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8067 DAG.getConstant(Value, dl, MVT::i32),
8068 DAG.getConstant(Shift, dl, MVT::i32));
8069 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8076 // Try 8-bit splatted SIMD immediate.
8077 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8078 const APInt &Bits) {
8079 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8080 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8081 EVT VT = Op.getValueType();
8082 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
8084 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
8085 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
8088 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8089 DAG.getConstant(Value, dl, MVT::i32));
8090 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8097 // Try FP splatted SIMD immediate.
8098 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
8099 const APInt &Bits) {
8100 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
8101 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
8102 EVT VT = Op.getValueType();
8103 bool isWide = (VT.getSizeInBits() == 128);
8105 bool isAdvSIMDModImm = false;
8107 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
8108 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
8109 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
8112 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
8113 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
8117 if (isAdvSIMDModImm) {
8119 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
8120 DAG.getConstant(Value, dl, MVT::i32));
8121 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
8128 // Specialized code to quickly find if PotentialBVec is a BuildVector that
8129 // consists of only the same constant int value, returned in reference arg
8131 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
8132 uint64_t &ConstVal) {
8133 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
8136 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
8139 EVT VT = Bvec->getValueType(0);
8140 unsigned NumElts = VT.getVectorNumElements();
8141 for (unsigned i = 1; i < NumElts; ++i)
8142 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
8144 ConstVal = FirstElt->getZExtValue();
8148 static unsigned getIntrinsicID(const SDNode *N) {
8149 unsigned Opcode = N->getOpcode();
8152 return Intrinsic::not_intrinsic;
8153 case ISD::INTRINSIC_WO_CHAIN: {
8154 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8155 if (IID < Intrinsic::num_intrinsics)
8157 return Intrinsic::not_intrinsic;
8162 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
8163 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
8164 // BUILD_VECTORs with constant element C1, C2 is a constant, and:
8165 // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
8166 // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
8167 // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
8168 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
8169 EVT VT = N->getValueType(0);
8179 SDValue FirstOp = N->getOperand(0);
8180 unsigned FirstOpc = FirstOp.getOpcode();
8181 SDValue SecondOp = N->getOperand(1);
8182 unsigned SecondOpc = SecondOp.getOpcode();
8184 // Is one of the operands an AND or a BICi? The AND may have been optimised to
8185 // a BICi in order to use an immediate instead of a register.
8186 // Is the other operand an shl or lshr? This will have been turned into:
8187 // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
8188 if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
8189 (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
8193 } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
8194 (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
8200 bool IsAnd = And.getOpcode() == ISD::AND;
8201 bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
8203 // Is the shift amount constant?
8204 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8210 // Is the and mask vector all constant?
8211 if (!isAllConstantBuildVector(And.getOperand(1), C1))
8214 // Reconstruct the corresponding AND immediate from the two BICi immediates.
8215 ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
8216 ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
8217 assert(C1nodeImm && C1nodeShift);
8218 C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
8221 // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
8222 // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
8223 // how much one can shift elements of a particular size?
8224 uint64_t C2 = C2node->getZExtValue();
8225 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8226 if (C2 > ElemSizeInBits)
8229 APInt C1AsAPInt(ElemSizeInBits, C1);
8230 APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
8231 : APInt::getLowBitsSet(ElemSizeInBits, C2);
8232 if (C1AsAPInt != RequiredC1)
8235 SDValue X = And.getOperand(0);
8236 SDValue Y = Shift.getOperand(0);
8238 unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
8239 SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
8241 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
8242 LLVM_DEBUG(N->dump(&DAG));
8243 LLVM_DEBUG(dbgs() << "into: \n");
8244 LLVM_DEBUG(ResultSLI->dump(&DAG));
8250 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
8251 SelectionDAG &DAG) const {
8252 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
8253 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
8256 EVT VT = Op.getValueType();
8258 SDValue LHS = Op.getOperand(0);
8259 BuildVectorSDNode *BVN =
8260 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
8262 // OR commutes, so try swapping the operands.
8263 LHS = Op.getOperand(1);
8264 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
8269 APInt DefBits(VT.getSizeInBits(), 0);
8270 APInt UndefBits(VT.getSizeInBits(), 0);
8271 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8274 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8276 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8280 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
8281 UndefBits, &LHS)) ||
8282 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
8287 // We can always fall back to a non-immediate OR.
8291 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
8292 // be truncated to fit element width.
8293 static SDValue NormalizeBuildVector(SDValue Op,
8294 SelectionDAG &DAG) {
8295 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
8297 EVT VT = Op.getValueType();
8298 EVT EltTy= VT.getVectorElementType();
8300 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
8303 SmallVector<SDValue, 16> Ops;
8304 for (SDValue Lane : Op->ops()) {
8305 // For integer vectors, type legalization would have promoted the
8306 // operands already. Otherwise, if Op is a floating-point splat
8307 // (with operands cast to integers), then the only possibilities
8308 // are constants and UNDEFs.
8309 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
8310 APInt LowBits(EltTy.getSizeInBits(),
8311 CstLane->getZExtValue());
8312 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
8313 } else if (Lane.getNode()->isUndef()) {
8314 Lane = DAG.getUNDEF(MVT::i32);
8316 assert(Lane.getValueType() == MVT::i32 &&
8317 "Unexpected BUILD_VECTOR operand type");
8319 Ops.push_back(Lane);
8321 return DAG.getBuildVector(VT, dl, Ops);
8324 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
8325 EVT VT = Op.getValueType();
8327 APInt DefBits(VT.getSizeInBits(), 0);
8328 APInt UndefBits(VT.getSizeInBits(), 0);
8329 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8330 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
8332 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8333 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8334 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8335 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8336 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8337 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8341 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8342 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8343 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8346 DefBits = UndefBits;
8347 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
8348 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8349 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
8350 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
8351 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
8352 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
8355 DefBits = ~UndefBits;
8356 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
8357 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
8358 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
8365 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
8366 SelectionDAG &DAG) const {
8367 EVT VT = Op.getValueType();
8369 // Try to build a simple constant vector.
8370 Op = NormalizeBuildVector(Op, DAG);
8371 if (VT.isInteger()) {
8372 // Certain vector constants, used to express things like logical NOT and
8373 // arithmetic NEG, are passed through unmodified. This allows special
8374 // patterns for these operations to match, which will lower these constants
8375 // to whatever is proven necessary.
8376 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
8377 if (BVN->isConstant())
8378 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
8379 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
8381 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
8382 if (Val.isNullValue() || Val.isAllOnesValue())
8387 if (SDValue V = ConstantBuildVector(Op, DAG))
8390 // Scan through the operands to find some interesting properties we can
8392 // 1) If only one value is used, we can use a DUP, or
8393 // 2) if only the low element is not undef, we can just insert that, or
8394 // 3) if only one constant value is used (w/ some non-constant lanes),
8395 // we can splat the constant value into the whole vector then fill
8396 // in the non-constant lanes.
8397 // 4) FIXME: If different constant values are used, but we can intelligently
8398 // select the values we'll be overwriting for the non-constant
8399 // lanes such that we can directly materialize the vector
8400 // some other way (MOVI, e.g.), we can be sneaky.
8401 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
8403 unsigned NumElts = VT.getVectorNumElements();
8404 bool isOnlyLowElement = true;
8405 bool usesOnlyOneValue = true;
8406 bool usesOnlyOneConstantValue = true;
8407 bool isConstant = true;
8408 bool AllLanesExtractElt = true;
8409 unsigned NumConstantLanes = 0;
8411 SDValue ConstantValue;
8412 for (unsigned i = 0; i < NumElts; ++i) {
8413 SDValue V = Op.getOperand(i);
8414 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8415 AllLanesExtractElt = false;
8419 isOnlyLowElement = false;
8420 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
8423 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
8425 if (!ConstantValue.getNode())
8427 else if (ConstantValue != V)
8428 usesOnlyOneConstantValue = false;
8431 if (!Value.getNode())
8433 else if (V != Value)
8434 usesOnlyOneValue = false;
8437 if (!Value.getNode()) {
8439 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
8440 return DAG.getUNDEF(VT);
8443 // Convert BUILD_VECTOR where all elements but the lowest are undef into
8444 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
8445 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
8446 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
8447 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
8448 "SCALAR_TO_VECTOR node\n");
8449 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
8452 if (AllLanesExtractElt) {
8453 SDNode *Vector = nullptr;
8456 // Check whether the extract elements match the Even pattern <0,2,4,...> or
8457 // the Odd pattern <1,3,5,...>.
8458 for (unsigned i = 0; i < NumElts; ++i) {
8459 SDValue V = Op.getOperand(i);
8460 const SDNode *N = V.getNode();
8461 if (!isa<ConstantSDNode>(N->getOperand(1)))
8463 SDValue N0 = N->getOperand(0);
8465 // All elements are extracted from the same vector.
8467 Vector = N0.getNode();
8468 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
8470 if (VT.getVectorElementType() !=
8471 N0.getValueType().getVectorElementType())
8473 } else if (Vector != N0.getNode()) {
8479 // Extracted values are either at Even indices <0,2,4,...> or at Odd
8480 // indices <1,3,5,...>.
8481 uint64_t Val = N->getConstantOperandVal(1);
8486 if (Val - 1 == 2 * i) {
8491 // Something does not match: abort.
8498 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8499 DAG.getConstant(0, dl, MVT::i64));
8501 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
8502 DAG.getConstant(NumElts, dl, MVT::i64));
8505 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
8508 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
8513 // Use DUP for non-constant splats. For f32 constant splats, reduce to
8514 // i32 and try again.
8515 if (usesOnlyOneValue) {
8517 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8518 Value.getValueType() != VT) {
8520 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
8521 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
8524 // This is actually a DUPLANExx operation, which keeps everything vectory.
8526 SDValue Lane = Value.getOperand(1);
8527 Value = Value.getOperand(0);
8528 if (Value.getValueSizeInBits() == 64) {
8530 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8532 Value = WidenVector(Value, DAG);
8535 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8536 return DAG.getNode(Opcode, dl, VT, Value, Lane);
8539 if (VT.getVectorElementType().isFloatingPoint()) {
8540 SmallVector<SDValue, 8> Ops;
8541 EVT EltTy = VT.getVectorElementType();
8542 assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
8543 EltTy == MVT::f64) && "Unsupported floating-point vector type");
8545 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8546 "BITCASTS, and try again\n");
8547 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8548 for (unsigned i = 0; i < NumElts; ++i)
8549 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8550 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8551 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8552 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8554 Val = LowerBUILD_VECTOR(Val, DAG);
8556 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8560 // If there was only one constant value used and for more than one lane,
8561 // start by splatting that value, then replace the non-constant lanes. This
8562 // is better than the default, which will perform a separate initialization
8564 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8565 // Firstly, try to materialize the splat constant.
8566 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8567 Val = ConstantBuildVector(Vec, DAG);
8569 // Otherwise, materialize the constant and splat it.
8570 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8571 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8574 // Now insert the non-constant lanes.
8575 for (unsigned i = 0; i < NumElts; ++i) {
8576 SDValue V = Op.getOperand(i);
8577 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8578 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8579 // Note that type legalization likely mucked about with the VT of the
8580 // source operand, so we may have to convert it here before inserting.
8581 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8586 // This will generate a load from the constant pool.
8589 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8594 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8596 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8600 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8601 // know the default expansion would otherwise fall back on something even
8602 // worse. For a vector with one or two non-undef values, that's
8603 // scalar_to_vector for the elements followed by a shuffle (provided the
8604 // shuffle is valid for the target) and materialization element by element
8605 // on the stack followed by a load for everything else.
8606 if (!isConstant && !usesOnlyOneValue) {
8608 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8609 "of INSERT_VECTOR_ELT\n");
8611 SDValue Vec = DAG.getUNDEF(VT);
8612 SDValue Op0 = Op.getOperand(0);
8615 // Use SCALAR_TO_VECTOR for lane zero to
8616 // a) Avoid a RMW dependency on the full vector register, and
8617 // b) Allow the register coalescer to fold away the copy if the
8618 // value is already in an S or D register, and we're forced to emit an
8619 // INSERT_SUBREG that we can't fold anywhere.
8621 // We also allow types like i8 and i16 which are illegal scalar but legal
8622 // vector element types. After type-legalization the inserted value is
8623 // extended (i32) and it is safe to cast them to the vector type by ignoring
8624 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8625 if (!Op0.isUndef()) {
8626 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8627 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8630 LLVM_DEBUG(if (i < NumElts) dbgs()
8631 << "Creating nodes for the other vector elements:\n";);
8632 for (; i < NumElts; ++i) {
8633 SDValue V = Op.getOperand(i);
8636 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8637 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8643 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8644 "better alternative\n");
8648 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8649 SelectionDAG &DAG) const {
8650 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8652 // Check for non-constant or out of range lane.
8653 EVT VT = Op.getOperand(0).getValueType();
8654 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8655 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8659 // Insertion/extraction are legal for V128 types.
8660 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8661 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8662 VT == MVT::v8f16 || VT == MVT::v8bf16)
8665 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8666 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8670 // For V64 types, we perform insertion by expanding the value
8671 // to a V128 type and perform the insertion on that.
8673 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8674 EVT WideTy = WideVec.getValueType();
8676 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8677 Op.getOperand(1), Op.getOperand(2));
8678 // Re-narrow the resultant vector.
8679 return NarrowVector(Node, DAG);
8683 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8684 SelectionDAG &DAG) const {
8685 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8687 // Check for non-constant or out of range lane.
8688 EVT VT = Op.getOperand(0).getValueType();
8689 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8690 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8694 // Insertion/extraction are legal for V128 types.
8695 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8696 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8697 VT == MVT::v8f16 || VT == MVT::v8bf16)
8700 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8701 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
8705 // For V64 types, we perform extraction by expanding the value
8706 // to a V128 type and perform the extraction on that.
8708 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8709 EVT WideTy = WideVec.getValueType();
8711 EVT ExtrTy = WideTy.getVectorElementType();
8712 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8715 // For extractions, we just return the result directly.
8716 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8720 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8721 SelectionDAG &DAG) const {
8722 assert(Op.getValueType().isFixedLengthVector() &&
8723 "Only cases that extract a fixed length vector are supported!");
8725 EVT InVT = Op.getOperand(0).getValueType();
8726 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8727 unsigned Size = Op.getValueSizeInBits();
8729 if (InVT.isScalableVector()) {
8730 // This will be matched by custom code during ISelDAGToDAG.
8731 if (Idx == 0 && isPackedVectorType(InVT, DAG))
8737 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8738 if (Idx == 0 && InVT.getSizeInBits() <= 128)
8741 // If this is extracting the upper 64-bits of a 128-bit vector, we match
8743 if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64)
8749 SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
8750 SelectionDAG &DAG) const {
8751 assert(Op.getValueType().isScalableVector() &&
8752 "Only expect to lower inserts into scalable vectors!");
8754 EVT InVT = Op.getOperand(1).getValueType();
8755 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8757 // We don't have any patterns for scalable vector yet.
8758 if (InVT.isScalableVector() || !useSVEForFixedLengthVectorVT(InVT))
8761 // This will be matched by custom code during ISelDAGToDAG.
8762 if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
8768 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8769 // Currently no fixed length shuffles that require SVE are legal.
8770 if (useSVEForFixedLengthVectorVT(VT))
8773 if (VT.getVectorNumElements() == 4 &&
8774 (VT.is128BitVector() || VT.is64BitVector())) {
8775 unsigned PFIndexes[4];
8776 for (unsigned i = 0; i != 4; ++i) {
8780 PFIndexes[i] = M[i];
8783 // Compute the index in the perfect shuffle table.
8784 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8785 PFIndexes[2] * 9 + PFIndexes[3];
8786 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8787 unsigned Cost = (PFEntry >> 30);
8795 unsigned DummyUnsigned;
8797 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8798 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8799 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8800 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8801 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8802 isZIPMask(M, VT, DummyUnsigned) ||
8803 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8804 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8805 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8806 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8807 isConcatMask(M, VT, VT.getSizeInBits() == 128));
8810 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8811 /// operand of a vector shift operation, where all the elements of the
8812 /// build_vector must have the same constant integer value.
8813 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8814 // Ignore bit_converts.
8815 while (Op.getOpcode() == ISD::BITCAST)
8816 Op = Op.getOperand(0);
8817 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8818 APInt SplatBits, SplatUndef;
8819 unsigned SplatBitSize;
8821 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8822 HasAnyUndefs, ElementBits) ||
8823 SplatBitSize > ElementBits)
8825 Cnt = SplatBits.getSExtValue();
8829 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8830 /// operand of a vector shift left operation. That value must be in the range:
8831 /// 0 <= Value < ElementBits for a left shift; or
8832 /// 0 <= Value <= ElementBits for a long left shift.
8833 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8834 assert(VT.isVector() && "vector shift count is not a vector type");
8835 int64_t ElementBits = VT.getScalarSizeInBits();
8836 if (!getVShiftImm(Op, ElementBits, Cnt))
8838 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8841 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8842 /// operand of a vector shift right operation. The value must be in the range:
8843 /// 1 <= Value <= ElementBits for a right shift; or
8844 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8845 assert(VT.isVector() && "vector shift count is not a vector type");
8846 int64_t ElementBits = VT.getScalarSizeInBits();
8847 if (!getVShiftImm(Op, ElementBits, Cnt))
8849 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8852 // Attempt to form urhadd(OpA, OpB) from
8853 // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1)).
8854 // The original form of this expression is
8855 // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and before this function
8856 // is called the srl will have been lowered to AArch64ISD::VLSHR and the
8857 // ((OpA + OpB + 1) >> 1) expression will have been changed to (OpB - (~OpA)).
8858 // This pass can also recognize a variant of this pattern that uses sign
8859 // extension instead of zero extension and form a srhadd(OpA, OpB) from it.
8860 SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
8861 SelectionDAG &DAG) const {
8862 EVT VT = Op.getValueType();
8864 if (VT.getScalarType() == MVT::i1) {
8865 // Lower i1 truncate to `(x & 1) != 0`.
8867 EVT OpVT = Op.getOperand(0).getValueType();
8868 SDValue Zero = DAG.getConstant(0, dl, OpVT);
8869 SDValue One = DAG.getConstant(1, dl, OpVT);
8870 SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
8871 return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
8874 if (!VT.isVector() || VT.isScalableVector())
8877 if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
8878 return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
8880 // Since we are looking for a right shift by a constant value of 1 and we are
8881 // operating on types at least 16 bits in length (sign/zero extended OpA and
8882 // OpB, which are at least 8 bits), it follows that the truncate will always
8883 // discard the shifted-in bit and therefore the right shift will be logical
8884 // regardless of the signedness of OpA and OpB.
8885 SDValue Shift = Op.getOperand(0);
8886 if (Shift.getOpcode() != AArch64ISD::VLSHR)
8889 // Is the right shift using an immediate value of 1?
8890 uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
8891 if (ShiftAmount != 1)
8894 SDValue Sub = Shift->getOperand(0);
8895 if (Sub.getOpcode() != ISD::SUB)
8898 SDValue Xor = Sub.getOperand(1);
8899 if (Xor.getOpcode() != ISD::XOR)
8902 SDValue ExtendOpA = Xor.getOperand(0);
8903 SDValue ExtendOpB = Sub.getOperand(0);
8904 unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
8905 unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
8906 if (!(ExtendOpAOpc == ExtendOpBOpc &&
8907 (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
8910 // Is the result of the right shift being truncated to the same value type as
8911 // the original operands, OpA and OpB?
8912 SDValue OpA = ExtendOpA.getOperand(0);
8913 SDValue OpB = ExtendOpB.getOperand(0);
8914 EVT OpAVT = OpA.getValueType();
8915 assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
8916 if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
8919 // Is the XOR using a constant amount of all ones in the right hand side?
8921 if (!isAllConstantBuildVector(Xor.getOperand(1), C))
8924 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
8925 APInt CAsAPInt(ElemSizeInBits, C);
8926 if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
8930 bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
8931 unsigned RHADDOpc = IsSignExtend ? AArch64ISD::SRHADD : AArch64ISD::URHADD;
8932 SDValue ResultURHADD = DAG.getNode(RHADDOpc, DL, VT, OpA, OpB);
8934 return ResultURHADD;
8937 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8938 SelectionDAG &DAG) const {
8939 EVT VT = Op.getValueType();
8943 if (!Op.getOperand(1).getValueType().isVector())
8945 unsigned EltSize = VT.getScalarSizeInBits();
8947 switch (Op.getOpcode()) {
8949 llvm_unreachable("unexpected shift opcode");
8952 if (VT.isScalableVector())
8953 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_MERGE_OP1);
8955 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8956 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8957 DAG.getConstant(Cnt, DL, MVT::i32));
8958 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8959 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8961 Op.getOperand(0), Op.getOperand(1));
8964 if (VT.isScalableVector()) {
8965 unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_MERGE_OP1
8966 : AArch64ISD::SRL_MERGE_OP1;
8967 return LowerToPredicatedOp(Op, DAG, Opc);
8970 // Right shift immediate
8971 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8973 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8974 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8975 DAG.getConstant(Cnt, DL, MVT::i32));
8978 // Right shift register. Note, there is not a shift right register
8979 // instruction, but the shift left register instruction takes a signed
8980 // value, where negative numbers specify a right shift.
8981 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8982 : Intrinsic::aarch64_neon_ushl;
8983 // negate the shift amount
8984 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8985 SDValue NegShiftLeft =
8986 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8987 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8989 return NegShiftLeft;
8995 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8996 AArch64CC::CondCode CC, bool NoNans, EVT VT,
8997 const SDLoc &dl, SelectionDAG &DAG) {
8998 EVT SrcVT = LHS.getValueType();
8999 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
9000 "function only supposed to emit natural comparisons");
9002 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9003 APInt CnstBits(VT.getSizeInBits(), 0);
9004 APInt UndefBits(VT.getSizeInBits(), 0);
9005 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
9006 bool IsZero = IsCnst && (CnstBits == 0);
9008 if (SrcVT.getVectorElementType().isFloatingPoint()) {
9012 case AArch64CC::NE: {
9015 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9017 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9018 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
9022 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
9023 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
9026 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
9027 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
9030 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
9031 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
9034 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
9035 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
9039 // If we ignore NaNs then we can use to the MI implementation.
9043 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
9044 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
9051 case AArch64CC::NE: {
9054 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9056 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9057 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
9061 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
9062 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
9065 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
9066 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
9069 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
9070 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
9073 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
9074 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
9076 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
9078 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
9081 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
9082 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
9084 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
9086 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
9090 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
9091 SelectionDAG &DAG) const {
9092 if (Op.getValueType().isScalableVector()) {
9093 if (Op.getOperand(0).getValueType().isFloatingPoint())
9095 return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
9098 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9099 SDValue LHS = Op.getOperand(0);
9100 SDValue RHS = Op.getOperand(1);
9101 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
9104 if (LHS.getValueType().getVectorElementType().isInteger()) {
9105 assert(LHS.getValueType() == RHS.getValueType());
9106 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
9108 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
9109 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9112 const bool FullFP16 =
9113 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
9115 // Make v4f16 (only) fcmp operations utilise vector instructions
9116 // v8f16 support will be a litle more complicated
9117 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
9118 if (LHS.getValueType().getVectorNumElements() == 4) {
9119 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
9120 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
9121 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
9122 DAG.ReplaceAllUsesWith(Op, NewSetcc);
9128 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
9129 LHS.getValueType().getVectorElementType() != MVT::f128);
9131 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
9132 // clean. Some of them require two branches to implement.
9133 AArch64CC::CondCode CC1, CC2;
9135 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
9137 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
9139 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
9143 if (CC2 != AArch64CC::AL) {
9145 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
9146 if (!Cmp2.getNode())
9149 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
9152 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
9155 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
9160 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
9161 SelectionDAG &DAG) {
9162 SDValue VecOp = ScalarOp.getOperand(0);
9163 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
9164 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
9165 DAG.getConstant(0, DL, MVT::i64));
9168 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
9169 SelectionDAG &DAG) const {
9171 switch (Op.getOpcode()) {
9172 case ISD::VECREDUCE_ADD:
9173 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
9174 case ISD::VECREDUCE_SMAX:
9175 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
9176 case ISD::VECREDUCE_SMIN:
9177 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
9178 case ISD::VECREDUCE_UMAX:
9179 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
9180 case ISD::VECREDUCE_UMIN:
9181 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
9182 case ISD::VECREDUCE_FMAX: {
9183 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
9185 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9186 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
9189 case ISD::VECREDUCE_FMIN: {
9190 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
9192 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
9193 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
9197 llvm_unreachable("Unhandled reduction");
9201 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
9202 SelectionDAG &DAG) const {
9203 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9204 if (!Subtarget.hasLSE())
9207 // LSE has an atomic load-add instruction, but not a load-sub.
9209 MVT VT = Op.getSimpleValueType();
9210 SDValue RHS = Op.getOperand(2);
9211 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9212 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
9213 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
9214 Op.getOperand(0), Op.getOperand(1), RHS,
9215 AN->getMemOperand());
9218 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
9219 SelectionDAG &DAG) const {
9220 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
9221 if (!Subtarget.hasLSE())
9224 // LSE has an atomic load-clear instruction, but not a load-and.
9226 MVT VT = Op.getSimpleValueType();
9227 SDValue RHS = Op.getOperand(2);
9228 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
9229 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
9230 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
9231 Op.getOperand(0), Op.getOperand(1), RHS,
9232 AN->getMemOperand());
9235 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
9236 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
9238 EVT PtrVT = getPointerTy(DAG.getDataLayout());
9239 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
9241 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
9242 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
9243 if (Subtarget->hasCustomCallingConv())
9244 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
9246 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
9247 DAG.getConstant(4, dl, MVT::i64));
9248 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
9250 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
9251 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
9252 DAG.getRegisterMask(Mask), Chain.getValue(1));
9253 // To match the actual intent better, we should read the output from X15 here
9254 // again (instead of potentially spilling it to the stack), but rereading Size
9255 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
9258 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
9259 DAG.getConstant(4, dl, MVT::i64));
9264 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9265 SelectionDAG &DAG) const {
9266 assert(Subtarget->isTargetWindows() &&
9267 "Only Windows alloca probing supported");
9270 SDNode *Node = Op.getNode();
9271 SDValue Chain = Op.getOperand(0);
9272 SDValue Size = Op.getOperand(1);
9274 cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
9275 EVT VT = Node->getValueType(0);
9277 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
9278 "no-stack-arg-probe")) {
9279 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9280 Chain = SP.getValue(1);
9281 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9283 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9284 DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9285 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9286 SDValue Ops[2] = {SP, Chain};
9287 return DAG.getMergeValues(Ops, dl);
9290 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
9292 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
9294 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
9295 Chain = SP.getValue(1);
9296 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
9298 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
9299 DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
9300 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
9302 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
9303 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
9305 SDValue Ops[2] = {SP, Chain};
9306 return DAG.getMergeValues(Ops, dl);
9309 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
9310 SelectionDAG &DAG) const {
9311 EVT VT = Op.getValueType();
9312 assert(VT != MVT::i64 && "Expected illegal VSCALE node");
9315 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
9316 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
9320 /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
9321 template <unsigned NumVecs>
9322 static bool setInfoSVEStN(AArch64TargetLowering::IntrinsicInfo &Info,
9323 const CallInst &CI) {
9324 Info.opc = ISD::INTRINSIC_VOID;
9325 // Retrieve EC from first vector argument.
9326 const EVT VT = EVT::getEVT(CI.getArgOperand(0)->getType());
9327 ElementCount EC = VT.getVectorElementCount();
9329 // Check the assumption that all input vectors are the same type.
9330 for (unsigned I = 0; I < NumVecs; ++I)
9331 assert(VT == EVT::getEVT(CI.getArgOperand(I)->getType()) &&
9334 // memVT is `NumVecs * VT`.
9335 Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
9337 Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
9340 Info.flags = MachineMemOperand::MOStore;
9344 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9345 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
9346 /// specified in the intrinsic calls.
9347 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9349 MachineFunction &MF,
9350 unsigned Intrinsic) const {
9351 auto &DL = I.getModule()->getDataLayout();
9352 switch (Intrinsic) {
9353 case Intrinsic::aarch64_sve_st2:
9354 return setInfoSVEStN<2>(Info, I);
9355 case Intrinsic::aarch64_sve_st3:
9356 return setInfoSVEStN<3>(Info, I);
9357 case Intrinsic::aarch64_sve_st4:
9358 return setInfoSVEStN<4>(Info, I);
9359 case Intrinsic::aarch64_neon_ld2:
9360 case Intrinsic::aarch64_neon_ld3:
9361 case Intrinsic::aarch64_neon_ld4:
9362 case Intrinsic::aarch64_neon_ld1x2:
9363 case Intrinsic::aarch64_neon_ld1x3:
9364 case Intrinsic::aarch64_neon_ld1x4:
9365 case Intrinsic::aarch64_neon_ld2lane:
9366 case Intrinsic::aarch64_neon_ld3lane:
9367 case Intrinsic::aarch64_neon_ld4lane:
9368 case Intrinsic::aarch64_neon_ld2r:
9369 case Intrinsic::aarch64_neon_ld3r:
9370 case Intrinsic::aarch64_neon_ld4r: {
9371 Info.opc = ISD::INTRINSIC_W_CHAIN;
9372 // Conservatively set memVT to the entire set of vectors loaded.
9373 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
9374 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9375 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9378 // volatile loads with NEON intrinsics not supported
9379 Info.flags = MachineMemOperand::MOLoad;
9382 case Intrinsic::aarch64_neon_st2:
9383 case Intrinsic::aarch64_neon_st3:
9384 case Intrinsic::aarch64_neon_st4:
9385 case Intrinsic::aarch64_neon_st1x2:
9386 case Intrinsic::aarch64_neon_st1x3:
9387 case Intrinsic::aarch64_neon_st1x4:
9388 case Intrinsic::aarch64_neon_st2lane:
9389 case Intrinsic::aarch64_neon_st3lane:
9390 case Intrinsic::aarch64_neon_st4lane: {
9391 Info.opc = ISD::INTRINSIC_VOID;
9392 // Conservatively set memVT to the entire set of vectors stored.
9393 unsigned NumElts = 0;
9394 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9395 Type *ArgTy = I.getArgOperand(ArgI)->getType();
9396 if (!ArgTy->isVectorTy())
9398 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
9400 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9401 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
9404 // volatile stores with NEON intrinsics not supported
9405 Info.flags = MachineMemOperand::MOStore;
9408 case Intrinsic::aarch64_ldaxr:
9409 case Intrinsic::aarch64_ldxr: {
9410 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
9411 Info.opc = ISD::INTRINSIC_W_CHAIN;
9412 Info.memVT = MVT::getVT(PtrTy->getElementType());
9413 Info.ptrVal = I.getArgOperand(0);
9415 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9416 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9419 case Intrinsic::aarch64_stlxr:
9420 case Intrinsic::aarch64_stxr: {
9421 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9422 Info.opc = ISD::INTRINSIC_W_CHAIN;
9423 Info.memVT = MVT::getVT(PtrTy->getElementType());
9424 Info.ptrVal = I.getArgOperand(1);
9426 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9427 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9430 case Intrinsic::aarch64_ldaxp:
9431 case Intrinsic::aarch64_ldxp:
9432 Info.opc = ISD::INTRINSIC_W_CHAIN;
9433 Info.memVT = MVT::i128;
9434 Info.ptrVal = I.getArgOperand(0);
9436 Info.align = Align(16);
9437 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
9439 case Intrinsic::aarch64_stlxp:
9440 case Intrinsic::aarch64_stxp:
9441 Info.opc = ISD::INTRINSIC_W_CHAIN;
9442 Info.memVT = MVT::i128;
9443 Info.ptrVal = I.getArgOperand(2);
9445 Info.align = Align(16);
9446 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
9448 case Intrinsic::aarch64_sve_ldnt1: {
9449 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
9450 Info.opc = ISD::INTRINSIC_W_CHAIN;
9451 Info.memVT = MVT::getVT(I.getType());
9452 Info.ptrVal = I.getArgOperand(1);
9454 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9455 Info.flags = MachineMemOperand::MOLoad;
9456 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
9457 Info.flags |= MachineMemOperand::MONonTemporal;
9460 case Intrinsic::aarch64_sve_stnt1: {
9461 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
9462 Info.opc = ISD::INTRINSIC_W_CHAIN;
9463 Info.memVT = MVT::getVT(I.getOperand(0)->getType());
9464 Info.ptrVal = I.getArgOperand(2);
9466 Info.align = DL.getABITypeAlign(PtrTy->getElementType());
9467 Info.flags = MachineMemOperand::MOStore;
9468 if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
9469 Info.flags |= MachineMemOperand::MONonTemporal;
9479 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
9480 ISD::LoadExtType ExtTy,
9482 // TODO: This may be worth removing. Check regression tests for diffs.
9483 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
9486 // If we're reducing the load width in order to avoid having to use an extra
9487 // instruction to do extension then it's probably a good idea.
9488 if (ExtTy != ISD::NON_EXTLOAD)
9490 // Don't reduce load width if it would prevent us from combining a shift into
9492 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
9494 const SDValue &Base = Mem->getBasePtr();
9495 if (Base.getOpcode() == ISD::ADD &&
9496 Base.getOperand(1).getOpcode() == ISD::SHL &&
9497 Base.getOperand(1).hasOneUse() &&
9498 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
9499 // The shift can be combined if it matches the size of the value being
9500 // loaded (and so reducing the width would make it not match).
9501 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
9502 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
9503 if (ShiftAmount == Log2_32(LoadBytes))
9506 // We have no reason to disallow reducing the load width, so allow it.
9510 // Truncations from 64-bit GPR to 32-bit GPR is free.
9511 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9512 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9514 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9515 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9516 return NumBits1 > NumBits2;
9518 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9519 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9521 unsigned NumBits1 = VT1.getSizeInBits();
9522 unsigned NumBits2 = VT2.getSizeInBits();
9523 return NumBits1 > NumBits2;
9526 /// Check if it is profitable to hoist instruction in then/else to if.
9527 /// Not profitable if I and it's user can form a FMA instruction
9528 /// because we prefer FMSUB/FMADD.
9529 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
9530 if (I->getOpcode() != Instruction::FMul)
9533 if (!I->hasOneUse())
9536 Instruction *User = I->user_back();
9539 !(User->getOpcode() == Instruction::FSub ||
9540 User->getOpcode() == Instruction::FAdd))
9543 const TargetOptions &Options = getTargetMachine().Options;
9544 const Function *F = I->getFunction();
9545 const DataLayout &DL = F->getParent()->getDataLayout();
9546 Type *Ty = User->getOperand(0)->getType();
9548 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
9549 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
9550 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
9551 Options.UnsafeFPMath));
9554 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
9556 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
9557 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9559 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9560 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9561 return NumBits1 == 32 && NumBits2 == 64;
9563 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9564 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
9566 unsigned NumBits1 = VT1.getSizeInBits();
9567 unsigned NumBits2 = VT2.getSizeInBits();
9568 return NumBits1 == 32 && NumBits2 == 64;
9571 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9572 EVT VT1 = Val.getValueType();
9573 if (isZExtFree(VT1, VT2)) {
9577 if (Val.getOpcode() != ISD::LOAD)
9580 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
9581 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
9582 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
9583 VT1.getSizeInBits() <= 32);
9586 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
9587 if (isa<FPExtInst>(Ext))
9590 // Vector types are not free.
9591 if (Ext->getType()->isVectorTy())
9594 for (const Use &U : Ext->uses()) {
9595 // The extension is free if we can fold it with a left shift in an
9596 // addressing mode or an arithmetic operation: add, sub, and cmp.
9598 // Is there a shift?
9599 const Instruction *Instr = cast<Instruction>(U.getUser());
9601 // Is this a constant shift?
9602 switch (Instr->getOpcode()) {
9603 case Instruction::Shl:
9604 if (!isa<ConstantInt>(Instr->getOperand(1)))
9607 case Instruction::GetElementPtr: {
9608 gep_type_iterator GTI = gep_type_begin(Instr);
9609 auto &DL = Ext->getModule()->getDataLayout();
9610 std::advance(GTI, U.getOperandNo()-1);
9611 Type *IdxTy = GTI.getIndexedType();
9612 // This extension will end up with a shift because of the scaling factor.
9613 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
9614 // Get the shift amount based on the scaling factor:
9615 // log2(sizeof(IdxTy)) - log2(8).
9617 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
9618 // Is the constant foldable in the shift of the addressing mode?
9619 // I.e., shift amount is between 1 and 4 inclusive.
9620 if (ShiftAmt == 0 || ShiftAmt > 4)
9624 case Instruction::Trunc:
9625 // Check if this is a noop.
9626 // trunc(sext ty1 to ty2) to ty1.
9627 if (Instr->getType() == Ext->getOperand(0)->getType())
9634 // At this point we can use the bfm family, so this extension is free
9640 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
9641 /// or upper half of the vector elements.
9642 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
9643 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
9644 auto *FullTy = FullV->getType();
9645 auto *HalfTy = HalfV->getType();
9646 return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
9647 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
9650 auto extractHalf = [](Value *FullV, Value *HalfV) {
9651 auto *FullVT = cast<FixedVectorType>(FullV->getType());
9652 auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
9653 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
9656 ArrayRef<int> M1, M2;
9657 Value *S1Op1, *S2Op1;
9658 if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
9659 !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
9662 // Check that the operands are half as wide as the result and we extract
9663 // half of the elements of the input vectors.
9664 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
9665 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
9668 // Check the mask extracts either the lower or upper half of vector
9672 int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
9673 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
9674 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
9675 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
9681 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
9682 /// of the vector elements.
9683 static bool areExtractExts(Value *Ext1, Value *Ext2) {
9684 auto areExtDoubled = [](Instruction *Ext) {
9685 return Ext->getType()->getScalarSizeInBits() ==
9686 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
9689 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
9690 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
9691 !areExtDoubled(cast<Instruction>(Ext1)) ||
9692 !areExtDoubled(cast<Instruction>(Ext2)))
9698 /// Check if Op could be used with vmull_high_p64 intrinsic.
9699 static bool isOperandOfVmullHighP64(Value *Op) {
9700 Value *VectorOperand = nullptr;
9701 ConstantInt *ElementIndex = nullptr;
9702 return match(Op, m_ExtractElt(m_Value(VectorOperand),
9703 m_ConstantInt(ElementIndex))) &&
9704 ElementIndex->getValue() == 1 &&
9705 isa<FixedVectorType>(VectorOperand->getType()) &&
9706 cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
9709 /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
9710 static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
9711 return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
9714 /// Check if sinking \p I's operands to I's basic block is profitable, because
9715 /// the operands can be folded into a target instruction, e.g.
9716 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9717 bool AArch64TargetLowering::shouldSinkOperands(
9718 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9719 if (!I->getType()->isVectorTy())
9722 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9723 switch (II->getIntrinsicID()) {
9724 case Intrinsic::aarch64_neon_umull:
9725 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9727 Ops.push_back(&II->getOperandUse(0));
9728 Ops.push_back(&II->getOperandUse(1));
9731 case Intrinsic::aarch64_neon_pmull64:
9732 if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
9733 II->getArgOperand(1)))
9735 Ops.push_back(&II->getArgOperandUse(0));
9736 Ops.push_back(&II->getArgOperandUse(1));
9744 switch (I->getOpcode()) {
9745 case Instruction::Sub:
9746 case Instruction::Add: {
9747 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9750 // If the exts' operands extract either the lower or upper elements, we
9751 // can sink them too.
9752 auto Ext1 = cast<Instruction>(I->getOperand(0));
9753 auto Ext2 = cast<Instruction>(I->getOperand(1));
9754 if (areExtractShuffleVectors(Ext1, Ext2)) {
9755 Ops.push_back(&Ext1->getOperandUse(0));
9756 Ops.push_back(&Ext2->getOperandUse(0));
9759 Ops.push_back(&I->getOperandUse(0));
9760 Ops.push_back(&I->getOperandUse(1));
9770 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9771 Align &RequiredAligment) const {
9772 if (!LoadedType.isSimple() ||
9773 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9775 // Cyclone supports unaligned accesses.
9776 RequiredAligment = Align(1);
9777 unsigned NumBits = LoadedType.getSizeInBits();
9778 return NumBits == 32 || NumBits == 64;
9781 /// A helper function for determining the number of interleaved accesses we
9782 /// will generate when lowering accesses of the given type.
9784 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9785 const DataLayout &DL) const {
9786 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9789 MachineMemOperand::Flags
9790 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9791 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9792 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9793 return MOStridedAccess;
9794 return MachineMemOperand::MONone;
9797 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9798 VectorType *VecTy, const DataLayout &DL) const {
9800 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9801 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9803 // Ensure the number of vector elements is greater than 1.
9804 if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
9807 // Ensure the element type is legal.
9808 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9811 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9812 // 128 will be split into multiple interleaved accesses.
9813 return VecSize == 64 || VecSize % 128 == 0;
9816 /// Lower an interleaved load into a ldN intrinsic.
9818 /// E.g. Lower an interleaved load (Factor = 2):
9819 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9820 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
9821 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
9824 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9825 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9826 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9827 bool AArch64TargetLowering::lowerInterleavedLoad(
9828 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9829 ArrayRef<unsigned> Indices, unsigned Factor) const {
9830 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9831 "Invalid interleave factor");
9832 assert(!Shuffles.empty() && "Empty shufflevector input");
9833 assert(Shuffles.size() == Indices.size() &&
9834 "Unmatched number of shufflevectors and indices");
9836 const DataLayout &DL = LI->getModule()->getDataLayout();
9838 VectorType *VTy = Shuffles[0]->getType();
9840 // Skip if we do not have NEON and skip illegal vector types. We can
9841 // "legalize" wide vector types into multiple interleaved accesses as long as
9842 // the vector types are divisible by 128.
9843 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
9846 unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
9848 auto *FVTy = cast<FixedVectorType>(VTy);
9850 // A pointer vector can not be the return type of the ldN intrinsics. Need to
9851 // load integer vectors first and then convert to pointer vectors.
9852 Type *EltTy = FVTy->getElementType();
9853 if (EltTy->isPointerTy())
9855 FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
9857 IRBuilder<> Builder(LI);
9859 // The base address of the load.
9860 Value *BaseAddr = LI->getPointerOperand();
9863 // If we're going to generate more than one load, reset the sub-vector type
9864 // to something legal.
9865 FVTy = FixedVectorType::get(FVTy->getElementType(),
9866 FVTy->getNumElements() / NumLoads);
9868 // We will compute the pointer operand of each load from the original base
9869 // address using GEPs. Cast the base address to a pointer to the scalar
9871 BaseAddr = Builder.CreateBitCast(
9873 FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
9876 Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
9877 Type *Tys[2] = {FVTy, PtrTy};
9878 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9879 Intrinsic::aarch64_neon_ld3,
9880 Intrinsic::aarch64_neon_ld4};
9882 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9884 // Holds sub-vectors extracted from the load intrinsic return values. The
9885 // sub-vectors are associated with the shufflevector instructions they will
9887 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9889 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9891 // If we're generating more than one load, compute the base address of
9892 // subsequent loads as an offset from the previous.
9894 BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
9895 FVTy->getNumElements() * Factor);
9897 CallInst *LdN = Builder.CreateCall(
9898 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9900 // Extract and store the sub-vectors returned by the load intrinsic.
9901 for (unsigned i = 0; i < Shuffles.size(); i++) {
9902 ShuffleVectorInst *SVI = Shuffles[i];
9903 unsigned Index = Indices[i];
9905 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9907 // Convert the integer vector to pointer vector if the element is pointer.
9908 if (EltTy->isPointerTy())
9909 SubVec = Builder.CreateIntToPtr(
9910 SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
9911 FVTy->getNumElements()));
9912 SubVecs[SVI].push_back(SubVec);
9916 // Replace uses of the shufflevector instructions with the sub-vectors
9917 // returned by the load intrinsic. If a shufflevector instruction is
9918 // associated with more than one sub-vector, those sub-vectors will be
9919 // concatenated into a single wide vector.
9920 for (ShuffleVectorInst *SVI : Shuffles) {
9921 auto &SubVec = SubVecs[SVI];
9923 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9924 SVI->replaceAllUsesWith(WideVec);
9930 /// Lower an interleaved store into a stN intrinsic.
9932 /// E.g. Lower an interleaved store (Factor = 3):
9933 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9934 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9935 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
9938 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9939 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9940 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9941 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9943 /// Note that the new shufflevectors will be removed and we'll only generate one
9944 /// st3 instruction in CodeGen.
9946 /// Example for a more general valid mask (Factor 3). Lower:
9947 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9948 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9949 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
9952 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9953 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9954 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9955 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9956 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9957 ShuffleVectorInst *SVI,
9958 unsigned Factor) const {
9959 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9960 "Invalid interleave factor");
9962 auto *VecTy = cast<FixedVectorType>(SVI->getType());
9963 assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
9965 unsigned LaneLen = VecTy->getNumElements() / Factor;
9966 Type *EltTy = VecTy->getElementType();
9967 auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
9969 const DataLayout &DL = SI->getModule()->getDataLayout();
9971 // Skip if we do not have NEON and skip illegal vector types. We can
9972 // "legalize" wide vector types into multiple interleaved accesses as long as
9973 // the vector types are divisible by 128.
9974 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9977 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9979 Value *Op0 = SVI->getOperand(0);
9980 Value *Op1 = SVI->getOperand(1);
9981 IRBuilder<> Builder(SI);
9983 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9984 // vectors to integer vectors.
9985 if (EltTy->isPointerTy()) {
9986 Type *IntTy = DL.getIntPtrType(EltTy);
9987 unsigned NumOpElts =
9988 cast<FixedVectorType>(Op0->getType())->getNumElements();
9990 // Convert to the corresponding integer vector.
9991 auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
9992 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9993 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9995 SubVecTy = FixedVectorType::get(IntTy, LaneLen);
9998 // The base address of the store.
9999 Value *BaseAddr = SI->getPointerOperand();
10001 if (NumStores > 1) {
10002 // If we're going to generate more than one store, reset the lane length
10003 // and sub-vector type to something legal.
10004 LaneLen /= NumStores;
10005 SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
10007 // We will compute the pointer operand of each store from the original base
10008 // address using GEPs. Cast the base address to a pointer to the scalar
10010 BaseAddr = Builder.CreateBitCast(
10012 SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
10015 auto Mask = SVI->getShuffleMask();
10017 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
10018 Type *Tys[2] = {SubVecTy, PtrTy};
10019 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
10020 Intrinsic::aarch64_neon_st3,
10021 Intrinsic::aarch64_neon_st4};
10022 Function *StNFunc =
10023 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
10025 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
10027 SmallVector<Value *, 5> Ops;
10029 // Split the shufflevector operands into sub vectors for the new stN call.
10030 for (unsigned i = 0; i < Factor; i++) {
10031 unsigned IdxI = StoreCount * LaneLen * Factor + i;
10032 if (Mask[IdxI] >= 0) {
10033 Ops.push_back(Builder.CreateShuffleVector(
10034 Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
10036 unsigned StartMask = 0;
10037 for (unsigned j = 1; j < LaneLen; j++) {
10038 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
10039 if (Mask[IdxJ * Factor + IdxI] >= 0) {
10040 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
10044 // Note: Filling undef gaps with random elements is ok, since
10045 // those elements were being written anyway (with undefs).
10046 // In the case of all undefs we're defaulting to using elems from 0
10047 // Note: StartMask cannot be negative, it's checked in
10048 // isReInterleaveMask
10049 Ops.push_back(Builder.CreateShuffleVector(
10050 Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
10054 // If we generating more than one store, we compute the base address of
10055 // subsequent stores as an offset from the previous.
10056 if (StoreCount > 0)
10057 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
10058 BaseAddr, LaneLen * Factor);
10060 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
10061 Builder.CreateCall(StNFunc, Ops);
10066 // Lower an SVE structured load intrinsic returning a tuple type to target
10067 // specific intrinsic taking the same input but returning a multi-result value
10068 // of the split tuple type.
10070 // E.g. Lowering an LD3:
10072 // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
10073 // <vscale x 4 x i1> %pred,
10074 // <vscale x 4 x i32>* %addr)
10078 // t0: ch = EntryToken
10079 // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
10080 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
10081 // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
10082 // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
10084 // This is called pre-legalization to avoid widening/splitting issues with
10085 // non-power-of-2 tuple types used for LD3, such as nxv12i32.
10086 SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
10087 ArrayRef<SDValue> LoadOps,
10088 EVT VT, SelectionDAG &DAG,
10089 const SDLoc &DL) const {
10090 assert(VT.isScalableVector() && "Can only lower scalable vectors");
10092 unsigned N, Opcode;
10093 static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
10094 {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
10095 {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
10096 {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
10098 std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
10099 assert(VT.getVectorElementCount().Min % N == 0 &&
10100 "invalid tuple vector type!");
10102 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10103 VT.getVectorElementCount() / N);
10104 assert(isTypeLegal(SplitVT));
10106 SmallVector<EVT, 5> VTs(N, SplitVT);
10107 VTs.push_back(MVT::Other); // Chain
10108 SDVTList NodeTys = DAG.getVTList(VTs);
10110 SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
10111 SmallVector<SDValue, 4> PseudoLoadOps;
10112 for (unsigned I = 0; I < N; ++I)
10113 PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
10114 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
10117 EVT AArch64TargetLowering::getOptimalMemOpType(
10118 const MemOp &Op, const AttributeList &FuncAttributes) const {
10119 bool CanImplicitFloat =
10120 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10121 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10122 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10123 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10124 // taken one instruction to materialize the v2i64 zero and one store (with
10125 // restrictive addressing mode). Just do i64 stores.
10126 bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10127 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10128 if (Op.isAligned(AlignCheck))
10131 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10136 if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10137 AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10139 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10141 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10143 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10148 LLT AArch64TargetLowering::getOptimalMemOpLLT(
10149 const MemOp &Op, const AttributeList &FuncAttributes) const {
10150 bool CanImplicitFloat =
10151 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
10152 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
10153 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
10154 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
10155 // taken one instruction to materialize the v2i64 zero and one store (with
10156 // restrictive addressing mode). Just do i64 stores.
10157 bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
10158 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
10159 if (Op.isAligned(AlignCheck))
10162 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
10167 if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
10168 AlignmentIsAcceptable(MVT::v2i64, Align(16)))
10169 return LLT::vector(2, 64);
10170 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
10171 return LLT::scalar(128);
10172 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
10173 return LLT::scalar(64);
10174 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
10175 return LLT::scalar(32);
10179 // 12-bit optionally shifted immediates are legal for adds.
10180 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
10181 if (Immed == std::numeric_limits<int64_t>::min()) {
10182 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
10183 << ": avoid UB for INT64_MIN\n");
10186 // Same encoding for add/sub, just flip the sign.
10187 Immed = std::abs(Immed);
10188 bool IsLegal = ((Immed >> 12) == 0 ||
10189 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
10190 LLVM_DEBUG(dbgs() << "Is " << Immed
10191 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
10195 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
10196 // immediates is the same as for an add or a sub.
10197 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
10198 return isLegalAddImmediate(Immed);
10201 /// isLegalAddressingMode - Return true if the addressing mode represented
10202 /// by AM is legal for this target, for a load/store of the specified type.
10203 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
10204 const AddrMode &AM, Type *Ty,
10205 unsigned AS, Instruction *I) const {
10206 // AArch64 has five basic addressing modes:
10208 // reg + 9-bit signed offset
10209 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
10211 // reg + SIZE_IN_BYTES * reg
10213 // No global is ever allowed as a base.
10217 // No reg+reg+imm addressing.
10218 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
10221 // FIXME: Update this method to support scalable addressing modes.
10222 if (isa<ScalableVectorType>(Ty))
10223 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
10225 // check reg + imm case:
10226 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
10227 uint64_t NumBytes = 0;
10228 if (Ty->isSized()) {
10229 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
10230 NumBytes = NumBits / 8;
10231 if (!isPowerOf2_64(NumBits))
10236 int64_t Offset = AM.BaseOffs;
10238 // 9-bit signed offset
10239 if (isInt<9>(Offset))
10242 // 12-bit unsigned offset
10243 unsigned shift = Log2_64(NumBytes);
10244 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
10245 // Must be a multiple of NumBytes (NumBytes is a power of 2)
10246 (Offset >> shift) << shift == Offset)
10251 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
10253 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
10256 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
10257 // Consider splitting large offset of struct or array.
10261 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
10262 const AddrMode &AM, Type *Ty,
10263 unsigned AS) const {
10264 // Scaling factors are not free at all.
10265 // Operands | Rt Latency
10266 // -------------------------------------------
10267 // Rt, [Xn, Xm] | 4
10268 // -------------------------------------------
10269 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
10270 // Rt, [Xn, Wm, <extend> #imm] |
10271 if (isLegalAddressingMode(DL, AM, Ty, AS))
10272 // Scale represents reg2 * scale, thus account for 1 if
10273 // it is not equal to 0 or 1.
10274 return AM.Scale != 0 && AM.Scale != 1;
10278 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
10279 const MachineFunction &MF, EVT VT) const {
10280 VT = VT.getScalarType();
10282 if (!VT.isSimple())
10285 switch (VT.getSimpleVT().SimpleTy) {
10296 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
10298 switch (Ty->getScalarType()->getTypeID()) {
10299 case Type::FloatTyID:
10300 case Type::DoubleTyID:
10308 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
10309 // LR is a callee-save register, but we must treat it as clobbered by any call
10310 // site. Hence we include LR in the scratch registers, which are in turn added
10311 // as implicit-defs for stackmaps and patchpoints.
10312 static const MCPhysReg ScratchRegs[] = {
10313 AArch64::X16, AArch64::X17, AArch64::LR, 0
10315 return ScratchRegs;
10319 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10320 CombineLevel Level) const {
10321 N = N->getOperand(0).getNode();
10322 EVT VT = N->getValueType(0);
10323 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
10324 // it with shift to let it be lowered to UBFX.
10325 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
10326 isa<ConstantSDNode>(N->getOperand(1))) {
10327 uint64_t TruncMask = N->getConstantOperandVal(1);
10328 if (isMask_64(TruncMask) &&
10329 N->getOperand(0).getOpcode() == ISD::SRL &&
10330 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
10336 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10338 assert(Ty->isIntegerTy());
10340 unsigned BitSize = Ty->getPrimitiveSizeInBits();
10344 int64_t Val = Imm.getSExtValue();
10345 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
10348 if ((int64_t)Val < 0)
10351 Val &= (1LL << 32) - 1;
10353 unsigned LZ = countLeadingZeros((uint64_t)Val);
10354 unsigned Shift = (63 - LZ) / 16;
10355 // MOVZ is free so return true for one or fewer MOVK.
10359 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
10360 unsigned Index) const {
10361 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
10364 return (Index == 0 || Index == ResVT.getVectorNumElements());
10367 /// Turn vector tests of the signbit in the form of:
10368 /// xor (sra X, elt_size(X)-1), -1
10371 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
10372 const AArch64Subtarget *Subtarget) {
10373 EVT VT = N->getValueType(0);
10374 if (!Subtarget->hasNEON() || !VT.isVector())
10377 // There must be a shift right algebraic before the xor, and the xor must be a
10378 // 'not' operation.
10379 SDValue Shift = N->getOperand(0);
10380 SDValue Ones = N->getOperand(1);
10381 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
10382 !ISD::isBuildVectorAllOnes(Ones.getNode()))
10385 // The shift should be smearing the sign bit across each vector element.
10386 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
10387 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
10388 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
10391 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
10394 // Generate SUBS and CSEL for integer abs.
10395 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
10396 EVT VT = N->getValueType(0);
10398 SDValue N0 = N->getOperand(0);
10399 SDValue N1 = N->getOperand(1);
10402 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
10403 // and change it to SUB and CSEL.
10404 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
10405 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
10406 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
10407 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
10408 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
10409 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
10411 // Generate SUBS & CSEL.
10413 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
10414 N0.getOperand(0), DAG.getConstant(0, DL, VT));
10415 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
10416 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
10417 SDValue(Cmp.getNode(), 1));
10422 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
10423 TargetLowering::DAGCombinerInfo &DCI,
10424 const AArch64Subtarget *Subtarget) {
10425 if (DCI.isBeforeLegalizeOps())
10428 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
10431 return performIntegerAbsCombine(N, DAG);
10435 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10437 SmallVectorImpl<SDNode *> &Created) const {
10438 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10439 if (isIntDivCheap(N->getValueType(0), Attr))
10440 return SDValue(N,0); // Lower SDIV as SDIV
10442 // fold (sdiv X, pow2)
10443 EVT VT = N->getValueType(0);
10444 if ((VT != MVT::i32 && VT != MVT::i64) ||
10445 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10449 SDValue N0 = N->getOperand(0);
10450 unsigned Lg2 = Divisor.countTrailingZeros();
10451 SDValue Zero = DAG.getConstant(0, DL, VT);
10452 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10454 // Add (N0 < 0) ? Pow2 - 1 : 0;
10456 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
10457 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10458 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
10460 Created.push_back(Cmp.getNode());
10461 Created.push_back(Add.getNode());
10462 Created.push_back(CSel.getNode());
10466 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
10468 // If we're dividing by a positive value, we're done. Otherwise, we must
10469 // negate the result.
10470 if (Divisor.isNonNegative())
10473 Created.push_back(SRA.getNode());
10474 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
10477 static bool IsSVECntIntrinsic(SDValue S) {
10478 switch(getIntrinsicID(S.getNode())) {
10481 case Intrinsic::aarch64_sve_cntb:
10482 case Intrinsic::aarch64_sve_cnth:
10483 case Intrinsic::aarch64_sve_cntw:
10484 case Intrinsic::aarch64_sve_cntd:
10490 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
10491 TargetLowering::DAGCombinerInfo &DCI,
10492 const AArch64Subtarget *Subtarget) {
10493 if (DCI.isBeforeLegalizeOps())
10496 // The below optimizations require a constant RHS.
10497 if (!isa<ConstantSDNode>(N->getOperand(1)))
10500 SDValue N0 = N->getOperand(0);
10501 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
10502 const APInt &ConstValue = C->getAPIntValue();
10504 // Allow the scaling to be folded into the `cnt` instruction by preventing
10505 // the scaling to be obscured here. This makes it easier to pattern match.
10506 if (IsSVECntIntrinsic(N0) ||
10507 (N0->getOpcode() == ISD::TRUNCATE &&
10508 (IsSVECntIntrinsic(N0->getOperand(0)))))
10509 if (ConstValue.sge(1) && ConstValue.sle(16))
10512 // Multiplication of a power of two plus/minus one can be done more
10513 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
10514 // future CPUs have a cheaper MADD instruction, this may need to be
10515 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
10516 // 64-bit is 5 cycles, so this is always a win.
10517 // More aggressively, some multiplications N0 * C can be lowered to
10518 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
10519 // e.g. 6=3*2=(2+1)*2.
10520 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
10521 // which equals to (1+2)*16-(1+2).
10522 // TrailingZeroes is used to test if the mul can be lowered to
10523 // shift+add+shift.
10524 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
10525 if (TrailingZeroes) {
10526 // Conservatively do not lower to shift+add+shift if the mul might be
10527 // folded into smul or umul.
10528 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
10529 isZeroExtended(N0.getNode(), DAG)))
10531 // Conservatively do not lower to shift+add+shift if the mul might be
10532 // folded into madd or msub.
10533 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
10534 N->use_begin()->getOpcode() == ISD::SUB))
10537 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
10538 // and shift+add+shift.
10539 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
10541 unsigned ShiftAmt, AddSubOpc;
10542 // Is the shifted value the LHS operand of the add/sub?
10543 bool ShiftValUseIsN0 = true;
10544 // Do we need to negate the result?
10545 bool NegateResult = false;
10547 if (ConstValue.isNonNegative()) {
10548 // (mul x, 2^N + 1) => (add (shl x, N), x)
10549 // (mul x, 2^N - 1) => (sub (shl x, N), x)
10550 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
10551 APInt SCVMinus1 = ShiftedConstValue - 1;
10552 APInt CVPlus1 = ConstValue + 1;
10553 if (SCVMinus1.isPowerOf2()) {
10554 ShiftAmt = SCVMinus1.logBase2();
10555 AddSubOpc = ISD::ADD;
10556 } else if (CVPlus1.isPowerOf2()) {
10557 ShiftAmt = CVPlus1.logBase2();
10558 AddSubOpc = ISD::SUB;
10562 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10563 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10564 APInt CVNegPlus1 = -ConstValue + 1;
10565 APInt CVNegMinus1 = -ConstValue - 1;
10566 if (CVNegPlus1.isPowerOf2()) {
10567 ShiftAmt = CVNegPlus1.logBase2();
10568 AddSubOpc = ISD::SUB;
10569 ShiftValUseIsN0 = false;
10570 } else if (CVNegMinus1.isPowerOf2()) {
10571 ShiftAmt = CVNegMinus1.logBase2();
10572 AddSubOpc = ISD::ADD;
10573 NegateResult = true;
10579 EVT VT = N->getValueType(0);
10580 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
10581 DAG.getConstant(ShiftAmt, DL, MVT::i64));
10583 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
10584 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
10585 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
10586 assert(!(NegateResult && TrailingZeroes) &&
10587 "NegateResult and TrailingZeroes cannot both be true for now.");
10588 // Negate the result.
10590 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
10591 // Shift the result.
10592 if (TrailingZeroes)
10593 return DAG.getNode(ISD::SHL, DL, VT, Res,
10594 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
10598 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
10599 SelectionDAG &DAG) {
10600 // Take advantage of vector comparisons producing 0 or -1 in each lane to
10601 // optimize away operation when it's from a constant.
10603 // The general transformation is:
10604 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
10605 // AND(VECTOR_CMP(x,y), constant2)
10606 // constant2 = UNARYOP(constant)
10608 // Early exit if this isn't a vector operation, the operand of the
10609 // unary operation isn't a bitwise AND, or if the sizes of the operations
10610 // aren't the same.
10611 EVT VT = N->getValueType(0);
10612 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
10613 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
10614 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
10617 // Now check that the other operand of the AND is a constant. We could
10618 // make the transformation for non-constant splats as well, but it's unclear
10619 // that would be a benefit as it would not eliminate any operations, just
10620 // perform one more step in scalar code before moving to the vector unit.
10621 if (BuildVectorSDNode *BV =
10622 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
10623 // Bail out if the vector isn't a constant.
10624 if (!BV->isConstant())
10627 // Everything checks out. Build up the new and improved node.
10629 EVT IntVT = BV->getValueType(0);
10630 // Create a new constant of the appropriate type for the transformed
10632 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
10633 // The AND node needs bitcasts to/from an integer vector type around it.
10634 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
10635 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
10636 N->getOperand(0)->getOperand(0), MaskConst);
10637 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
10644 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
10645 const AArch64Subtarget *Subtarget) {
10646 // First try to optimize away the conversion when it's conditionally from
10647 // a constant. Vectors only.
10648 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
10651 EVT VT = N->getValueType(0);
10652 if (VT != MVT::f32 && VT != MVT::f64)
10655 // Only optimize when the source and destination types have the same width.
10656 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
10659 // If the result of an integer load is only used by an integer-to-float
10660 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
10661 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
10662 SDValue N0 = N->getOperand(0);
10663 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10664 // Do not change the width of a volatile load.
10665 !cast<LoadSDNode>(N0)->isVolatile()) {
10666 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
10667 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
10668 LN0->getPointerInfo(), LN0->getAlignment(),
10669 LN0->getMemOperand()->getFlags());
10671 // Make sure successors of the original load stay after it by updating them
10672 // to use the new Chain.
10673 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
10676 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
10677 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
10683 /// Fold a floating-point multiply by power of two into floating-point to
10684 /// fixed-point conversion.
10685 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
10686 TargetLowering::DAGCombinerInfo &DCI,
10687 const AArch64Subtarget *Subtarget) {
10688 if (!Subtarget->hasNEON())
10691 if (!N->getValueType(0).isSimple())
10694 SDValue Op = N->getOperand(0);
10695 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10696 Op.getOpcode() != ISD::FMUL)
10699 SDValue ConstVec = Op->getOperand(1);
10700 if (!isa<BuildVectorSDNode>(ConstVec))
10703 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10704 uint32_t FloatBits = FloatTy.getSizeInBits();
10705 if (FloatBits != 32 && FloatBits != 64)
10708 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10709 uint32_t IntBits = IntTy.getSizeInBits();
10710 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10713 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
10714 if (IntBits > FloatBits)
10717 BitVector UndefElements;
10718 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10719 int32_t Bits = IntBits == 64 ? 64 : 32;
10720 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
10721 if (C == -1 || C == 0 || C > Bits)
10725 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10726 switch (NumLanes) {
10730 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10733 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10737 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10740 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
10741 "Illegal vector type after legalization");
10744 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10745 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
10746 : Intrinsic::aarch64_neon_vcvtfp2fxu;
10748 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
10749 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
10750 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
10751 // We can handle smaller integers by generating an extra trunc.
10752 if (IntBits < FloatBits)
10753 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
10758 /// Fold a floating-point divide by power of two into fixed-point to
10759 /// floating-point conversion.
10760 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10761 TargetLowering::DAGCombinerInfo &DCI,
10762 const AArch64Subtarget *Subtarget) {
10763 if (!Subtarget->hasNEON())
10766 SDValue Op = N->getOperand(0);
10767 unsigned Opc = Op->getOpcode();
10768 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10769 !Op.getOperand(0).getValueType().isSimple() ||
10770 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10773 SDValue ConstVec = N->getOperand(1);
10774 if (!isa<BuildVectorSDNode>(ConstVec))
10777 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10778 int32_t IntBits = IntTy.getSizeInBits();
10779 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10782 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10783 int32_t FloatBits = FloatTy.getSizeInBits();
10784 if (FloatBits != 32 && FloatBits != 64)
10787 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10788 if (IntBits > FloatBits)
10791 BitVector UndefElements;
10792 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10793 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10794 if (C == -1 || C == 0 || C > FloatBits)
10798 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10799 switch (NumLanes) {
10803 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10806 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10810 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10814 SDValue ConvInput = Op.getOperand(0);
10815 bool IsSigned = Opc == ISD::SINT_TO_FP;
10816 if (IntBits < FloatBits)
10817 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10820 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10821 : Intrinsic::aarch64_neon_vcvtfxu2fp;
10822 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10823 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10824 DAG.getConstant(C, DL, MVT::i32));
10827 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10828 /// searches for and classifies those shifts.
10829 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10831 if (N.getOpcode() == ISD::SHL)
10833 else if (N.getOpcode() == ISD::SRL)
10838 if (!isa<ConstantSDNode>(N.getOperand(1)))
10841 ShiftAmount = N->getConstantOperandVal(1);
10842 Src = N->getOperand(0);
10846 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10847 /// registers viewed as a high/low pair. This function looks for the pattern:
10848 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10849 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10850 /// aren't independent.
10851 static SDValue tryCombineToEXTR(SDNode *N,
10852 TargetLowering::DAGCombinerInfo &DCI) {
10853 SelectionDAG &DAG = DCI.DAG;
10855 EVT VT = N->getValueType(0);
10857 assert(N->getOpcode() == ISD::OR && "Unexpected root");
10859 if (VT != MVT::i32 && VT != MVT::i64)
10863 uint32_t ShiftLHS = 0;
10864 bool LHSFromHi = false;
10865 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10869 uint32_t ShiftRHS = 0;
10870 bool RHSFromHi = false;
10871 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10874 // If they're both trying to come from the high part of the register, they're
10875 // not really an EXTR.
10876 if (LHSFromHi == RHSFromHi)
10879 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10883 std::swap(LHS, RHS);
10884 std::swap(ShiftLHS, ShiftRHS);
10887 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10888 DAG.getConstant(ShiftRHS, DL, MVT::i64));
10891 static SDValue tryCombineToBSL(SDNode *N,
10892 TargetLowering::DAGCombinerInfo &DCI) {
10893 EVT VT = N->getValueType(0);
10894 SelectionDAG &DAG = DCI.DAG;
10897 if (!VT.isVector())
10900 SDValue N0 = N->getOperand(0);
10901 if (N0.getOpcode() != ISD::AND)
10904 SDValue N1 = N->getOperand(1);
10905 if (N1.getOpcode() != ISD::AND)
10908 // We only have to look for constant vectors here since the general, variable
10909 // case can be handled in TableGen.
10910 unsigned Bits = VT.getScalarSizeInBits();
10911 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10912 for (int i = 1; i >= 0; --i)
10913 for (int j = 1; j >= 0; --j) {
10914 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10915 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10916 if (!BVN0 || !BVN1)
10919 bool FoundMatch = true;
10920 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10921 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10922 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10923 if (!CN0 || !CN1 ||
10924 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10925 FoundMatch = false;
10931 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
10932 N0->getOperand(1 - i), N1->getOperand(1 - j));
10938 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10939 const AArch64Subtarget *Subtarget) {
10940 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10941 SelectionDAG &DAG = DCI.DAG;
10942 EVT VT = N->getValueType(0);
10944 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10947 if (SDValue Res = tryCombineToEXTR(N, DCI))
10950 if (SDValue Res = tryCombineToBSL(N, DCI))
10956 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10957 if (!MemVT.getVectorElementType().isSimple())
10960 uint64_t MaskForTy = 0ull;
10961 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10963 MaskForTy = 0xffull;
10966 MaskForTy = 0xffffull;
10969 MaskForTy = 0xffffffffull;
10976 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10977 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10978 return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10983 static SDValue performSVEAndCombine(SDNode *N,
10984 TargetLowering::DAGCombinerInfo &DCI) {
10985 if (DCI.isBeforeLegalizeOps())
10988 SelectionDAG &DAG = DCI.DAG;
10989 SDValue Src = N->getOperand(0);
10990 unsigned Opc = Src->getOpcode();
10992 // Zero/any extend of an unsigned unpack
10993 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
10994 SDValue UnpkOp = Src->getOperand(0);
10995 SDValue Dup = N->getOperand(1);
10997 if (Dup.getOpcode() != AArch64ISD::DUP)
11001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
11002 uint64_t ExtVal = C->getZExtValue();
11004 // If the mask is fully covered by the unpack, we don't need to push
11005 // a new AND onto the operand
11006 EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
11007 if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
11008 (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
11009 (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
11012 // Truncate to prevent a DUP with an over wide constant
11013 APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
11015 // Otherwise, make sure we propagate the AND to the operand
11017 Dup = DAG.getNode(AArch64ISD::DUP, DL,
11018 UnpkOp->getValueType(0),
11019 DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
11021 SDValue And = DAG.getNode(ISD::AND, DL,
11022 UnpkOp->getValueType(0), UnpkOp, Dup);
11024 return DAG.getNode(Opc, DL, N->getValueType(0), And);
11027 SDValue Mask = N->getOperand(1);
11029 if (!Src.hasOneUse())
11034 // SVE load instructions perform an implicit zero-extend, which makes them
11035 // perfect candidates for combining.
11037 case AArch64ISD::LD1_MERGE_ZERO:
11038 case AArch64ISD::LDNF1_MERGE_ZERO:
11039 case AArch64ISD::LDFF1_MERGE_ZERO:
11040 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
11042 case AArch64ISD::GLD1_MERGE_ZERO:
11043 case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
11044 case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
11045 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
11046 case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
11047 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
11048 case AArch64ISD::GLD1_IMM_MERGE_ZERO:
11049 case AArch64ISD::GLDFF1_MERGE_ZERO:
11050 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
11051 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
11052 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
11053 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
11054 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
11055 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
11056 case AArch64ISD::GLDNT1_MERGE_ZERO:
11057 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
11063 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
11069 static SDValue performANDCombine(SDNode *N,
11070 TargetLowering::DAGCombinerInfo &DCI) {
11071 SelectionDAG &DAG = DCI.DAG;
11072 SDValue LHS = N->getOperand(0);
11073 EVT VT = N->getValueType(0);
11074 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
11077 if (VT.isScalableVector())
11078 return performSVEAndCombine(N, DCI);
11080 BuildVectorSDNode *BVN =
11081 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
11085 // AND does not accept an immediate, so check if we can use a BIC immediate
11086 // instruction instead. We do this here instead of using a (and x, (mvni imm))
11087 // pattern in isel, because some immediates may be lowered to the preferred
11088 // (and x, (movi imm)) form, even though an mvni representation also exists.
11089 APInt DefBits(VT.getSizeInBits(), 0);
11090 APInt UndefBits(VT.getSizeInBits(), 0);
11091 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
11094 DefBits = ~DefBits;
11095 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11097 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11101 UndefBits = ~UndefBits;
11102 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
11103 UndefBits, &LHS)) ||
11104 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
11112 static SDValue performSRLCombine(SDNode *N,
11113 TargetLowering::DAGCombinerInfo &DCI) {
11114 SelectionDAG &DAG = DCI.DAG;
11115 EVT VT = N->getValueType(0);
11116 if (VT != MVT::i32 && VT != MVT::i64)
11119 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
11120 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
11121 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
11122 SDValue N0 = N->getOperand(0);
11123 if (N0.getOpcode() == ISD::BSWAP) {
11125 SDValue N1 = N->getOperand(1);
11126 SDValue N00 = N0.getOperand(0);
11127 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11128 uint64_t ShiftAmt = C->getZExtValue();
11129 if (VT == MVT::i32 && ShiftAmt == 16 &&
11130 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
11131 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11132 if (VT == MVT::i64 && ShiftAmt == 32 &&
11133 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
11134 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
11140 static SDValue performConcatVectorsCombine(SDNode *N,
11141 TargetLowering::DAGCombinerInfo &DCI,
11142 SelectionDAG &DAG) {
11144 EVT VT = N->getValueType(0);
11145 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
11146 unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
11148 // Optimize concat_vectors of truncated vectors, where the intermediate
11149 // type is illegal, to avoid said illegality, e.g.,
11150 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
11151 // (v2i16 (truncate (v2i64)))))
11153 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
11154 // (v4i32 (bitcast (v2i64))),
11156 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
11157 // on both input and result type, so we might generate worse code.
11158 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
11159 if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
11160 N1Opc == ISD::TRUNCATE) {
11161 SDValue N00 = N0->getOperand(0);
11162 SDValue N10 = N1->getOperand(0);
11163 EVT N00VT = N00.getValueType();
11165 if (N00VT == N10.getValueType() &&
11166 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
11167 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
11168 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
11169 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
11170 for (size_t i = 0; i < Mask.size(); ++i)
11172 return DAG.getNode(ISD::TRUNCATE, dl, VT,
11173 DAG.getVectorShuffle(
11175 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
11176 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
11180 // Wait 'til after everything is legalized to try this. That way we have
11181 // legal vector types and such.
11182 if (DCI.isBeforeLegalizeOps())
11185 // Optimise concat_vectors of two [us]rhadds that use extracted subvectors
11186 // from the same original vectors. Combine these into a single [us]rhadd that
11187 // operates on the two original vectors. Example:
11188 // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
11189 // extract_subvector (v16i8 OpB,
11191 // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
11192 // extract_subvector (v16i8 OpB,
11195 // (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
11196 if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
11197 (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD)) {
11198 SDValue N00 = N0->getOperand(0);
11199 SDValue N01 = N0->getOperand(1);
11200 SDValue N10 = N1->getOperand(0);
11201 SDValue N11 = N1->getOperand(1);
11203 EVT N00VT = N00.getValueType();
11204 EVT N10VT = N10.getValueType();
11206 if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11207 N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11208 N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
11209 N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
11210 SDValue N00Source = N00->getOperand(0);
11211 SDValue N01Source = N01->getOperand(0);
11212 SDValue N10Source = N10->getOperand(0);
11213 SDValue N11Source = N11->getOperand(0);
11215 if (N00Source == N10Source && N01Source == N11Source &&
11216 N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
11217 assert(N0.getValueType() == N1.getValueType());
11219 uint64_t N00Index = N00.getConstantOperandVal(1);
11220 uint64_t N01Index = N01.getConstantOperandVal(1);
11221 uint64_t N10Index = N10.getConstantOperandVal(1);
11222 uint64_t N11Index = N11.getConstantOperandVal(1);
11224 if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
11225 N10Index == N00VT.getVectorNumElements())
11226 return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
11231 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
11232 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
11233 // canonicalise to that.
11234 if (N0 == N1 && VT.getVectorNumElements() == 2) {
11235 assert(VT.getScalarSizeInBits() == 64);
11236 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
11237 DAG.getConstant(0, dl, MVT::i64));
11240 // Canonicalise concat_vectors so that the right-hand vector has as few
11241 // bit-casts as possible before its real operation. The primary matching
11242 // destination for these operations will be the narrowing "2" instructions,
11243 // which depend on the operation being performed on this right-hand vector.
11245 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
11247 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
11249 if (N1Opc != ISD::BITCAST)
11251 SDValue RHS = N1->getOperand(0);
11252 MVT RHSTy = RHS.getValueType().getSimpleVT();
11253 // If the RHS is not a vector, this is not the pattern we're looking for.
11254 if (!RHSTy.isVector())
11258 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
11260 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
11261 RHSTy.getVectorNumElements() * 2);
11262 return DAG.getNode(ISD::BITCAST, dl, VT,
11263 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
11264 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
11268 static SDValue tryCombineFixedPointConvert(SDNode *N,
11269 TargetLowering::DAGCombinerInfo &DCI,
11270 SelectionDAG &DAG) {
11271 // Wait until after everything is legalized to try this. That way we have
11272 // legal vector types and such.
11273 if (DCI.isBeforeLegalizeOps())
11275 // Transform a scalar conversion of a value from a lane extract into a
11276 // lane extract of a vector conversion. E.g., from foo1 to foo2:
11277 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
11278 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
11280 // The second form interacts better with instruction selection and the
11281 // register allocator to avoid cross-class register copies that aren't
11282 // coalescable due to a lane reference.
11284 // Check the operand and see if it originates from a lane extract.
11285 SDValue Op1 = N->getOperand(1);
11286 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11287 // Yep, no additional predication needed. Perform the transform.
11288 SDValue IID = N->getOperand(0);
11289 SDValue Shift = N->getOperand(2);
11290 SDValue Vec = Op1.getOperand(0);
11291 SDValue Lane = Op1.getOperand(1);
11292 EVT ResTy = N->getValueType(0);
11296 // The vector width should be 128 bits by the time we get here, even
11297 // if it started as 64 bits (the extract_vector handling will have
11299 assert(Vec.getValueSizeInBits() == 128 &&
11300 "unexpected vector size on extract_vector_elt!");
11301 if (Vec.getValueType() == MVT::v4i32)
11302 VecResTy = MVT::v4f32;
11303 else if (Vec.getValueType() == MVT::v2i64)
11304 VecResTy = MVT::v2f64;
11306 llvm_unreachable("unexpected vector type!");
11309 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
11310 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
11315 // AArch64 high-vector "long" operations are formed by performing the non-high
11316 // version on an extract_subvector of each operand which gets the high half:
11318 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
11320 // However, there are cases which don't have an extract_high explicitly, but
11321 // have another operation that can be made compatible with one for free. For
11324 // (dupv64 scalar) --> (extract_high (dup128 scalar))
11326 // This routine does the actual conversion of such DUPs, once outer routines
11327 // have determined that everything else is in order.
11328 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
11330 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
11331 switch (N.getOpcode()) {
11332 case AArch64ISD::DUP:
11333 case AArch64ISD::DUPLANE8:
11334 case AArch64ISD::DUPLANE16:
11335 case AArch64ISD::DUPLANE32:
11336 case AArch64ISD::DUPLANE64:
11337 case AArch64ISD::MOVI:
11338 case AArch64ISD::MOVIshift:
11339 case AArch64ISD::MOVIedit:
11340 case AArch64ISD::MOVImsl:
11341 case AArch64ISD::MVNIshift:
11342 case AArch64ISD::MVNImsl:
11345 // FMOV could be supported, but isn't very useful, as it would only occur
11346 // if you passed a bitcast' floating point immediate to an eligible long
11347 // integer op (addl, smull, ...).
11351 MVT NarrowTy = N.getSimpleValueType();
11352 if (!NarrowTy.is64BitVector())
11355 MVT ElementTy = NarrowTy.getVectorElementType();
11356 unsigned NumElems = NarrowTy.getVectorNumElements();
11357 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
11360 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
11361 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
11362 DAG.getConstant(NumElems, dl, MVT::i64));
11365 static bool isEssentiallyExtractHighSubvector(SDValue N) {
11366 if (N.getOpcode() == ISD::BITCAST)
11367 N = N.getOperand(0);
11368 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11370 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
11371 N.getOperand(0).getValueType().getVectorNumElements() / 2;
11374 /// Helper structure to keep track of ISD::SET_CC operands.
11375 struct GenericSetCCInfo {
11376 const SDValue *Opnd0;
11377 const SDValue *Opnd1;
11381 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
11382 struct AArch64SetCCInfo {
11383 const SDValue *Cmp;
11384 AArch64CC::CondCode CC;
11387 /// Helper structure to keep track of SetCC information.
11389 GenericSetCCInfo Generic;
11390 AArch64SetCCInfo AArch64;
11393 /// Helper structure to be able to read SetCC information. If set to
11394 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
11395 /// GenericSetCCInfo.
11396 struct SetCCInfoAndKind {
11401 /// Check whether or not \p Op is a SET_CC operation, either a generic or
11403 /// AArch64 lowered one.
11404 /// \p SetCCInfo is filled accordingly.
11405 /// \post SetCCInfo is meanginfull only when this function returns true.
11406 /// \return True when Op is a kind of SET_CC operation.
11407 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
11408 // If this is a setcc, this is straight forward.
11409 if (Op.getOpcode() == ISD::SETCC) {
11410 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
11411 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
11412 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11413 SetCCInfo.IsAArch64 = false;
11416 // Otherwise, check if this is a matching csel instruction.
11419 // - csel 0, 1, !cc
11420 if (Op.getOpcode() != AArch64ISD::CSEL)
11422 // Set the information about the operands.
11423 // TODO: we want the operands of the Cmp not the csel
11424 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
11425 SetCCInfo.IsAArch64 = true;
11426 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
11427 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11429 // Check that the operands matches the constraints:
11430 // (1) Both operands must be constants.
11431 // (2) One must be 1 and the other must be 0.
11432 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
11433 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11436 if (!TValue || !FValue)
11440 if (!TValue->isOne()) {
11441 // Update the comparison when we are interested in !cc.
11442 std::swap(TValue, FValue);
11443 SetCCInfo.Info.AArch64.CC =
11444 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
11446 return TValue->isOne() && FValue->isNullValue();
11449 // Returns true if Op is setcc or zext of setcc.
11450 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
11451 if (isSetCC(Op, Info))
11453 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
11454 isSetCC(Op->getOperand(0), Info));
11457 // The folding we want to perform is:
11458 // (add x, [zext] (setcc cc ...) )
11460 // (csel x, (add x, 1), !cc ...)
11462 // The latter will get matched to a CSINC instruction.
11463 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
11464 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
11465 SDValue LHS = Op->getOperand(0);
11466 SDValue RHS = Op->getOperand(1);
11467 SetCCInfoAndKind InfoAndKind;
11469 // If neither operand is a SET_CC, give up.
11470 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
11471 std::swap(LHS, RHS);
11472 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
11476 // FIXME: This could be generatized to work for FP comparisons.
11477 EVT CmpVT = InfoAndKind.IsAArch64
11478 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
11479 : InfoAndKind.Info.Generic.Opnd0->getValueType();
11480 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
11486 if (InfoAndKind.IsAArch64) {
11487 CCVal = DAG.getConstant(
11488 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
11490 Cmp = *InfoAndKind.Info.AArch64.Cmp;
11492 Cmp = getAArch64Cmp(
11493 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
11494 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
11497 EVT VT = Op->getValueType(0);
11498 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
11499 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
11502 // The basic add/sub long vector instructions have variants with "2" on the end
11503 // which act on the high-half of their inputs. They are normally matched by
11506 // (add (zeroext (extract_high LHS)),
11507 // (zeroext (extract_high RHS)))
11508 // -> uaddl2 vD, vN, vM
11510 // However, if one of the extracts is something like a duplicate, this
11511 // instruction can still be used profitably. This function puts the DAG into a
11512 // more appropriate form for those patterns to trigger.
11513 static SDValue performAddSubLongCombine(SDNode *N,
11514 TargetLowering::DAGCombinerInfo &DCI,
11515 SelectionDAG &DAG) {
11516 if (DCI.isBeforeLegalizeOps())
11519 MVT VT = N->getSimpleValueType(0);
11520 if (!VT.is128BitVector()) {
11521 if (N->getOpcode() == ISD::ADD)
11522 return performSetccAddFolding(N, DAG);
11526 // Make sure both branches are extended in the same way.
11527 SDValue LHS = N->getOperand(0);
11528 SDValue RHS = N->getOperand(1);
11529 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
11530 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
11531 LHS.getOpcode() != RHS.getOpcode())
11534 unsigned ExtType = LHS.getOpcode();
11536 // It's not worth doing if at least one of the inputs isn't already an
11537 // extract, but we don't know which it'll be so we have to try both.
11538 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
11539 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
11540 if (!RHS.getNode())
11543 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
11544 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
11545 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
11546 if (!LHS.getNode())
11549 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
11552 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
11555 // Massage DAGs which we can use the high-half "long" operations on into
11556 // something isel will recognize better. E.g.
11558 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
11559 // (aarch64_neon_umull (extract_high (v2i64 vec)))
11560 // (extract_high (v2i64 (dup128 scalar)))))
11562 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
11563 TargetLowering::DAGCombinerInfo &DCI,
11564 SelectionDAG &DAG) {
11565 if (DCI.isBeforeLegalizeOps())
11568 SDValue LHS = N->getOperand(1);
11569 SDValue RHS = N->getOperand(2);
11570 assert(LHS.getValueType().is64BitVector() &&
11571 RHS.getValueType().is64BitVector() &&
11572 "unexpected shape for long operation");
11574 // Either node could be a DUP, but it's not worth doing both of them (you'd
11575 // just as well use the non-high version) so look for a corresponding extract
11576 // operation on the other "wing".
11577 if (isEssentiallyExtractHighSubvector(LHS)) {
11578 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
11579 if (!RHS.getNode())
11581 } else if (isEssentiallyExtractHighSubvector(RHS)) {
11582 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
11583 if (!LHS.getNode())
11587 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
11588 N->getOperand(0), LHS, RHS);
11591 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
11592 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
11593 unsigned ElemBits = ElemTy.getSizeInBits();
11595 int64_t ShiftAmount;
11596 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
11597 APInt SplatValue, SplatUndef;
11598 unsigned SplatBitSize;
11600 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11601 HasAnyUndefs, ElemBits) ||
11602 SplatBitSize != ElemBits)
11605 ShiftAmount = SplatValue.getSExtValue();
11606 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
11607 ShiftAmount = CVN->getSExtValue();
11615 llvm_unreachable("Unknown shift intrinsic");
11616 case Intrinsic::aarch64_neon_sqshl:
11617 Opcode = AArch64ISD::SQSHL_I;
11618 IsRightShift = false;
11620 case Intrinsic::aarch64_neon_uqshl:
11621 Opcode = AArch64ISD::UQSHL_I;
11622 IsRightShift = false;
11624 case Intrinsic::aarch64_neon_srshl:
11625 Opcode = AArch64ISD::SRSHR_I;
11626 IsRightShift = true;
11628 case Intrinsic::aarch64_neon_urshl:
11629 Opcode = AArch64ISD::URSHR_I;
11630 IsRightShift = true;
11632 case Intrinsic::aarch64_neon_sqshlu:
11633 Opcode = AArch64ISD::SQSHLU_I;
11634 IsRightShift = false;
11636 case Intrinsic::aarch64_neon_sshl:
11637 case Intrinsic::aarch64_neon_ushl:
11638 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
11639 // left shift for positive shift amounts. Below, we only replace the current
11640 // node with VSHL, if this condition is met.
11641 Opcode = AArch64ISD::VSHL;
11642 IsRightShift = false;
11646 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
11648 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11649 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
11650 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
11652 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
11653 DAG.getConstant(ShiftAmount, dl, MVT::i32));
11659 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
11660 // the intrinsics must be legal and take an i32, this means there's almost
11661 // certainly going to be a zext in the DAG which we can eliminate.
11662 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
11663 SDValue AndN = N->getOperand(2);
11664 if (AndN.getOpcode() != ISD::AND)
11667 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
11668 if (!CMask || CMask->getZExtValue() != Mask)
11671 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
11672 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
11675 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
11676 SelectionDAG &DAG) {
11678 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
11679 DAG.getNode(Opc, dl,
11680 N->getOperand(1).getSimpleValueType(),
11682 DAG.getConstant(0, dl, MVT::i64));
11685 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
11686 SelectionDAG &DAG) {
11688 LLVMContext &Ctx = *DAG.getContext();
11689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11691 EVT VT = N->getValueType(0);
11692 SDValue Pred = N->getOperand(1);
11693 SDValue Data = N->getOperand(2);
11694 EVT DataVT = Data.getValueType();
11696 if (DataVT.getVectorElementType().isScalarInteger() &&
11697 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
11698 if (!TLI.isTypeLegal(DataVT))
11701 EVT OutputVT = EVT::getVectorVT(Ctx, VT,
11702 AArch64::NeonBitsPerVector / VT.getSizeInBits());
11703 SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
11704 SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
11705 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
11713 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
11715 SDValue Op1 = N->getOperand(1);
11716 SDValue Op2 = N->getOperand(2);
11717 EVT ScalarTy = Op1.getValueType();
11719 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
11720 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
11721 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
11724 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
11728 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
11730 SDValue Scalar = N->getOperand(3);
11731 EVT ScalarTy = Scalar.getValueType();
11733 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
11734 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
11736 SDValue Passthru = N->getOperand(1);
11737 SDValue Pred = N->getOperand(2);
11738 return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
11739 Pred, Scalar, Passthru);
11742 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
11744 LLVMContext &Ctx = *DAG.getContext();
11745 EVT VT = N->getValueType(0);
11747 assert(VT.isScalableVector() && "Expected a scalable vector.");
11749 // Current lowering only supports the SVE-ACLE types.
11750 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
11753 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
11754 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
11755 EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
11757 // Convert everything to the domain of EXT (i.e bytes).
11758 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
11759 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
11760 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
11761 DAG.getConstant(ElemSize, dl, MVT::i32));
11763 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
11764 return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
11767 static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
11768 TargetLowering::DAGCombinerInfo &DCI,
11769 SelectionDAG &DAG) {
11770 if (DCI.isBeforeLegalize())
11773 SDValue Comparator = N->getOperand(3);
11774 if (Comparator.getOpcode() == AArch64ISD::DUP ||
11775 Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
11776 unsigned IID = getIntrinsicID(N);
11777 EVT VT = N->getValueType(0);
11778 EVT CmpVT = N->getOperand(2).getValueType();
11779 SDValue Pred = N->getOperand(1);
11785 llvm_unreachable("Called with wrong intrinsic!");
11788 // Signed comparisons
11789 case Intrinsic::aarch64_sve_cmpeq_wide:
11790 case Intrinsic::aarch64_sve_cmpne_wide:
11791 case Intrinsic::aarch64_sve_cmpge_wide:
11792 case Intrinsic::aarch64_sve_cmpgt_wide:
11793 case Intrinsic::aarch64_sve_cmplt_wide:
11794 case Intrinsic::aarch64_sve_cmple_wide: {
11795 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11796 int64_t ImmVal = CN->getSExtValue();
11797 if (ImmVal >= -16 && ImmVal <= 15)
11798 Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11804 // Unsigned comparisons
11805 case Intrinsic::aarch64_sve_cmphs_wide:
11806 case Intrinsic::aarch64_sve_cmphi_wide:
11807 case Intrinsic::aarch64_sve_cmplo_wide:
11808 case Intrinsic::aarch64_sve_cmpls_wide: {
11809 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
11810 uint64_t ImmVal = CN->getZExtValue();
11812 Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
11823 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
11824 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
11825 N->getOperand(2), Splat, DAG.getCondCode(CC));
11831 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
11832 AArch64CC::CondCode Cond) {
11833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11836 assert(Op.getValueType().isScalableVector() &&
11837 TLI.isTypeLegal(Op.getValueType()) &&
11838 "Expected legal scalable vector type!");
11840 // Ensure target specific opcodes are using legal type.
11841 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
11842 SDValue TVal = DAG.getConstant(1, DL, OutVT);
11843 SDValue FVal = DAG.getConstant(0, DL, OutVT);
11845 // Set condition code (CC) flags.
11846 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
11848 // Convert CC to integer based on requested condition.
11849 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
11850 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
11851 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
11852 return DAG.getZExtOrTrunc(Res, DL, VT);
11855 static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
11856 SelectionDAG &DAG) {
11859 SDValue Pred = N->getOperand(1);
11860 SDValue VecToReduce = N->getOperand(2);
11862 EVT ReduceVT = VecToReduce.getValueType();
11863 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
11865 // SVE reductions set the whole vector register with the first element
11866 // containing the reduction result, which we'll now extract.
11867 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11868 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11872 static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
11873 SelectionDAG &DAG) {
11876 SDValue Pred = N->getOperand(1);
11877 SDValue InitVal = N->getOperand(2);
11878 SDValue VecToReduce = N->getOperand(3);
11879 EVT ReduceVT = VecToReduce.getValueType();
11881 // Ordered reductions use the first lane of the result vector as the
11882 // reduction's initial value.
11883 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
11884 InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
11885 DAG.getUNDEF(ReduceVT), InitVal, Zero);
11887 SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
11889 // SVE reductions set the whole vector register with the first element
11890 // containing the reduction result, which we'll now extract.
11891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
11895 static SDValue performIntrinsicCombine(SDNode *N,
11896 TargetLowering::DAGCombinerInfo &DCI,
11897 const AArch64Subtarget *Subtarget) {
11898 SelectionDAG &DAG = DCI.DAG;
11899 unsigned IID = getIntrinsicID(N);
11903 case Intrinsic::aarch64_neon_vcvtfxs2fp:
11904 case Intrinsic::aarch64_neon_vcvtfxu2fp:
11905 return tryCombineFixedPointConvert(N, DCI, DAG);
11906 case Intrinsic::aarch64_neon_saddv:
11907 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
11908 case Intrinsic::aarch64_neon_uaddv:
11909 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
11910 case Intrinsic::aarch64_neon_sminv:
11911 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
11912 case Intrinsic::aarch64_neon_uminv:
11913 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
11914 case Intrinsic::aarch64_neon_smaxv:
11915 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11916 case Intrinsic::aarch64_neon_umaxv:
11917 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11918 case Intrinsic::aarch64_neon_fmax:
11919 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11920 N->getOperand(1), N->getOperand(2));
11921 case Intrinsic::aarch64_neon_fmin:
11922 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11923 N->getOperand(1), N->getOperand(2));
11924 case Intrinsic::aarch64_neon_fmaxnm:
11925 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11926 N->getOperand(1), N->getOperand(2));
11927 case Intrinsic::aarch64_neon_fminnm:
11928 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11929 N->getOperand(1), N->getOperand(2));
11930 case Intrinsic::aarch64_neon_smull:
11931 case Intrinsic::aarch64_neon_umull:
11932 case Intrinsic::aarch64_neon_pmull:
11933 case Intrinsic::aarch64_neon_sqdmull:
11934 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11935 case Intrinsic::aarch64_neon_sqshl:
11936 case Intrinsic::aarch64_neon_uqshl:
11937 case Intrinsic::aarch64_neon_sqshlu:
11938 case Intrinsic::aarch64_neon_srshl:
11939 case Intrinsic::aarch64_neon_urshl:
11940 case Intrinsic::aarch64_neon_sshl:
11941 case Intrinsic::aarch64_neon_ushl:
11942 return tryCombineShiftImm(IID, N, DAG);
11943 case Intrinsic::aarch64_crc32b:
11944 case Intrinsic::aarch64_crc32cb:
11945 return tryCombineCRC32(0xff, N, DAG);
11946 case Intrinsic::aarch64_crc32h:
11947 case Intrinsic::aarch64_crc32ch:
11948 return tryCombineCRC32(0xffff, N, DAG);
11949 case Intrinsic::aarch64_sve_smaxv:
11950 return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11951 case Intrinsic::aarch64_sve_umaxv:
11952 return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11953 case Intrinsic::aarch64_sve_sminv:
11954 return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11955 case Intrinsic::aarch64_sve_uminv:
11956 return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11957 case Intrinsic::aarch64_sve_orv:
11958 return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11959 case Intrinsic::aarch64_sve_eorv:
11960 return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11961 case Intrinsic::aarch64_sve_andv:
11962 return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11963 case Intrinsic::aarch64_sve_index:
11964 return LowerSVEIntrinsicIndex(N, DAG);
11965 case Intrinsic::aarch64_sve_dup:
11966 return LowerSVEIntrinsicDUP(N, DAG);
11967 case Intrinsic::aarch64_sve_dup_x:
11968 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
11970 case Intrinsic::aarch64_sve_ext:
11971 return LowerSVEIntrinsicEXT(N, DAG);
11972 case Intrinsic::aarch64_sve_smin:
11973 return DAG.getNode(AArch64ISD::SMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11974 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11975 case Intrinsic::aarch64_sve_umin:
11976 return DAG.getNode(AArch64ISD::UMIN_MERGE_OP1, SDLoc(N), N->getValueType(0),
11977 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11978 case Intrinsic::aarch64_sve_smax:
11979 return DAG.getNode(AArch64ISD::SMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
11980 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11981 case Intrinsic::aarch64_sve_umax:
11982 return DAG.getNode(AArch64ISD::UMAX_MERGE_OP1, SDLoc(N), N->getValueType(0),
11983 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11984 case Intrinsic::aarch64_sve_lsl:
11985 return DAG.getNode(AArch64ISD::SHL_MERGE_OP1, SDLoc(N), N->getValueType(0),
11986 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11987 case Intrinsic::aarch64_sve_lsr:
11988 return DAG.getNode(AArch64ISD::SRL_MERGE_OP1, SDLoc(N), N->getValueType(0),
11989 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11990 case Intrinsic::aarch64_sve_asr:
11991 return DAG.getNode(AArch64ISD::SRA_MERGE_OP1, SDLoc(N), N->getValueType(0),
11992 N->getOperand(1), N->getOperand(2), N->getOperand(3));
11993 case Intrinsic::aarch64_sve_cmphs:
11994 if (!N->getOperand(2).getValueType().isFloatingPoint())
11995 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
11996 N->getValueType(0), N->getOperand(1), N->getOperand(2),
11997 N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
11999 case Intrinsic::aarch64_sve_cmphi:
12000 if (!N->getOperand(2).getValueType().isFloatingPoint())
12001 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12002 N->getValueType(0), N->getOperand(1), N->getOperand(2),
12003 N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
12005 case Intrinsic::aarch64_sve_cmpge:
12006 if (!N->getOperand(2).getValueType().isFloatingPoint())
12007 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12008 N->getValueType(0), N->getOperand(1), N->getOperand(2),
12009 N->getOperand(3), DAG.getCondCode(ISD::SETGE));
12011 case Intrinsic::aarch64_sve_cmpgt:
12012 if (!N->getOperand(2).getValueType().isFloatingPoint())
12013 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12014 N->getValueType(0), N->getOperand(1), N->getOperand(2),
12015 N->getOperand(3), DAG.getCondCode(ISD::SETGT));
12017 case Intrinsic::aarch64_sve_cmpeq:
12018 if (!N->getOperand(2).getValueType().isFloatingPoint())
12019 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12020 N->getValueType(0), N->getOperand(1), N->getOperand(2),
12021 N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
12023 case Intrinsic::aarch64_sve_cmpne:
12024 if (!N->getOperand(2).getValueType().isFloatingPoint())
12025 return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
12026 N->getValueType(0), N->getOperand(1), N->getOperand(2),
12027 N->getOperand(3), DAG.getCondCode(ISD::SETNE));
12029 case Intrinsic::aarch64_sve_fadda:
12030 return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
12031 case Intrinsic::aarch64_sve_faddv:
12032 return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
12033 case Intrinsic::aarch64_sve_fmaxnmv:
12034 return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
12035 case Intrinsic::aarch64_sve_fmaxv:
12036 return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
12037 case Intrinsic::aarch64_sve_fminnmv:
12038 return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
12039 case Intrinsic::aarch64_sve_fminv:
12040 return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
12041 case Intrinsic::aarch64_sve_sel:
12042 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
12043 N->getOperand(1), N->getOperand(2), N->getOperand(3));
12044 case Intrinsic::aarch64_sve_cmpeq_wide:
12045 return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
12046 case Intrinsic::aarch64_sve_cmpne_wide:
12047 return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
12048 case Intrinsic::aarch64_sve_cmpge_wide:
12049 return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
12050 case Intrinsic::aarch64_sve_cmpgt_wide:
12051 return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
12052 case Intrinsic::aarch64_sve_cmplt_wide:
12053 return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
12054 case Intrinsic::aarch64_sve_cmple_wide:
12055 return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
12056 case Intrinsic::aarch64_sve_cmphs_wide:
12057 return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
12058 case Intrinsic::aarch64_sve_cmphi_wide:
12059 return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
12060 case Intrinsic::aarch64_sve_cmplo_wide:
12061 return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
12062 case Intrinsic::aarch64_sve_cmpls_wide:
12063 return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
12064 case Intrinsic::aarch64_sve_ptest_any:
12065 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12066 AArch64CC::ANY_ACTIVE);
12067 case Intrinsic::aarch64_sve_ptest_first:
12068 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12069 AArch64CC::FIRST_ACTIVE);
12070 case Intrinsic::aarch64_sve_ptest_last:
12071 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
12072 AArch64CC::LAST_ACTIVE);
12077 static SDValue performExtendCombine(SDNode *N,
12078 TargetLowering::DAGCombinerInfo &DCI,
12079 SelectionDAG &DAG) {
12080 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
12081 // we can convert that DUP into another extract_high (of a bigger DUP), which
12082 // helps the backend to decide that an sabdl2 would be useful, saving a real
12083 // extract_high operation.
12084 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
12085 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
12086 SDNode *ABDNode = N->getOperand(0).getNode();
12087 unsigned IID = getIntrinsicID(ABDNode);
12088 if (IID == Intrinsic::aarch64_neon_sabd ||
12089 IID == Intrinsic::aarch64_neon_uabd) {
12090 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
12091 if (!NewABD.getNode())
12094 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
12099 // This is effectively a custom type legalization for AArch64.
12101 // Type legalization will split an extend of a small, legal, type to a larger
12102 // illegal type by first splitting the destination type, often creating
12103 // illegal source types, which then get legalized in isel-confusing ways,
12104 // leading to really terrible codegen. E.g.,
12105 // %result = v8i32 sext v8i8 %value
12107 // %losrc = extract_subreg %value, ...
12108 // %hisrc = extract_subreg %value, ...
12109 // %lo = v4i32 sext v4i8 %losrc
12110 // %hi = v4i32 sext v4i8 %hisrc
12111 // Things go rapidly downhill from there.
12113 // For AArch64, the [sz]ext vector instructions can only go up one element
12114 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
12115 // take two instructions.
12117 // This implies that the most efficient way to do the extend from v8i8
12118 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
12119 // the normal splitting to happen for the v8i16->v8i32.
12121 // This is pre-legalization to catch some cases where the default
12122 // type legalization will create ill-tempered code.
12123 if (!DCI.isBeforeLegalizeOps())
12126 // We're only interested in cleaning things up for non-legal vector types
12127 // here. If both the source and destination are legal, things will just
12128 // work naturally without any fiddling.
12129 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12130 EVT ResVT = N->getValueType(0);
12131 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
12133 // If the vector type isn't a simple VT, it's beyond the scope of what
12134 // we're worried about here. Let legalization do its thing and hope for
12136 SDValue Src = N->getOperand(0);
12137 EVT SrcVT = Src->getValueType(0);
12138 if (!ResVT.isSimple() || !SrcVT.isSimple())
12141 // If the source VT is a 64-bit fixed or scalable vector, we can play games
12142 // and get the better results we want.
12143 if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
12146 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
12147 ElementCount SrcEC = SrcVT.getVectorElementCount();
12148 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
12150 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
12152 // Now split the rest of the operation into two halves, each with a 64
12156 LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
12158 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
12159 LoVT.getVectorElementCount());
12160 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12161 DAG.getConstant(0, DL, MVT::i64));
12162 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
12163 DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
12164 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
12165 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
12167 // Now combine the parts back together so we still have a single result
12168 // like the combiner expects.
12169 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
12172 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
12173 SDValue SplatVal, unsigned NumVecElts) {
12174 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
12175 unsigned OrigAlignment = St.getAlignment();
12176 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
12178 // Create scalar stores. This is at least as good as the code sequence for a
12179 // split unaligned store which is a dup.s, ext.b, and two stores.
12180 // Most of the time the three stores should be replaced by store pair
12181 // instructions (stp).
12183 SDValue BasePtr = St.getBasePtr();
12184 uint64_t BaseOffset = 0;
12186 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
12188 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
12189 OrigAlignment, St.getMemOperand()->getFlags());
12191 // As this in ISel, we will not merge this add which may degrade results.
12192 if (BasePtr->getOpcode() == ISD::ADD &&
12193 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
12194 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
12195 BasePtr = BasePtr->getOperand(0);
12198 unsigned Offset = EltOffset;
12199 while (--NumVecElts) {
12200 unsigned Alignment = MinAlign(OrigAlignment, Offset);
12201 SDValue OffsetPtr =
12202 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12203 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
12204 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
12205 PtrInfo.getWithOffset(Offset), Alignment,
12206 St.getMemOperand()->getFlags());
12207 Offset += EltOffset;
12212 // Returns an SVE type that ContentTy can be trivially sign or zero extended
12214 static MVT getSVEContainerType(EVT ContentTy) {
12215 assert(ContentTy.isSimple() && "No SVE containers for extended types");
12217 switch (ContentTy.getSimpleVT().SimpleTy) {
12219 llvm_unreachable("No known SVE container for this MVT type");
12226 return MVT::nxv2i64;
12231 return MVT::nxv4i32;
12235 case MVT::nxv8bf16:
12236 return MVT::nxv8i16;
12238 return MVT::nxv16i8;
12242 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
12244 EVT VT = N->getValueType(0);
12246 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12249 EVT ContainerVT = VT;
12250 if (ContainerVT.isInteger())
12251 ContainerVT = getSVEContainerType(ContainerVT);
12253 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
12254 SDValue Ops[] = { N->getOperand(0), // Chain
12255 N->getOperand(2), // Pg
12256 N->getOperand(3), // Base
12257 DAG.getValueType(VT) };
12259 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
12260 SDValue LoadChain = SDValue(Load.getNode(), 1);
12262 if (ContainerVT.isInteger() && (VT != ContainerVT))
12263 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
12265 return DAG.getMergeValues({ Load, LoadChain }, DL);
12268 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
12270 EVT VT = N->getValueType(0);
12271 EVT PtrTy = N->getOperand(3).getValueType();
12273 if (VT == MVT::nxv8bf16 &&
12274 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12278 if (VT.isFloatingPoint())
12279 LoadVT = VT.changeTypeToInteger();
12281 auto *MINode = cast<MemIntrinsicSDNode>(N);
12282 SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
12283 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
12284 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
12285 MINode->getOperand(2), PassThru,
12286 MINode->getMemoryVT(), MINode->getMemOperand(),
12287 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
12289 if (VT.isFloatingPoint()) {
12290 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
12291 return DAG.getMergeValues(Ops, DL);
12297 template <unsigned Opcode>
12298 static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
12299 static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
12300 Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
12301 "Unsupported opcode.");
12303 EVT VT = N->getValueType(0);
12304 if (VT == MVT::nxv8bf16 &&
12305 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12309 if (VT.isFloatingPoint())
12310 LoadVT = VT.changeTypeToInteger();
12312 SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
12313 SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
12314 SDValue LoadChain = SDValue(Load.getNode(), 1);
12316 if (VT.isFloatingPoint())
12317 Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
12319 return DAG.getMergeValues({Load, LoadChain}, DL);
12322 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
12324 SDValue Data = N->getOperand(2);
12325 EVT DataVT = Data.getValueType();
12326 EVT HwSrcVt = getSVEContainerType(DataVT);
12327 SDValue InputVT = DAG.getValueType(DataVT);
12329 if (DataVT == MVT::nxv8bf16 &&
12330 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12333 if (DataVT.isFloatingPoint())
12334 InputVT = DAG.getValueType(HwSrcVt);
12337 if (Data.getValueType().isFloatingPoint())
12338 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
12340 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
12342 SDValue Ops[] = { N->getOperand(0), // Chain
12344 N->getOperand(4), // Base
12345 N->getOperand(3), // Pg
12349 return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
12352 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
12355 SDValue Data = N->getOperand(2);
12356 EVT DataVT = Data.getValueType();
12357 EVT PtrTy = N->getOperand(4).getValueType();
12359 if (DataVT == MVT::nxv8bf16 &&
12360 !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
12363 if (DataVT.isFloatingPoint())
12364 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
12366 auto *MINode = cast<MemIntrinsicSDNode>(N);
12367 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
12368 DAG.getUNDEF(PtrTy), MINode->getOperand(3),
12369 MINode->getMemoryVT(), MINode->getMemOperand(),
12370 ISD::UNINDEXED, false, false);
12373 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
12374 /// load store optimizer pass will merge them to store pair stores. This should
12375 /// be better than a movi to create the vector zero followed by a vector store
12376 /// if the zero constant is not re-used, since one instructions and one register
12377 /// live range will be removed.
12379 /// For example, the final generated code should be:
12381 /// stp xzr, xzr, [x0]
12388 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12389 SDValue StVal = St.getValue();
12390 EVT VT = StVal.getValueType();
12392 // Avoid scalarizing zero splat stores for scalable vectors.
12393 if (VT.isScalableVector())
12396 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
12397 // 2, 3 or 4 i32 elements.
12398 int NumVecElts = VT.getVectorNumElements();
12399 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
12400 VT.getVectorElementType().getSizeInBits() == 64) ||
12401 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
12402 VT.getVectorElementType().getSizeInBits() == 32)))
12405 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
12408 // If the zero constant has more than one use then the vector store could be
12409 // better since the constant mov will be amortized and stp q instructions
12410 // should be able to be formed.
12411 if (!StVal.hasOneUse())
12414 // If the store is truncating then it's going down to i16 or smaller, which
12415 // means it can be implemented in a single store anyway.
12416 if (St.isTruncatingStore())
12419 // If the immediate offset of the address operand is too large for the stp
12420 // instruction, then bail out.
12421 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
12422 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
12423 if (Offset < -512 || Offset > 504)
12427 for (int I = 0; I < NumVecElts; ++I) {
12428 SDValue EltVal = StVal.getOperand(I);
12429 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
12433 // Use a CopyFromReg WZR/XZR here to prevent
12434 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
12438 if (VT.getVectorElementType().getSizeInBits() == 32) {
12439 ZeroReg = AArch64::WZR;
12442 ZeroReg = AArch64::XZR;
12446 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
12447 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12450 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
12451 /// value. The load store optimizer pass will merge them to store pair stores.
12452 /// This has better performance than a splat of the scalar followed by a split
12453 /// vector store. Even if the stores are not merged it is four stores vs a dup,
12454 /// followed by an ext.b and two stores.
12455 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
12456 SDValue StVal = St.getValue();
12457 EVT VT = StVal.getValueType();
12459 // Don't replace floating point stores, they possibly won't be transformed to
12460 // stp because of the store pair suppress pass.
12461 if (VT.isFloatingPoint())
12464 // We can express a splat as store pair(s) for 2 or 4 elements.
12465 unsigned NumVecElts = VT.getVectorNumElements();
12466 if (NumVecElts != 4 && NumVecElts != 2)
12469 // If the store is truncating then it's going down to i16 or smaller, which
12470 // means it can be implemented in a single store anyway.
12471 if (St.isTruncatingStore())
12474 // Check that this is a splat.
12475 // Make sure that each of the relevant vector element locations are inserted
12476 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
12477 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
12479 for (unsigned I = 0; I < NumVecElts; ++I) {
12480 // Check for insert vector elements.
12481 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
12484 // Check that same value is inserted at each vector element.
12486 SplatVal = StVal.getOperand(1);
12487 else if (StVal.getOperand(1) != SplatVal)
12490 // Check insert element index.
12491 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
12494 uint64_t IndexVal = CIndex->getZExtValue();
12495 if (IndexVal >= NumVecElts)
12497 IndexNotInserted.reset(IndexVal);
12499 StVal = StVal.getOperand(0);
12501 // Check that all vector element locations were inserted to.
12502 if (IndexNotInserted.any())
12505 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
12508 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12510 const AArch64Subtarget *Subtarget) {
12512 StoreSDNode *S = cast<StoreSDNode>(N);
12513 if (S->isVolatile() || S->isIndexed())
12516 SDValue StVal = S->getValue();
12517 EVT VT = StVal.getValueType();
12519 if (!VT.isFixedLengthVector())
12522 // If we get a splat of zeros, convert this vector store to a store of
12523 // scalars. They will be merged into store pairs of xzr thereby removing one
12524 // instruction and one register.
12525 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
12526 return ReplacedZeroSplat;
12528 // FIXME: The logic for deciding if an unaligned store should be split should
12529 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
12530 // a call to that function here.
12532 if (!Subtarget->isMisaligned128StoreSlow())
12535 // Don't split at -Oz.
12536 if (DAG.getMachineFunction().getFunction().hasMinSize())
12539 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
12540 // those up regresses performance on micro-benchmarks and olden/bh.
12541 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
12544 // Split unaligned 16B stores. They are terrible for performance.
12545 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
12546 // extensions can use this to mark that it does not want splitting to happen
12547 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
12548 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
12549 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
12550 S->getAlignment() <= 2)
12553 // If we get a splat of a scalar convert this vector store to a store of
12554 // scalars. They will be merged into store pairs thereby removing two
12556 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
12557 return ReplacedSplat;
12561 // Split VT into two.
12562 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
12563 unsigned NumElts = HalfVT.getVectorNumElements();
12564 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12565 DAG.getConstant(0, DL, MVT::i64));
12566 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
12567 DAG.getConstant(NumElts, DL, MVT::i64));
12568 SDValue BasePtr = S->getBasePtr();
12570 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
12571 S->getAlignment(), S->getMemOperand()->getFlags());
12572 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
12573 DAG.getConstant(8, DL, MVT::i64));
12574 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
12575 S->getPointerInfo(), S->getAlignment(),
12576 S->getMemOperand()->getFlags());
12579 /// Target-specific DAG combine function for post-increment LD1 (lane) and
12580 /// post-increment LD1R.
12581 static SDValue performPostLD1Combine(SDNode *N,
12582 TargetLowering::DAGCombinerInfo &DCI,
12584 if (DCI.isBeforeLegalizeOps())
12587 SelectionDAG &DAG = DCI.DAG;
12588 EVT VT = N->getValueType(0);
12590 if (VT.isScalableVector())
12593 unsigned LoadIdx = IsLaneOp ? 1 : 0;
12594 SDNode *LD = N->getOperand(LoadIdx).getNode();
12595 // If it is not LOAD, can not do such combine.
12596 if (LD->getOpcode() != ISD::LOAD)
12599 // The vector lane must be a constant in the LD1LANE opcode.
12602 Lane = N->getOperand(2);
12603 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
12604 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
12608 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
12609 EVT MemVT = LoadSDN->getMemoryVT();
12610 // Check if memory operand is the same type as the vector element.
12611 if (MemVT != VT.getVectorElementType())
12614 // Check if there are other uses. If so, do not combine as it will introduce
12616 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
12618 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
12624 SDValue Addr = LD->getOperand(1);
12625 SDValue Vector = N->getOperand(0);
12626 // Search for a use of the address operand that is an increment.
12627 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
12628 Addr.getNode()->use_end(); UI != UE; ++UI) {
12629 SDNode *User = *UI;
12630 if (User->getOpcode() != ISD::ADD
12631 || UI.getUse().getResNo() != Addr.getResNo())
12634 // If the increment is a constant, it must match the memory ref size.
12635 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12636 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12637 uint32_t IncVal = CInc->getZExtValue();
12638 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
12639 if (IncVal != NumBytes)
12641 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12644 // To avoid cycle construction make sure that neither the load nor the add
12645 // are predecessors to each other or the Vector.
12646 SmallPtrSet<const SDNode *, 32> Visited;
12647 SmallVector<const SDNode *, 16> Worklist;
12648 Visited.insert(Addr.getNode());
12649 Worklist.push_back(User);
12650 Worklist.push_back(LD);
12651 Worklist.push_back(Vector.getNode());
12652 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
12653 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12656 SmallVector<SDValue, 8> Ops;
12657 Ops.push_back(LD->getOperand(0)); // Chain
12659 Ops.push_back(Vector); // The vector to be inserted
12660 Ops.push_back(Lane); // The lane to be inserted in the vector
12662 Ops.push_back(Addr);
12663 Ops.push_back(Inc);
12665 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
12666 SDVTList SDTys = DAG.getVTList(Tys);
12667 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
12668 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
12670 LoadSDN->getMemOperand());
12672 // Update the uses.
12673 SDValue NewResults[] = {
12674 SDValue(LD, 0), // The result of load
12675 SDValue(UpdN.getNode(), 2) // Chain
12677 DCI.CombineTo(LD, NewResults);
12678 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
12679 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
12686 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
12687 /// address translation.
12688 static bool performTBISimplification(SDValue Addr,
12689 TargetLowering::DAGCombinerInfo &DCI,
12690 SelectionDAG &DAG) {
12691 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
12693 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
12694 !DCI.isBeforeLegalizeOps());
12695 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12696 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
12697 DCI.CommitTargetLoweringOpt(TLO);
12703 static SDValue performSTORECombine(SDNode *N,
12704 TargetLowering::DAGCombinerInfo &DCI,
12706 const AArch64Subtarget *Subtarget) {
12707 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
12710 if (Subtarget->supportsAddressTopByteIgnored() &&
12711 performTBISimplification(N->getOperand(2), DCI, DAG))
12712 return SDValue(N, 0);
12718 /// Target-specific DAG combine function for NEON load/store intrinsics
12719 /// to merge base address updates.
12720 static SDValue performNEONPostLDSTCombine(SDNode *N,
12721 TargetLowering::DAGCombinerInfo &DCI,
12722 SelectionDAG &DAG) {
12723 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12726 unsigned AddrOpIdx = N->getNumOperands() - 1;
12727 SDValue Addr = N->getOperand(AddrOpIdx);
12729 // Search for a use of the address operand that is an increment.
12730 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
12731 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
12732 SDNode *User = *UI;
12733 if (User->getOpcode() != ISD::ADD ||
12734 UI.getUse().getResNo() != Addr.getResNo())
12737 // Check that the add is independent of the load/store. Otherwise, folding
12738 // it would create a cycle.
12739 SmallPtrSet<const SDNode *, 32> Visited;
12740 SmallVector<const SDNode *, 16> Worklist;
12741 Visited.insert(Addr.getNode());
12742 Worklist.push_back(N);
12743 Worklist.push_back(User);
12744 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
12745 SDNode::hasPredecessorHelper(User, Visited, Worklist))
12748 // Find the new opcode for the updating load/store.
12749 bool IsStore = false;
12750 bool IsLaneOp = false;
12751 bool IsDupOp = false;
12752 unsigned NewOpc = 0;
12753 unsigned NumVecs = 0;
12754 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
12756 default: llvm_unreachable("unexpected intrinsic for Neon base update");
12757 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
12758 NumVecs = 2; break;
12759 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
12760 NumVecs = 3; break;
12761 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
12762 NumVecs = 4; break;
12763 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
12764 NumVecs = 2; IsStore = true; break;
12765 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
12766 NumVecs = 3; IsStore = true; break;
12767 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
12768 NumVecs = 4; IsStore = true; break;
12769 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
12770 NumVecs = 2; break;
12771 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
12772 NumVecs = 3; break;
12773 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
12774 NumVecs = 4; break;
12775 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
12776 NumVecs = 2; IsStore = true; break;
12777 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
12778 NumVecs = 3; IsStore = true; break;
12779 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
12780 NumVecs = 4; IsStore = true; break;
12781 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
12782 NumVecs = 2; IsDupOp = true; break;
12783 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
12784 NumVecs = 3; IsDupOp = true; break;
12785 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
12786 NumVecs = 4; IsDupOp = true; break;
12787 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
12788 NumVecs = 2; IsLaneOp = true; break;
12789 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
12790 NumVecs = 3; IsLaneOp = true; break;
12791 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
12792 NumVecs = 4; IsLaneOp = true; break;
12793 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
12794 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
12795 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
12796 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
12797 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
12798 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
12803 VecTy = N->getOperand(2).getValueType();
12805 VecTy = N->getValueType(0);
12807 // If the increment is a constant, it must match the memory ref size.
12808 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
12809 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
12810 uint32_t IncVal = CInc->getZExtValue();
12811 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
12812 if (IsLaneOp || IsDupOp)
12813 NumBytes /= VecTy.getVectorNumElements();
12814 if (IncVal != NumBytes)
12816 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
12818 SmallVector<SDValue, 8> Ops;
12819 Ops.push_back(N->getOperand(0)); // Incoming chain
12820 // Load lane and store have vector list as input.
12821 if (IsLaneOp || IsStore)
12822 for (unsigned i = 2; i < AddrOpIdx; ++i)
12823 Ops.push_back(N->getOperand(i));
12824 Ops.push_back(Addr); // Base register
12825 Ops.push_back(Inc);
12829 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
12831 for (n = 0; n < NumResultVecs; ++n)
12833 Tys[n++] = MVT::i64; // Type of write back register
12834 Tys[n] = MVT::Other; // Type of the chain
12835 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
12837 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
12838 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
12839 MemInt->getMemoryVT(),
12840 MemInt->getMemOperand());
12842 // Update the uses.
12843 std::vector<SDValue> NewResults;
12844 for (unsigned i = 0; i < NumResultVecs; ++i) {
12845 NewResults.push_back(SDValue(UpdN.getNode(), i));
12847 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
12848 DCI.CombineTo(N, NewResults);
12849 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
12856 // Checks to see if the value is the prescribed width and returns information
12857 // about its extension mode.
12859 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
12860 ExtType = ISD::NON_EXTLOAD;
12861 switch(V.getNode()->getOpcode()) {
12865 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
12866 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
12867 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
12868 ExtType = LoadNode->getExtensionType();
12873 case ISD::AssertSext: {
12874 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12875 if ((TypeNode->getVT() == MVT::i8 && width == 8)
12876 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12877 ExtType = ISD::SEXTLOAD;
12882 case ISD::AssertZext: {
12883 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
12884 if ((TypeNode->getVT() == MVT::i8 && width == 8)
12885 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
12886 ExtType = ISD::ZEXTLOAD;
12891 case ISD::Constant:
12892 case ISD::TargetConstant: {
12893 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
12894 1LL << (width - 1);
12901 // This function does a whole lot of voodoo to determine if the tests are
12902 // equivalent without and with a mask. Essentially what happens is that given a
12905 // +-------------+ +-------------+ +-------------+ +-------------+
12906 // | Input | | AddConstant | | CompConstant| | CC |
12907 // +-------------+ +-------------+ +-------------+ +-------------+
12909 // V V | +----------+
12910 // +-------------+ +----+ | |
12911 // | ADD | |0xff| | |
12912 // +-------------+ +----+ | |
12915 // +-------------+ | |
12917 // +-------------+ | |
12926 // The AND node may be safely removed for some combinations of inputs. In
12927 // particular we need to take into account the extension type of the Input,
12928 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
12929 // width of the input (this can work for any width inputs, the above graph is
12930 // specific to 8 bits.
12932 // The specific equations were worked out by generating output tables for each
12933 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
12934 // problem was simplified by working with 4 bit inputs, which means we only
12935 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
12936 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
12937 // patterns present in both extensions (0,7). For every distinct set of
12938 // AddConstant and CompConstants bit patterns we can consider the masked and
12939 // unmasked versions to be equivalent if the result of this function is true for
12940 // all 16 distinct bit patterns of for the current extension type of Input (w0).
12943 // and w10, w8, #0x0f
12945 // cset w9, AArch64CC
12947 // cset w11, AArch64CC
12952 // Since the above function shows when the outputs are equivalent it defines
12953 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
12954 // would be expensive to run during compiles. The equations below were written
12955 // in a test harness that confirmed they gave equivalent outputs to the above
12956 // for all inputs function, so they can be used determine if the removal is
12959 // isEquivalentMaskless() is the code for testing if the AND can be removed
12960 // factored out of the DAG recognition as the DAG can take several forms.
12962 static bool isEquivalentMaskless(unsigned CC, unsigned width,
12963 ISD::LoadExtType ExtType, int AddConstant,
12964 int CompConstant) {
12965 // By being careful about our equations and only writing the in term
12966 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
12967 // make them generally applicable to all bit widths.
12968 int MaxUInt = (1 << width);
12970 // For the purposes of these comparisons sign extending the type is
12971 // equivalent to zero extending the add and displacing it by half the integer
12972 // width. Provided we are careful and make sure our equations are valid over
12973 // the whole range we can just adjust the input and avoid writing equations
12974 // for sign extended inputs.
12975 if (ExtType == ISD::SEXTLOAD)
12976 AddConstant -= (1 << (width-1));
12979 case AArch64CC::LE:
12980 case AArch64CC::GT:
12981 if ((AddConstant == 0) ||
12982 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
12983 (AddConstant >= 0 && CompConstant < 0) ||
12984 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
12987 case AArch64CC::LT:
12988 case AArch64CC::GE:
12989 if ((AddConstant == 0) ||
12990 (AddConstant >= 0 && CompConstant <= 0) ||
12991 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
12994 case AArch64CC::HI:
12995 case AArch64CC::LS:
12996 if ((AddConstant >= 0 && CompConstant < 0) ||
12997 (AddConstant <= 0 && CompConstant >= -1 &&
12998 CompConstant < AddConstant + MaxUInt))
13001 case AArch64CC::PL:
13002 case AArch64CC::MI:
13003 if ((AddConstant == 0) ||
13004 (AddConstant > 0 && CompConstant <= 0) ||
13005 (AddConstant < 0 && CompConstant <= AddConstant))
13008 case AArch64CC::LO:
13009 case AArch64CC::HS:
13010 if ((AddConstant >= 0 && CompConstant <= 0) ||
13011 (AddConstant <= 0 && CompConstant >= 0 &&
13012 CompConstant <= AddConstant + MaxUInt))
13015 case AArch64CC::EQ:
13016 case AArch64CC::NE:
13017 if ((AddConstant > 0 && CompConstant < 0) ||
13018 (AddConstant < 0 && CompConstant >= 0 &&
13019 CompConstant < AddConstant + MaxUInt) ||
13020 (AddConstant >= 0 && CompConstant >= 0 &&
13021 CompConstant >= AddConstant) ||
13022 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
13025 case AArch64CC::VS:
13026 case AArch64CC::VC:
13027 case AArch64CC::AL:
13028 case AArch64CC::NV:
13030 case AArch64CC::Invalid:
13038 SDValue performCONDCombine(SDNode *N,
13039 TargetLowering::DAGCombinerInfo &DCI,
13040 SelectionDAG &DAG, unsigned CCIndex,
13041 unsigned CmpIndex) {
13042 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
13043 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
13044 unsigned CondOpcode = SubsNode->getOpcode();
13046 if (CondOpcode != AArch64ISD::SUBS)
13049 // There is a SUBS feeding this condition. Is it fed by a mask we can
13052 SDNode *AndNode = SubsNode->getOperand(0).getNode();
13053 unsigned MaskBits = 0;
13055 if (AndNode->getOpcode() != ISD::AND)
13058 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
13059 uint32_t CNV = CN->getZExtValue();
13062 else if (CNV == 65535)
13069 SDValue AddValue = AndNode->getOperand(0);
13071 if (AddValue.getOpcode() != ISD::ADD)
13074 // The basic dag structure is correct, grab the inputs and validate them.
13076 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
13077 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
13078 SDValue SubsInputValue = SubsNode->getOperand(1);
13080 // The mask is present and the provenance of all the values is a smaller type,
13081 // lets see if the mask is superfluous.
13083 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
13084 !isa<ConstantSDNode>(SubsInputValue.getNode()))
13087 ISD::LoadExtType ExtType;
13089 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
13090 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
13091 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
13094 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
13095 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
13096 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
13099 // The AND is not necessary, remove it.
13101 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
13102 SubsNode->getValueType(1));
13103 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
13105 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
13106 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
13108 return SDValue(N, 0);
13111 // Optimize compare with zero and branch.
13112 static SDValue performBRCONDCombine(SDNode *N,
13113 TargetLowering::DAGCombinerInfo &DCI,
13114 SelectionDAG &DAG) {
13115 MachineFunction &MF = DAG.getMachineFunction();
13116 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
13117 // will not be produced, as they are conditional branch instructions that do
13119 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
13122 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
13124 SDValue Chain = N->getOperand(0);
13125 SDValue Dest = N->getOperand(1);
13126 SDValue CCVal = N->getOperand(2);
13127 SDValue Cmp = N->getOperand(3);
13129 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
13130 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
13131 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
13134 unsigned CmpOpc = Cmp.getOpcode();
13135 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
13138 // Only attempt folding if there is only one use of the flag and no use of the
13140 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
13143 SDValue LHS = Cmp.getOperand(0);
13144 SDValue RHS = Cmp.getOperand(1);
13146 assert(LHS.getValueType() == RHS.getValueType() &&
13147 "Expected the value type to be the same for both operands!");
13148 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
13151 if (isNullConstant(LHS))
13152 std::swap(LHS, RHS);
13154 if (!isNullConstant(RHS))
13157 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
13158 LHS.getOpcode() == ISD::SRL)
13161 // Fold the compare into the branch instruction.
13163 if (CC == AArch64CC::EQ)
13164 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13166 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
13168 // Do not add new nodes to DAG combiner worklist.
13169 DCI.CombineTo(N, BR, false);
13174 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
13175 // as well as whether the test should be inverted. This code is required to
13176 // catch these cases (as opposed to standard dag combines) because
13177 // AArch64ISD::TBZ is matched during legalization.
13178 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
13179 SelectionDAG &DAG) {
13181 if (!Op->hasOneUse())
13184 // We don't handle undef/constant-fold cases below, as they should have
13185 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
13188 // (tbz (trunc x), b) -> (tbz x, b)
13189 // This case is just here to enable more of the below cases to be caught.
13190 if (Op->getOpcode() == ISD::TRUNCATE &&
13191 Bit < Op->getValueType(0).getSizeInBits()) {
13192 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13195 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
13196 if (Op->getOpcode() == ISD::ANY_EXTEND &&
13197 Bit < Op->getOperand(0).getValueSizeInBits()) {
13198 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13201 if (Op->getNumOperands() != 2)
13204 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13208 switch (Op->getOpcode()) {
13212 // (tbz (and x, m), b) -> (tbz x, b)
13214 if ((C->getZExtValue() >> Bit) & 1)
13215 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13218 // (tbz (shl x, c), b) -> (tbz x, b-c)
13220 if (C->getZExtValue() <= Bit &&
13221 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13222 Bit = Bit - C->getZExtValue();
13223 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13227 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
13229 Bit = Bit + C->getZExtValue();
13230 if (Bit >= Op->getValueType(0).getSizeInBits())
13231 Bit = Op->getValueType(0).getSizeInBits() - 1;
13232 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13234 // (tbz (srl x, c), b) -> (tbz x, b+c)
13236 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
13237 Bit = Bit + C->getZExtValue();
13238 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13242 // (tbz (xor x, -1), b) -> (tbnz x, b)
13244 if ((C->getZExtValue() >> Bit) & 1)
13246 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
13250 // Optimize test single bit zero/non-zero and branch.
13251 static SDValue performTBZCombine(SDNode *N,
13252 TargetLowering::DAGCombinerInfo &DCI,
13253 SelectionDAG &DAG) {
13254 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13255 bool Invert = false;
13256 SDValue TestSrc = N->getOperand(1);
13257 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
13259 if (TestSrc == NewTestSrc)
13262 unsigned NewOpc = N->getOpcode();
13264 if (NewOpc == AArch64ISD::TBZ)
13265 NewOpc = AArch64ISD::TBNZ;
13267 assert(NewOpc == AArch64ISD::TBNZ);
13268 NewOpc = AArch64ISD::TBZ;
13273 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
13274 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
13277 // vselect (v1i1 setcc) ->
13278 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
13279 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
13280 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
13282 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
13283 SDValue N0 = N->getOperand(0);
13284 EVT CCVT = N0.getValueType();
13286 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
13287 CCVT.getVectorElementType() != MVT::i1)
13290 EVT ResVT = N->getValueType(0);
13291 EVT CmpVT = N0.getOperand(0).getValueType();
13292 // Only combine when the result type is of the same size as the compared
13294 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
13297 SDValue IfTrue = N->getOperand(1);
13298 SDValue IfFalse = N->getOperand(2);
13300 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
13301 N0.getOperand(0), N0.getOperand(1),
13302 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13303 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
13307 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
13308 /// the compare-mask instructions rather than going via NZCV, even if LHS and
13309 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
13310 /// with a vector one followed by a DUP shuffle on the result.
13311 static SDValue performSelectCombine(SDNode *N,
13312 TargetLowering::DAGCombinerInfo &DCI) {
13313 SelectionDAG &DAG = DCI.DAG;
13314 SDValue N0 = N->getOperand(0);
13315 EVT ResVT = N->getValueType(0);
13317 if (N0.getOpcode() != ISD::SETCC)
13320 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
13321 // scalar SetCCResultType. We also don't expect vectors, because we assume
13322 // that selects fed by vector SETCCs are canonicalized to VSELECT.
13323 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
13324 "Scalar-SETCC feeding SELECT has unexpected result type!");
13326 // If NumMaskElts == 0, the comparison is larger than select result. The
13327 // largest real NEON comparison is 64-bits per lane, which means the result is
13328 // at most 32-bits and an illegal vector. Just bail out for now.
13329 EVT SrcVT = N0.getOperand(0).getValueType();
13331 // Don't try to do this optimization when the setcc itself has i1 operands.
13332 // There are no legal vectors of i1, so this would be pointless.
13333 if (SrcVT == MVT::i1)
13336 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
13337 if (!ResVT.isVector() || NumMaskElts == 0)
13340 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
13341 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
13343 // Also bail out if the vector CCVT isn't the same size as ResVT.
13344 // This can happen if the SETCC operand size doesn't divide the ResVT size
13345 // (e.g., f64 vs v3f32).
13346 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
13349 // Make sure we didn't create illegal types, if we're not supposed to.
13350 assert(DCI.isBeforeLegalize() ||
13351 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
13353 // First perform a vector comparison, where lane 0 is the one we're interested
13357 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
13359 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
13360 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
13362 // Now duplicate the comparison mask we want across all other lanes.
13363 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
13364 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
13365 Mask = DAG.getNode(ISD::BITCAST, DL,
13366 ResVT.changeVectorElementTypeToInteger(), Mask);
13368 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
13371 /// Get rid of unnecessary NVCASTs (that don't change the type).
13372 static SDValue performNVCASTCombine(SDNode *N) {
13373 if (N->getValueType(0) == N->getOperand(0).getValueType())
13374 return N->getOperand(0);
13379 // If all users of the globaladdr are of the form (globaladdr + constant), find
13380 // the smallest constant, fold it into the globaladdr's offset and rewrite the
13381 // globaladdr as (globaladdr + constant) - constant.
13382 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
13383 const AArch64Subtarget *Subtarget,
13384 const TargetMachine &TM) {
13385 auto *GN = cast<GlobalAddressSDNode>(N);
13386 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
13387 AArch64II::MO_NO_FLAG)
13390 uint64_t MinOffset = -1ull;
13391 for (SDNode *N : GN->uses()) {
13392 if (N->getOpcode() != ISD::ADD)
13394 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
13396 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13399 MinOffset = std::min(MinOffset, C->getZExtValue());
13401 uint64_t Offset = MinOffset + GN->getOffset();
13403 // Require that the new offset is larger than the existing one. Otherwise, we
13404 // can end up oscillating between two possible DAGs, for example,
13405 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
13406 if (Offset <= uint64_t(GN->getOffset()))
13409 // Check whether folding this offset is legal. It must not go out of bounds of
13410 // the referenced object to avoid violating the code model, and must be
13411 // smaller than 2^21 because this is the largest offset expressible in all
13414 // This check also prevents us from folding negative offsets, which will end
13415 // up being treated in the same way as large positive ones. They could also
13416 // cause code model violations, and aren't really common enough to matter.
13417 if (Offset >= (1 << 21))
13420 const GlobalValue *GV = GN->getGlobal();
13421 Type *T = GV->getValueType();
13422 if (!T->isSized() ||
13423 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
13427 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
13428 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
13429 DAG.getConstant(MinOffset, DL, MVT::i64));
13432 // Turns the vector of indices into a vector of byte offstes by scaling Offset
13433 // by (BitWidth / 8).
13434 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
13435 SDLoc DL, unsigned BitWidth) {
13436 assert(Offset.getValueType().isScalableVector() &&
13437 "This method is only for scalable vectors of offsets");
13439 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
13440 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
13442 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
13445 /// Check if the value of \p OffsetInBytes can be used as an immediate for
13446 /// the gather load/prefetch and scatter store instructions with vector base and
13447 /// immediate offset addressing mode:
13449 /// [<Zn>.[S|D]{, #<imm>}]
13451 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13453 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
13454 unsigned ScalarSizeInBytes) {
13455 // The immediate is not a multiple of the scalar size.
13456 if (OffsetInBytes % ScalarSizeInBytes)
13459 // The immediate is out of range.
13460 if (OffsetInBytes / ScalarSizeInBytes > 31)
13466 /// Check if the value of \p Offset represents a valid immediate for the SVE
13467 /// gather load/prefetch and scatter store instructiona with vector base and
13468 /// immediate offset addressing mode:
13470 /// [<Zn>.[S|D]{, #<imm>}]
13472 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
13473 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
13474 unsigned ScalarSizeInBytes) {
13475 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
13476 return OffsetConst && isValidImmForSVEVecImmAddrMode(
13477 OffsetConst->getZExtValue(), ScalarSizeInBytes);
13480 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
13482 bool OnlyPackedOffsets = true) {
13483 const SDValue Src = N->getOperand(2);
13484 const EVT SrcVT = Src->getValueType(0);
13485 assert(SrcVT.isScalableVector() &&
13486 "Scatter stores are only possible for SVE vectors");
13489 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
13491 // Make sure that source data will fit into an SVE register
13492 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13495 // For FPs, ACLE only supports _packed_ single and double precision types.
13496 if (SrcElVT.isFloatingPoint())
13497 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
13500 // Depending on the addressing mode, this is either a pointer or a vector of
13501 // pointers (that fits into one register)
13502 SDValue Base = N->getOperand(4);
13503 // Depending on the addressing mode, this is either a single offset or a
13504 // vector of offsets (that fits into one register)
13505 SDValue Offset = N->getOperand(5);
13507 // For "scalar + vector of indices", just scale the indices. This only
13508 // applies to non-temporal scatters because there's no instruction that takes
13510 if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
13512 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
13513 Opcode = AArch64ISD::SSTNT1_PRED;
13516 // In the case of non-temporal gather loads there's only one SVE instruction
13517 // per data-size: "scalar + vector", i.e.
13518 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13519 // Since we do have intrinsics that allow the arguments to be in a different
13520 // order, we may need to swap them to match the spec.
13521 if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
13522 std::swap(Base, Offset);
13524 // SST1_IMM requires that the offset is an immediate that is:
13525 // * a multiple of #SizeInBytes,
13526 // * in the range [0, 31 x #SizeInBytes],
13527 // where #SizeInBytes is the size in bytes of the stored items. For
13528 // immediates outside that range and non-immediate scalar offsets use SST1 or
13529 // SST1_UXTW instead.
13530 if (Opcode == AArch64ISD::SST1_IMM_PRED) {
13531 if (!isValidImmForSVEVecImmAddrMode(Offset,
13532 SrcVT.getScalarSizeInBits() / 8)) {
13533 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13534 Opcode = AArch64ISD::SST1_UXTW_PRED;
13536 Opcode = AArch64ISD::SST1_PRED;
13538 std::swap(Base, Offset);
13542 auto &TLI = DAG.getTargetLoweringInfo();
13543 if (!TLI.isTypeLegal(Base.getValueType()))
13546 // Some scatter store variants allow unpacked offsets, but only as nxv2i32
13547 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13548 // nxv2i64. Legalize accordingly.
13549 if (!OnlyPackedOffsets &&
13550 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13551 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13553 if (!TLI.isTypeLegal(Offset.getValueType()))
13556 // Source value type that is representable in hardware
13557 EVT HwSrcVt = getSVEContainerType(SrcVT);
13559 // Keep the original type of the input data to store - this is needed to be
13560 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
13561 // FP values we want the integer equivalent, so just use HwSrcVt.
13562 SDValue InputVT = DAG.getValueType(SrcVT);
13563 if (SrcVT.isFloatingPoint())
13564 InputVT = DAG.getValueType(HwSrcVt);
13566 SDVTList VTs = DAG.getVTList(MVT::Other);
13569 if (Src.getValueType().isFloatingPoint())
13570 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
13572 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
13574 SDValue Ops[] = {N->getOperand(0), // Chain
13576 N->getOperand(3), // Pg
13581 return DAG.getNode(Opcode, DL, VTs, Ops);
13584 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
13586 bool OnlyPackedOffsets = true) {
13587 const EVT RetVT = N->getValueType(0);
13588 assert(RetVT.isScalableVector() &&
13589 "Gather loads are only possible for SVE vectors");
13593 // Make sure that the loaded data will fit into an SVE register
13594 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
13597 // Depending on the addressing mode, this is either a pointer or a vector of
13598 // pointers (that fits into one register)
13599 SDValue Base = N->getOperand(3);
13600 // Depending on the addressing mode, this is either a single offset or a
13601 // vector of offsets (that fits into one register)
13602 SDValue Offset = N->getOperand(4);
13604 // For "scalar + vector of indices", just scale the indices. This only
13605 // applies to non-temporal gathers because there's no instruction that takes
13607 if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
13608 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
13609 RetVT.getScalarSizeInBits());
13610 Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
13613 // In the case of non-temporal gather loads there's only one SVE instruction
13614 // per data-size: "scalar + vector", i.e.
13615 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
13616 // Since we do have intrinsics that allow the arguments to be in a different
13617 // order, we may need to swap them to match the spec.
13618 if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
13619 Offset.getValueType().isVector())
13620 std::swap(Base, Offset);
13622 // GLD{FF}1_IMM requires that the offset is an immediate that is:
13623 // * a multiple of #SizeInBytes,
13624 // * in the range [0, 31 x #SizeInBytes],
13625 // where #SizeInBytes is the size in bytes of the loaded items. For
13626 // immediates outside that range and non-immediate scalar offsets use
13627 // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
13628 if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
13629 Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
13630 if (!isValidImmForSVEVecImmAddrMode(Offset,
13631 RetVT.getScalarSizeInBits() / 8)) {
13632 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
13633 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13634 ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
13635 : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
13637 Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
13638 ? AArch64ISD::GLD1_MERGE_ZERO
13639 : AArch64ISD::GLDFF1_MERGE_ZERO;
13641 std::swap(Base, Offset);
13645 auto &TLI = DAG.getTargetLoweringInfo();
13646 if (!TLI.isTypeLegal(Base.getValueType()))
13649 // Some gather load variants allow unpacked offsets, but only as nxv2i32
13650 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
13651 // nxv2i64. Legalize accordingly.
13652 if (!OnlyPackedOffsets &&
13653 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
13654 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
13656 // Return value type that is representable in hardware
13657 EVT HwRetVt = getSVEContainerType(RetVT);
13659 // Keep the original output value type around - this is needed to be able to
13660 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
13661 // values we want the integer equivalent, so just use HwRetVT.
13662 SDValue OutVT = DAG.getValueType(RetVT);
13663 if (RetVT.isFloatingPoint())
13664 OutVT = DAG.getValueType(HwRetVt);
13666 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
13667 SDValue Ops[] = {N->getOperand(0), // Chain
13668 N->getOperand(2), // Pg
13669 Base, Offset, OutVT};
13671 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
13672 SDValue LoadChain = SDValue(Load.getNode(), 1);
13674 if (RetVT.isInteger() && (RetVT != HwRetVt))
13675 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
13677 // If the original return value was FP, bitcast accordingly. Doing it here
13678 // means that we can avoid adding TableGen patterns for FPs.
13679 if (RetVT.isFloatingPoint())
13680 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
13682 return DAG.getMergeValues({Load, LoadChain}, DL);
13686 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13687 SelectionDAG &DAG) {
13688 if (DCI.isBeforeLegalizeOps())
13692 SDValue Src = N->getOperand(0);
13693 unsigned Opc = Src->getOpcode();
13695 // Sign extend of an unsigned unpack -> signed unpack
13696 if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
13698 unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
13699 : AArch64ISD::SUNPKLO;
13701 // Push the sign extend to the operand of the unpack
13702 // This is necessary where, for example, the operand of the unpack
13703 // is another unpack:
13704 // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
13706 // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
13708 // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
13709 SDValue ExtOp = Src->getOperand(0);
13710 auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
13711 EVT EltTy = VT.getVectorElementType();
13714 assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
13715 "Sign extending from an invalid type");
13717 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13718 VT.getVectorElementType(),
13719 VT.getVectorElementCount() * 2);
13721 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
13722 ExtOp, DAG.getValueType(ExtVT));
13724 return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
13727 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
13728 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
13730 unsigned MemVTOpNum = 4;
13732 case AArch64ISD::LD1_MERGE_ZERO:
13733 NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
13736 case AArch64ISD::LDNF1_MERGE_ZERO:
13737 NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
13740 case AArch64ISD::LDFF1_MERGE_ZERO:
13741 NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
13744 case AArch64ISD::GLD1_MERGE_ZERO:
13745 NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
13747 case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
13748 NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
13750 case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
13751 NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
13753 case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
13754 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
13756 case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
13757 NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
13759 case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
13760 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
13762 case AArch64ISD::GLD1_IMM_MERGE_ZERO:
13763 NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
13765 case AArch64ISD::GLDFF1_MERGE_ZERO:
13766 NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
13768 case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
13769 NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
13771 case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
13772 NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
13774 case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
13775 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
13777 case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
13778 NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
13780 case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
13781 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
13783 case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
13784 NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
13786 case AArch64ISD::GLDNT1_MERGE_ZERO:
13787 NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
13793 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
13794 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
13796 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
13799 EVT DstVT = N->getValueType(0);
13800 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
13802 SmallVector<SDValue, 5> Ops;
13803 for (unsigned I = 0; I < Src->getNumOperands(); ++I)
13804 Ops.push_back(Src->getOperand(I));
13806 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
13807 DCI.CombineTo(N, ExtLoad);
13808 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
13810 // Return N so it doesn't get rechecked
13811 return SDValue(N, 0);
13814 /// Legalize the gather prefetch (scalar + vector addressing mode) when the
13815 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
13816 /// != nxv2i32) do not need legalization.
13817 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
13818 const unsigned OffsetPos = 4;
13819 SDValue Offset = N->getOperand(OffsetPos);
13821 // Not an unpacked vector, bail out.
13822 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
13825 // Extend the unpacked offset vector to 64-bit lanes.
13827 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
13828 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13829 // Replace the offset operand with the 64-bit one.
13830 Ops[OffsetPos] = Offset;
13832 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13835 /// Combines a node carrying the intrinsic
13836 /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
13837 /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
13838 /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
13839 /// sve gather prefetch instruction with vector plus immediate addressing mode.
13840 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
13841 unsigned ScalarSizeInBytes) {
13842 const unsigned ImmPos = 4, OffsetPos = 3;
13843 // No need to combine the node if the immediate is valid...
13844 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
13847 // ...otherwise swap the offset base with the offset...
13848 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
13849 std::swap(Ops[ImmPos], Ops[OffsetPos]);
13850 // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
13851 // `aarch64_sve_prfb_gather_uxtw_index`.
13853 Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
13856 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
13859 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
13860 DAGCombinerInfo &DCI) const {
13861 SelectionDAG &DAG = DCI.DAG;
13862 switch (N->getOpcode()) {
13864 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
13868 return performAddSubLongCombine(N, DCI, DAG);
13870 return performXorCombine(N, DAG, DCI, Subtarget);
13872 return performMulCombine(N, DAG, DCI, Subtarget);
13873 case ISD::SINT_TO_FP:
13874 case ISD::UINT_TO_FP:
13875 return performIntToFpCombine(N, DAG, Subtarget);
13876 case ISD::FP_TO_SINT:
13877 case ISD::FP_TO_UINT:
13878 return performFpToIntCombine(N, DAG, DCI, Subtarget);
13880 return performFDivCombine(N, DAG, DCI, Subtarget);
13882 return performORCombine(N, DCI, Subtarget);
13884 return performANDCombine(N, DCI);
13886 return performSRLCombine(N, DCI);
13887 case ISD::INTRINSIC_WO_CHAIN:
13888 return performIntrinsicCombine(N, DCI, Subtarget);
13889 case ISD::ANY_EXTEND:
13890 case ISD::ZERO_EXTEND:
13891 case ISD::SIGN_EXTEND:
13892 return performExtendCombine(N, DCI, DAG);
13893 case ISD::SIGN_EXTEND_INREG:
13894 return performSignExtendInRegCombine(N, DCI, DAG);
13895 case ISD::CONCAT_VECTORS:
13896 return performConcatVectorsCombine(N, DCI, DAG);
13898 return performSelectCombine(N, DCI);
13900 return performVSelectCombine(N, DCI.DAG);
13902 if (performTBISimplification(N->getOperand(1), DCI, DAG))
13903 return SDValue(N, 0);
13906 return performSTORECombine(N, DCI, DAG, Subtarget);
13907 case AArch64ISD::BRCOND:
13908 return performBRCONDCombine(N, DCI, DAG);
13909 case AArch64ISD::TBNZ:
13910 case AArch64ISD::TBZ:
13911 return performTBZCombine(N, DCI, DAG);
13912 case AArch64ISD::CSEL:
13913 return performCONDCombine(N, DCI, DAG, 2, 3);
13914 case AArch64ISD::DUP:
13915 return performPostLD1Combine(N, DCI, false);
13916 case AArch64ISD::NVCAST:
13917 return performNVCASTCombine(N);
13918 case ISD::INSERT_VECTOR_ELT:
13919 return performPostLD1Combine(N, DCI, true);
13920 case ISD::INTRINSIC_VOID:
13921 case ISD::INTRINSIC_W_CHAIN:
13922 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13923 case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
13924 return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
13925 case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
13926 return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
13927 case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
13928 return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
13929 case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
13930 return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
13931 case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
13932 case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
13933 case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
13934 case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
13935 case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
13936 case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
13937 case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
13938 case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
13939 return legalizeSVEGatherPrefetchOffsVec(N, DAG);
13940 case Intrinsic::aarch64_neon_ld2:
13941 case Intrinsic::aarch64_neon_ld3:
13942 case Intrinsic::aarch64_neon_ld4:
13943 case Intrinsic::aarch64_neon_ld1x2:
13944 case Intrinsic::aarch64_neon_ld1x3:
13945 case Intrinsic::aarch64_neon_ld1x4:
13946 case Intrinsic::aarch64_neon_ld2lane:
13947 case Intrinsic::aarch64_neon_ld3lane:
13948 case Intrinsic::aarch64_neon_ld4lane:
13949 case Intrinsic::aarch64_neon_ld2r:
13950 case Intrinsic::aarch64_neon_ld3r:
13951 case Intrinsic::aarch64_neon_ld4r:
13952 case Intrinsic::aarch64_neon_st2:
13953 case Intrinsic::aarch64_neon_st3:
13954 case Intrinsic::aarch64_neon_st4:
13955 case Intrinsic::aarch64_neon_st1x2:
13956 case Intrinsic::aarch64_neon_st1x3:
13957 case Intrinsic::aarch64_neon_st1x4:
13958 case Intrinsic::aarch64_neon_st2lane:
13959 case Intrinsic::aarch64_neon_st3lane:
13960 case Intrinsic::aarch64_neon_st4lane:
13961 return performNEONPostLDSTCombine(N, DCI, DAG);
13962 case Intrinsic::aarch64_sve_ldnt1:
13963 return performLDNT1Combine(N, DAG);
13964 case Intrinsic::aarch64_sve_ld1rq:
13965 return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
13966 case Intrinsic::aarch64_sve_ld1ro:
13967 return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
13968 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
13969 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13970 case Intrinsic::aarch64_sve_ldnt1_gather:
13971 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13972 case Intrinsic::aarch64_sve_ldnt1_gather_index:
13973 return performGatherLoadCombine(N, DAG,
13974 AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
13975 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
13976 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
13977 case Intrinsic::aarch64_sve_ld1:
13978 return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
13979 case Intrinsic::aarch64_sve_ldnf1:
13980 return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
13981 case Intrinsic::aarch64_sve_ldff1:
13982 return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
13983 case Intrinsic::aarch64_sve_st1:
13984 return performST1Combine(N, DAG);
13985 case Intrinsic::aarch64_sve_stnt1:
13986 return performSTNT1Combine(N, DAG);
13987 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
13988 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13989 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
13990 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13991 case Intrinsic::aarch64_sve_stnt1_scatter:
13992 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
13993 case Intrinsic::aarch64_sve_stnt1_scatter_index:
13994 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
13995 case Intrinsic::aarch64_sve_ld1_gather:
13996 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
13997 case Intrinsic::aarch64_sve_ld1_gather_index:
13998 return performGatherLoadCombine(N, DAG,
13999 AArch64ISD::GLD1_SCALED_MERGE_ZERO);
14000 case Intrinsic::aarch64_sve_ld1_gather_sxtw:
14001 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
14002 /*OnlyPackedOffsets=*/false);
14003 case Intrinsic::aarch64_sve_ld1_gather_uxtw:
14004 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
14005 /*OnlyPackedOffsets=*/false);
14006 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
14007 return performGatherLoadCombine(N, DAG,
14008 AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
14009 /*OnlyPackedOffsets=*/false);
14010 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
14011 return performGatherLoadCombine(N, DAG,
14012 AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
14013 /*OnlyPackedOffsets=*/false);
14014 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
14015 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
14016 case Intrinsic::aarch64_sve_ldff1_gather:
14017 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
14018 case Intrinsic::aarch64_sve_ldff1_gather_index:
14019 return performGatherLoadCombine(N, DAG,
14020 AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
14021 case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
14022 return performGatherLoadCombine(N, DAG,
14023 AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
14024 /*OnlyPackedOffsets=*/false);
14025 case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
14026 return performGatherLoadCombine(N, DAG,
14027 AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
14028 /*OnlyPackedOffsets=*/false);
14029 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
14030 return performGatherLoadCombine(N, DAG,
14031 AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
14032 /*OnlyPackedOffsets=*/false);
14033 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
14034 return performGatherLoadCombine(N, DAG,
14035 AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
14036 /*OnlyPackedOffsets=*/false);
14037 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
14038 return performGatherLoadCombine(N, DAG,
14039 AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
14040 case Intrinsic::aarch64_sve_st1_scatter:
14041 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
14042 case Intrinsic::aarch64_sve_st1_scatter_index:
14043 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
14044 case Intrinsic::aarch64_sve_st1_scatter_sxtw:
14045 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
14046 /*OnlyPackedOffsets=*/false);
14047 case Intrinsic::aarch64_sve_st1_scatter_uxtw:
14048 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
14049 /*OnlyPackedOffsets=*/false);
14050 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
14051 return performScatterStoreCombine(N, DAG,
14052 AArch64ISD::SST1_SXTW_SCALED_PRED,
14053 /*OnlyPackedOffsets=*/false);
14054 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
14055 return performScatterStoreCombine(N, DAG,
14056 AArch64ISD::SST1_UXTW_SCALED_PRED,
14057 /*OnlyPackedOffsets=*/false);
14058 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
14059 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
14060 case Intrinsic::aarch64_sve_tuple_get: {
14062 SDValue Chain = N->getOperand(0);
14063 SDValue Src1 = N->getOperand(2);
14064 SDValue Idx = N->getOperand(3);
14066 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14067 EVT ResVT = N->getValueType(0);
14068 uint64_t NumLanes = ResVT.getVectorElementCount().Min;
14070 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1,
14071 DAG.getConstant(IdxConst * NumLanes, DL, MVT::i32));
14072 return DAG.getMergeValues({Val, Chain}, DL);
14074 case Intrinsic::aarch64_sve_tuple_set: {
14076 SDValue Chain = N->getOperand(0);
14077 SDValue Tuple = N->getOperand(2);
14078 SDValue Idx = N->getOperand(3);
14079 SDValue Vec = N->getOperand(4);
14081 EVT TupleVT = Tuple.getValueType();
14082 uint64_t TupleLanes = TupleVT.getVectorElementCount().Min;
14084 uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
14085 uint64_t NumLanes = Vec.getValueType().getVectorElementCount().Min;
14087 if ((TupleLanes % NumLanes) != 0)
14088 report_fatal_error("invalid tuple vector!");
14090 uint64_t NumVecs = TupleLanes / NumLanes;
14092 SmallVector<SDValue, 4> Opnds;
14093 for (unsigned I = 0; I < NumVecs; ++I) {
14095 Opnds.push_back(Vec);
14098 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, Vec.getValueType(), Tuple,
14099 DAG.getConstant(I * NumLanes, DL, MVT::i32)));
14103 DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
14104 return DAG.getMergeValues({Concat, Chain}, DL);
14106 case Intrinsic::aarch64_sve_tuple_create2:
14107 case Intrinsic::aarch64_sve_tuple_create3:
14108 case Intrinsic::aarch64_sve_tuple_create4: {
14110 SDValue Chain = N->getOperand(0);
14112 SmallVector<SDValue, 4> Opnds;
14113 for (unsigned I = 2; I < N->getNumOperands(); ++I)
14114 Opnds.push_back(N->getOperand(I));
14116 EVT VT = Opnds[0].getValueType();
14117 EVT EltVT = VT.getVectorElementType();
14118 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
14119 VT.getVectorElementCount() *
14120 (N->getNumOperands() - 2));
14121 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
14122 return DAG.getMergeValues({Concat, Chain}, DL);
14124 case Intrinsic::aarch64_sve_ld2:
14125 case Intrinsic::aarch64_sve_ld3:
14126 case Intrinsic::aarch64_sve_ld4: {
14128 SDValue Chain = N->getOperand(0);
14129 SDValue Mask = N->getOperand(2);
14130 SDValue BasePtr = N->getOperand(3);
14131 SDValue LoadOps[] = {Chain, Mask, BasePtr};
14132 unsigned IntrinsicID =
14133 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14135 LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
14136 return DAG.getMergeValues({Result, Chain}, DL);
14142 case ISD::GlobalAddress:
14143 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
14148 // Check if the return value is used as only a return value, as otherwise
14149 // we can't perform a tail-call. In particular, we need to check for
14150 // target ISD nodes that are returns and any other "odd" constructs
14151 // that the generic analysis code won't necessarily catch.
14152 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
14153 SDValue &Chain) const {
14154 if (N->getNumValues() != 1)
14156 if (!N->hasNUsesOfValue(1, 0))
14159 SDValue TCChain = Chain;
14160 SDNode *Copy = *N->use_begin();
14161 if (Copy->getOpcode() == ISD::CopyToReg) {
14162 // If the copy has a glue operand, we conservatively assume it isn't safe to
14163 // perform a tail call.
14164 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
14167 TCChain = Copy->getOperand(0);
14168 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
14171 bool HasRet = false;
14172 for (SDNode *Node : Copy->uses()) {
14173 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
14185 // Return whether the an instruction can potentially be optimized to a tail
14186 // call. This will cause the optimizers to attempt to move, or duplicate,
14187 // return instructions to help enable tail call optimizations for this
14189 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
14190 return CI->isTailCall();
14193 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
14195 ISD::MemIndexedMode &AM,
14197 SelectionDAG &DAG) const {
14198 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
14201 Base = Op->getOperand(0);
14202 // All of the indexed addressing mode instructions take a signed
14203 // 9 bit immediate offset.
14204 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
14205 int64_t RHSC = RHS->getSExtValue();
14206 if (Op->getOpcode() == ISD::SUB)
14207 RHSC = -(uint64_t)RHSC;
14208 if (!isInt<9>(RHSC))
14210 IsInc = (Op->getOpcode() == ISD::ADD);
14211 Offset = Op->getOperand(1);
14217 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
14219 ISD::MemIndexedMode &AM,
14220 SelectionDAG &DAG) const {
14223 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14224 VT = LD->getMemoryVT();
14225 Ptr = LD->getBasePtr();
14226 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14227 VT = ST->getMemoryVT();
14228 Ptr = ST->getBasePtr();
14233 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
14235 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
14239 bool AArch64TargetLowering::getPostIndexedAddressParts(
14240 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
14241 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
14244 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
14245 VT = LD->getMemoryVT();
14246 Ptr = LD->getBasePtr();
14247 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
14248 VT = ST->getMemoryVT();
14249 Ptr = ST->getBasePtr();
14254 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
14256 // Post-indexing updates the base, so it's not a valid transform
14257 // if that's not the same as the load's pointer.
14260 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
14264 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
14265 SelectionDAG &DAG) {
14267 SDValue Op = N->getOperand(0);
14269 if (N->getValueType(0) != MVT::i16 ||
14270 (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
14274 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
14275 DAG.getUNDEF(MVT::i32), Op,
14276 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
14278 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
14279 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
14282 static void ReplaceReductionResults(SDNode *N,
14283 SmallVectorImpl<SDValue> &Results,
14284 SelectionDAG &DAG, unsigned InterOp,
14285 unsigned AcrossOp) {
14289 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
14290 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
14291 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
14292 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
14293 Results.push_back(SplitVal);
14296 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
14298 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
14299 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
14300 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
14301 DAG.getConstant(64, DL, MVT::i64)));
14302 return std::make_pair(Lo, Hi);
14305 void AArch64TargetLowering::ReplaceExtractSubVectorResults(
14306 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14307 SDValue In = N->getOperand(0);
14308 EVT InVT = In.getValueType();
14310 // Common code will handle these just fine.
14311 if (!InVT.isScalableVector() || !InVT.isInteger())
14315 EVT VT = N->getValueType(0);
14317 // The following checks bail if this is not a halving operation.
14319 ElementCount ResEC = VT.getVectorElementCount();
14321 if (InVT.getVectorElementCount().Min != (ResEC.Min * 2))
14324 auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
14328 unsigned Index = CIndex->getZExtValue();
14329 if ((Index != 0) && (Index != ResEC.Min))
14332 unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
14333 EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
14335 SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
14336 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
14339 // Create an even/odd pair of X registers holding integer value V.
14340 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
14341 SDLoc dl(V.getNode());
14342 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
14343 SDValue VHi = DAG.getAnyExtOrTrunc(
14344 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
14346 if (DAG.getDataLayout().isBigEndian())
14347 std::swap (VLo, VHi);
14349 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
14350 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
14351 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
14352 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
14354 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
14357 static void ReplaceCMP_SWAP_128Results(SDNode *N,
14358 SmallVectorImpl<SDValue> &Results,
14360 const AArch64Subtarget *Subtarget) {
14361 assert(N->getValueType(0) == MVT::i128 &&
14362 "AtomicCmpSwap on types less than 128 should be legal");
14364 if (Subtarget->hasLSE()) {
14365 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
14366 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
14368 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
14369 createGPRPairNode(DAG, N->getOperand(3)), // Store value
14370 N->getOperand(1), // Ptr
14371 N->getOperand(0), // Chain in
14374 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14377 switch (MemOp->getOrdering()) {
14378 case AtomicOrdering::Monotonic:
14379 Opcode = AArch64::CASPX;
14381 case AtomicOrdering::Acquire:
14382 Opcode = AArch64::CASPAX;
14384 case AtomicOrdering::Release:
14385 Opcode = AArch64::CASPLX;
14387 case AtomicOrdering::AcquireRelease:
14388 case AtomicOrdering::SequentiallyConsistent:
14389 Opcode = AArch64::CASPALX;
14392 llvm_unreachable("Unexpected ordering!");
14395 MachineSDNode *CmpSwap = DAG.getMachineNode(
14396 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
14397 DAG.setNodeMemRefs(CmpSwap, {MemOp});
14399 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
14400 if (DAG.getDataLayout().isBigEndian())
14401 std::swap(SubReg1, SubReg2);
14402 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
14403 SDValue(CmpSwap, 0));
14404 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
14405 SDValue(CmpSwap, 0));
14407 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
14408 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
14412 auto Desired = splitInt128(N->getOperand(2), DAG);
14413 auto New = splitInt128(N->getOperand(3), DAG);
14414 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
14415 New.first, New.second, N->getOperand(0)};
14416 SDNode *CmpSwap = DAG.getMachineNode(
14417 AArch64::CMP_SWAP_128, SDLoc(N),
14418 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
14420 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
14421 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
14423 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14424 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
14425 Results.push_back(SDValue(CmpSwap, 3));
14428 void AArch64TargetLowering::ReplaceNodeResults(
14429 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
14430 switch (N->getOpcode()) {
14432 llvm_unreachable("Don't know how to custom expand this");
14434 ReplaceBITCASTResults(N, Results, DAG);
14436 case ISD::VECREDUCE_ADD:
14437 case ISD::VECREDUCE_SMAX:
14438 case ISD::VECREDUCE_SMIN:
14439 case ISD::VECREDUCE_UMAX:
14440 case ISD::VECREDUCE_UMIN:
14441 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
14445 Results.push_back(LowerCTPOP(SDValue(N, 0), DAG));
14447 case AArch64ISD::SADDV:
14448 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
14450 case AArch64ISD::UADDV:
14451 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
14453 case AArch64ISD::SMINV:
14454 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
14456 case AArch64ISD::UMINV:
14457 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
14459 case AArch64ISD::SMAXV:
14460 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
14462 case AArch64ISD::UMAXV:
14463 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
14465 case ISD::FP_TO_UINT:
14466 case ISD::FP_TO_SINT:
14467 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
14468 // Let normal code take care of it by not adding anything to Results.
14470 case ISD::ATOMIC_CMP_SWAP:
14471 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
14474 assert(SDValue(N, 0).getValueType() == MVT::i128 &&
14475 "unexpected load's value type");
14476 LoadSDNode *LoadNode = cast<LoadSDNode>(N);
14477 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
14478 // Non-volatile loads are optimized later in AArch64's load/store
14483 SDValue Result = DAG.getMemIntrinsicNode(
14484 AArch64ISD::LDP, SDLoc(N),
14485 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
14486 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
14487 LoadNode->getMemOperand());
14489 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
14490 Result.getValue(0), Result.getValue(1));
14491 Results.append({Pair, Result.getValue(2) /* Chain */});
14494 case ISD::EXTRACT_SUBVECTOR:
14495 ReplaceExtractSubVectorResults(N, Results, DAG);
14497 case ISD::INTRINSIC_WO_CHAIN: {
14498 EVT VT = N->getValueType(0);
14499 assert((VT == MVT::i8 || VT == MVT::i16) &&
14500 "custom lowering for unexpected type");
14502 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
14503 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
14507 case Intrinsic::aarch64_sve_clasta_n: {
14509 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14510 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
14511 N->getOperand(1), Op2, N->getOperand(3));
14512 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14515 case Intrinsic::aarch64_sve_clastb_n: {
14517 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
14518 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
14519 N->getOperand(1), Op2, N->getOperand(3));
14520 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14523 case Intrinsic::aarch64_sve_lasta: {
14525 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
14526 N->getOperand(1), N->getOperand(2));
14527 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14530 case Intrinsic::aarch64_sve_lastb: {
14532 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
14533 N->getOperand(1), N->getOperand(2));
14534 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
14542 bool AArch64TargetLowering::useLoadStackGuardNode() const {
14543 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
14544 return TargetLowering::useLoadStackGuardNode();
14548 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
14549 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
14550 // reciprocal if there are three or more FDIVs.
14554 TargetLoweringBase::LegalizeTypeAction
14555 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
14556 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
14557 // v4i16, v2i32 instead of to promote.
14558 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
14560 return TypeWidenVector;
14562 return TargetLoweringBase::getPreferredVectorAction(VT);
14565 // Loads and stores less than 128-bits are already atomic; ones above that
14566 // are doomed anyway, so defer to the default libcall and blame the OS when
14567 // things go wrong.
14568 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14569 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14570 return Size == 128;
14573 // Loads and stores less than 128-bits are already atomic; ones above that
14574 // are doomed anyway, so defer to the default libcall and blame the OS when
14575 // things go wrong.
14576 TargetLowering::AtomicExpansionKind
14577 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14578 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14579 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
14582 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
14583 TargetLowering::AtomicExpansionKind
14584 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14585 if (AI->isFloatingPointOperation())
14586 return AtomicExpansionKind::CmpXChg;
14588 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14589 if (Size > 128) return AtomicExpansionKind::None;
14590 // Nand not supported in LSE.
14591 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
14592 // Leave 128 bits to LLSC.
14593 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
14596 TargetLowering::AtomicExpansionKind
14597 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
14598 AtomicCmpXchgInst *AI) const {
14599 // If subtarget has LSE, leave cmpxchg intact for codegen.
14600 if (Subtarget->hasLSE())
14601 return AtomicExpansionKind::None;
14602 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14603 // implement cmpxchg without spilling. If the address being exchanged is also
14604 // on the stack and close enough to the spill slot, this can lead to a
14605 // situation where the monitor always gets cleared and the atomic operation
14606 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14607 if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
14608 return AtomicExpansionKind::None;
14609 return AtomicExpansionKind::LLSC;
14612 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14613 AtomicOrdering Ord) const {
14614 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14615 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14616 bool IsAcquire = isAcquireOrStronger(Ord);
14618 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
14619 // intrinsic must return {i64, i64} and we have to recombine them into a
14620 // single i128 here.
14621 if (ValTy->getPrimitiveSizeInBits() == 128) {
14622 Intrinsic::ID Int =
14623 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
14624 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
14626 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14627 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
14629 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14630 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14631 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14632 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14633 return Builder.CreateOr(
14634 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
14637 Type *Tys[] = { Addr->getType() };
14638 Intrinsic::ID Int =
14639 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
14640 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
14642 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
14644 const DataLayout &DL = M->getDataLayout();
14645 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
14646 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
14648 return Builder.CreateBitCast(Trunc, EltTy);
14651 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14652 IRBuilder<> &Builder) const {
14653 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14654 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
14657 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
14658 Value *Val, Value *Addr,
14659 AtomicOrdering Ord) const {
14660 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14661 bool IsRelease = isReleaseOrStronger(Ord);
14663 // Since the intrinsics must have legal type, the i128 intrinsics take two
14664 // parameters: "i64, i64". We must marshal Val into the appropriate form
14665 // before the call.
14666 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
14667 Intrinsic::ID Int =
14668 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
14669 Function *Stxr = Intrinsic::getDeclaration(M, Int);
14670 Type *Int64Ty = Type::getInt64Ty(M->getContext());
14672 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
14673 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
14674 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14675 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
14678 Intrinsic::ID Int =
14679 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
14680 Type *Tys[] = { Addr->getType() };
14681 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
14683 const DataLayout &DL = M->getDataLayout();
14684 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
14685 Val = Builder.CreateBitCast(Val, IntValTy);
14687 return Builder.CreateCall(Stxr,
14688 {Builder.CreateZExtOrBitCast(
14689 Val, Stxr->getFunctionType()->getParamType(0)),
14693 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
14694 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14695 return Ty->isArrayTy();
14698 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
14703 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
14704 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
14705 Function *ThreadPointerFunc =
14706 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
14707 return IRB.CreatePointerCast(
14708 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
14710 IRB.getInt8PtrTy()->getPointerTo(0));
14713 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
14714 // Android provides a fixed TLS slot for the stack cookie. See the definition
14715 // of TLS_SLOT_STACK_GUARD in
14716 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14717 if (Subtarget->isTargetAndroid())
14718 return UseTlsOffset(IRB, 0x28);
14720 // Fuchsia is similar.
14721 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
14722 if (Subtarget->isTargetFuchsia())
14723 return UseTlsOffset(IRB, -0x10);
14725 return TargetLowering::getIRStackGuard(IRB);
14728 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
14729 // MSVC CRT provides functionalities for stack protection.
14730 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
14731 // MSVC CRT has a global variable holding security cookie.
14732 M.getOrInsertGlobal("__security_cookie",
14733 Type::getInt8PtrTy(M.getContext()));
14735 // MSVC CRT has a function to validate security cookie.
14736 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
14737 "__security_check_cookie", Type::getVoidTy(M.getContext()),
14738 Type::getInt8PtrTy(M.getContext()));
14739 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
14740 F->setCallingConv(CallingConv::Win64);
14741 F->addAttribute(1, Attribute::AttrKind::InReg);
14745 TargetLowering::insertSSPDeclarations(M);
14748 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
14749 // MSVC CRT has a global variable holding security cookie.
14750 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14751 return M.getGlobalVariable("__security_cookie");
14752 return TargetLowering::getSDagStackGuard(M);
14755 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
14756 // MSVC CRT has a function to validate security cookie.
14757 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
14758 return M.getFunction("__security_check_cookie");
14759 return TargetLowering::getSSPStackGuardCheck(M);
14762 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
14763 // Android provides a fixed TLS slot for the SafeStack pointer. See the
14764 // definition of TLS_SLOT_SAFESTACK in
14765 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
14766 if (Subtarget->isTargetAndroid())
14767 return UseTlsOffset(IRB, 0x48);
14769 // Fuchsia is similar.
14770 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
14771 if (Subtarget->isTargetFuchsia())
14772 return UseTlsOffset(IRB, -0x8);
14774 return TargetLowering::getSafeStackPointerLocation(IRB);
14777 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
14778 const Instruction &AndI) const {
14779 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
14780 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
14781 // may be beneficial to sink in other cases, but we would have to check that
14782 // the cmp would not get folded into the br to form a cbz for these to be
14784 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
14787 return Mask->getValue().isPowerOf2();
14790 bool AArch64TargetLowering::
14791 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14792 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
14793 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
14794 SelectionDAG &DAG) const {
14795 // Does baseline recommend not to perform the fold by default?
14796 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
14797 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
14799 // Else, if this is a vector shift, prefer 'shl'.
14800 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
14803 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
14805 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
14806 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
14811 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14812 // Update IsSplitCSR in AArch64unctionInfo.
14813 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
14814 AFI->setIsSplitCSR(true);
14817 void AArch64TargetLowering::insertCopiesSplitCSR(
14818 MachineBasicBlock *Entry,
14819 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14820 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
14821 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14825 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14826 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14827 MachineBasicBlock::iterator MBBI = Entry->begin();
14828 for (const MCPhysReg *I = IStart; *I; ++I) {
14829 const TargetRegisterClass *RC = nullptr;
14830 if (AArch64::GPR64RegClass.contains(*I))
14831 RC = &AArch64::GPR64RegClass;
14832 else if (AArch64::FPR64RegClass.contains(*I))
14833 RC = &AArch64::FPR64RegClass;
14835 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14837 Register NewVR = MRI->createVirtualRegister(RC);
14838 // Create copy from CSR to a virtual register.
14839 // FIXME: this currently does not emit CFI pseudo-instructions, it works
14840 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14841 // nounwind. If we want to generalize this later, we may need to emit
14842 // CFI pseudo-instructions.
14843 assert(Entry->getParent()->getFunction().hasFnAttribute(
14844 Attribute::NoUnwind) &&
14845 "Function should be nounwind in insertCopiesSplitCSR!");
14846 Entry->addLiveIn(*I);
14847 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14850 // Insert the copy-back instructions right before the terminator.
14851 for (auto *Exit : Exits)
14852 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14853 TII->get(TargetOpcode::COPY), *I)
14858 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
14859 // Integer division on AArch64 is expensive. However, when aggressively
14860 // optimizing for code size, we prefer to use a div instruction, as it is
14861 // usually smaller than the alternative sequence.
14862 // The exception to this is vector division. Since AArch64 doesn't have vector
14863 // integer division, leaving the division as-is is a loss even in terms of
14864 // size, because it will have to be scalarized, while the alternative code
14865 // sequence can be performed in vector form.
14866 bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
14867 return OptSize && !VT.isVector();
14870 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
14871 // We want inc-of-add for scalars and sub-of-not for vectors.
14872 return VT.isScalarInteger();
14875 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
14876 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
14880 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
14881 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
14882 return getPointerTy(DL).getSizeInBits();
14884 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
14887 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
14888 MF.getFrameInfo().computeMaxCallFrameSize(MF);
14889 TargetLoweringBase::finalizeLowering(MF);
14892 // Unlike X86, we let frame lowering assign offsets to all catch objects.
14893 bool AArch64TargetLowering::needsFixedCatchObjects() const {
14897 bool AArch64TargetLowering::shouldLocalize(
14898 const MachineInstr &MI, const TargetTransformInfo *TTI) const {
14899 switch (MI.getOpcode()) {
14900 case TargetOpcode::G_GLOBAL_VALUE: {
14901 // On Darwin, TLS global vars get selected into function calls, which
14902 // we don't want localized, as they can get moved into the middle of a
14903 // another call sequence.
14904 const GlobalValue &GV = *MI.getOperand(1).getGlobal();
14905 if (GV.isThreadLocal() && Subtarget->isTargetMachO())
14909 // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
14911 case AArch64::ADRP:
14912 case AArch64::G_ADD_LOW:
14917 return TargetLoweringBase::shouldLocalize(MI, TTI);
14920 bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
14921 if (isa<ScalableVectorType>(Inst.getType()))
14924 for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
14925 if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
14928 if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
14929 if (isa<ScalableVectorType>(AI->getAllocatedType()))
14936 // Return the largest legal scalable vector type that matches VT's element type.
14937 static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
14938 assert(VT.isFixedLengthVector() &&
14939 DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14940 "Expected legal fixed length vector!");
14941 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
14943 llvm_unreachable("unexpected element type for SVE container");
14945 return EVT(MVT::nxv16i8);
14947 return EVT(MVT::nxv8i16);
14949 return EVT(MVT::nxv4i32);
14951 return EVT(MVT::nxv2i64);
14953 return EVT(MVT::nxv8f16);
14955 return EVT(MVT::nxv4f32);
14957 return EVT(MVT::nxv2f64);
14961 // Return a PTRUE with active lanes corresponding to the extent of VT.
14962 static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
14964 assert(VT.isFixedLengthVector() &&
14965 DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14966 "Expected legal fixed length vector!");
14969 switch (VT.getVectorNumElements()) {
14971 llvm_unreachable("unexpected element count for SVE predicate");
14973 PgPattern = AArch64SVEPredPattern::vl1;
14976 PgPattern = AArch64SVEPredPattern::vl2;
14979 PgPattern = AArch64SVEPredPattern::vl4;
14982 PgPattern = AArch64SVEPredPattern::vl8;
14985 PgPattern = AArch64SVEPredPattern::vl16;
14988 PgPattern = AArch64SVEPredPattern::vl32;
14991 PgPattern = AArch64SVEPredPattern::vl64;
14994 PgPattern = AArch64SVEPredPattern::vl128;
14997 PgPattern = AArch64SVEPredPattern::vl256;
15001 // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
15002 // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
15003 // variants of instructions when available.
15006 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
15008 llvm_unreachable("unexpected element type for SVE predicate");
15010 MaskVT = MVT::nxv16i1;
15014 MaskVT = MVT::nxv8i1;
15018 MaskVT = MVT::nxv4i1;
15022 MaskVT = MVT::nxv2i1;
15026 return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
15027 DAG.getTargetConstant(PgPattern, DL, MVT::i64));
15030 static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
15032 assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15033 "Expected legal scalable vector!");
15034 auto PredTy = VT.changeVectorElementType(MVT::i1);
15035 return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
15038 static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
15039 if (VT.isFixedLengthVector())
15040 return getPredicateForFixedLengthVector(DAG, DL, VT);
15042 return getPredicateForScalableVector(DAG, DL, VT);
15045 // Grow V to consume an entire SVE register.
15046 static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15047 assert(VT.isScalableVector() &&
15048 "Expected to convert into a scalable vector!");
15049 assert(V.getValueType().isFixedLengthVector() &&
15050 "Expected a fixed length vector operand!");
15052 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15053 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
15056 // Shrink V so it's just big enough to maintain a VT's worth of data.
15057 static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
15058 assert(VT.isFixedLengthVector() &&
15059 "Expected to convert into a fixed length vector!");
15060 assert(V.getValueType().isScalableVector() &&
15061 "Expected a scalable vector operand!");
15063 SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
15064 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
15067 // Convert all fixed length vector loads larger than NEON to masked_loads.
15068 SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
15069 SDValue Op, SelectionDAG &DAG) const {
15070 auto Load = cast<LoadSDNode>(Op);
15073 EVT VT = Op.getValueType();
15074 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15076 auto NewLoad = DAG.getMaskedLoad(
15077 ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
15078 getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
15079 Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
15080 Load->getExtensionType());
15082 auto Result = convertFromScalableVector(DAG, VT, NewLoad);
15083 SDValue MergedValues[2] = {Result, Load->getChain()};
15084 return DAG.getMergeValues(MergedValues, DL);
15087 // Convert all fixed length vector stores larger than NEON to masked_stores.
15088 SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
15089 SDValue Op, SelectionDAG &DAG) const {
15090 auto Store = cast<StoreSDNode>(Op);
15093 EVT VT = Store->getValue().getValueType();
15094 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15096 auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
15097 return DAG.getMaskedStore(
15098 Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
15099 getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
15100 Store->getMemOperand(), Store->getAddressingMode(),
15101 Store->isTruncatingStore());
15104 SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
15105 SDValue Op, SelectionDAG &DAG) const {
15106 EVT VT = Op.getValueType();
15107 assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
15110 SDValue Val = Op.getOperand(0);
15111 EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
15112 Val = convertToScalableVector(DAG, ContainerVT, Val);
15114 // Repeatedly truncate Val until the result is of the desired element type.
15115 switch (ContainerVT.getSimpleVT().SimpleTy) {
15117 llvm_unreachable("unimplemented container type");
15119 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
15120 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
15121 if (VT.getVectorElementType() == MVT::i32)
15125 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
15126 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
15127 if (VT.getVectorElementType() == MVT::i16)
15131 Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
15132 Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
15133 assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
15137 return convertFromScalableVector(DAG, VT, Val);
15140 SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
15142 unsigned NewOp) const {
15143 EVT VT = Op.getValueType();
15145 auto Pg = getPredicateForVector(DAG, DL, VT);
15147 if (useSVEForFixedLengthVectorVT(VT)) {
15148 EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
15150 // Create list of operands by convereting existing ones to scalable types.
15151 SmallVector<SDValue, 4> Operands = {Pg};
15152 for (const SDValue &V : Op->op_values()) {
15153 if (isa<CondCodeSDNode>(V)) {
15154 Operands.push_back(V);
15158 assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
15159 "Only fixed length vectors are supported!");
15160 Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
15163 auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
15164 return convertFromScalableVector(DAG, VT, ScalableRes);
15167 assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
15169 SmallVector<SDValue, 4> Operands = {Pg};
15170 for (const SDValue &V : Op->op_values()) {
15171 assert((isa<CondCodeSDNode>(V) || V.getValueType().isScalableVector()) &&
15172 "Only scalable vectors are supported!");
15173 Operands.push_back(V);
15176 return DAG.getNode(NewOp, DL, VT, Operands);