[PowerPC] Collect some CallLowering arguments into a struct. [NFC]
[llvm-project.git] / llvm / lib / Target / AArch64 / AArch64ISelLowering.cpp
blobe5bdf22e2cd25c2e226e82ad54997628d24e9a41
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the AArch64TargetLowering class.
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"
81 #include <algorithm>
82 #include <bitset>
83 #include <cassert>
84 #include <cctype>
85 #include <cstdint>
86 #include <cstdlib>
87 #include <iterator>
88 #include <limits>
89 #include <tuple>
90 #include <utility>
91 #include <vector>
93 using namespace llvm;
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 static cl::opt<bool>
103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
104 cl::desc("Allow AArch64 SLI/SRI formation"),
105 cl::init(false));
107 // FIXME: The necessary dtprel relocations don't seem to be supported
108 // well in the GNU bfd and gold linkers at the moment. Therefore, by
109 // default, for now, fall back to GeneralDynamic code generation.
110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
111 "aarch64-elf-ldtls-generation", cl::Hidden,
112 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
113 cl::init(false));
115 static cl::opt<bool>
116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
117 cl::desc("Enable AArch64 logical imm instruction "
118 "optimization"),
119 cl::init(true));
121 /// Value type used for condition codes.
122 static const MVT MVT_CC = MVT::i32;
124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
125 const AArch64Subtarget &STI)
126 : TargetLowering(TM), Subtarget(&STI) {
127 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
128 // we have to make something up. Arbitrarily, choose ZeroOrOne.
129 setBooleanContents(ZeroOrOneBooleanContent);
130 // When comparing vectors the result sets the different elements in the
131 // vector to all-one or all-zero.
132 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
134 // Set up the register classes.
135 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
136 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
138 if (Subtarget->hasFPARMv8()) {
139 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
140 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
141 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
142 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
145 if (Subtarget->hasNEON()) {
146 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
147 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
148 // Someone set us up the NEON.
149 addDRTypeForNEON(MVT::v2f32);
150 addDRTypeForNEON(MVT::v8i8);
151 addDRTypeForNEON(MVT::v4i16);
152 addDRTypeForNEON(MVT::v2i32);
153 addDRTypeForNEON(MVT::v1i64);
154 addDRTypeForNEON(MVT::v1f64);
155 addDRTypeForNEON(MVT::v4f16);
157 addQRTypeForNEON(MVT::v4f32);
158 addQRTypeForNEON(MVT::v2f64);
159 addQRTypeForNEON(MVT::v16i8);
160 addQRTypeForNEON(MVT::v8i16);
161 addQRTypeForNEON(MVT::v4i32);
162 addQRTypeForNEON(MVT::v2i64);
163 addQRTypeForNEON(MVT::v8f16);
166 if (Subtarget->hasSVE()) {
167 // Add legal sve predicate types
168 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
169 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
170 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
171 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
173 // Add legal sve data types
174 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
175 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
176 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
177 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
179 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
180 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
181 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
186 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
187 setOperationAction(ISD::SADDSAT, VT, Legal);
188 setOperationAction(ISD::UADDSAT, VT, Legal);
189 setOperationAction(ISD::SSUBSAT, VT, Legal);
190 setOperationAction(ISD::USUBSAT, VT, Legal);
191 setOperationAction(ISD::SMAX, VT, Legal);
192 setOperationAction(ISD::UMAX, VT, Legal);
193 setOperationAction(ISD::SMIN, VT, Legal);
194 setOperationAction(ISD::UMIN, VT, Legal);
197 for (auto VT :
198 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
199 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
200 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
203 // Compute derived properties from the register classes
204 computeRegisterProperties(Subtarget->getRegisterInfo());
206 // Provide all sorts of operation actions
207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
209 setOperationAction(ISD::SETCC, MVT::i32, Custom);
210 setOperationAction(ISD::SETCC, MVT::i64, Custom);
211 setOperationAction(ISD::SETCC, MVT::f16, Custom);
212 setOperationAction(ISD::SETCC, MVT::f32, Custom);
213 setOperationAction(ISD::SETCC, MVT::f64, Custom);
214 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
215 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
216 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
217 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
218 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
219 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
220 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
221 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
222 setOperationAction(ISD::SELECT, MVT::i32, Custom);
223 setOperationAction(ISD::SELECT, MVT::i64, Custom);
224 setOperationAction(ISD::SELECT, MVT::f16, Custom);
225 setOperationAction(ISD::SELECT, MVT::f32, Custom);
226 setOperationAction(ISD::SELECT, MVT::f64, Custom);
227 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
228 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
229 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
230 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
231 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
232 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
233 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
235 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
236 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
237 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
239 setOperationAction(ISD::FREM, MVT::f32, Expand);
240 setOperationAction(ISD::FREM, MVT::f64, Expand);
241 setOperationAction(ISD::FREM, MVT::f80, Expand);
243 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
245 // Custom lowering hooks are needed for XOR
246 // to fold it into CSINC/CSINV.
247 setOperationAction(ISD::XOR, MVT::i32, Custom);
248 setOperationAction(ISD::XOR, MVT::i64, Custom);
250 // Virtually no operation on f128 is legal, but LLVM can't expand them when
251 // there's a valid register class, so we need custom operations in most cases.
252 setOperationAction(ISD::FABS, MVT::f128, Expand);
253 setOperationAction(ISD::FADD, MVT::f128, Custom);
254 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
255 setOperationAction(ISD::FCOS, MVT::f128, Expand);
256 setOperationAction(ISD::FDIV, MVT::f128, Custom);
257 setOperationAction(ISD::FMA, MVT::f128, Expand);
258 setOperationAction(ISD::FMUL, MVT::f128, Custom);
259 setOperationAction(ISD::FNEG, MVT::f128, Expand);
260 setOperationAction(ISD::FPOW, MVT::f128, Expand);
261 setOperationAction(ISD::FREM, MVT::f128, Expand);
262 setOperationAction(ISD::FRINT, MVT::f128, Expand);
263 setOperationAction(ISD::FSIN, MVT::f128, Expand);
264 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
265 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
266 setOperationAction(ISD::FSUB, MVT::f128, Custom);
267 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
268 setOperationAction(ISD::SETCC, MVT::f128, Custom);
269 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
270 setOperationAction(ISD::SELECT, MVT::f128, Custom);
271 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
272 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
274 // Lowering for many of the conversions is actually specified by the non-f128
275 // type. The LowerXXX function will be trivial when f128 isn't involved.
276 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
277 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
278 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
279 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
280 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
281 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
282 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
283 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
284 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
285 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
286 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
287 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
288 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
289 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
291 // Variable arguments.
292 setOperationAction(ISD::VASTART, MVT::Other, Custom);
293 setOperationAction(ISD::VAARG, MVT::Other, Custom);
294 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
295 setOperationAction(ISD::VAEND, MVT::Other, Expand);
297 // Variable-sized objects.
298 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
299 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
301 if (Subtarget->isTargetWindows())
302 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
303 else
304 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
306 // Constant pool entries
307 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
309 // BlockAddress
310 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
312 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
313 setOperationAction(ISD::ADDC, MVT::i32, Custom);
314 setOperationAction(ISD::ADDE, MVT::i32, Custom);
315 setOperationAction(ISD::SUBC, MVT::i32, Custom);
316 setOperationAction(ISD::SUBE, MVT::i32, Custom);
317 setOperationAction(ISD::ADDC, MVT::i64, Custom);
318 setOperationAction(ISD::ADDE, MVT::i64, Custom);
319 setOperationAction(ISD::SUBC, MVT::i64, Custom);
320 setOperationAction(ISD::SUBE, MVT::i64, Custom);
322 // AArch64 lacks both left-rotate and popcount instructions.
323 setOperationAction(ISD::ROTL, MVT::i32, Expand);
324 setOperationAction(ISD::ROTL, MVT::i64, Expand);
325 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
326 setOperationAction(ISD::ROTL, VT, Expand);
327 setOperationAction(ISD::ROTR, VT, Expand);
330 // AArch64 doesn't have {U|S}MUL_LOHI.
331 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
332 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
334 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
335 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
337 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
338 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
339 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
340 setOperationAction(ISD::SDIVREM, VT, Expand);
341 setOperationAction(ISD::UDIVREM, VT, Expand);
343 setOperationAction(ISD::SREM, MVT::i32, Expand);
344 setOperationAction(ISD::SREM, MVT::i64, Expand);
345 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
346 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
347 setOperationAction(ISD::UREM, MVT::i32, Expand);
348 setOperationAction(ISD::UREM, MVT::i64, Expand);
350 // Custom lower Add/Sub/Mul with overflow.
351 setOperationAction(ISD::SADDO, MVT::i32, Custom);
352 setOperationAction(ISD::SADDO, MVT::i64, Custom);
353 setOperationAction(ISD::UADDO, MVT::i32, Custom);
354 setOperationAction(ISD::UADDO, MVT::i64, Custom);
355 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
356 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
357 setOperationAction(ISD::USUBO, MVT::i32, Custom);
358 setOperationAction(ISD::USUBO, MVT::i64, Custom);
359 setOperationAction(ISD::SMULO, MVT::i32, Custom);
360 setOperationAction(ISD::SMULO, MVT::i64, Custom);
361 setOperationAction(ISD::UMULO, MVT::i32, Custom);
362 setOperationAction(ISD::UMULO, MVT::i64, Custom);
364 setOperationAction(ISD::FSIN, MVT::f32, Expand);
365 setOperationAction(ISD::FSIN, MVT::f64, Expand);
366 setOperationAction(ISD::FCOS, MVT::f32, Expand);
367 setOperationAction(ISD::FCOS, MVT::f64, Expand);
368 setOperationAction(ISD::FPOW, MVT::f32, Expand);
369 setOperationAction(ISD::FPOW, MVT::f64, Expand);
370 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
371 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
372 if (Subtarget->hasFullFP16())
373 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
374 else
375 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
377 setOperationAction(ISD::FREM, MVT::f16, Promote);
378 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
379 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
380 setOperationAction(ISD::FPOW, MVT::f16, Promote);
381 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
382 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
383 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
384 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
385 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
386 setOperationAction(ISD::FCOS, MVT::f16, Promote);
387 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
388 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
389 setOperationAction(ISD::FSIN, MVT::f16, Promote);
390 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
391 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
392 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
393 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
394 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
395 setOperationAction(ISD::FEXP, MVT::f16, Promote);
396 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
397 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
398 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
399 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
400 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
401 setOperationAction(ISD::FLOG, MVT::f16, Promote);
402 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
403 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
404 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
405 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
406 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
407 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
408 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
409 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
411 if (!Subtarget->hasFullFP16()) {
412 setOperationAction(ISD::SELECT, MVT::f16, Promote);
413 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
414 setOperationAction(ISD::SETCC, MVT::f16, Promote);
415 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
416 setOperationAction(ISD::FADD, MVT::f16, Promote);
417 setOperationAction(ISD::FSUB, MVT::f16, Promote);
418 setOperationAction(ISD::FMUL, MVT::f16, Promote);
419 setOperationAction(ISD::FDIV, MVT::f16, Promote);
420 setOperationAction(ISD::FMA, MVT::f16, Promote);
421 setOperationAction(ISD::FNEG, MVT::f16, Promote);
422 setOperationAction(ISD::FABS, MVT::f16, Promote);
423 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
424 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
425 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
426 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
427 setOperationAction(ISD::FRINT, MVT::f16, Promote);
428 setOperationAction(ISD::FROUND, MVT::f16, Promote);
429 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
430 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
431 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
432 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
433 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
435 // promote v4f16 to v4f32 when that is known to be safe.
436 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
437 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
438 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
439 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
440 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
441 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
442 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
443 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
445 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
446 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
447 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
448 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
449 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
450 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
451 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
452 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
453 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
455 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
456 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
457 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
458 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
459 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
461 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
462 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
463 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
465 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
466 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
467 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
468 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
469 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
470 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
471 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
472 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
473 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
474 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
475 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
476 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
477 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
478 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
479 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
480 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
483 // AArch64 has implementations of a lot of rounding-like FP operations.
484 for (MVT Ty : {MVT::f32, MVT::f64}) {
485 setOperationAction(ISD::FFLOOR, Ty, Legal);
486 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
487 setOperationAction(ISD::FCEIL, Ty, Legal);
488 setOperationAction(ISD::FRINT, Ty, Legal);
489 setOperationAction(ISD::FTRUNC, Ty, Legal);
490 setOperationAction(ISD::FROUND, Ty, Legal);
491 setOperationAction(ISD::FMINNUM, Ty, Legal);
492 setOperationAction(ISD::FMAXNUM, Ty, Legal);
493 setOperationAction(ISD::FMINIMUM, Ty, Legal);
494 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
495 setOperationAction(ISD::LROUND, Ty, Legal);
496 setOperationAction(ISD::LLROUND, Ty, Legal);
497 setOperationAction(ISD::LRINT, Ty, Legal);
498 setOperationAction(ISD::LLRINT, Ty, Legal);
501 if (Subtarget->hasFullFP16()) {
502 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
503 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
504 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
505 setOperationAction(ISD::FRINT, MVT::f16, Legal);
506 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
507 setOperationAction(ISD::FROUND, MVT::f16, Legal);
508 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
509 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
510 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
511 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
514 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
516 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
518 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
524 // 128-bit loads and stores can be done without expanding
525 setOperationAction(ISD::LOAD, MVT::i128, Custom);
526 setOperationAction(ISD::STORE, MVT::i128, Custom);
528 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
529 // custom lowering, as there are no un-paired non-temporal stores and
530 // legalization will break up 256 bit inputs.
531 setOperationAction(ISD::STORE, MVT::v32i8, Custom);
532 setOperationAction(ISD::STORE, MVT::v16i16, Custom);
533 setOperationAction(ISD::STORE, MVT::v16f16, Custom);
534 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
535 setOperationAction(ISD::STORE, MVT::v8f32, Custom);
536 setOperationAction(ISD::STORE, MVT::v4f64, Custom);
537 setOperationAction(ISD::STORE, MVT::v4i64, Custom);
539 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
540 // This requires the Performance Monitors extension.
541 if (Subtarget->hasPerfMon())
542 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
544 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
545 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
546 // Issue __sincos_stret if available.
547 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
548 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
549 } else {
550 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
551 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554 if (Subtarget->getTargetTriple().isOSMSVCRT()) {
555 // MSVCRT doesn't have powi; fall back to pow
556 setLibcallName(RTLIB::POWI_F32, nullptr);
557 setLibcallName(RTLIB::POWI_F64, nullptr);
560 // Make floating-point constants legal for the large code model, so they don't
561 // become loads from the constant pool.
562 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
563 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
564 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
567 // AArch64 does not have floating-point extending loads, i1 sign-extending
568 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
569 for (MVT VT : MVT::fp_valuetypes()) {
570 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
571 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
572 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
573 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
575 for (MVT VT : MVT::integer_valuetypes())
576 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
578 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
579 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
580 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
581 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
582 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
583 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
584 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
586 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
587 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
589 // Indexed loads and stores are supported.
590 for (unsigned im = (unsigned)ISD::PRE_INC;
591 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
592 setIndexedLoadAction(im, MVT::i8, Legal);
593 setIndexedLoadAction(im, MVT::i16, Legal);
594 setIndexedLoadAction(im, MVT::i32, Legal);
595 setIndexedLoadAction(im, MVT::i64, Legal);
596 setIndexedLoadAction(im, MVT::f64, Legal);
597 setIndexedLoadAction(im, MVT::f32, Legal);
598 setIndexedLoadAction(im, MVT::f16, Legal);
599 setIndexedStoreAction(im, MVT::i8, Legal);
600 setIndexedStoreAction(im, MVT::i16, Legal);
601 setIndexedStoreAction(im, MVT::i32, Legal);
602 setIndexedStoreAction(im, MVT::i64, Legal);
603 setIndexedStoreAction(im, MVT::f64, Legal);
604 setIndexedStoreAction(im, MVT::f32, Legal);
605 setIndexedStoreAction(im, MVT::f16, Legal);
608 // Trap.
609 setOperationAction(ISD::TRAP, MVT::Other, Legal);
610 if (Subtarget->isTargetWindows())
611 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
613 // We combine OR nodes for bitfield operations.
614 setTargetDAGCombine(ISD::OR);
615 // Try to create BICs for vector ANDs.
616 setTargetDAGCombine(ISD::AND);
618 // Vector add and sub nodes may conceal a high-half opportunity.
619 // Also, try to fold ADD into CSINC/CSINV..
620 setTargetDAGCombine(ISD::ADD);
621 setTargetDAGCombine(ISD::SUB);
622 setTargetDAGCombine(ISD::SRL);
623 setTargetDAGCombine(ISD::XOR);
624 setTargetDAGCombine(ISD::SINT_TO_FP);
625 setTargetDAGCombine(ISD::UINT_TO_FP);
627 setTargetDAGCombine(ISD::FP_TO_SINT);
628 setTargetDAGCombine(ISD::FP_TO_UINT);
629 setTargetDAGCombine(ISD::FDIV);
631 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
633 setTargetDAGCombine(ISD::ANY_EXTEND);
634 setTargetDAGCombine(ISD::ZERO_EXTEND);
635 setTargetDAGCombine(ISD::SIGN_EXTEND);
636 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
637 setTargetDAGCombine(ISD::CONCAT_VECTORS);
638 setTargetDAGCombine(ISD::STORE);
639 if (Subtarget->supportsAddressTopByteIgnored())
640 setTargetDAGCombine(ISD::LOAD);
642 setTargetDAGCombine(ISD::MUL);
644 setTargetDAGCombine(ISD::SELECT);
645 setTargetDAGCombine(ISD::VSELECT);
647 setTargetDAGCombine(ISD::INTRINSIC_VOID);
648 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
649 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
651 setTargetDAGCombine(ISD::GlobalAddress);
653 // In case of strict alignment, avoid an excessive number of byte wide stores.
654 MaxStoresPerMemsetOptSize = 8;
655 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
656 ? MaxStoresPerMemsetOptSize : 32;
658 MaxGluedStoresPerMemcpy = 4;
659 MaxStoresPerMemcpyOptSize = 4;
660 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
661 ? MaxStoresPerMemcpyOptSize : 16;
663 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
665 MaxLoadsPerMemcmpOptSize = 4;
666 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
667 ? MaxLoadsPerMemcmpOptSize : 8;
669 setStackPointerRegisterToSaveRestore(AArch64::SP);
671 setSchedulingPreference(Sched::Hybrid);
673 EnableExtLdPromotion = true;
675 // Set required alignment.
676 setMinFunctionAlignment(Align(4));
677 // Set preferred alignments.
678 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
679 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
681 // Only change the limit for entries in a jump table if specified by
682 // the sub target, but not at the command line.
683 unsigned MaxJT = STI.getMaximumJumpTableSize();
684 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
685 setMaximumJumpTableSize(MaxJT);
687 setHasExtractBitsInsn(true);
689 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
691 if (Subtarget->hasNEON()) {
692 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
693 // silliness like this:
694 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
695 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
696 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
697 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
698 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
699 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
700 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
701 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
702 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
703 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
704 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
705 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
706 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
707 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
708 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
709 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
710 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
711 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
712 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
713 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
714 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
715 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
716 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
717 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
718 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
720 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
721 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
722 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
723 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
724 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
726 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
728 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
729 // elements smaller than i32, so promote the input to i32 first.
730 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
731 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
732 // i8 vector elements also need promotion to i32 for v8i8
733 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
734 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
735 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
736 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
737 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
738 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
739 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
740 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
741 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
742 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
743 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
745 if (Subtarget->hasFullFP16()) {
746 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
747 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
748 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
749 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
750 } else {
751 // when AArch64 doesn't have fullfp16 support, promote the input
752 // to i32 first.
753 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
754 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
755 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
756 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
759 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
760 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
762 // AArch64 doesn't have MUL.2d:
763 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
764 // Custom handling for some quad-vector types to detect MULL.
765 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
766 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
767 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
769 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
770 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
771 // Vector reductions
772 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
773 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
774 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
775 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
776 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
778 // Saturates
779 setOperationAction(ISD::SADDSAT, VT, Legal);
780 setOperationAction(ISD::UADDSAT, VT, Legal);
781 setOperationAction(ISD::SSUBSAT, VT, Legal);
782 setOperationAction(ISD::USUBSAT, VT, Legal);
784 for (MVT VT : { MVT::v4f16, MVT::v2f32,
785 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
786 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
787 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
790 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
791 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
792 // Likewise, narrowing and extending vector loads/stores aren't handled
793 // directly.
794 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
795 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
797 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
798 setOperationAction(ISD::MULHS, VT, Legal);
799 setOperationAction(ISD::MULHU, VT, Legal);
800 } else {
801 setOperationAction(ISD::MULHS, VT, Expand);
802 setOperationAction(ISD::MULHU, VT, Expand);
804 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
805 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
807 setOperationAction(ISD::BSWAP, VT, Expand);
808 setOperationAction(ISD::CTTZ, VT, Expand);
810 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
811 setTruncStoreAction(VT, InnerVT, Expand);
812 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
813 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
814 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
818 // AArch64 has implementations of a lot of rounding-like FP operations.
819 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
820 setOperationAction(ISD::FFLOOR, Ty, Legal);
821 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
822 setOperationAction(ISD::FCEIL, Ty, Legal);
823 setOperationAction(ISD::FRINT, Ty, Legal);
824 setOperationAction(ISD::FTRUNC, Ty, Legal);
825 setOperationAction(ISD::FROUND, Ty, Legal);
828 if (Subtarget->hasFullFP16()) {
829 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
830 setOperationAction(ISD::FFLOOR, Ty, Legal);
831 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
832 setOperationAction(ISD::FCEIL, Ty, Legal);
833 setOperationAction(ISD::FRINT, Ty, Legal);
834 setOperationAction(ISD::FTRUNC, Ty, Legal);
835 setOperationAction(ISD::FROUND, Ty, Legal);
839 if (Subtarget->hasSVE())
840 setOperationAction(ISD::VSCALE, MVT::i32, Custom);
842 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
845 if (Subtarget->hasSVE()) {
846 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
847 // splat of 0 or undef) once vector selects supported in SVE codegen. See
848 // D68877 for more details.
849 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) {
850 if (isTypeLegal(VT))
851 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
853 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
854 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
857 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
860 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
861 assert(VT.isVector() && "VT should be a vector type");
863 if (VT.isFloatingPoint()) {
864 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
865 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
866 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
869 // Mark vector float intrinsics as expand.
870 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
871 setOperationAction(ISD::FSIN, VT, Expand);
872 setOperationAction(ISD::FCOS, VT, Expand);
873 setOperationAction(ISD::FPOW, VT, Expand);
874 setOperationAction(ISD::FLOG, VT, Expand);
875 setOperationAction(ISD::FLOG2, VT, Expand);
876 setOperationAction(ISD::FLOG10, VT, Expand);
877 setOperationAction(ISD::FEXP, VT, Expand);
878 setOperationAction(ISD::FEXP2, VT, Expand);
880 // But we do support custom-lowering for FCOPYSIGN.
881 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
884 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
885 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
886 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
888 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
889 setOperationAction(ISD::SRA, VT, Custom);
890 setOperationAction(ISD::SRL, VT, Custom);
891 setOperationAction(ISD::SHL, VT, Custom);
892 setOperationAction(ISD::OR, VT, Custom);
893 setOperationAction(ISD::SETCC, VT, Custom);
894 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
896 setOperationAction(ISD::SELECT, VT, Expand);
897 setOperationAction(ISD::SELECT_CC, VT, Expand);
898 setOperationAction(ISD::VSELECT, VT, Expand);
899 for (MVT InnerVT : MVT::all_valuetypes())
900 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
902 // CNT supports only B element sizes, then use UADDLP to widen.
903 if (VT != MVT::v8i8 && VT != MVT::v16i8)
904 setOperationAction(ISD::CTPOP, VT, Custom);
906 setOperationAction(ISD::UDIV, VT, Expand);
907 setOperationAction(ISD::SDIV, VT, Expand);
908 setOperationAction(ISD::UREM, VT, Expand);
909 setOperationAction(ISD::SREM, VT, Expand);
910 setOperationAction(ISD::FREM, VT, Expand);
912 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
913 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
915 if (!VT.isFloatingPoint())
916 setOperationAction(ISD::ABS, VT, Legal);
918 // [SU][MIN|MAX] are available for all NEON types apart from i64.
919 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
920 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
921 setOperationAction(Opcode, VT, Legal);
923 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
924 if (VT.isFloatingPoint() &&
925 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
926 for (unsigned Opcode :
927 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
928 setOperationAction(Opcode, VT, Legal);
930 if (Subtarget->isLittleEndian()) {
931 for (unsigned im = (unsigned)ISD::PRE_INC;
932 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
933 setIndexedLoadAction(im, VT, Legal);
934 setIndexedStoreAction(im, VT, Legal);
939 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
940 addRegisterClass(VT, &AArch64::FPR64RegClass);
941 addTypeForNEON(VT, MVT::v2i32);
944 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
945 addRegisterClass(VT, &AArch64::FPR128RegClass);
946 addTypeForNEON(VT, MVT::v4i32);
949 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
950 EVT VT) const {
951 if (!VT.isVector())
952 return MVT::i32;
953 return VT.changeVectorElementTypeToInteger();
956 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
957 const APInt &Demanded,
958 TargetLowering::TargetLoweringOpt &TLO,
959 unsigned NewOpc) {
960 uint64_t OldImm = Imm, NewImm, Enc;
961 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
963 // Return if the immediate is already all zeros, all ones, a bimm32 or a
964 // bimm64.
965 if (Imm == 0 || Imm == Mask ||
966 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
967 return false;
969 unsigned EltSize = Size;
970 uint64_t DemandedBits = Demanded.getZExtValue();
972 // Clear bits that are not demanded.
973 Imm &= DemandedBits;
975 while (true) {
976 // The goal here is to set the non-demanded bits in a way that minimizes
977 // the number of switching between 0 and 1. In order to achieve this goal,
978 // we set the non-demanded bits to the value of the preceding demanded bits.
979 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
980 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
981 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
982 // The final result is 0b11000011.
983 uint64_t NonDemandedBits = ~DemandedBits;
984 uint64_t InvertedImm = ~Imm & DemandedBits;
985 uint64_t RotatedImm =
986 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
987 NonDemandedBits;
988 uint64_t Sum = RotatedImm + NonDemandedBits;
989 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
990 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
991 NewImm = (Imm | Ones) & Mask;
993 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
994 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
995 // we halve the element size and continue the search.
996 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
997 break;
999 // We cannot shrink the element size any further if it is 2-bits.
1000 if (EltSize == 2)
1001 return false;
1003 EltSize /= 2;
1004 Mask >>= EltSize;
1005 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
1007 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
1008 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
1009 return false;
1011 // Merge the upper and lower halves of Imm and DemandedBits.
1012 Imm |= Hi;
1013 DemandedBits |= DemandedBitsHi;
1016 ++NumOptimizedImms;
1018 // Replicate the element across the register width.
1019 while (EltSize < Size) {
1020 NewImm |= NewImm << EltSize;
1021 EltSize *= 2;
1024 (void)OldImm;
1025 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
1026 "demanded bits should never be altered");
1027 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
1029 // Create the new constant immediate node.
1030 EVT VT = Op.getValueType();
1031 SDLoc DL(Op);
1032 SDValue New;
1034 // If the new constant immediate is all-zeros or all-ones, let the target
1035 // independent DAG combine optimize this node.
1036 if (NewImm == 0 || NewImm == OrigMask) {
1037 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
1038 TLO.DAG.getConstant(NewImm, DL, VT));
1039 // Otherwise, create a machine node so that target independent DAG combine
1040 // doesn't undo this optimization.
1041 } else {
1042 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
1043 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
1044 New = SDValue(
1045 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
1048 return TLO.CombineTo(Op, New);
1051 bool AArch64TargetLowering::targetShrinkDemandedConstant(
1052 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1053 // Delay this optimization to as late as possible.
1054 if (!TLO.LegalOps)
1055 return false;
1057 if (!EnableOptimizeLogicalImm)
1058 return false;
1060 EVT VT = Op.getValueType();
1061 if (VT.isVector())
1062 return false;
1064 unsigned Size = VT.getSizeInBits();
1065 assert((Size == 32 || Size == 64) &&
1066 "i32 or i64 is expected after legalization.");
1068 // Exit early if we demand all bits.
1069 if (Demanded.countPopulation() == Size)
1070 return false;
1072 unsigned NewOpc;
1073 switch (Op.getOpcode()) {
1074 default:
1075 return false;
1076 case ISD::AND:
1077 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1078 break;
1079 case ISD::OR:
1080 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1081 break;
1082 case ISD::XOR:
1083 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1084 break;
1086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1087 if (!C)
1088 return false;
1089 uint64_t Imm = C->getZExtValue();
1090 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1093 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1094 /// Mask are known to be either zero or one and return them Known.
1095 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1096 const SDValue Op, KnownBits &Known,
1097 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1098 switch (Op.getOpcode()) {
1099 default:
1100 break;
1101 case AArch64ISD::CSEL: {
1102 KnownBits Known2;
1103 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1104 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1105 Known.Zero &= Known2.Zero;
1106 Known.One &= Known2.One;
1107 break;
1109 case AArch64ISD::LOADgot:
1110 case AArch64ISD::ADDlow: {
1111 if (!Subtarget->isTargetILP32())
1112 break;
1113 // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1114 Known.Zero = APInt::getHighBitsSet(64, 32);
1115 break;
1117 case ISD::INTRINSIC_W_CHAIN: {
1118 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1119 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1120 switch (IntID) {
1121 default: return;
1122 case Intrinsic::aarch64_ldaxr:
1123 case Intrinsic::aarch64_ldxr: {
1124 unsigned BitWidth = Known.getBitWidth();
1125 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1126 unsigned MemBits = VT.getScalarSizeInBits();
1127 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1128 return;
1131 break;
1133 case ISD::INTRINSIC_WO_CHAIN:
1134 case ISD::INTRINSIC_VOID: {
1135 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1136 switch (IntNo) {
1137 default:
1138 break;
1139 case Intrinsic::aarch64_neon_umaxv:
1140 case Intrinsic::aarch64_neon_uminv: {
1141 // Figure out the datatype of the vector operand. The UMINV instruction
1142 // will zero extend the result, so we can mark as known zero all the
1143 // bits larger than the element datatype. 32-bit or larget doesn't need
1144 // this as those are legal types and will be handled by isel directly.
1145 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1146 unsigned BitWidth = Known.getBitWidth();
1147 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1148 assert(BitWidth >= 8 && "Unexpected width!");
1149 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1150 Known.Zero |= Mask;
1151 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1152 assert(BitWidth >= 16 && "Unexpected width!");
1153 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1154 Known.Zero |= Mask;
1156 break;
1157 } break;
1163 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1164 EVT) const {
1165 return MVT::i64;
1168 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1169 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1170 bool *Fast) const {
1171 if (Subtarget->requiresStrictAlign())
1172 return false;
1174 if (Fast) {
1175 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1176 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1177 // See comments in performSTORECombine() for more details about
1178 // these conditions.
1180 // Code that uses clang vector extensions can mark that it
1181 // wants unaligned accesses to be treated as fast by
1182 // underspecifying alignment to be 1 or 2.
1183 Align <= 2 ||
1185 // Disregard v2i64. Memcpy lowering produces those and splitting
1186 // them regresses performance on micro-benchmarks and olden/bh.
1187 VT == MVT::v2i64;
1189 return true;
1192 // Same as above but handling LLTs instead.
1193 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1194 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1195 bool *Fast) const {
1196 if (Subtarget->requiresStrictAlign())
1197 return false;
1199 if (Fast) {
1200 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1201 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1202 Ty.getSizeInBytes() != 16 ||
1203 // See comments in performSTORECombine() for more details about
1204 // these conditions.
1206 // Code that uses clang vector extensions can mark that it
1207 // wants unaligned accesses to be treated as fast by
1208 // underspecifying alignment to be 1 or 2.
1209 Align <= 2 ||
1211 // Disregard v2i64. Memcpy lowering produces those and splitting
1212 // them regresses performance on micro-benchmarks and olden/bh.
1213 Ty == LLT::vector(2, 64);
1215 return true;
1218 FastISel *
1219 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1220 const TargetLibraryInfo *libInfo) const {
1221 return AArch64::createFastISel(funcInfo, libInfo);
1224 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1225 switch ((AArch64ISD::NodeType)Opcode) {
1226 case AArch64ISD::FIRST_NUMBER: break;
1227 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1228 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1229 case AArch64ISD::ADR: return "AArch64ISD::ADR";
1230 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1231 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1232 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1233 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1234 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1235 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1236 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1237 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1238 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1239 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1240 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1241 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1242 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1243 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1244 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1245 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1246 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1247 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1248 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1249 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1250 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1251 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1252 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1253 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1254 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1255 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1256 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1257 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1258 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1259 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1260 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1261 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1262 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1263 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1264 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1265 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1266 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1267 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1268 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1269 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1270 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1271 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1272 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1273 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1274 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1275 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1276 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1277 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1278 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1279 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1280 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1281 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1282 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1283 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1284 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1285 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1286 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1287 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1288 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1289 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1290 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1291 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1292 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1293 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1294 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1295 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1296 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1297 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1298 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1299 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1300 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1301 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1302 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1303 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1304 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1305 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1306 case AArch64ISD::SMAXV_PRED: return "AArch64ISD::SMAXV_PRED";
1307 case AArch64ISD::UMAXV_PRED: return "AArch64ISD::UMAXV_PRED";
1308 case AArch64ISD::SMINV_PRED: return "AArch64ISD::SMINV_PRED";
1309 case AArch64ISD::UMINV_PRED: return "AArch64ISD::UMINV_PRED";
1310 case AArch64ISD::ORV_PRED: return "AArch64ISD::ORV_PRED";
1311 case AArch64ISD::EORV_PRED: return "AArch64ISD::EORV_PRED";
1312 case AArch64ISD::ANDV_PRED: return "AArch64ISD::ANDV_PRED";
1313 case AArch64ISD::CLASTA_N: return "AArch64ISD::CLASTA_N";
1314 case AArch64ISD::CLASTB_N: return "AArch64ISD::CLASTB_N";
1315 case AArch64ISD::LASTA: return "AArch64ISD::LASTA";
1316 case AArch64ISD::LASTB: return "AArch64ISD::LASTB";
1317 case AArch64ISD::REV: return "AArch64ISD::REV";
1318 case AArch64ISD::TBL: return "AArch64ISD::TBL";
1319 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1320 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1321 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1322 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1323 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1324 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1325 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1326 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1327 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1328 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1329 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1330 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1331 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1332 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1333 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1334 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1335 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1336 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1337 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1338 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1339 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1340 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1341 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1342 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1343 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1344 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1345 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1346 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1347 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1348 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1349 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1350 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1351 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1352 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1353 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1354 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1355 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1356 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1357 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1358 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1359 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1360 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1361 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1362 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1363 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1364 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1365 case AArch64ISD::STG: return "AArch64ISD::STG";
1366 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1367 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1368 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
1369 case AArch64ISD::SUNPKHI: return "AArch64ISD::SUNPKHI";
1370 case AArch64ISD::SUNPKLO: return "AArch64ISD::SUNPKLO";
1371 case AArch64ISD::UUNPKHI: return "AArch64ISD::UUNPKHI";
1372 case AArch64ISD::UUNPKLO: return "AArch64ISD::UUNPKLO";
1373 case AArch64ISD::INSR: return "AArch64ISD::INSR";
1374 case AArch64ISD::PTEST: return "AArch64ISD::PTEST";
1375 case AArch64ISD::PTRUE: return "AArch64ISD::PTRUE";
1376 case AArch64ISD::LDNF1: return "AArch64ISD::LDNF1";
1377 case AArch64ISD::LDNF1S: return "AArch64ISD::LDNF1S";
1378 case AArch64ISD::GLD1: return "AArch64ISD::GLD1";
1379 case AArch64ISD::GLD1_SCALED: return "AArch64ISD::GLD1_SCALED";
1380 case AArch64ISD::GLD1_SXTW: return "AArch64ISD::GLD1_SXTW";
1381 case AArch64ISD::GLD1_UXTW: return "AArch64ISD::GLD1_UXTW";
1382 case AArch64ISD::GLD1_SXTW_SCALED: return "AArch64ISD::GLD1_SXTW_SCALED";
1383 case AArch64ISD::GLD1_UXTW_SCALED: return "AArch64ISD::GLD1_UXTW_SCALED";
1384 case AArch64ISD::GLD1_IMM: return "AArch64ISD::GLD1_IMM";
1385 case AArch64ISD::GLD1S: return "AArch64ISD::GLD1S";
1386 case AArch64ISD::GLD1S_SCALED: return "AArch64ISD::GLD1S_SCALED";
1387 case AArch64ISD::GLD1S_SXTW: return "AArch64ISD::GLD1S_SXTW";
1388 case AArch64ISD::GLD1S_UXTW: return "AArch64ISD::GLD1S_UXTW";
1389 case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED";
1390 case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED";
1391 case AArch64ISD::GLD1S_IMM: return "AArch64ISD::GLD1S_IMM";
1392 case AArch64ISD::SST1: return "AArch64ISD::SST1";
1393 case AArch64ISD::SST1_SCALED: return "AArch64ISD::SST1_SCALED";
1394 case AArch64ISD::SST1_SXTW: return "AArch64ISD::SST1_SXTW";
1395 case AArch64ISD::SST1_UXTW: return "AArch64ISD::SST1_UXTW";
1396 case AArch64ISD::SST1_SXTW_SCALED: return "AArch64ISD::SST1_SXTW_SCALED";
1397 case AArch64ISD::SST1_UXTW_SCALED: return "AArch64ISD::SST1_UXTW_SCALED";
1398 case AArch64ISD::SST1_IMM: return "AArch64ISD::SST1_IMM";
1399 case AArch64ISD::LDP: return "AArch64ISD::LDP";
1400 case AArch64ISD::STP: return "AArch64ISD::STP";
1401 case AArch64ISD::STNP: return "AArch64ISD::STNP";
1403 return nullptr;
1406 MachineBasicBlock *
1407 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1408 MachineBasicBlock *MBB) const {
1409 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1410 // phi node:
1412 // OrigBB:
1413 // [... previous instrs leading to comparison ...]
1414 // b.ne TrueBB
1415 // b EndBB
1416 // TrueBB:
1417 // ; Fallthrough
1418 // EndBB:
1419 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1421 MachineFunction *MF = MBB->getParent();
1422 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1423 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1424 DebugLoc DL = MI.getDebugLoc();
1425 MachineFunction::iterator It = ++MBB->getIterator();
1427 Register DestReg = MI.getOperand(0).getReg();
1428 Register IfTrueReg = MI.getOperand(1).getReg();
1429 Register IfFalseReg = MI.getOperand(2).getReg();
1430 unsigned CondCode = MI.getOperand(3).getImm();
1431 bool NZCVKilled = MI.getOperand(4).isKill();
1433 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1434 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1435 MF->insert(It, TrueBB);
1436 MF->insert(It, EndBB);
1438 // Transfer rest of current basic-block to EndBB
1439 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1440 MBB->end());
1441 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1443 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1444 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1445 MBB->addSuccessor(TrueBB);
1446 MBB->addSuccessor(EndBB);
1448 // TrueBB falls through to the end.
1449 TrueBB->addSuccessor(EndBB);
1451 if (!NZCVKilled) {
1452 TrueBB->addLiveIn(AArch64::NZCV);
1453 EndBB->addLiveIn(AArch64::NZCV);
1456 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1457 .addReg(IfTrueReg)
1458 .addMBB(TrueBB)
1459 .addReg(IfFalseReg)
1460 .addMBB(MBB);
1462 MI.eraseFromParent();
1463 return EndBB;
1466 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1467 MachineInstr &MI, MachineBasicBlock *BB) const {
1468 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1469 BB->getParent()->getFunction().getPersonalityFn())) &&
1470 "SEH does not use catchret!");
1471 return BB;
1474 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1475 MachineInstr &MI, MachineBasicBlock *BB) const {
1476 MI.eraseFromParent();
1477 return BB;
1480 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1481 MachineInstr &MI, MachineBasicBlock *BB) const {
1482 switch (MI.getOpcode()) {
1483 default:
1484 #ifndef NDEBUG
1485 MI.dump();
1486 #endif
1487 llvm_unreachable("Unexpected instruction for custom inserter!");
1489 case AArch64::F128CSEL:
1490 return EmitF128CSEL(MI, BB);
1492 case TargetOpcode::STACKMAP:
1493 case TargetOpcode::PATCHPOINT:
1494 return emitPatchPoint(MI, BB);
1496 case AArch64::CATCHRET:
1497 return EmitLoweredCatchRet(MI, BB);
1498 case AArch64::CATCHPAD:
1499 return EmitLoweredCatchPad(MI, BB);
1503 //===----------------------------------------------------------------------===//
1504 // AArch64 Lowering private implementation.
1505 //===----------------------------------------------------------------------===//
1507 //===----------------------------------------------------------------------===//
1508 // Lowering Code
1509 //===----------------------------------------------------------------------===//
1511 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1512 /// CC
1513 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1514 switch (CC) {
1515 default:
1516 llvm_unreachable("Unknown condition code!");
1517 case ISD::SETNE:
1518 return AArch64CC::NE;
1519 case ISD::SETEQ:
1520 return AArch64CC::EQ;
1521 case ISD::SETGT:
1522 return AArch64CC::GT;
1523 case ISD::SETGE:
1524 return AArch64CC::GE;
1525 case ISD::SETLT:
1526 return AArch64CC::LT;
1527 case ISD::SETLE:
1528 return AArch64CC::LE;
1529 case ISD::SETUGT:
1530 return AArch64CC::HI;
1531 case ISD::SETUGE:
1532 return AArch64CC::HS;
1533 case ISD::SETULT:
1534 return AArch64CC::LO;
1535 case ISD::SETULE:
1536 return AArch64CC::LS;
1540 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1541 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1542 AArch64CC::CondCode &CondCode,
1543 AArch64CC::CondCode &CondCode2) {
1544 CondCode2 = AArch64CC::AL;
1545 switch (CC) {
1546 default:
1547 llvm_unreachable("Unknown FP condition!");
1548 case ISD::SETEQ:
1549 case ISD::SETOEQ:
1550 CondCode = AArch64CC::EQ;
1551 break;
1552 case ISD::SETGT:
1553 case ISD::SETOGT:
1554 CondCode = AArch64CC::GT;
1555 break;
1556 case ISD::SETGE:
1557 case ISD::SETOGE:
1558 CondCode = AArch64CC::GE;
1559 break;
1560 case ISD::SETOLT:
1561 CondCode = AArch64CC::MI;
1562 break;
1563 case ISD::SETOLE:
1564 CondCode = AArch64CC::LS;
1565 break;
1566 case ISD::SETONE:
1567 CondCode = AArch64CC::MI;
1568 CondCode2 = AArch64CC::GT;
1569 break;
1570 case ISD::SETO:
1571 CondCode = AArch64CC::VC;
1572 break;
1573 case ISD::SETUO:
1574 CondCode = AArch64CC::VS;
1575 break;
1576 case ISD::SETUEQ:
1577 CondCode = AArch64CC::EQ;
1578 CondCode2 = AArch64CC::VS;
1579 break;
1580 case ISD::SETUGT:
1581 CondCode = AArch64CC::HI;
1582 break;
1583 case ISD::SETUGE:
1584 CondCode = AArch64CC::PL;
1585 break;
1586 case ISD::SETLT:
1587 case ISD::SETULT:
1588 CondCode = AArch64CC::LT;
1589 break;
1590 case ISD::SETLE:
1591 case ISD::SETULE:
1592 CondCode = AArch64CC::LE;
1593 break;
1594 case ISD::SETNE:
1595 case ISD::SETUNE:
1596 CondCode = AArch64CC::NE;
1597 break;
1601 /// Convert a DAG fp condition code to an AArch64 CC.
1602 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1603 /// should be AND'ed instead of OR'ed.
1604 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1605 AArch64CC::CondCode &CondCode,
1606 AArch64CC::CondCode &CondCode2) {
1607 CondCode2 = AArch64CC::AL;
1608 switch (CC) {
1609 default:
1610 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1611 assert(CondCode2 == AArch64CC::AL);
1612 break;
1613 case ISD::SETONE:
1614 // (a one b)
1615 // == ((a olt b) || (a ogt b))
1616 // == ((a ord b) && (a une b))
1617 CondCode = AArch64CC::VC;
1618 CondCode2 = AArch64CC::NE;
1619 break;
1620 case ISD::SETUEQ:
1621 // (a ueq b)
1622 // == ((a uno b) || (a oeq b))
1623 // == ((a ule b) && (a uge b))
1624 CondCode = AArch64CC::PL;
1625 CondCode2 = AArch64CC::LE;
1626 break;
1630 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1631 /// CC usable with the vector instructions. Fewer operations are available
1632 /// without a real NZCV register, so we have to use less efficient combinations
1633 /// to get the same effect.
1634 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1635 AArch64CC::CondCode &CondCode,
1636 AArch64CC::CondCode &CondCode2,
1637 bool &Invert) {
1638 Invert = false;
1639 switch (CC) {
1640 default:
1641 // Mostly the scalar mappings work fine.
1642 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1643 break;
1644 case ISD::SETUO:
1645 Invert = true;
1646 LLVM_FALLTHROUGH;
1647 case ISD::SETO:
1648 CondCode = AArch64CC::MI;
1649 CondCode2 = AArch64CC::GE;
1650 break;
1651 case ISD::SETUEQ:
1652 case ISD::SETULT:
1653 case ISD::SETULE:
1654 case ISD::SETUGT:
1655 case ISD::SETUGE:
1656 // All of the compare-mask comparisons are ordered, but we can switch
1657 // between the two by a double inversion. E.g. ULE == !OGT.
1658 Invert = true;
1659 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
1660 CondCode, CondCode2);
1661 break;
1665 static bool isLegalArithImmed(uint64_t C) {
1666 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1667 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1668 LLVM_DEBUG(dbgs() << "Is imm " << C
1669 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1670 return IsLegal;
1673 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1674 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1675 // can be set differently by this operation. It comes down to whether
1676 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1677 // everything is fine. If not then the optimization is wrong. Thus general
1678 // comparisons are only valid if op2 != 0.
1680 // So, finally, the only LLVM-native comparisons that don't mention C and V
1681 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1682 // the absence of information about op2.
1683 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1684 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1685 (CC == ISD::SETEQ || CC == ISD::SETNE);
1688 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1689 const SDLoc &dl, SelectionDAG &DAG) {
1690 EVT VT = LHS.getValueType();
1691 const bool FullFP16 =
1692 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1694 if (VT.isFloatingPoint()) {
1695 assert(VT != MVT::f128);
1696 if (VT == MVT::f16 && !FullFP16) {
1697 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1698 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1699 VT = MVT::f32;
1701 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1704 // The CMP instruction is just an alias for SUBS, and representing it as
1705 // SUBS means that it's possible to get CSE with subtract operations.
1706 // A later phase can perform the optimization of setting the destination
1707 // register to WZR/XZR if it ends up being unused.
1708 unsigned Opcode = AArch64ISD::SUBS;
1710 if (isCMN(RHS, CC)) {
1711 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1712 Opcode = AArch64ISD::ADDS;
1713 RHS = RHS.getOperand(1);
1714 } else if (isCMN(LHS, CC)) {
1715 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1716 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1717 Opcode = AArch64ISD::ADDS;
1718 LHS = LHS.getOperand(1);
1719 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1720 !isUnsignedIntSetCC(CC)) {
1721 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1722 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1723 // of the signed comparisons.
1724 Opcode = AArch64ISD::ANDS;
1725 RHS = LHS.getOperand(1);
1726 LHS = LHS.getOperand(0);
1729 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1730 .getValue(1);
1733 /// \defgroup AArch64CCMP CMP;CCMP matching
1735 /// These functions deal with the formation of CMP;CCMP;... sequences.
1736 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1737 /// a comparison. They set the NZCV flags to a predefined value if their
1738 /// predicate is false. This allows to express arbitrary conjunctions, for
1739 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1740 /// expressed as:
1741 /// cmp A
1742 /// ccmp B, inv(CB), CA
1743 /// check for CB flags
1745 /// This naturally lets us implement chains of AND operations with SETCC
1746 /// operands. And we can even implement some other situations by transforming
1747 /// them:
1748 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1749 /// negating the flags used in a CCMP/FCCMP operations.
1750 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1751 /// by negating the flags we test for afterwards. i.e.
1752 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1753 /// - Note that we can only ever negate all previously processed results.
1754 /// What we can not implement by flipping the flags to test is a negation
1755 /// of two sub-trees (because the negation affects all sub-trees emitted so
1756 /// far, so the 2nd sub-tree we emit would also affect the first).
1757 /// With those tools we can implement some OR operations:
1758 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1759 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1760 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1761 /// elimination rules from earlier to implement the whole thing as a
1762 /// CCMP/FCCMP chain.
1764 /// As complete example:
1765 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1766 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1767 /// can be reassociated to:
1768 /// or (and (setCC (cmp C)) setCD (cmp D))
1769 // (or (setCA (cmp A)) (setCB (cmp B)))
1770 /// can be transformed to:
1771 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1772 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1773 /// which can be implemented as:
1774 /// cmp C
1775 /// ccmp D, inv(CD), CC
1776 /// ccmp A, CA, inv(CD)
1777 /// ccmp B, CB, inv(CA)
1778 /// check for CB flags
1780 /// A counterexample is "or (and A B) (and C D)" which translates to
1781 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1782 /// can only implement 1 of the inner (not) operations, but not both!
1783 /// @{
1785 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1786 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1787 ISD::CondCode CC, SDValue CCOp,
1788 AArch64CC::CondCode Predicate,
1789 AArch64CC::CondCode OutCC,
1790 const SDLoc &DL, SelectionDAG &DAG) {
1791 unsigned Opcode = 0;
1792 const bool FullFP16 =
1793 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1795 if (LHS.getValueType().isFloatingPoint()) {
1796 assert(LHS.getValueType() != MVT::f128);
1797 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1798 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1799 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1801 Opcode = AArch64ISD::FCCMP;
1802 } else if (RHS.getOpcode() == ISD::SUB) {
1803 SDValue SubOp0 = RHS.getOperand(0);
1804 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1805 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1806 Opcode = AArch64ISD::CCMN;
1807 RHS = RHS.getOperand(1);
1810 if (Opcode == 0)
1811 Opcode = AArch64ISD::CCMP;
1813 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1814 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1815 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1816 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1817 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1820 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1821 /// expressed as a conjunction. See \ref AArch64CCMP.
1822 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1823 /// changing the conditions on the SETCC tests.
1824 /// (this means we can call emitConjunctionRec() with
1825 /// Negate==true on this sub-tree)
1826 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1827 /// cannot do the negation naturally. We are required to
1828 /// emit the subtree first in this case.
1829 /// \param WillNegate Is true if are called when the result of this
1830 /// subexpression must be negated. This happens when the
1831 /// outer expression is an OR. We can use this fact to know
1832 /// that we have a double negation (or (or ...) ...) that
1833 /// can be implemented for free.
1834 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1835 bool &MustBeFirst, bool WillNegate,
1836 unsigned Depth = 0) {
1837 if (!Val.hasOneUse())
1838 return false;
1839 unsigned Opcode = Val->getOpcode();
1840 if (Opcode == ISD::SETCC) {
1841 if (Val->getOperand(0).getValueType() == MVT::f128)
1842 return false;
1843 CanNegate = true;
1844 MustBeFirst = false;
1845 return true;
1847 // Protect against exponential runtime and stack overflow.
1848 if (Depth > 6)
1849 return false;
1850 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1851 bool IsOR = Opcode == ISD::OR;
1852 SDValue O0 = Val->getOperand(0);
1853 SDValue O1 = Val->getOperand(1);
1854 bool CanNegateL;
1855 bool MustBeFirstL;
1856 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1857 return false;
1858 bool CanNegateR;
1859 bool MustBeFirstR;
1860 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1861 return false;
1863 if (MustBeFirstL && MustBeFirstR)
1864 return false;
1866 if (IsOR) {
1867 // For an OR expression we need to be able to naturally negate at least
1868 // one side or we cannot do the transformation at all.
1869 if (!CanNegateL && !CanNegateR)
1870 return false;
1871 // If we the result of the OR will be negated and we can naturally negate
1872 // the leafs, then this sub-tree as a whole negates naturally.
1873 CanNegate = WillNegate && CanNegateL && CanNegateR;
1874 // If we cannot naturally negate the whole sub-tree, then this must be
1875 // emitted first.
1876 MustBeFirst = !CanNegate;
1877 } else {
1878 assert(Opcode == ISD::AND && "Must be OR or AND");
1879 // We cannot naturally negate an AND operation.
1880 CanNegate = false;
1881 MustBeFirst = MustBeFirstL || MustBeFirstR;
1883 return true;
1885 return false;
1888 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1889 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1890 /// Tries to transform the given i1 producing node @p Val to a series compare
1891 /// and conditional compare operations. @returns an NZCV flags producing node
1892 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1893 /// transformation was not possible.
1894 /// \p Negate is true if we want this sub-tree being negated just by changing
1895 /// SETCC conditions.
1896 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1897 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1898 AArch64CC::CondCode Predicate) {
1899 // We're at a tree leaf, produce a conditional comparison operation.
1900 unsigned Opcode = Val->getOpcode();
1901 if (Opcode == ISD::SETCC) {
1902 SDValue LHS = Val->getOperand(0);
1903 SDValue RHS = Val->getOperand(1);
1904 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1905 bool isInteger = LHS.getValueType().isInteger();
1906 if (Negate)
1907 CC = getSetCCInverse(CC, LHS.getValueType());
1908 SDLoc DL(Val);
1909 // Determine OutCC and handle FP special case.
1910 if (isInteger) {
1911 OutCC = changeIntCCToAArch64CC(CC);
1912 } else {
1913 assert(LHS.getValueType().isFloatingPoint());
1914 AArch64CC::CondCode ExtraCC;
1915 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1916 // Some floating point conditions can't be tested with a single condition
1917 // code. Construct an additional comparison in this case.
1918 if (ExtraCC != AArch64CC::AL) {
1919 SDValue ExtraCmp;
1920 if (!CCOp.getNode())
1921 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1922 else
1923 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1924 ExtraCC, DL, DAG);
1925 CCOp = ExtraCmp;
1926 Predicate = ExtraCC;
1930 // Produce a normal comparison if we are first in the chain
1931 if (!CCOp)
1932 return emitComparison(LHS, RHS, CC, DL, DAG);
1933 // Otherwise produce a ccmp.
1934 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1935 DAG);
1937 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1939 bool IsOR = Opcode == ISD::OR;
1941 SDValue LHS = Val->getOperand(0);
1942 bool CanNegateL;
1943 bool MustBeFirstL;
1944 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1945 assert(ValidL && "Valid conjunction/disjunction tree");
1946 (void)ValidL;
1948 SDValue RHS = Val->getOperand(1);
1949 bool CanNegateR;
1950 bool MustBeFirstR;
1951 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1952 assert(ValidR && "Valid conjunction/disjunction tree");
1953 (void)ValidR;
1955 // Swap sub-tree that must come first to the right side.
1956 if (MustBeFirstL) {
1957 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1958 std::swap(LHS, RHS);
1959 std::swap(CanNegateL, CanNegateR);
1960 std::swap(MustBeFirstL, MustBeFirstR);
1963 bool NegateR;
1964 bool NegateAfterR;
1965 bool NegateL;
1966 bool NegateAfterAll;
1967 if (Opcode == ISD::OR) {
1968 // Swap the sub-tree that we can negate naturally to the left.
1969 if (!CanNegateL) {
1970 assert(CanNegateR && "at least one side must be negatable");
1971 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1972 assert(!Negate);
1973 std::swap(LHS, RHS);
1974 NegateR = false;
1975 NegateAfterR = true;
1976 } else {
1977 // Negate the left sub-tree if possible, otherwise negate the result.
1978 NegateR = CanNegateR;
1979 NegateAfterR = !CanNegateR;
1981 NegateL = true;
1982 NegateAfterAll = !Negate;
1983 } else {
1984 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1985 assert(!Negate && "Valid conjunction/disjunction tree");
1987 NegateL = false;
1988 NegateR = false;
1989 NegateAfterR = false;
1990 NegateAfterAll = false;
1993 // Emit sub-trees.
1994 AArch64CC::CondCode RHSCC;
1995 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1996 if (NegateAfterR)
1997 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1998 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1999 if (NegateAfterAll)
2000 OutCC = AArch64CC::getInvertedCondCode(OutCC);
2001 return CmpL;
2004 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
2005 /// In some cases this is even possible with OR operations in the expression.
2006 /// See \ref AArch64CCMP.
2007 /// \see emitConjunctionRec().
2008 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
2009 AArch64CC::CondCode &OutCC) {
2010 bool DummyCanNegate;
2011 bool DummyMustBeFirst;
2012 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
2013 return SDValue();
2015 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
2018 /// @}
2020 /// Returns how profitable it is to fold a comparison's operand's shift and/or
2021 /// extension operations.
2022 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
2023 auto isSupportedExtend = [&](SDValue V) {
2024 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
2025 return true;
2027 if (V.getOpcode() == ISD::AND)
2028 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2029 uint64_t Mask = MaskCst->getZExtValue();
2030 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
2033 return false;
2036 if (!Op.hasOneUse())
2037 return 0;
2039 if (isSupportedExtend(Op))
2040 return 1;
2042 unsigned Opc = Op.getOpcode();
2043 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
2044 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2045 uint64_t Shift = ShiftCst->getZExtValue();
2046 if (isSupportedExtend(Op.getOperand(0)))
2047 return (Shift <= 4) ? 2 : 1;
2048 EVT VT = Op.getValueType();
2049 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
2050 return 1;
2053 return 0;
2056 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2057 SDValue &AArch64cc, SelectionDAG &DAG,
2058 const SDLoc &dl) {
2059 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2060 EVT VT = RHS.getValueType();
2061 uint64_t C = RHSC->getZExtValue();
2062 if (!isLegalArithImmed(C)) {
2063 // Constant does not fit, try adjusting it by one?
2064 switch (CC) {
2065 default:
2066 break;
2067 case ISD::SETLT:
2068 case ISD::SETGE:
2069 if ((VT == MVT::i32 && C != 0x80000000 &&
2070 isLegalArithImmed((uint32_t)(C - 1))) ||
2071 (VT == MVT::i64 && C != 0x80000000ULL &&
2072 isLegalArithImmed(C - 1ULL))) {
2073 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2074 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2075 RHS = DAG.getConstant(C, dl, VT);
2077 break;
2078 case ISD::SETULT:
2079 case ISD::SETUGE:
2080 if ((VT == MVT::i32 && C != 0 &&
2081 isLegalArithImmed((uint32_t)(C - 1))) ||
2082 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
2083 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2084 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
2085 RHS = DAG.getConstant(C, dl, VT);
2087 break;
2088 case ISD::SETLE:
2089 case ISD::SETGT:
2090 if ((VT == MVT::i32 && C != INT32_MAX &&
2091 isLegalArithImmed((uint32_t)(C + 1))) ||
2092 (VT == MVT::i64 && C != INT64_MAX &&
2093 isLegalArithImmed(C + 1ULL))) {
2094 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2095 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2096 RHS = DAG.getConstant(C, dl, VT);
2098 break;
2099 case ISD::SETULE:
2100 case ISD::SETUGT:
2101 if ((VT == MVT::i32 && C != UINT32_MAX &&
2102 isLegalArithImmed((uint32_t)(C + 1))) ||
2103 (VT == MVT::i64 && C != UINT64_MAX &&
2104 isLegalArithImmed(C + 1ULL))) {
2105 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2106 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2107 RHS = DAG.getConstant(C, dl, VT);
2109 break;
2114 // Comparisons are canonicalized so that the RHS operand is simpler than the
2115 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2116 // can fold some shift+extend operations on the RHS operand, so swap the
2117 // operands if that can be done.
2119 // For example:
2120 // lsl w13, w11, #1
2121 // cmp w13, w12
2122 // can be turned into:
2123 // cmp w12, w11, lsl #1
2124 if (!isa<ConstantSDNode>(RHS) ||
2125 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2126 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2128 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2129 std::swap(LHS, RHS);
2130 CC = ISD::getSetCCSwappedOperands(CC);
2134 SDValue Cmp;
2135 AArch64CC::CondCode AArch64CC;
2136 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2137 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2139 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2140 // For the i8 operand, the largest immediate is 255, so this can be easily
2141 // encoded in the compare instruction. For the i16 operand, however, the
2142 // largest immediate cannot be encoded in the compare.
2143 // Therefore, use a sign extending load and cmn to avoid materializing the
2144 // -1 constant. For example,
2145 // movz w1, #65535
2146 // ldrh w0, [x0, #0]
2147 // cmp w0, w1
2148 // >
2149 // ldrsh w0, [x0, #0]
2150 // cmn w0, #1
2151 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2152 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2153 // ensure both the LHS and RHS are truly zero extended and to make sure the
2154 // transformation is profitable.
2155 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2156 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2157 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2158 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2159 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2160 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2161 SDValue SExt =
2162 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2163 DAG.getValueType(MVT::i16));
2164 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2165 RHS.getValueType()),
2166 CC, dl, DAG);
2167 AArch64CC = changeIntCCToAArch64CC(CC);
2171 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2172 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2173 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2174 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2179 if (!Cmp) {
2180 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2181 AArch64CC = changeIntCCToAArch64CC(CC);
2183 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2184 return Cmp;
2187 static std::pair<SDValue, SDValue>
2188 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2189 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2190 "Unsupported value type");
2191 SDValue Value, Overflow;
2192 SDLoc DL(Op);
2193 SDValue LHS = Op.getOperand(0);
2194 SDValue RHS = Op.getOperand(1);
2195 unsigned Opc = 0;
2196 switch (Op.getOpcode()) {
2197 default:
2198 llvm_unreachable("Unknown overflow instruction!");
2199 case ISD::SADDO:
2200 Opc = AArch64ISD::ADDS;
2201 CC = AArch64CC::VS;
2202 break;
2203 case ISD::UADDO:
2204 Opc = AArch64ISD::ADDS;
2205 CC = AArch64CC::HS;
2206 break;
2207 case ISD::SSUBO:
2208 Opc = AArch64ISD::SUBS;
2209 CC = AArch64CC::VS;
2210 break;
2211 case ISD::USUBO:
2212 Opc = AArch64ISD::SUBS;
2213 CC = AArch64CC::LO;
2214 break;
2215 // Multiply needs a little bit extra work.
2216 case ISD::SMULO:
2217 case ISD::UMULO: {
2218 CC = AArch64CC::NE;
2219 bool IsSigned = Op.getOpcode() == ISD::SMULO;
2220 if (Op.getValueType() == MVT::i32) {
2221 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2222 // For a 32 bit multiply with overflow check we want the instruction
2223 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2224 // need to generate the following pattern:
2225 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2226 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2227 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2228 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2229 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2230 DAG.getConstant(0, DL, MVT::i64));
2231 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2232 // operation. We need to clear out the upper 32 bits, because we used a
2233 // widening multiply that wrote all 64 bits. In the end this should be a
2234 // noop.
2235 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2236 if (IsSigned) {
2237 // The signed overflow check requires more than just a simple check for
2238 // any bit set in the upper 32 bits of the result. These bits could be
2239 // just the sign bits of a negative number. To perform the overflow
2240 // check we have to arithmetic shift right the 32nd bit of the result by
2241 // 31 bits. Then we compare the result to the upper 32 bits.
2242 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2243 DAG.getConstant(32, DL, MVT::i64));
2244 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2245 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2246 DAG.getConstant(31, DL, MVT::i64));
2247 // It is important that LowerBits is last, otherwise the arithmetic
2248 // shift will not be folded into the compare (SUBS).
2249 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2250 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2251 .getValue(1);
2252 } else {
2253 // The overflow check for unsigned multiply is easy. We only need to
2254 // check if any of the upper 32 bits are set. This can be done with a
2255 // CMP (shifted register). For that we need to generate the following
2256 // pattern:
2257 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2258 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2259 DAG.getConstant(32, DL, MVT::i64));
2260 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2261 Overflow =
2262 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2263 DAG.getConstant(0, DL, MVT::i64),
2264 UpperBits).getValue(1);
2266 break;
2268 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2269 // For the 64 bit multiply
2270 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2271 if (IsSigned) {
2272 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2273 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2274 DAG.getConstant(63, DL, MVT::i64));
2275 // It is important that LowerBits is last, otherwise the arithmetic
2276 // shift will not be folded into the compare (SUBS).
2277 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2278 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2279 .getValue(1);
2280 } else {
2281 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2282 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2283 Overflow =
2284 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2285 DAG.getConstant(0, DL, MVT::i64),
2286 UpperBits).getValue(1);
2288 break;
2290 } // switch (...)
2292 if (Opc) {
2293 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2295 // Emit the AArch64 operation with overflow check.
2296 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2297 Overflow = Value.getValue(1);
2299 return std::make_pair(Value, Overflow);
2302 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2303 RTLIB::Libcall Call) const {
2304 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2305 MakeLibCallOptions CallOptions;
2306 return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
2309 // Returns true if the given Op is the overflow flag result of an overflow
2310 // intrinsic operation.
2311 static bool isOverflowIntrOpRes(SDValue Op) {
2312 unsigned Opc = Op.getOpcode();
2313 return (Op.getResNo() == 1 &&
2314 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2315 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2318 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2319 SDValue Sel = Op.getOperand(0);
2320 SDValue Other = Op.getOperand(1);
2321 SDLoc dl(Sel);
2323 // If the operand is an overflow checking operation, invert the condition
2324 // code and kill the Not operation. I.e., transform:
2325 // (xor (overflow_op_bool, 1))
2326 // -->
2327 // (csel 1, 0, invert(cc), overflow_op_bool)
2328 // ... which later gets transformed to just a cset instruction with an
2329 // inverted condition code, rather than a cset + eor sequence.
2330 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2331 // Only lower legal XALUO ops.
2332 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2333 return SDValue();
2335 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2336 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2337 AArch64CC::CondCode CC;
2338 SDValue Value, Overflow;
2339 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2340 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2341 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2342 CCVal, Overflow);
2344 // If neither operand is a SELECT_CC, give up.
2345 if (Sel.getOpcode() != ISD::SELECT_CC)
2346 std::swap(Sel, Other);
2347 if (Sel.getOpcode() != ISD::SELECT_CC)
2348 return Op;
2350 // The folding we want to perform is:
2351 // (xor x, (select_cc a, b, cc, 0, -1) )
2352 // -->
2353 // (csel x, (xor x, -1), cc ...)
2355 // The latter will get matched to a CSINV instruction.
2357 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2358 SDValue LHS = Sel.getOperand(0);
2359 SDValue RHS = Sel.getOperand(1);
2360 SDValue TVal = Sel.getOperand(2);
2361 SDValue FVal = Sel.getOperand(3);
2363 // FIXME: This could be generalized to non-integer comparisons.
2364 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2365 return Op;
2367 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2368 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2370 // The values aren't constants, this isn't the pattern we're looking for.
2371 if (!CFVal || !CTVal)
2372 return Op;
2374 // We can commute the SELECT_CC by inverting the condition. This
2375 // might be needed to make this fit into a CSINV pattern.
2376 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2377 std::swap(TVal, FVal);
2378 std::swap(CTVal, CFVal);
2379 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
2382 // If the constants line up, perform the transform!
2383 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2384 SDValue CCVal;
2385 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2387 FVal = Other;
2388 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2389 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2391 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2392 CCVal, Cmp);
2395 return Op;
2398 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2399 EVT VT = Op.getValueType();
2401 // Let legalize expand this if it isn't a legal type yet.
2402 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2403 return SDValue();
2405 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2407 unsigned Opc;
2408 bool ExtraOp = false;
2409 switch (Op.getOpcode()) {
2410 default:
2411 llvm_unreachable("Invalid code");
2412 case ISD::ADDC:
2413 Opc = AArch64ISD::ADDS;
2414 break;
2415 case ISD::SUBC:
2416 Opc = AArch64ISD::SUBS;
2417 break;
2418 case ISD::ADDE:
2419 Opc = AArch64ISD::ADCS;
2420 ExtraOp = true;
2421 break;
2422 case ISD::SUBE:
2423 Opc = AArch64ISD::SBCS;
2424 ExtraOp = true;
2425 break;
2428 if (!ExtraOp)
2429 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2430 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2431 Op.getOperand(2));
2434 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2435 // Let legalize expand this if it isn't a legal type yet.
2436 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2437 return SDValue();
2439 SDLoc dl(Op);
2440 AArch64CC::CondCode CC;
2441 // The actual operation that sets the overflow or carry flag.
2442 SDValue Value, Overflow;
2443 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2445 // We use 0 and 1 as false and true values.
2446 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2447 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2449 // We use an inverted condition, because the conditional select is inverted
2450 // too. This will allow it to be selected to a single instruction:
2451 // CSINC Wd, WZR, WZR, invert(cond).
2452 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2453 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2454 CCVal, Overflow);
2456 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2457 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2460 // Prefetch operands are:
2461 // 1: Address to prefetch
2462 // 2: bool isWrite
2463 // 3: int locality (0 = no locality ... 3 = extreme locality)
2464 // 4: bool isDataCache
2465 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2466 SDLoc DL(Op);
2467 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2468 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2469 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2471 bool IsStream = !Locality;
2472 // When the locality number is set
2473 if (Locality) {
2474 // The front-end should have filtered out the out-of-range values
2475 assert(Locality <= 3 && "Prefetch locality out-of-range");
2476 // The locality degree is the opposite of the cache speed.
2477 // Put the number the other way around.
2478 // The encoding starts at 0 for level 1
2479 Locality = 3 - Locality;
2482 // built the mask value encoding the expected behavior.
2483 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2484 (!IsData << 3) | // IsDataCache bit
2485 (Locality << 1) | // Cache level bits
2486 (unsigned)IsStream; // Stream bit
2487 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2488 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2491 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2492 SelectionDAG &DAG) const {
2493 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2495 RTLIB::Libcall LC;
2496 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2498 return LowerF128Call(Op, DAG, LC);
2501 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2502 SelectionDAG &DAG) const {
2503 if (Op.getOperand(0).getValueType() != MVT::f128) {
2504 // It's legal except when f128 is involved
2505 return Op;
2508 RTLIB::Libcall LC;
2509 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2511 // FP_ROUND node has a second operand indicating whether it is known to be
2512 // precise. That doesn't take part in the LibCall so we can't directly use
2513 // LowerF128Call.
2514 SDValue SrcVal = Op.getOperand(0);
2515 MakeLibCallOptions CallOptions;
2516 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
2517 SDLoc(Op)).first;
2520 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2521 SelectionDAG &DAG) const {
2522 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2523 // Any additional optimization in this function should be recorded
2524 // in the cost tables.
2525 EVT InVT = Op.getOperand(0).getValueType();
2526 EVT VT = Op.getValueType();
2527 unsigned NumElts = InVT.getVectorNumElements();
2529 // f16 conversions are promoted to f32 when full fp16 is not supported.
2530 if (InVT.getVectorElementType() == MVT::f16 &&
2531 !Subtarget->hasFullFP16()) {
2532 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2533 SDLoc dl(Op);
2534 return DAG.getNode(
2535 Op.getOpcode(), dl, Op.getValueType(),
2536 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2539 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2540 SDLoc dl(Op);
2541 SDValue Cv =
2542 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2543 Op.getOperand(0));
2544 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2547 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2548 SDLoc dl(Op);
2549 MVT ExtVT =
2550 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2551 VT.getVectorNumElements());
2552 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2553 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2556 // Type changing conversions are illegal.
2557 return Op;
2560 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2561 SelectionDAG &DAG) const {
2562 if (Op.getOperand(0).getValueType().isVector())
2563 return LowerVectorFP_TO_INT(Op, DAG);
2565 // f16 conversions are promoted to f32 when full fp16 is not supported.
2566 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2567 !Subtarget->hasFullFP16()) {
2568 SDLoc dl(Op);
2569 return DAG.getNode(
2570 Op.getOpcode(), dl, Op.getValueType(),
2571 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2574 if (Op.getOperand(0).getValueType() != MVT::f128) {
2575 // It's legal except when f128 is involved
2576 return Op;
2579 RTLIB::Libcall LC;
2580 if (Op.getOpcode() == ISD::FP_TO_SINT)
2581 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2582 else
2583 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2585 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2586 MakeLibCallOptions CallOptions;
2587 return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
2590 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2591 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2592 // Any additional optimization in this function should be recorded
2593 // in the cost tables.
2594 EVT VT = Op.getValueType();
2595 SDLoc dl(Op);
2596 SDValue In = Op.getOperand(0);
2597 EVT InVT = In.getValueType();
2599 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2600 MVT CastVT =
2601 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2602 InVT.getVectorNumElements());
2603 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2604 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2607 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2608 unsigned CastOpc =
2609 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2610 EVT CastVT = VT.changeVectorElementTypeToInteger();
2611 In = DAG.getNode(CastOpc, dl, CastVT, In);
2612 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2615 return Op;
2618 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2619 SelectionDAG &DAG) const {
2620 if (Op.getValueType().isVector())
2621 return LowerVectorINT_TO_FP(Op, DAG);
2623 // f16 conversions are promoted to f32 when full fp16 is not supported.
2624 if (Op.getValueType() == MVT::f16 &&
2625 !Subtarget->hasFullFP16()) {
2626 SDLoc dl(Op);
2627 return DAG.getNode(
2628 ISD::FP_ROUND, dl, MVT::f16,
2629 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2630 DAG.getIntPtrConstant(0, dl));
2633 // i128 conversions are libcalls.
2634 if (Op.getOperand(0).getValueType() == MVT::i128)
2635 return SDValue();
2637 // Other conversions are legal, unless it's to the completely software-based
2638 // fp128.
2639 if (Op.getValueType() != MVT::f128)
2640 return Op;
2642 RTLIB::Libcall LC;
2643 if (Op.getOpcode() == ISD::SINT_TO_FP)
2644 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2645 else
2646 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2648 return LowerF128Call(Op, DAG, LC);
2651 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2652 SelectionDAG &DAG) const {
2653 // For iOS, we want to call an alternative entry point: __sincos_stret,
2654 // which returns the values in two S / D registers.
2655 SDLoc dl(Op);
2656 SDValue Arg = Op.getOperand(0);
2657 EVT ArgVT = Arg.getValueType();
2658 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2660 ArgListTy Args;
2661 ArgListEntry Entry;
2663 Entry.Node = Arg;
2664 Entry.Ty = ArgTy;
2665 Entry.IsSExt = false;
2666 Entry.IsZExt = false;
2667 Args.push_back(Entry);
2669 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2670 : RTLIB::SINCOS_STRET_F32;
2671 const char *LibcallName = getLibcallName(LC);
2672 SDValue Callee =
2673 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2675 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2676 TargetLowering::CallLoweringInfo CLI(DAG);
2677 CLI.setDebugLoc(dl)
2678 .setChain(DAG.getEntryNode())
2679 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2681 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2682 return CallResult.first;
2685 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2686 if (Op.getValueType() != MVT::f16)
2687 return SDValue();
2689 assert(Op.getOperand(0).getValueType() == MVT::i16);
2690 SDLoc DL(Op);
2692 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2693 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2694 return SDValue(
2695 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2696 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2700 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2701 if (OrigVT.getSizeInBits() >= 64)
2702 return OrigVT;
2704 assert(OrigVT.isSimple() && "Expecting a simple value type");
2706 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2707 switch (OrigSimpleTy) {
2708 default: llvm_unreachable("Unexpected Vector Type");
2709 case MVT::v2i8:
2710 case MVT::v2i16:
2711 return MVT::v2i32;
2712 case MVT::v4i8:
2713 return MVT::v4i16;
2717 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2718 const EVT &OrigTy,
2719 const EVT &ExtTy,
2720 unsigned ExtOpcode) {
2721 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2722 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2723 // 64-bits we need to insert a new extension so that it will be 64-bits.
2724 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2725 if (OrigTy.getSizeInBits() >= 64)
2726 return N;
2728 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2729 EVT NewVT = getExtensionTo64Bits(OrigTy);
2731 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2734 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2735 bool isSigned) {
2736 EVT VT = N->getValueType(0);
2738 if (N->getOpcode() != ISD::BUILD_VECTOR)
2739 return false;
2741 for (const SDValue &Elt : N->op_values()) {
2742 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2743 unsigned EltSize = VT.getScalarSizeInBits();
2744 unsigned HalfSize = EltSize / 2;
2745 if (isSigned) {
2746 if (!isIntN(HalfSize, C->getSExtValue()))
2747 return false;
2748 } else {
2749 if (!isUIntN(HalfSize, C->getZExtValue()))
2750 return false;
2752 continue;
2754 return false;
2757 return true;
2760 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2761 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2762 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2763 N->getOperand(0)->getValueType(0),
2764 N->getValueType(0),
2765 N->getOpcode());
2767 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2768 EVT VT = N->getValueType(0);
2769 SDLoc dl(N);
2770 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2771 unsigned NumElts = VT.getVectorNumElements();
2772 MVT TruncVT = MVT::getIntegerVT(EltSize);
2773 SmallVector<SDValue, 8> Ops;
2774 for (unsigned i = 0; i != NumElts; ++i) {
2775 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2776 const APInt &CInt = C->getAPIntValue();
2777 // Element types smaller than 32 bits are not legal, so use i32 elements.
2778 // The values are implicitly truncated so sext vs. zext doesn't matter.
2779 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2781 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2784 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2785 return N->getOpcode() == ISD::SIGN_EXTEND ||
2786 isExtendedBUILD_VECTOR(N, DAG, true);
2789 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2790 return N->getOpcode() == ISD::ZERO_EXTEND ||
2791 isExtendedBUILD_VECTOR(N, DAG, false);
2794 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2795 unsigned Opcode = N->getOpcode();
2796 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2797 SDNode *N0 = N->getOperand(0).getNode();
2798 SDNode *N1 = N->getOperand(1).getNode();
2799 return N0->hasOneUse() && N1->hasOneUse() &&
2800 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2802 return false;
2805 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2806 unsigned Opcode = N->getOpcode();
2807 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2808 SDNode *N0 = N->getOperand(0).getNode();
2809 SDNode *N1 = N->getOperand(1).getNode();
2810 return N0->hasOneUse() && N1->hasOneUse() &&
2811 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2813 return false;
2816 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2817 SelectionDAG &DAG) const {
2818 // The rounding mode is in bits 23:22 of the FPSCR.
2819 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2820 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2821 // so that the shift + and get folded into a bitfield extract.
2822 SDLoc dl(Op);
2824 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2825 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2826 MVT::i64));
2827 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2828 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2829 DAG.getConstant(1U << 22, dl, MVT::i32));
2830 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2831 DAG.getConstant(22, dl, MVT::i32));
2832 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2833 DAG.getConstant(3, dl, MVT::i32));
2836 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2837 // Multiplications are only custom-lowered for 128-bit vectors so that
2838 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2839 EVT VT = Op.getValueType();
2840 assert(VT.is128BitVector() && VT.isInteger() &&
2841 "unexpected type for custom-lowering ISD::MUL");
2842 SDNode *N0 = Op.getOperand(0).getNode();
2843 SDNode *N1 = Op.getOperand(1).getNode();
2844 unsigned NewOpc = 0;
2845 bool isMLA = false;
2846 bool isN0SExt = isSignExtended(N0, DAG);
2847 bool isN1SExt = isSignExtended(N1, DAG);
2848 if (isN0SExt && isN1SExt)
2849 NewOpc = AArch64ISD::SMULL;
2850 else {
2851 bool isN0ZExt = isZeroExtended(N0, DAG);
2852 bool isN1ZExt = isZeroExtended(N1, DAG);
2853 if (isN0ZExt && isN1ZExt)
2854 NewOpc = AArch64ISD::UMULL;
2855 else if (isN1SExt || isN1ZExt) {
2856 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2857 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2858 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2859 NewOpc = AArch64ISD::SMULL;
2860 isMLA = true;
2861 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2862 NewOpc = AArch64ISD::UMULL;
2863 isMLA = true;
2864 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2865 std::swap(N0, N1);
2866 NewOpc = AArch64ISD::UMULL;
2867 isMLA = true;
2871 if (!NewOpc) {
2872 if (VT == MVT::v2i64)
2873 // Fall through to expand this. It is not legal.
2874 return SDValue();
2875 else
2876 // Other vector multiplications are legal.
2877 return Op;
2881 // Legalize to a S/UMULL instruction
2882 SDLoc DL(Op);
2883 SDValue Op0;
2884 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2885 if (!isMLA) {
2886 Op0 = skipExtensionForVectorMULL(N0, DAG);
2887 assert(Op0.getValueType().is64BitVector() &&
2888 Op1.getValueType().is64BitVector() &&
2889 "unexpected types for extended operands to VMULL");
2890 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2892 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2893 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2894 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2895 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2896 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2897 EVT Op1VT = Op1.getValueType();
2898 return DAG.getNode(N0->getOpcode(), DL, VT,
2899 DAG.getNode(NewOpc, DL, VT,
2900 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2901 DAG.getNode(NewOpc, DL, VT,
2902 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2905 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2906 SelectionDAG &DAG) const {
2907 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2908 SDLoc dl(Op);
2909 switch (IntNo) {
2910 default: return SDValue(); // Don't custom lower most intrinsics.
2911 case Intrinsic::thread_pointer: {
2912 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2913 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2915 case Intrinsic::aarch64_neon_abs: {
2916 EVT Ty = Op.getValueType();
2917 if (Ty == MVT::i64) {
2918 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2919 Op.getOperand(1));
2920 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2921 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2922 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2923 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2924 } else {
2925 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2928 case Intrinsic::aarch64_neon_smax:
2929 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2930 Op.getOperand(1), Op.getOperand(2));
2931 case Intrinsic::aarch64_neon_umax:
2932 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2933 Op.getOperand(1), Op.getOperand(2));
2934 case Intrinsic::aarch64_neon_smin:
2935 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2936 Op.getOperand(1), Op.getOperand(2));
2937 case Intrinsic::aarch64_neon_umin:
2938 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2939 Op.getOperand(1), Op.getOperand(2));
2941 case Intrinsic::aarch64_sve_sunpkhi:
2942 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
2943 Op.getOperand(1));
2944 case Intrinsic::aarch64_sve_sunpklo:
2945 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
2946 Op.getOperand(1));
2947 case Intrinsic::aarch64_sve_uunpkhi:
2948 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
2949 Op.getOperand(1));
2950 case Intrinsic::aarch64_sve_uunpklo:
2951 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
2952 Op.getOperand(1));
2953 case Intrinsic::aarch64_sve_clasta_n:
2954 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
2955 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2956 case Intrinsic::aarch64_sve_clastb_n:
2957 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
2958 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2959 case Intrinsic::aarch64_sve_lasta:
2960 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
2961 Op.getOperand(1), Op.getOperand(2));
2962 case Intrinsic::aarch64_sve_lastb:
2963 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
2964 Op.getOperand(1), Op.getOperand(2));
2965 case Intrinsic::aarch64_sve_rev:
2966 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
2967 Op.getOperand(1));
2968 case Intrinsic::aarch64_sve_tbl:
2969 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
2970 Op.getOperand(1), Op.getOperand(2));
2971 case Intrinsic::aarch64_sve_trn1:
2972 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
2973 Op.getOperand(1), Op.getOperand(2));
2974 case Intrinsic::aarch64_sve_trn2:
2975 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
2976 Op.getOperand(1), Op.getOperand(2));
2977 case Intrinsic::aarch64_sve_uzp1:
2978 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
2979 Op.getOperand(1), Op.getOperand(2));
2980 case Intrinsic::aarch64_sve_uzp2:
2981 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
2982 Op.getOperand(1), Op.getOperand(2));
2983 case Intrinsic::aarch64_sve_zip1:
2984 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
2985 Op.getOperand(1), Op.getOperand(2));
2986 case Intrinsic::aarch64_sve_zip2:
2987 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
2988 Op.getOperand(1), Op.getOperand(2));
2989 case Intrinsic::aarch64_sve_ptrue:
2990 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
2991 Op.getOperand(1));
2993 case Intrinsic::aarch64_sve_insr: {
2994 SDValue Scalar = Op.getOperand(2);
2995 EVT ScalarTy = Scalar.getValueType();
2996 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
2997 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
2999 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
3000 Op.getOperand(1), Scalar);
3003 case Intrinsic::localaddress: {
3004 const auto &MF = DAG.getMachineFunction();
3005 const auto *RegInfo = Subtarget->getRegisterInfo();
3006 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
3007 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
3008 Op.getSimpleValueType());
3011 case Intrinsic::eh_recoverfp: {
3012 // FIXME: This needs to be implemented to correctly handle highly aligned
3013 // stack objects. For now we simply return the incoming FP. Refer D53541
3014 // for more details.
3015 SDValue FnOp = Op.getOperand(1);
3016 SDValue IncomingFPOp = Op.getOperand(2);
3017 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
3018 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
3019 if (!Fn)
3020 report_fatal_error(
3021 "llvm.eh.recoverfp must take a function as the first argument");
3022 return IncomingFPOp;
3027 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
3028 return ExtVal.getValueType().isScalableVector();
3031 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
3032 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
3033 EVT VT, EVT MemVT,
3034 SelectionDAG &DAG) {
3035 assert(VT.isVector() && "VT should be a vector type");
3036 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
3038 SDValue Value = ST->getValue();
3040 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
3041 // the word lane which represent the v4i8 subvector. It optimizes the store
3042 // to:
3044 // xtn v0.8b, v0.8h
3045 // str s0, [x0]
3047 SDValue Undef = DAG.getUNDEF(MVT::i16);
3048 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
3049 {Undef, Undef, Undef, Undef});
3051 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
3052 Value, UndefVec);
3053 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
3055 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
3056 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
3057 Trunc, DAG.getConstant(0, DL, MVT::i64));
3059 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
3060 ST->getBasePtr(), ST->getMemOperand());
3063 // Custom lowering for any store, vector or scalar and/or default or with
3064 // a truncate operations. Currently only custom lower truncate operation
3065 // from vector v4i16 to v4i8 or volatile stores of i128.
3066 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
3067 SelectionDAG &DAG) const {
3068 SDLoc Dl(Op);
3069 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
3070 assert (StoreNode && "Can only custom lower store nodes");
3072 SDValue Value = StoreNode->getValue();
3074 EVT VT = Value.getValueType();
3075 EVT MemVT = StoreNode->getMemoryVT();
3077 if (VT.isVector()) {
3078 unsigned AS = StoreNode->getAddressSpace();
3079 unsigned Align = StoreNode->getAlignment();
3080 if (Align < MemVT.getStoreSize() &&
3081 !allowsMisalignedMemoryAccesses(MemVT, AS, Align,
3082 StoreNode->getMemOperand()->getFlags(),
3083 nullptr)) {
3084 return scalarizeVectorStore(StoreNode, DAG);
3087 if (StoreNode->isTruncatingStore()) {
3088 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
3090 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
3091 // the custom lowering, as there are no un-paired non-temporal stores and
3092 // legalization will break up 256 bit inputs.
3093 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
3094 MemVT.getVectorElementCount().Min % 2u == 0 &&
3095 ((MemVT.getScalarSizeInBits() == 8u ||
3096 MemVT.getScalarSizeInBits() == 16u ||
3097 MemVT.getScalarSizeInBits() == 32u ||
3098 MemVT.getScalarSizeInBits() == 64u))) {
3099 SDValue Lo =
3100 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
3101 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3102 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
3103 SDValue Hi = DAG.getNode(
3104 ISD::EXTRACT_SUBVECTOR, Dl,
3105 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
3106 StoreNode->getValue(),
3107 DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64));
3108 SDValue Result = DAG.getMemIntrinsicNode(
3109 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
3110 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3111 StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3112 return Result;
3114 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
3115 assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
3116 SDValue Lo =
3117 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3118 DAG.getConstant(0, Dl, MVT::i64));
3119 SDValue Hi =
3120 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
3121 DAG.getConstant(1, Dl, MVT::i64));
3122 SDValue Result = DAG.getMemIntrinsicNode(
3123 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
3124 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
3125 StoreNode->getMemoryVT(), StoreNode->getMemOperand());
3126 return Result;
3129 return SDValue();
3132 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
3133 SelectionDAG &DAG) const {
3134 LLVM_DEBUG(dbgs() << "Custom lowering: ");
3135 LLVM_DEBUG(Op.dump());
3137 switch (Op.getOpcode()) {
3138 default:
3139 llvm_unreachable("unimplemented operand");
3140 return SDValue();
3141 case ISD::BITCAST:
3142 return LowerBITCAST(Op, DAG);
3143 case ISD::GlobalAddress:
3144 return LowerGlobalAddress(Op, DAG);
3145 case ISD::GlobalTLSAddress:
3146 return LowerGlobalTLSAddress(Op, DAG);
3147 case ISD::SETCC:
3148 return LowerSETCC(Op, DAG);
3149 case ISD::BR_CC:
3150 return LowerBR_CC(Op, DAG);
3151 case ISD::SELECT:
3152 return LowerSELECT(Op, DAG);
3153 case ISD::SELECT_CC:
3154 return LowerSELECT_CC(Op, DAG);
3155 case ISD::JumpTable:
3156 return LowerJumpTable(Op, DAG);
3157 case ISD::BR_JT:
3158 return LowerBR_JT(Op, DAG);
3159 case ISD::ConstantPool:
3160 return LowerConstantPool(Op, DAG);
3161 case ISD::BlockAddress:
3162 return LowerBlockAddress(Op, DAG);
3163 case ISD::VASTART:
3164 return LowerVASTART(Op, DAG);
3165 case ISD::VACOPY:
3166 return LowerVACOPY(Op, DAG);
3167 case ISD::VAARG:
3168 return LowerVAARG(Op, DAG);
3169 case ISD::ADDC:
3170 case ISD::ADDE:
3171 case ISD::SUBC:
3172 case ISD::SUBE:
3173 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
3174 case ISD::SADDO:
3175 case ISD::UADDO:
3176 case ISD::SSUBO:
3177 case ISD::USUBO:
3178 case ISD::SMULO:
3179 case ISD::UMULO:
3180 return LowerXALUO(Op, DAG);
3181 case ISD::FADD:
3182 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
3183 case ISD::FSUB:
3184 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
3185 case ISD::FMUL:
3186 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
3187 case ISD::FDIV:
3188 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
3189 case ISD::FP_ROUND:
3190 return LowerFP_ROUND(Op, DAG);
3191 case ISD::FP_EXTEND:
3192 return LowerFP_EXTEND(Op, DAG);
3193 case ISD::FRAMEADDR:
3194 return LowerFRAMEADDR(Op, DAG);
3195 case ISD::SPONENTRY:
3196 return LowerSPONENTRY(Op, DAG);
3197 case ISD::RETURNADDR:
3198 return LowerRETURNADDR(Op, DAG);
3199 case ISD::ADDROFRETURNADDR:
3200 return LowerADDROFRETURNADDR(Op, DAG);
3201 case ISD::INSERT_VECTOR_ELT:
3202 return LowerINSERT_VECTOR_ELT(Op, DAG);
3203 case ISD::EXTRACT_VECTOR_ELT:
3204 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3205 case ISD::BUILD_VECTOR:
3206 return LowerBUILD_VECTOR(Op, DAG);
3207 case ISD::VECTOR_SHUFFLE:
3208 return LowerVECTOR_SHUFFLE(Op, DAG);
3209 case ISD::SPLAT_VECTOR:
3210 return LowerSPLAT_VECTOR(Op, DAG);
3211 case ISD::EXTRACT_SUBVECTOR:
3212 return LowerEXTRACT_SUBVECTOR(Op, DAG);
3213 case ISD::SRA:
3214 case ISD::SRL:
3215 case ISD::SHL:
3216 return LowerVectorSRA_SRL_SHL(Op, DAG);
3217 case ISD::SHL_PARTS:
3218 return LowerShiftLeftParts(Op, DAG);
3219 case ISD::SRL_PARTS:
3220 case ISD::SRA_PARTS:
3221 return LowerShiftRightParts(Op, DAG);
3222 case ISD::CTPOP:
3223 return LowerCTPOP(Op, DAG);
3224 case ISD::FCOPYSIGN:
3225 return LowerFCOPYSIGN(Op, DAG);
3226 case ISD::OR:
3227 return LowerVectorOR(Op, DAG);
3228 case ISD::XOR:
3229 return LowerXOR(Op, DAG);
3230 case ISD::PREFETCH:
3231 return LowerPREFETCH(Op, DAG);
3232 case ISD::SINT_TO_FP:
3233 case ISD::UINT_TO_FP:
3234 return LowerINT_TO_FP(Op, DAG);
3235 case ISD::FP_TO_SINT:
3236 case ISD::FP_TO_UINT:
3237 return LowerFP_TO_INT(Op, DAG);
3238 case ISD::FSINCOS:
3239 return LowerFSINCOS(Op, DAG);
3240 case ISD::FLT_ROUNDS_:
3241 return LowerFLT_ROUNDS_(Op, DAG);
3242 case ISD::MUL:
3243 return LowerMUL(Op, DAG);
3244 case ISD::INTRINSIC_WO_CHAIN:
3245 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3246 case ISD::STORE:
3247 return LowerSTORE(Op, DAG);
3248 case ISD::VECREDUCE_ADD:
3249 case ISD::VECREDUCE_SMAX:
3250 case ISD::VECREDUCE_SMIN:
3251 case ISD::VECREDUCE_UMAX:
3252 case ISD::VECREDUCE_UMIN:
3253 case ISD::VECREDUCE_FMAX:
3254 case ISD::VECREDUCE_FMIN:
3255 return LowerVECREDUCE(Op, DAG);
3256 case ISD::ATOMIC_LOAD_SUB:
3257 return LowerATOMIC_LOAD_SUB(Op, DAG);
3258 case ISD::ATOMIC_LOAD_AND:
3259 return LowerATOMIC_LOAD_AND(Op, DAG);
3260 case ISD::DYNAMIC_STACKALLOC:
3261 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3262 case ISD::VSCALE:
3263 return LowerVSCALE(Op, DAG);
3267 //===----------------------------------------------------------------------===//
3268 // Calling Convention Implementation
3269 //===----------------------------------------------------------------------===//
3271 /// Selects the correct CCAssignFn for a given CallingConvention value.
3272 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3273 bool IsVarArg) const {
3274 switch (CC) {
3275 default:
3276 report_fatal_error("Unsupported calling convention.");
3277 case CallingConv::AArch64_SVE_VectorCall:
3278 // Calling SVE functions is currently not yet supported.
3279 report_fatal_error("Unsupported calling convention.");
3280 case CallingConv::WebKit_JS:
3281 return CC_AArch64_WebKit_JS;
3282 case CallingConv::GHC:
3283 return CC_AArch64_GHC;
3284 case CallingConv::C:
3285 case CallingConv::Fast:
3286 case CallingConv::PreserveMost:
3287 case CallingConv::CXX_FAST_TLS:
3288 case CallingConv::Swift:
3289 if (Subtarget->isTargetWindows() && IsVarArg)
3290 return CC_AArch64_Win64_VarArg;
3291 if (!Subtarget->isTargetDarwin())
3292 return CC_AArch64_AAPCS;
3293 if (!IsVarArg)
3294 return CC_AArch64_DarwinPCS;
3295 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3296 : CC_AArch64_DarwinPCS_VarArg;
3297 case CallingConv::Win64:
3298 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3299 case CallingConv::CFGuard_Check:
3300 return CC_AArch64_Win64_CFGuard_Check;
3301 case CallingConv::AArch64_VectorCall:
3302 return CC_AArch64_AAPCS;
3306 CCAssignFn *
3307 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3308 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3309 : RetCC_AArch64_AAPCS;
3312 SDValue AArch64TargetLowering::LowerFormalArguments(
3313 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3314 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3315 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3316 MachineFunction &MF = DAG.getMachineFunction();
3317 MachineFrameInfo &MFI = MF.getFrameInfo();
3318 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3320 // Assign locations to all of the incoming arguments.
3321 SmallVector<CCValAssign, 16> ArgLocs;
3322 DenseMap<unsigned, SDValue> CopiedRegs;
3323 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3324 *DAG.getContext());
3326 // At this point, Ins[].VT may already be promoted to i32. To correctly
3327 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3328 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3329 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3330 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3331 // LocVT.
3332 unsigned NumArgs = Ins.size();
3333 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3334 unsigned CurArgIdx = 0;
3335 for (unsigned i = 0; i != NumArgs; ++i) {
3336 MVT ValVT = Ins[i].VT;
3337 if (Ins[i].isOrigArg()) {
3338 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3339 CurArgIdx = Ins[i].getOrigArgIndex();
3341 // Get type of the original argument.
3342 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3343 /*AllowUnknown*/ true);
3344 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3345 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3346 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3347 ValVT = MVT::i8;
3348 else if (ActualMVT == MVT::i16)
3349 ValVT = MVT::i16;
3351 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3352 bool Res =
3353 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3354 assert(!Res && "Call operand has unhandled type");
3355 (void)Res;
3357 assert(ArgLocs.size() == Ins.size());
3358 SmallVector<SDValue, 16> ArgValues;
3359 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3360 CCValAssign &VA = ArgLocs[i];
3362 if (Ins[i].Flags.isByVal()) {
3363 // Byval is used for HFAs in the PCS, but the system should work in a
3364 // non-compliant manner for larger structs.
3365 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3366 int Size = Ins[i].Flags.getByValSize();
3367 unsigned NumRegs = (Size + 7) / 8;
3369 // FIXME: This works on big-endian for composite byvals, which are the common
3370 // case. It should also work for fundamental types too.
3371 unsigned FrameIdx =
3372 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3373 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3374 InVals.push_back(FrameIdxN);
3376 continue;
3379 SDValue ArgValue;
3380 if (VA.isRegLoc()) {
3381 // Arguments stored in registers.
3382 EVT RegVT = VA.getLocVT();
3383 const TargetRegisterClass *RC;
3385 if (RegVT == MVT::i32)
3386 RC = &AArch64::GPR32RegClass;
3387 else if (RegVT == MVT::i64)
3388 RC = &AArch64::GPR64RegClass;
3389 else if (RegVT == MVT::f16)
3390 RC = &AArch64::FPR16RegClass;
3391 else if (RegVT == MVT::f32)
3392 RC = &AArch64::FPR32RegClass;
3393 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3394 RC = &AArch64::FPR64RegClass;
3395 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3396 RC = &AArch64::FPR128RegClass;
3397 else if (RegVT.isScalableVector() &&
3398 RegVT.getVectorElementType() == MVT::i1)
3399 RC = &AArch64::PPRRegClass;
3400 else if (RegVT.isScalableVector())
3401 RC = &AArch64::ZPRRegClass;
3402 else
3403 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3405 // Transform the arguments in physical registers into virtual ones.
3406 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3407 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3409 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3410 // to 64 bits. Insert an assert[sz]ext to capture this, then
3411 // truncate to the right size.
3412 switch (VA.getLocInfo()) {
3413 default:
3414 llvm_unreachable("Unknown loc info!");
3415 case CCValAssign::Full:
3416 break;
3417 case CCValAssign::Indirect:
3418 assert(VA.getValVT().isScalableVector() &&
3419 "Only scalable vectors can be passed indirectly");
3420 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3421 case CCValAssign::BCvt:
3422 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3423 break;
3424 case CCValAssign::AExt:
3425 case CCValAssign::SExt:
3426 case CCValAssign::ZExt:
3427 break;
3428 case CCValAssign::AExtUpper:
3429 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3430 DAG.getConstant(32, DL, RegVT));
3431 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3432 break;
3434 } else { // VA.isRegLoc()
3435 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3436 unsigned ArgOffset = VA.getLocMemOffset();
3437 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3439 uint32_t BEAlign = 0;
3440 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3441 !Ins[i].Flags.isInConsecutiveRegs())
3442 BEAlign = 8 - ArgSize;
3444 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3446 // Create load nodes to retrieve arguments from the stack.
3447 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3449 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3450 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3451 MVT MemVT = VA.getValVT();
3453 switch (VA.getLocInfo()) {
3454 default:
3455 break;
3456 case CCValAssign::Trunc:
3457 case CCValAssign::BCvt:
3458 MemVT = VA.getLocVT();
3459 break;
3460 case CCValAssign::Indirect:
3461 assert(VA.getValVT().isScalableVector() &&
3462 "Only scalable vectors can be passed indirectly");
3463 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3464 case CCValAssign::SExt:
3465 ExtType = ISD::SEXTLOAD;
3466 break;
3467 case CCValAssign::ZExt:
3468 ExtType = ISD::ZEXTLOAD;
3469 break;
3470 case CCValAssign::AExt:
3471 ExtType = ISD::EXTLOAD;
3472 break;
3475 ArgValue = DAG.getExtLoad(
3476 ExtType, DL, VA.getLocVT(), Chain, FIN,
3477 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3478 MemVT);
3481 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3482 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3483 ArgValue, DAG.getValueType(MVT::i32));
3484 InVals.push_back(ArgValue);
3487 // varargs
3488 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3489 if (isVarArg) {
3490 if (!Subtarget->isTargetDarwin() || IsWin64) {
3491 // The AAPCS variadic function ABI is identical to the non-variadic
3492 // one. As a result there may be more arguments in registers and we should
3493 // save them for future reference.
3494 // Win64 variadic functions also pass arguments in registers, but all float
3495 // arguments are passed in integer registers.
3496 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3499 // This will point to the next argument passed via stack.
3500 unsigned StackOffset = CCInfo.getNextStackOffset();
3501 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3502 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3503 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3505 if (MFI.hasMustTailInVarArgFunc()) {
3506 SmallVector<MVT, 2> RegParmTypes;
3507 RegParmTypes.push_back(MVT::i64);
3508 RegParmTypes.push_back(MVT::f128);
3509 // Compute the set of forwarded registers. The rest are scratch.
3510 SmallVectorImpl<ForwardedRegister> &Forwards =
3511 FuncInfo->getForwardedMustTailRegParms();
3512 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3513 CC_AArch64_AAPCS);
3515 // Conservatively forward X8, since it might be used for aggregate return.
3516 if (!CCInfo.isAllocated(AArch64::X8)) {
3517 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3518 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3523 // On Windows, InReg pointers must be returned, so record the pointer in a
3524 // virtual register at the start of the function so it can be returned in the
3525 // epilogue.
3526 if (IsWin64) {
3527 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3528 if (Ins[I].Flags.isInReg()) {
3529 assert(!FuncInfo->getSRetReturnReg());
3531 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3532 Register Reg =
3533 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3534 FuncInfo->setSRetReturnReg(Reg);
3536 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3537 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3538 break;
3543 unsigned StackArgSize = CCInfo.getNextStackOffset();
3544 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3545 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3546 // This is a non-standard ABI so by fiat I say we're allowed to make full
3547 // use of the stack area to be popped, which must be aligned to 16 bytes in
3548 // any case:
3549 StackArgSize = alignTo(StackArgSize, 16);
3551 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3552 // a multiple of 16.
3553 FuncInfo->setArgumentStackToRestore(StackArgSize);
3555 // This realignment carries over to the available bytes below. Our own
3556 // callers will guarantee the space is free by giving an aligned value to
3557 // CALLSEQ_START.
3559 // Even if we're not expected to free up the space, it's useful to know how
3560 // much is there while considering tail calls (because we can reuse it).
3561 FuncInfo->setBytesInStackArgArea(StackArgSize);
3563 if (Subtarget->hasCustomCallingConv())
3564 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3566 return Chain;
3569 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3570 SelectionDAG &DAG,
3571 const SDLoc &DL,
3572 SDValue &Chain) const {
3573 MachineFunction &MF = DAG.getMachineFunction();
3574 MachineFrameInfo &MFI = MF.getFrameInfo();
3575 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3576 auto PtrVT = getPointerTy(DAG.getDataLayout());
3577 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3579 SmallVector<SDValue, 8> MemOps;
3581 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3582 AArch64::X3, AArch64::X4, AArch64::X5,
3583 AArch64::X6, AArch64::X7 };
3584 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3585 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3587 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3588 int GPRIdx = 0;
3589 if (GPRSaveSize != 0) {
3590 if (IsWin64) {
3591 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3592 if (GPRSaveSize & 15)
3593 // The extra size here, if triggered, will always be 8.
3594 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3595 } else
3596 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3598 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3600 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3601 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3602 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3603 SDValue Store = DAG.getStore(
3604 Val.getValue(1), DL, Val, FIN,
3605 IsWin64
3606 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3607 GPRIdx,
3608 (i - FirstVariadicGPR) * 8)
3609 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3610 MemOps.push_back(Store);
3611 FIN =
3612 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3615 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3616 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3618 if (Subtarget->hasFPARMv8() && !IsWin64) {
3619 static const MCPhysReg FPRArgRegs[] = {
3620 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3621 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3622 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3623 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3625 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3626 int FPRIdx = 0;
3627 if (FPRSaveSize != 0) {
3628 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3630 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3632 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3633 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3634 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3636 SDValue Store = DAG.getStore(
3637 Val.getValue(1), DL, Val, FIN,
3638 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3639 MemOps.push_back(Store);
3640 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3641 DAG.getConstant(16, DL, PtrVT));
3644 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3645 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3648 if (!MemOps.empty()) {
3649 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3653 /// LowerCallResult - Lower the result values of a call into the
3654 /// appropriate copies out of appropriate physical registers.
3655 SDValue AArch64TargetLowering::LowerCallResult(
3656 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3657 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3658 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3659 SDValue ThisVal) const {
3660 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3661 ? RetCC_AArch64_WebKit_JS
3662 : RetCC_AArch64_AAPCS;
3663 // Assign locations to each value returned by this call.
3664 SmallVector<CCValAssign, 16> RVLocs;
3665 DenseMap<unsigned, SDValue> CopiedRegs;
3666 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3667 *DAG.getContext());
3668 CCInfo.AnalyzeCallResult(Ins, RetCC);
3670 // Copy all of the result registers out of their specified physreg.
3671 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3672 CCValAssign VA = RVLocs[i];
3674 // Pass 'this' value directly from the argument to return value, to avoid
3675 // reg unit interference
3676 if (i == 0 && isThisReturn) {
3677 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3678 "unexpected return calling convention register assignment");
3679 InVals.push_back(ThisVal);
3680 continue;
3683 // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3684 // allows one use of a physreg per block.
3685 SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3686 if (!Val) {
3687 Val =
3688 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3689 Chain = Val.getValue(1);
3690 InFlag = Val.getValue(2);
3691 CopiedRegs[VA.getLocReg()] = Val;
3694 switch (VA.getLocInfo()) {
3695 default:
3696 llvm_unreachable("Unknown loc info!");
3697 case CCValAssign::Full:
3698 break;
3699 case CCValAssign::BCvt:
3700 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3701 break;
3702 case CCValAssign::AExtUpper:
3703 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3704 DAG.getConstant(32, DL, VA.getLocVT()));
3705 LLVM_FALLTHROUGH;
3706 case CCValAssign::AExt:
3707 LLVM_FALLTHROUGH;
3708 case CCValAssign::ZExt:
3709 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3710 break;
3713 InVals.push_back(Val);
3716 return Chain;
3719 /// Return true if the calling convention is one that we can guarantee TCO for.
3720 static bool canGuaranteeTCO(CallingConv::ID CC) {
3721 return CC == CallingConv::Fast;
3724 /// Return true if we might ever do TCO for calls with this calling convention.
3725 static bool mayTailCallThisCC(CallingConv::ID CC) {
3726 switch (CC) {
3727 case CallingConv::C:
3728 case CallingConv::PreserveMost:
3729 case CallingConv::Swift:
3730 return true;
3731 default:
3732 return canGuaranteeTCO(CC);
3736 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3737 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3738 const SmallVectorImpl<ISD::OutputArg> &Outs,
3739 const SmallVectorImpl<SDValue> &OutVals,
3740 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3741 if (!mayTailCallThisCC(CalleeCC))
3742 return false;
3744 MachineFunction &MF = DAG.getMachineFunction();
3745 const Function &CallerF = MF.getFunction();
3746 CallingConv::ID CallerCC = CallerF.getCallingConv();
3747 bool CCMatch = CallerCC == CalleeCC;
3749 // Byval parameters hand the function a pointer directly into the stack area
3750 // we want to reuse during a tail call. Working around this *is* possible (see
3751 // X86) but less efficient and uglier in LowerCall.
3752 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3753 e = CallerF.arg_end();
3754 i != e; ++i) {
3755 if (i->hasByValAttr())
3756 return false;
3758 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3759 // In this case, it is necessary to save/restore X0 in the callee. Tail
3760 // call opt interferes with this. So we disable tail call opt when the
3761 // caller has an argument with "inreg" attribute.
3763 // FIXME: Check whether the callee also has an "inreg" argument.
3764 if (i->hasInRegAttr())
3765 return false;
3768 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3769 return canGuaranteeTCO(CalleeCC) && CCMatch;
3771 // Externally-defined functions with weak linkage should not be
3772 // tail-called on AArch64 when the OS does not support dynamic
3773 // pre-emption of symbols, as the AAELF spec requires normal calls
3774 // to undefined weak functions to be replaced with a NOP or jump to the
3775 // next instruction. The behaviour of branch instructions in this
3776 // situation (as used for tail calls) is implementation-defined, so we
3777 // cannot rely on the linker replacing the tail call with a return.
3778 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3779 const GlobalValue *GV = G->getGlobal();
3780 const Triple &TT = getTargetMachine().getTargetTriple();
3781 if (GV->hasExternalWeakLinkage() &&
3782 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3783 return false;
3786 // Now we search for cases where we can use a tail call without changing the
3787 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3788 // concept.
3790 // I want anyone implementing a new calling convention to think long and hard
3791 // about this assert.
3792 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3793 "Unexpected variadic calling convention");
3795 LLVMContext &C = *DAG.getContext();
3796 if (isVarArg && !Outs.empty()) {
3797 // At least two cases here: if caller is fastcc then we can't have any
3798 // memory arguments (we'd be expected to clean up the stack afterwards). If
3799 // caller is C then we could potentially use its argument area.
3801 // FIXME: for now we take the most conservative of these in both cases:
3802 // disallow all variadic memory operands.
3803 SmallVector<CCValAssign, 16> ArgLocs;
3804 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3806 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3807 for (const CCValAssign &ArgLoc : ArgLocs)
3808 if (!ArgLoc.isRegLoc())
3809 return false;
3812 // Check that the call results are passed in the same way.
3813 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3814 CCAssignFnForCall(CalleeCC, isVarArg),
3815 CCAssignFnForCall(CallerCC, isVarArg)))
3816 return false;
3817 // The callee has to preserve all registers the caller needs to preserve.
3818 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3819 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3820 if (!CCMatch) {
3821 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3822 if (Subtarget->hasCustomCallingConv()) {
3823 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3824 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3826 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3827 return false;
3830 // Nothing more to check if the callee is taking no arguments
3831 if (Outs.empty())
3832 return true;
3834 SmallVector<CCValAssign, 16> ArgLocs;
3835 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3837 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3839 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3841 // If the stack arguments for this call do not fit into our own save area then
3842 // the call cannot be made tail.
3843 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3844 return false;
3846 const MachineRegisterInfo &MRI = MF.getRegInfo();
3847 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3848 return false;
3850 return true;
3853 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3854 SelectionDAG &DAG,
3855 MachineFrameInfo &MFI,
3856 int ClobberedFI) const {
3857 SmallVector<SDValue, 8> ArgChains;
3858 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3859 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3861 // Include the original chain at the beginning of the list. When this is
3862 // used by target LowerCall hooks, this helps legalize find the
3863 // CALLSEQ_BEGIN node.
3864 ArgChains.push_back(Chain);
3866 // Add a chain value for each stack argument corresponding
3867 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3868 UE = DAG.getEntryNode().getNode()->use_end();
3869 U != UE; ++U)
3870 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3871 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3872 if (FI->getIndex() < 0) {
3873 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3874 int64_t InLastByte = InFirstByte;
3875 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3877 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3878 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3879 ArgChains.push_back(SDValue(L, 1));
3882 // Build a tokenfactor for all the chains.
3883 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3886 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3887 bool TailCallOpt) const {
3888 return CallCC == CallingConv::Fast && TailCallOpt;
3891 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3892 /// and add input and output parameter nodes.
3893 SDValue
3894 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3895 SmallVectorImpl<SDValue> &InVals) const {
3896 SelectionDAG &DAG = CLI.DAG;
3897 SDLoc &DL = CLI.DL;
3898 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3899 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3900 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3901 SDValue Chain = CLI.Chain;
3902 SDValue Callee = CLI.Callee;
3903 bool &IsTailCall = CLI.IsTailCall;
3904 CallingConv::ID CallConv = CLI.CallConv;
3905 bool IsVarArg = CLI.IsVarArg;
3907 MachineFunction &MF = DAG.getMachineFunction();
3908 MachineFunction::CallSiteInfo CSInfo;
3909 bool IsThisReturn = false;
3911 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3912 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3913 bool IsSibCall = false;
3915 if (IsTailCall) {
3916 // Check if it's really possible to do a tail call.
3917 IsTailCall = isEligibleForTailCallOptimization(
3918 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3919 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3920 report_fatal_error("failed to perform tail call elimination on a call "
3921 "site marked musttail");
3923 // A sibling call is one where we're under the usual C ABI and not planning
3924 // to change that but can still do a tail call:
3925 if (!TailCallOpt && IsTailCall)
3926 IsSibCall = true;
3928 if (IsTailCall)
3929 ++NumTailCalls;
3932 // Analyze operands of the call, assigning locations to each operand.
3933 SmallVector<CCValAssign, 16> ArgLocs;
3934 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3935 *DAG.getContext());
3937 if (IsVarArg) {
3938 // Handle fixed and variable vector arguments differently.
3939 // Variable vector arguments always go into memory.
3940 unsigned NumArgs = Outs.size();
3942 for (unsigned i = 0; i != NumArgs; ++i) {
3943 MVT ArgVT = Outs[i].VT;
3944 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3945 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3946 /*IsVarArg=*/ !Outs[i].IsFixed);
3947 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3948 assert(!Res && "Call operand has unhandled type");
3949 (void)Res;
3951 } else {
3952 // At this point, Outs[].VT may already be promoted to i32. To correctly
3953 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3954 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3955 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3956 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3957 // LocVT.
3958 unsigned NumArgs = Outs.size();
3959 for (unsigned i = 0; i != NumArgs; ++i) {
3960 MVT ValVT = Outs[i].VT;
3961 // Get type of the original argument.
3962 EVT ActualVT = getValueType(DAG.getDataLayout(),
3963 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3964 /*AllowUnknown*/ true);
3965 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3966 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3967 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3968 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3969 ValVT = MVT::i8;
3970 else if (ActualMVT == MVT::i16)
3971 ValVT = MVT::i16;
3973 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3974 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3975 assert(!Res && "Call operand has unhandled type");
3976 (void)Res;
3980 // Get a count of how many bytes are to be pushed on the stack.
3981 unsigned NumBytes = CCInfo.getNextStackOffset();
3983 if (IsSibCall) {
3984 // Since we're not changing the ABI to make this a tail call, the memory
3985 // operands are already available in the caller's incoming argument space.
3986 NumBytes = 0;
3989 // FPDiff is the byte offset of the call's argument area from the callee's.
3990 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3991 // by this amount for a tail call. In a sibling call it must be 0 because the
3992 // caller will deallocate the entire stack and the callee still expects its
3993 // arguments to begin at SP+0. Completely unused for non-tail calls.
3994 int FPDiff = 0;
3996 if (IsTailCall && !IsSibCall) {
3997 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3999 // Since callee will pop argument stack as a tail call, we must keep the
4000 // popped size 16-byte aligned.
4001 NumBytes = alignTo(NumBytes, 16);
4003 // FPDiff will be negative if this tail call requires more space than we
4004 // would automatically have in our incoming argument space. Positive if we
4005 // can actually shrink the stack.
4006 FPDiff = NumReusableBytes - NumBytes;
4008 // The stack pointer must be 16-byte aligned at all times it's used for a
4009 // memory operation, which in practice means at *all* times and in
4010 // particular across call boundaries. Therefore our own arguments started at
4011 // a 16-byte aligned SP and the delta applied for the tail call should
4012 // satisfy the same constraint.
4013 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
4016 // Adjust the stack pointer for the new arguments...
4017 // These operations are automatically eliminated by the prolog/epilog pass
4018 if (!IsSibCall)
4019 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
4021 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
4022 getPointerTy(DAG.getDataLayout()));
4024 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4025 SmallSet<unsigned, 8> RegsUsed;
4026 SmallVector<SDValue, 8> MemOpChains;
4027 auto PtrVT = getPointerTy(DAG.getDataLayout());
4029 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
4030 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
4031 for (const auto &F : Forwards) {
4032 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
4033 RegsToPass.emplace_back(F.PReg, Val);
4037 // Walk the register/memloc assignments, inserting copies/loads.
4038 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4039 CCValAssign &VA = ArgLocs[i];
4040 SDValue Arg = OutVals[i];
4041 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4043 // Promote the value if needed.
4044 switch (VA.getLocInfo()) {
4045 default:
4046 llvm_unreachable("Unknown loc info!");
4047 case CCValAssign::Full:
4048 break;
4049 case CCValAssign::SExt:
4050 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
4051 break;
4052 case CCValAssign::ZExt:
4053 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4054 break;
4055 case CCValAssign::AExt:
4056 if (Outs[i].ArgVT == MVT::i1) {
4057 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
4058 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4059 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
4061 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4062 break;
4063 case CCValAssign::AExtUpper:
4064 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4065 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
4066 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4067 DAG.getConstant(32, DL, VA.getLocVT()));
4068 break;
4069 case CCValAssign::BCvt:
4070 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
4071 break;
4072 case CCValAssign::Trunc:
4073 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4074 break;
4075 case CCValAssign::FPExt:
4076 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
4077 break;
4078 case CCValAssign::Indirect:
4079 assert(VA.getValVT().isScalableVector() &&
4080 "Only scalable vectors can be passed indirectly");
4081 llvm_unreachable("Spilling of SVE vectors not yet implemented");
4084 if (VA.isRegLoc()) {
4085 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
4086 Outs[0].VT == MVT::i64) {
4087 assert(VA.getLocVT() == MVT::i64 &&
4088 "unexpected calling convention register assignment");
4089 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
4090 "unexpected use of 'returned'");
4091 IsThisReturn = true;
4093 if (RegsUsed.count(VA.getLocReg())) {
4094 // If this register has already been used then we're trying to pack
4095 // parts of an [N x i32] into an X-register. The extension type will
4096 // take care of putting the two halves in the right place but we have to
4097 // combine them.
4098 SDValue &Bits =
4099 std::find_if(RegsToPass.begin(), RegsToPass.end(),
4100 [=](const std::pair<unsigned, SDValue> &Elt) {
4101 return Elt.first == VA.getLocReg();
4103 ->second;
4104 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4105 // Call site info is used for function's parameter entry value
4106 // tracking. For now we track only simple cases when parameter
4107 // is transferred through whole register.
4108 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
4109 [&VA](MachineFunction::ArgRegPair ArgReg) {
4110 return ArgReg.Reg == VA.getLocReg();
4112 CSInfo.end());
4113 } else {
4114 RegsToPass.emplace_back(VA.getLocReg(), Arg);
4115 RegsUsed.insert(VA.getLocReg());
4116 const TargetOptions &Options = DAG.getTarget().Options;
4117 if (Options.EnableDebugEntryValues)
4118 CSInfo.emplace_back(VA.getLocReg(), i);
4120 } else {
4121 assert(VA.isMemLoc());
4123 SDValue DstAddr;
4124 MachinePointerInfo DstInfo;
4126 // FIXME: This works on big-endian for composite byvals, which are the
4127 // common case. It should also work for fundamental types too.
4128 uint32_t BEAlign = 0;
4129 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
4130 : VA.getValVT().getSizeInBits();
4131 OpSize = (OpSize + 7) / 8;
4132 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
4133 !Flags.isInConsecutiveRegs()) {
4134 if (OpSize < 8)
4135 BEAlign = 8 - OpSize;
4137 unsigned LocMemOffset = VA.getLocMemOffset();
4138 int32_t Offset = LocMemOffset + BEAlign;
4139 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4140 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4142 if (IsTailCall) {
4143 Offset = Offset + FPDiff;
4144 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4146 DstAddr = DAG.getFrameIndex(FI, PtrVT);
4147 DstInfo =
4148 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
4150 // Make sure any stack arguments overlapping with where we're storing
4151 // are loaded before this eventual operation. Otherwise they'll be
4152 // clobbered.
4153 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
4154 } else {
4155 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
4157 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
4158 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
4159 LocMemOffset);
4162 if (Outs[i].Flags.isByVal()) {
4163 SDValue SizeNode =
4164 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
4165 SDValue Cpy = DAG.getMemcpy(
4166 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
4167 /*isVol = */ false, /*AlwaysInline = */ false,
4168 /*isTailCall = */ false,
4169 DstInfo, MachinePointerInfo());
4171 MemOpChains.push_back(Cpy);
4172 } else {
4173 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
4174 // promoted to a legal register type i32, we should truncate Arg back to
4175 // i1/i8/i16.
4176 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
4177 VA.getValVT() == MVT::i16)
4178 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
4180 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
4181 MemOpChains.push_back(Store);
4186 if (!MemOpChains.empty())
4187 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
4189 // Build a sequence of copy-to-reg nodes chained together with token chain
4190 // and flag operands which copy the outgoing args into the appropriate regs.
4191 SDValue InFlag;
4192 for (auto &RegToPass : RegsToPass) {
4193 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
4194 RegToPass.second, InFlag);
4195 InFlag = Chain.getValue(1);
4198 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
4199 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
4200 // node so that legalize doesn't hack it.
4201 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4202 auto GV = G->getGlobal();
4203 unsigned OpFlags =
4204 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
4205 if (OpFlags & AArch64II::MO_GOT) {
4206 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
4207 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4208 } else {
4209 const GlobalValue *GV = G->getGlobal();
4210 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4212 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4213 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4214 Subtarget->isTargetMachO()) {
4215 const char *Sym = S->getSymbol();
4216 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4217 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4218 } else {
4219 const char *Sym = S->getSymbol();
4220 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4224 // We don't usually want to end the call-sequence here because we would tidy
4225 // the frame up *after* the call, however in the ABI-changing tail-call case
4226 // we've carefully laid out the parameters so that when sp is reset they'll be
4227 // in the correct location.
4228 if (IsTailCall && !IsSibCall) {
4229 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4230 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4231 InFlag = Chain.getValue(1);
4234 std::vector<SDValue> Ops;
4235 Ops.push_back(Chain);
4236 Ops.push_back(Callee);
4238 if (IsTailCall) {
4239 // Each tail call may have to adjust the stack by a different amount, so
4240 // this information must travel along with the operation for eventual
4241 // consumption by emitEpilogue.
4242 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4245 // Add argument registers to the end of the list so that they are known live
4246 // into the call.
4247 for (auto &RegToPass : RegsToPass)
4248 Ops.push_back(DAG.getRegister(RegToPass.first,
4249 RegToPass.second.getValueType()));
4251 // Check callee args/returns for SVE registers and set calling convention
4252 // accordingly.
4253 if (CallConv == CallingConv::C) {
4254 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4255 return Out.VT.isScalableVector();
4257 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4258 return In.VT.isScalableVector();
4261 if (CalleeInSVE || CalleeOutSVE)
4262 CallConv = CallingConv::AArch64_SVE_VectorCall;
4265 // Add a register mask operand representing the call-preserved registers.
4266 const uint32_t *Mask;
4267 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4268 if (IsThisReturn) {
4269 // For 'this' returns, use the X0-preserving mask if applicable
4270 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4271 if (!Mask) {
4272 IsThisReturn = false;
4273 Mask = TRI->getCallPreservedMask(MF, CallConv);
4275 } else
4276 Mask = TRI->getCallPreservedMask(MF, CallConv);
4278 if (Subtarget->hasCustomCallingConv())
4279 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4281 if (TRI->isAnyArgRegReserved(MF))
4282 TRI->emitReservedArgRegCallError(MF);
4284 assert(Mask && "Missing call preserved mask for calling convention");
4285 Ops.push_back(DAG.getRegisterMask(Mask));
4287 if (InFlag.getNode())
4288 Ops.push_back(InFlag);
4290 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4292 // If we're doing a tall call, use a TC_RETURN here rather than an
4293 // actual call instruction.
4294 if (IsTailCall) {
4295 MF.getFrameInfo().setHasTailCall();
4296 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4297 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4298 return Ret;
4301 // Returns a chain and a flag for retval copy to use.
4302 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4303 InFlag = Chain.getValue(1);
4304 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4306 uint64_t CalleePopBytes =
4307 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4309 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4310 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4311 InFlag, DL);
4312 if (!Ins.empty())
4313 InFlag = Chain.getValue(1);
4315 // Handle result values, copying them out of physregs into vregs that we
4316 // return.
4317 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4318 InVals, IsThisReturn,
4319 IsThisReturn ? OutVals[0] : SDValue());
4322 bool AArch64TargetLowering::CanLowerReturn(
4323 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4324 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4325 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4326 ? RetCC_AArch64_WebKit_JS
4327 : RetCC_AArch64_AAPCS;
4328 SmallVector<CCValAssign, 16> RVLocs;
4329 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4330 return CCInfo.CheckReturn(Outs, RetCC);
4333 SDValue
4334 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4335 bool isVarArg,
4336 const SmallVectorImpl<ISD::OutputArg> &Outs,
4337 const SmallVectorImpl<SDValue> &OutVals,
4338 const SDLoc &DL, SelectionDAG &DAG) const {
4339 auto &MF = DAG.getMachineFunction();
4340 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4342 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4343 ? RetCC_AArch64_WebKit_JS
4344 : RetCC_AArch64_AAPCS;
4345 SmallVector<CCValAssign, 16> RVLocs;
4346 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4347 *DAG.getContext());
4348 CCInfo.AnalyzeReturn(Outs, RetCC);
4350 // Copy the result values into the output registers.
4351 SDValue Flag;
4352 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4353 SmallSet<unsigned, 4> RegsUsed;
4354 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4355 ++i, ++realRVLocIdx) {
4356 CCValAssign &VA = RVLocs[i];
4357 assert(VA.isRegLoc() && "Can only return in registers!");
4358 SDValue Arg = OutVals[realRVLocIdx];
4360 switch (VA.getLocInfo()) {
4361 default:
4362 llvm_unreachable("Unknown loc info!");
4363 case CCValAssign::Full:
4364 if (Outs[i].ArgVT == MVT::i1) {
4365 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4366 // value. This is strictly redundant on Darwin (which uses "zeroext
4367 // i1"), but will be optimised out before ISel.
4368 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4369 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4371 break;
4372 case CCValAssign::BCvt:
4373 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4374 break;
4375 case CCValAssign::AExt:
4376 case CCValAssign::ZExt:
4377 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4378 break;
4379 case CCValAssign::AExtUpper:
4380 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4381 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4382 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4383 DAG.getConstant(32, DL, VA.getLocVT()));
4384 break;
4387 if (RegsUsed.count(VA.getLocReg())) {
4388 SDValue &Bits =
4389 std::find_if(RetVals.begin(), RetVals.end(),
4390 [=](const std::pair<unsigned, SDValue> &Elt) {
4391 return Elt.first == VA.getLocReg();
4393 ->second;
4394 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4395 } else {
4396 RetVals.emplace_back(VA.getLocReg(), Arg);
4397 RegsUsed.insert(VA.getLocReg());
4401 SmallVector<SDValue, 4> RetOps(1, Chain);
4402 for (auto &RetVal : RetVals) {
4403 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4404 Flag = Chain.getValue(1);
4405 RetOps.push_back(
4406 DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4409 // Windows AArch64 ABIs require that for returning structs by value we copy
4410 // the sret argument into X0 for the return.
4411 // We saved the argument into a virtual register in the entry block,
4412 // so now we copy the value out and into X0.
4413 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4414 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4415 getPointerTy(MF.getDataLayout()));
4417 unsigned RetValReg = AArch64::X0;
4418 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4419 Flag = Chain.getValue(1);
4421 RetOps.push_back(
4422 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4425 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4426 const MCPhysReg *I =
4427 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4428 if (I) {
4429 for (; *I; ++I) {
4430 if (AArch64::GPR64RegClass.contains(*I))
4431 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4432 else if (AArch64::FPR64RegClass.contains(*I))
4433 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4434 else
4435 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4439 RetOps[0] = Chain; // Update chain.
4441 // Add the flag if we have it.
4442 if (Flag.getNode())
4443 RetOps.push_back(Flag);
4445 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4448 //===----------------------------------------------------------------------===//
4449 // Other Lowering Code
4450 //===----------------------------------------------------------------------===//
4452 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4453 SelectionDAG &DAG,
4454 unsigned Flag) const {
4455 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4456 N->getOffset(), Flag);
4459 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4460 SelectionDAG &DAG,
4461 unsigned Flag) const {
4462 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4465 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4466 SelectionDAG &DAG,
4467 unsigned Flag) const {
4468 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4469 N->getOffset(), Flag);
4472 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4473 SelectionDAG &DAG,
4474 unsigned Flag) const {
4475 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4478 // (loadGOT sym)
4479 template <class NodeTy>
4480 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4481 unsigned Flags) const {
4482 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4483 SDLoc DL(N);
4484 EVT Ty = getPointerTy(DAG.getDataLayout());
4485 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4486 // FIXME: Once remat is capable of dealing with instructions with register
4487 // operands, expand this into two nodes instead of using a wrapper node.
4488 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4491 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4492 template <class NodeTy>
4493 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4494 unsigned Flags) const {
4495 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4496 SDLoc DL(N);
4497 EVT Ty = getPointerTy(DAG.getDataLayout());
4498 const unsigned char MO_NC = AArch64II::MO_NC;
4499 return DAG.getNode(
4500 AArch64ISD::WrapperLarge, DL, Ty,
4501 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4502 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4503 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4504 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4507 // (addlow (adrp %hi(sym)) %lo(sym))
4508 template <class NodeTy>
4509 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4510 unsigned Flags) const {
4511 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4512 SDLoc DL(N);
4513 EVT Ty = getPointerTy(DAG.getDataLayout());
4514 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4515 SDValue Lo = getTargetNode(N, Ty, DAG,
4516 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4517 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4518 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4521 // (adr sym)
4522 template <class NodeTy>
4523 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4524 unsigned Flags) const {
4525 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4526 SDLoc DL(N);
4527 EVT Ty = getPointerTy(DAG.getDataLayout());
4528 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4529 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4532 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4533 SelectionDAG &DAG) const {
4534 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4535 const GlobalValue *GV = GN->getGlobal();
4536 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4538 if (OpFlags != AArch64II::MO_NO_FLAG)
4539 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4540 "unexpected offset in global node");
4542 // This also catches the large code model case for Darwin, and tiny code
4543 // model with got relocations.
4544 if ((OpFlags & AArch64II::MO_GOT) != 0) {
4545 return getGOT(GN, DAG, OpFlags);
4548 SDValue Result;
4549 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4550 Result = getAddrLarge(GN, DAG, OpFlags);
4551 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4552 Result = getAddrTiny(GN, DAG, OpFlags);
4553 } else {
4554 Result = getAddr(GN, DAG, OpFlags);
4556 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4557 SDLoc DL(GN);
4558 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4559 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4560 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4561 return Result;
4564 /// Convert a TLS address reference into the correct sequence of loads
4565 /// and calls to compute the variable's address (for Darwin, currently) and
4566 /// return an SDValue containing the final node.
4568 /// Darwin only has one TLS scheme which must be capable of dealing with the
4569 /// fully general situation, in the worst case. This means:
4570 /// + "extern __thread" declaration.
4571 /// + Defined in a possibly unknown dynamic library.
4573 /// The general system is that each __thread variable has a [3 x i64] descriptor
4574 /// which contains information used by the runtime to calculate the address. The
4575 /// only part of this the compiler needs to know about is the first xword, which
4576 /// contains a function pointer that must be called with the address of the
4577 /// entire descriptor in "x0".
4579 /// Since this descriptor may be in a different unit, in general even the
4580 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4581 /// is:
4582 /// adrp x0, _var@TLVPPAGE
4583 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4584 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4585 /// ; the function pointer
4586 /// blr x1 ; Uses descriptor address in x0
4587 /// ; Address of _var is now in x0.
4589 /// If the address of _var's descriptor *is* known to the linker, then it can
4590 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4591 /// a slight efficiency gain.
4592 SDValue
4593 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4594 SelectionDAG &DAG) const {
4595 assert(Subtarget->isTargetDarwin() &&
4596 "This function expects a Darwin target");
4598 SDLoc DL(Op);
4599 MVT PtrVT = getPointerTy(DAG.getDataLayout());
4600 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4601 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4603 SDValue TLVPAddr =
4604 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4605 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4607 // The first entry in the descriptor is a function pointer that we must call
4608 // to obtain the address of the variable.
4609 SDValue Chain = DAG.getEntryNode();
4610 SDValue FuncTLVGet = DAG.getLoad(
4611 PtrMemVT, DL, Chain, DescAddr,
4612 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4613 /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4614 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4615 Chain = FuncTLVGet.getValue(1);
4617 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4618 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4620 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4621 MFI.setAdjustsStack(true);
4623 // TLS calls preserve all registers except those that absolutely must be
4624 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4625 // silly).
4626 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4627 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4628 if (Subtarget->hasCustomCallingConv())
4629 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4631 // Finally, we can make the call. This is just a degenerate version of a
4632 // normal AArch64 call node: x0 takes the address of the descriptor, and
4633 // returns the address of the variable in this thread.
4634 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4635 Chain =
4636 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4637 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4638 DAG.getRegisterMask(Mask), Chain.getValue(1));
4639 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4642 /// Convert a thread-local variable reference into a sequence of instructions to
4643 /// compute the variable's address for the local exec TLS model of ELF targets.
4644 /// The sequence depends on the maximum TLS area size.
4645 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
4646 SDValue ThreadBase,
4647 const SDLoc &DL,
4648 SelectionDAG &DAG) const {
4649 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4650 SDValue TPOff, Addr;
4652 switch (DAG.getTarget().Options.TLSSize) {
4653 default:
4654 llvm_unreachable("Unexpected TLS size");
4656 case 12: {
4657 // mrs x0, TPIDR_EL0
4658 // add x0, x0, :tprel_lo12:a
4659 SDValue Var = DAG.getTargetGlobalAddress(
4660 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
4661 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4662 Var,
4663 DAG.getTargetConstant(0, DL, MVT::i32)),
4667 case 24: {
4668 // mrs x0, TPIDR_EL0
4669 // add x0, x0, :tprel_hi12:a
4670 // add x0, x0, :tprel_lo12_nc:a
4671 SDValue HiVar = DAG.getTargetGlobalAddress(
4672 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4673 SDValue LoVar = DAG.getTargetGlobalAddress(
4674 GV, DL, PtrVT, 0,
4675 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4676 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4677 HiVar,
4678 DAG.getTargetConstant(0, DL, MVT::i32)),
4680 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
4681 LoVar,
4682 DAG.getTargetConstant(0, DL, MVT::i32)),
4686 case 32: {
4687 // mrs x1, TPIDR_EL0
4688 // movz x0, #:tprel_g1:a
4689 // movk x0, #:tprel_g0_nc:a
4690 // add x0, x1, x0
4691 SDValue HiVar = DAG.getTargetGlobalAddress(
4692 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
4693 SDValue LoVar = DAG.getTargetGlobalAddress(
4694 GV, DL, PtrVT, 0,
4695 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4696 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4697 DAG.getTargetConstant(16, DL, MVT::i32)),
4699 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4700 DAG.getTargetConstant(0, DL, MVT::i32)),
4702 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4705 case 48: {
4706 // mrs x1, TPIDR_EL0
4707 // movz x0, #:tprel_g2:a
4708 // movk x0, #:tprel_g1_nc:a
4709 // movk x0, #:tprel_g0_nc:a
4710 // add x0, x1, x0
4711 SDValue HiVar = DAG.getTargetGlobalAddress(
4712 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
4713 SDValue MiVar = DAG.getTargetGlobalAddress(
4714 GV, DL, PtrVT, 0,
4715 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
4716 SDValue LoVar = DAG.getTargetGlobalAddress(
4717 GV, DL, PtrVT, 0,
4718 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
4719 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
4720 DAG.getTargetConstant(32, DL, MVT::i32)),
4722 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
4723 DAG.getTargetConstant(16, DL, MVT::i32)),
4725 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
4726 DAG.getTargetConstant(0, DL, MVT::i32)),
4728 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4733 /// When accessing thread-local variables under either the general-dynamic or
4734 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4735 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4736 /// is a function pointer to carry out the resolution.
4738 /// The sequence is:
4739 /// adrp x0, :tlsdesc:var
4740 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4741 /// add x0, x0, #:tlsdesc_lo12:var
4742 /// .tlsdesccall var
4743 /// blr x1
4744 /// (TPIDR_EL0 offset now in x0)
4746 /// The above sequence must be produced unscheduled, to enable the linker to
4747 /// optimize/relax this sequence.
4748 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4749 /// above sequence, and expanded really late in the compilation flow, to ensure
4750 /// the sequence is produced as per above.
4751 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4752 const SDLoc &DL,
4753 SelectionDAG &DAG) const {
4754 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4756 SDValue Chain = DAG.getEntryNode();
4757 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4759 Chain =
4760 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4761 SDValue Glue = Chain.getValue(1);
4763 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4766 SDValue
4767 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4768 SelectionDAG &DAG) const {
4769 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4771 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4773 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4775 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4776 if (Model == TLSModel::LocalDynamic)
4777 Model = TLSModel::GeneralDynamic;
4780 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4781 Model != TLSModel::LocalExec)
4782 report_fatal_error("ELF TLS only supported in small memory model or "
4783 "in local exec TLS model");
4784 // Different choices can be made for the maximum size of the TLS area for a
4785 // module. For the small address model, the default TLS size is 16MiB and the
4786 // maximum TLS size is 4GiB.
4787 // FIXME: add tiny and large code model support for TLS access models other
4788 // than local exec. We currently generate the same code as small for tiny,
4789 // which may be larger than needed.
4791 SDValue TPOff;
4792 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4793 SDLoc DL(Op);
4794 const GlobalValue *GV = GA->getGlobal();
4796 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4798 if (Model == TLSModel::LocalExec) {
4799 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
4800 } else if (Model == TLSModel::InitialExec) {
4801 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4802 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4803 } else if (Model == TLSModel::LocalDynamic) {
4804 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4805 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4806 // the beginning of the module's TLS region, followed by a DTPREL offset
4807 // calculation.
4809 // These accesses will need deduplicating if there's more than one.
4810 AArch64FunctionInfo *MFI =
4811 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4812 MFI->incNumLocalDynamicTLSAccesses();
4814 // The call needs a relocation too for linker relaxation. It doesn't make
4815 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4816 // the address.
4817 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4818 AArch64II::MO_TLS);
4820 // Now we can calculate the offset from TPIDR_EL0 to this module's
4821 // thread-local area.
4822 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4824 // Now use :dtprel_whatever: operations to calculate this variable's offset
4825 // in its thread-storage area.
4826 SDValue HiVar = DAG.getTargetGlobalAddress(
4827 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4828 SDValue LoVar = DAG.getTargetGlobalAddress(
4829 GV, DL, MVT::i64, 0,
4830 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4832 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4833 DAG.getTargetConstant(0, DL, MVT::i32)),
4835 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4836 DAG.getTargetConstant(0, DL, MVT::i32)),
4838 } else if (Model == TLSModel::GeneralDynamic) {
4839 // The call needs a relocation too for linker relaxation. It doesn't make
4840 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4841 // the address.
4842 SDValue SymAddr =
4843 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4845 // Finally we can make a call to calculate the offset from tpidr_el0.
4846 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4847 } else
4848 llvm_unreachable("Unsupported ELF TLS access model");
4850 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4853 SDValue
4854 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4855 SelectionDAG &DAG) const {
4856 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4858 SDValue Chain = DAG.getEntryNode();
4859 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4860 SDLoc DL(Op);
4862 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4864 // Load the ThreadLocalStoragePointer from the TEB
4865 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4866 SDValue TLSArray =
4867 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4868 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4869 Chain = TLSArray.getValue(1);
4871 // Load the TLS index from the C runtime;
4872 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4873 // This also does the same as LOADgot, but using a generic i32 load,
4874 // while LOADgot only loads i64.
4875 SDValue TLSIndexHi =
4876 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4877 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4878 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4879 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4880 SDValue TLSIndex =
4881 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4882 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4883 Chain = TLSIndex.getValue(1);
4885 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4886 // offset into the TLSArray.
4887 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4888 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4889 DAG.getConstant(3, DL, PtrVT));
4890 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4891 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4892 MachinePointerInfo());
4893 Chain = TLS.getValue(1);
4895 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4896 const GlobalValue *GV = GA->getGlobal();
4897 SDValue TGAHi = DAG.getTargetGlobalAddress(
4898 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4899 SDValue TGALo = DAG.getTargetGlobalAddress(
4900 GV, DL, PtrVT, 0,
4901 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4903 // Add the offset from the start of the .tls section (section base).
4904 SDValue Addr =
4905 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4906 DAG.getTargetConstant(0, DL, MVT::i32)),
4908 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4909 return Addr;
4912 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4913 SelectionDAG &DAG) const {
4914 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4915 if (DAG.getTarget().useEmulatedTLS())
4916 return LowerToTLSEmulatedModel(GA, DAG);
4918 if (Subtarget->isTargetDarwin())
4919 return LowerDarwinGlobalTLSAddress(Op, DAG);
4920 if (Subtarget->isTargetELF())
4921 return LowerELFGlobalTLSAddress(Op, DAG);
4922 if (Subtarget->isTargetWindows())
4923 return LowerWindowsGlobalTLSAddress(Op, DAG);
4925 llvm_unreachable("Unexpected platform trying to use TLS");
4928 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4929 SDValue Chain = Op.getOperand(0);
4930 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4931 SDValue LHS = Op.getOperand(2);
4932 SDValue RHS = Op.getOperand(3);
4933 SDValue Dest = Op.getOperand(4);
4934 SDLoc dl(Op);
4936 MachineFunction &MF = DAG.getMachineFunction();
4937 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4938 // will not be produced, as they are conditional branch instructions that do
4939 // not set flags.
4940 bool ProduceNonFlagSettingCondBr =
4941 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4943 // Handle f128 first, since lowering it will result in comparing the return
4944 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4945 // is expecting to deal with.
4946 if (LHS.getValueType() == MVT::f128) {
4947 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4949 // If softenSetCCOperands returned a scalar, we need to compare the result
4950 // against zero to select between true and false values.
4951 if (!RHS.getNode()) {
4952 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4953 CC = ISD::SETNE;
4957 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4958 // instruction.
4959 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4960 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4961 // Only lower legal XALUO ops.
4962 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4963 return SDValue();
4965 // The actual operation with overflow check.
4966 AArch64CC::CondCode OFCC;
4967 SDValue Value, Overflow;
4968 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4970 if (CC == ISD::SETNE)
4971 OFCC = getInvertedCondCode(OFCC);
4972 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4974 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4975 Overflow);
4978 if (LHS.getValueType().isInteger()) {
4979 assert((LHS.getValueType() == RHS.getValueType()) &&
4980 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4982 // If the RHS of the comparison is zero, we can potentially fold this
4983 // to a specialized branch.
4984 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4985 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4986 if (CC == ISD::SETEQ) {
4987 // See if we can use a TBZ to fold in an AND as well.
4988 // TBZ has a smaller branch displacement than CBZ. If the offset is
4989 // out of bounds, a late MI-layer pass rewrites branches.
4990 // 403.gcc is an example that hits this case.
4991 if (LHS.getOpcode() == ISD::AND &&
4992 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4993 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4994 SDValue Test = LHS.getOperand(0);
4995 uint64_t Mask = LHS.getConstantOperandVal(1);
4996 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4997 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4998 Dest);
5001 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
5002 } else if (CC == ISD::SETNE) {
5003 // See if we can use a TBZ to fold in an AND as well.
5004 // TBZ has a smaller branch displacement than CBZ. If the offset is
5005 // out of bounds, a late MI-layer pass rewrites branches.
5006 // 403.gcc is an example that hits this case.
5007 if (LHS.getOpcode() == ISD::AND &&
5008 isa<ConstantSDNode>(LHS.getOperand(1)) &&
5009 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
5010 SDValue Test = LHS.getOperand(0);
5011 uint64_t Mask = LHS.getConstantOperandVal(1);
5012 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
5013 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
5014 Dest);
5017 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
5018 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
5019 // Don't combine AND since emitComparison converts the AND to an ANDS
5020 // (a.k.a. TST) and the test in the test bit and branch instruction
5021 // becomes redundant. This would also increase register pressure.
5022 uint64_t Mask = LHS.getValueSizeInBits() - 1;
5023 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
5024 DAG.getConstant(Mask, dl, MVT::i64), Dest);
5027 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
5028 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
5029 // Don't combine AND since emitComparison converts the AND to an ANDS
5030 // (a.k.a. TST) and the test in the test bit and branch instruction
5031 // becomes redundant. This would also increase register pressure.
5032 uint64_t Mask = LHS.getValueSizeInBits() - 1;
5033 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
5034 DAG.getConstant(Mask, dl, MVT::i64), Dest);
5037 SDValue CCVal;
5038 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5039 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
5040 Cmp);
5043 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5044 LHS.getValueType() == MVT::f64);
5046 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5047 // clean. Some of them require two branches to implement.
5048 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5049 AArch64CC::CondCode CC1, CC2;
5050 changeFPCCToAArch64CC(CC, CC1, CC2);
5051 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5052 SDValue BR1 =
5053 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
5054 if (CC2 != AArch64CC::AL) {
5055 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5056 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
5057 Cmp);
5060 return BR1;
5063 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
5064 SelectionDAG &DAG) const {
5065 EVT VT = Op.getValueType();
5066 SDLoc DL(Op);
5068 SDValue In1 = Op.getOperand(0);
5069 SDValue In2 = Op.getOperand(1);
5070 EVT SrcVT = In2.getValueType();
5072 if (SrcVT.bitsLT(VT))
5073 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
5074 else if (SrcVT.bitsGT(VT))
5075 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
5077 EVT VecVT;
5078 uint64_t EltMask;
5079 SDValue VecVal1, VecVal2;
5081 auto setVecVal = [&] (int Idx) {
5082 if (!VT.isVector()) {
5083 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5084 DAG.getUNDEF(VecVT), In1);
5085 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
5086 DAG.getUNDEF(VecVT), In2);
5087 } else {
5088 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
5089 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
5093 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
5094 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
5095 EltMask = 0x80000000ULL;
5096 setVecVal(AArch64::ssub);
5097 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
5098 VecVT = MVT::v2i64;
5100 // We want to materialize a mask with the high bit set, but the AdvSIMD
5101 // immediate moves cannot materialize that in a single instruction for
5102 // 64-bit elements. Instead, materialize zero and then negate it.
5103 EltMask = 0;
5105 setVecVal(AArch64::dsub);
5106 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
5107 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
5108 EltMask = 0x8000ULL;
5109 setVecVal(AArch64::hsub);
5110 } else {
5111 llvm_unreachable("Invalid type for copysign!");
5114 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
5116 // If we couldn't materialize the mask above, then the mask vector will be
5117 // the zero vector, and we need to negate it here.
5118 if (VT == MVT::f64 || VT == MVT::v2f64) {
5119 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
5120 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
5121 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
5124 SDValue Sel =
5125 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
5127 if (VT == MVT::f16)
5128 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
5129 if (VT == MVT::f32)
5130 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
5131 else if (VT == MVT::f64)
5132 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
5133 else
5134 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
5137 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
5138 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
5139 Attribute::NoImplicitFloat))
5140 return SDValue();
5142 if (!Subtarget->hasNEON())
5143 return SDValue();
5145 // While there is no integer popcount instruction, it can
5146 // be more efficiently lowered to the following sequence that uses
5147 // AdvSIMD registers/instructions as long as the copies to/from
5148 // the AdvSIMD registers are cheap.
5149 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
5150 // CNT V0.8B, V0.8B // 8xbyte pop-counts
5151 // ADDV B0, V0.8B // sum 8xbyte pop-counts
5152 // UMOV X0, V0.B[0] // copy byte result back to integer reg
5153 SDValue Val = Op.getOperand(0);
5154 SDLoc DL(Op);
5155 EVT VT = Op.getValueType();
5157 if (VT == MVT::i32 || VT == MVT::i64) {
5158 if (VT == MVT::i32)
5159 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
5160 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
5162 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
5163 SDValue UaddLV = DAG.getNode(
5164 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
5165 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
5167 if (VT == MVT::i64)
5168 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
5169 return UaddLV;
5172 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5173 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5174 "Unexpected type for custom ctpop lowering");
5176 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5177 Val = DAG.getBitcast(VT8Bit, Val);
5178 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
5180 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5181 unsigned EltSize = 8;
5182 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5183 while (EltSize != VT.getScalarSizeInBits()) {
5184 EltSize *= 2;
5185 NumElts /= 2;
5186 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5187 Val = DAG.getNode(
5188 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
5189 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
5192 return Val;
5195 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
5197 if (Op.getValueType().isVector())
5198 return LowerVSETCC(Op, DAG);
5200 SDValue LHS = Op.getOperand(0);
5201 SDValue RHS = Op.getOperand(1);
5202 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5203 SDLoc dl(Op);
5205 // We chose ZeroOrOneBooleanContents, so use zero and one.
5206 EVT VT = Op.getValueType();
5207 SDValue TVal = DAG.getConstant(1, dl, VT);
5208 SDValue FVal = DAG.getConstant(0, dl, VT);
5210 // Handle f128 first, since one possible outcome is a normal integer
5211 // comparison which gets picked up by the next if statement.
5212 if (LHS.getValueType() == MVT::f128) {
5213 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5215 // If softenSetCCOperands returned a scalar, use it.
5216 if (!RHS.getNode()) {
5217 assert(LHS.getValueType() == Op.getValueType() &&
5218 "Unexpected setcc expansion!");
5219 return LHS;
5223 if (LHS.getValueType().isInteger()) {
5224 SDValue CCVal;
5225 SDValue Cmp = getAArch64Cmp(
5226 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
5228 // Note that we inverted the condition above, so we reverse the order of
5229 // the true and false operands here. This will allow the setcc to be
5230 // matched to a single CSINC instruction.
5231 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
5234 // Now we know we're dealing with FP values.
5235 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5236 LHS.getValueType() == MVT::f64);
5238 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
5239 // and do the comparison.
5240 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5242 AArch64CC::CondCode CC1, CC2;
5243 changeFPCCToAArch64CC(CC, CC1, CC2);
5244 if (CC2 == AArch64CC::AL) {
5245 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
5246 CC2);
5247 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5249 // Note that we inverted the condition above, so we reverse the order of
5250 // the true and false operands here. This will allow the setcc to be
5251 // matched to a single CSINC instruction.
5252 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
5253 } else {
5254 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
5255 // totally clean. Some of them require two CSELs to implement. As is in
5256 // this case, we emit the first CSEL and then emit a second using the output
5257 // of the first as the RHS. We're effectively OR'ing the two CC's together.
5259 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
5260 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5261 SDValue CS1 =
5262 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5264 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5265 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5269 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
5270 SDValue RHS, SDValue TVal,
5271 SDValue FVal, const SDLoc &dl,
5272 SelectionDAG &DAG) const {
5273 // Handle f128 first, because it will result in a comparison of some RTLIB
5274 // call result against zero.
5275 if (LHS.getValueType() == MVT::f128) {
5276 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
5278 // If softenSetCCOperands returned a scalar, we need to compare the result
5279 // against zero to select between true and false values.
5280 if (!RHS.getNode()) {
5281 RHS = DAG.getConstant(0, dl, LHS.getValueType());
5282 CC = ISD::SETNE;
5286 // Also handle f16, for which we need to do a f32 comparison.
5287 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5288 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5289 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5292 // Next, handle integers.
5293 if (LHS.getValueType().isInteger()) {
5294 assert((LHS.getValueType() == RHS.getValueType()) &&
5295 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5297 unsigned Opcode = AArch64ISD::CSEL;
5299 // If both the TVal and the FVal are constants, see if we can swap them in
5300 // order to for a CSINV or CSINC out of them.
5301 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5302 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5304 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5305 std::swap(TVal, FVal);
5306 std::swap(CTVal, CFVal);
5307 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5308 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5309 std::swap(TVal, FVal);
5310 std::swap(CTVal, CFVal);
5311 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5312 } else if (TVal.getOpcode() == ISD::XOR) {
5313 // If TVal is a NOT we want to swap TVal and FVal so that we can match
5314 // with a CSINV rather than a CSEL.
5315 if (isAllOnesConstant(TVal.getOperand(1))) {
5316 std::swap(TVal, FVal);
5317 std::swap(CTVal, CFVal);
5318 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5320 } else if (TVal.getOpcode() == ISD::SUB) {
5321 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5322 // that we can match with a CSNEG rather than a CSEL.
5323 if (isNullConstant(TVal.getOperand(0))) {
5324 std::swap(TVal, FVal);
5325 std::swap(CTVal, CFVal);
5326 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5328 } else if (CTVal && CFVal) {
5329 const int64_t TrueVal = CTVal->getSExtValue();
5330 const int64_t FalseVal = CFVal->getSExtValue();
5331 bool Swap = false;
5333 // If both TVal and FVal are constants, see if FVal is the
5334 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5335 // instead of a CSEL in that case.
5336 if (TrueVal == ~FalseVal) {
5337 Opcode = AArch64ISD::CSINV;
5338 } else if (TrueVal == -FalseVal) {
5339 Opcode = AArch64ISD::CSNEG;
5340 } else if (TVal.getValueType() == MVT::i32) {
5341 // If our operands are only 32-bit wide, make sure we use 32-bit
5342 // arithmetic for the check whether we can use CSINC. This ensures that
5343 // the addition in the check will wrap around properly in case there is
5344 // an overflow (which would not be the case if we do the check with
5345 // 64-bit arithmetic).
5346 const uint32_t TrueVal32 = CTVal->getZExtValue();
5347 const uint32_t FalseVal32 = CFVal->getZExtValue();
5349 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5350 Opcode = AArch64ISD::CSINC;
5352 if (TrueVal32 > FalseVal32) {
5353 Swap = true;
5356 // 64-bit check whether we can use CSINC.
5357 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5358 Opcode = AArch64ISD::CSINC;
5360 if (TrueVal > FalseVal) {
5361 Swap = true;
5365 // Swap TVal and FVal if necessary.
5366 if (Swap) {
5367 std::swap(TVal, FVal);
5368 std::swap(CTVal, CFVal);
5369 CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5372 if (Opcode != AArch64ISD::CSEL) {
5373 // Drop FVal since we can get its value by simply inverting/negating
5374 // TVal.
5375 FVal = TVal;
5379 // Avoid materializing a constant when possible by reusing a known value in
5380 // a register. However, don't perform this optimization if the known value
5381 // is one, zero or negative one in the case of a CSEL. We can always
5382 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5383 // FVal, respectively.
5384 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5385 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5386 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5387 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5388 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5389 // "a != C ? x : a" to avoid materializing C.
5390 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5391 TVal = LHS;
5392 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5393 FVal = LHS;
5394 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5395 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5396 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5397 // avoid materializing C.
5398 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5399 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5400 Opcode = AArch64ISD::CSINV;
5401 TVal = LHS;
5402 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5406 SDValue CCVal;
5407 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5408 EVT VT = TVal.getValueType();
5409 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5412 // Now we know we're dealing with FP values.
5413 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5414 LHS.getValueType() == MVT::f64);
5415 assert(LHS.getValueType() == RHS.getValueType());
5416 EVT VT = TVal.getValueType();
5417 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5419 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5420 // clean. Some of them require two CSELs to implement.
5421 AArch64CC::CondCode CC1, CC2;
5422 changeFPCCToAArch64CC(CC, CC1, CC2);
5424 if (DAG.getTarget().Options.UnsafeFPMath) {
5425 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5426 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5427 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5428 if (RHSVal && RHSVal->isZero()) {
5429 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5430 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5432 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5433 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5434 TVal = LHS;
5435 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5436 CFVal && CFVal->isZero() &&
5437 FVal.getValueType() == LHS.getValueType())
5438 FVal = LHS;
5442 // Emit first, and possibly only, CSEL.
5443 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5444 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5446 // If we need a second CSEL, emit it, using the output of the first as the
5447 // RHS. We're effectively OR'ing the two CC's together.
5448 if (CC2 != AArch64CC::AL) {
5449 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5450 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5453 // Otherwise, return the output of the first CSEL.
5454 return CS1;
5457 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5458 SelectionDAG &DAG) const {
5459 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5460 SDValue LHS = Op.getOperand(0);
5461 SDValue RHS = Op.getOperand(1);
5462 SDValue TVal = Op.getOperand(2);
5463 SDValue FVal = Op.getOperand(3);
5464 SDLoc DL(Op);
5465 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5468 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5469 SelectionDAG &DAG) const {
5470 SDValue CCVal = Op->getOperand(0);
5471 SDValue TVal = Op->getOperand(1);
5472 SDValue FVal = Op->getOperand(2);
5473 SDLoc DL(Op);
5475 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5476 // instruction.
5477 if (isOverflowIntrOpRes(CCVal)) {
5478 // Only lower legal XALUO ops.
5479 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5480 return SDValue();
5482 AArch64CC::CondCode OFCC;
5483 SDValue Value, Overflow;
5484 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5485 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5487 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5488 CCVal, Overflow);
5491 // Lower it the same way as we would lower a SELECT_CC node.
5492 ISD::CondCode CC;
5493 SDValue LHS, RHS;
5494 if (CCVal.getOpcode() == ISD::SETCC) {
5495 LHS = CCVal.getOperand(0);
5496 RHS = CCVal.getOperand(1);
5497 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5498 } else {
5499 LHS = CCVal;
5500 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5501 CC = ISD::SETNE;
5503 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5506 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5507 SelectionDAG &DAG) const {
5508 // Jump table entries as PC relative offsets. No additional tweaking
5509 // is necessary here. Just get the address of the jump table.
5510 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5512 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5513 !Subtarget->isTargetMachO()) {
5514 return getAddrLarge(JT, DAG);
5515 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5516 return getAddrTiny(JT, DAG);
5518 return getAddr(JT, DAG);
5521 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5522 SelectionDAG &DAG) const {
5523 // Jump table entries as PC relative offsets. No additional tweaking
5524 // is necessary here. Just get the address of the jump table.
5525 SDLoc DL(Op);
5526 SDValue JT = Op.getOperand(1);
5527 SDValue Entry = Op.getOperand(2);
5528 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5530 SDNode *Dest =
5531 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5532 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5533 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5534 SDValue(Dest, 0));
5537 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5538 SelectionDAG &DAG) const {
5539 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5541 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5542 // Use the GOT for the large code model on iOS.
5543 if (Subtarget->isTargetMachO()) {
5544 return getGOT(CP, DAG);
5546 return getAddrLarge(CP, DAG);
5547 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5548 return getAddrTiny(CP, DAG);
5549 } else {
5550 return getAddr(CP, DAG);
5554 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5555 SelectionDAG &DAG) const {
5556 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5557 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5558 !Subtarget->isTargetMachO()) {
5559 return getAddrLarge(BA, DAG);
5560 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5561 return getAddrTiny(BA, DAG);
5563 return getAddr(BA, DAG);
5566 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5567 SelectionDAG &DAG) const {
5568 AArch64FunctionInfo *FuncInfo =
5569 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5571 SDLoc DL(Op);
5572 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5573 getPointerTy(DAG.getDataLayout()));
5574 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5575 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5576 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5577 MachinePointerInfo(SV));
5580 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5581 SelectionDAG &DAG) const {
5582 AArch64FunctionInfo *FuncInfo =
5583 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5585 SDLoc DL(Op);
5586 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5587 ? FuncInfo->getVarArgsGPRIndex()
5588 : FuncInfo->getVarArgsStackIndex(),
5589 getPointerTy(DAG.getDataLayout()));
5590 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5591 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5592 MachinePointerInfo(SV));
5595 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5596 SelectionDAG &DAG) const {
5597 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5598 // Standard, section B.3.
5599 MachineFunction &MF = DAG.getMachineFunction();
5600 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5601 auto PtrVT = getPointerTy(DAG.getDataLayout());
5602 SDLoc DL(Op);
5604 SDValue Chain = Op.getOperand(0);
5605 SDValue VAList = Op.getOperand(1);
5606 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5607 SmallVector<SDValue, 4> MemOps;
5609 // void *__stack at offset 0
5610 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5611 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5612 MachinePointerInfo(SV), /* Alignment = */ 8));
5614 // void *__gr_top at offset 8
5615 int GPRSize = FuncInfo->getVarArgsGPRSize();
5616 if (GPRSize > 0) {
5617 SDValue GRTop, GRTopAddr;
5619 GRTopAddr =
5620 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5622 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5623 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5624 DAG.getConstant(GPRSize, DL, PtrVT));
5626 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5627 MachinePointerInfo(SV, 8),
5628 /* Alignment = */ 8));
5631 // void *__vr_top at offset 16
5632 int FPRSize = FuncInfo->getVarArgsFPRSize();
5633 if (FPRSize > 0) {
5634 SDValue VRTop, VRTopAddr;
5635 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5636 DAG.getConstant(16, DL, PtrVT));
5638 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5639 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5640 DAG.getConstant(FPRSize, DL, PtrVT));
5642 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5643 MachinePointerInfo(SV, 16),
5644 /* Alignment = */ 8));
5647 // int __gr_offs at offset 24
5648 SDValue GROffsAddr =
5649 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5650 MemOps.push_back(DAG.getStore(
5651 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5652 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5654 // int __vr_offs at offset 28
5655 SDValue VROffsAddr =
5656 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5657 MemOps.push_back(DAG.getStore(
5658 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5659 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5661 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5664 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5665 SelectionDAG &DAG) const {
5666 MachineFunction &MF = DAG.getMachineFunction();
5668 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5669 return LowerWin64_VASTART(Op, DAG);
5670 else if (Subtarget->isTargetDarwin())
5671 return LowerDarwin_VASTART(Op, DAG);
5672 else
5673 return LowerAAPCS_VASTART(Op, DAG);
5676 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5677 SelectionDAG &DAG) const {
5678 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5679 // pointer.
5680 SDLoc DL(Op);
5681 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5682 unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5683 Subtarget->isTargetWindows()) ? PtrSize : 32;
5684 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5685 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5687 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5688 DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5689 false, false, false, MachinePointerInfo(DestSV),
5690 MachinePointerInfo(SrcSV));
5693 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5694 assert(Subtarget->isTargetDarwin() &&
5695 "automatic va_arg instruction only works on Darwin");
5697 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5698 EVT VT = Op.getValueType();
5699 SDLoc DL(Op);
5700 SDValue Chain = Op.getOperand(0);
5701 SDValue Addr = Op.getOperand(1);
5702 unsigned Align = Op.getConstantOperandVal(3);
5703 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5704 auto PtrVT = getPointerTy(DAG.getDataLayout());
5705 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5706 SDValue VAList =
5707 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5708 Chain = VAList.getValue(1);
5709 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5711 if (Align > MinSlotSize) {
5712 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5713 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5714 DAG.getConstant(Align - 1, DL, PtrVT));
5715 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5716 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5719 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5720 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5722 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5723 // up to 64 bits. At the very least, we have to increase the striding of the
5724 // vaargs list to match this, and for FP values we need to introduce
5725 // FP_ROUND nodes as well.
5726 if (VT.isInteger() && !VT.isVector())
5727 ArgSize = std::max(ArgSize, MinSlotSize);
5728 bool NeedFPTrunc = false;
5729 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5730 ArgSize = 8;
5731 NeedFPTrunc = true;
5734 // Increment the pointer, VAList, to the next vaarg
5735 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5736 DAG.getConstant(ArgSize, DL, PtrVT));
5737 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5739 // Store the incremented VAList to the legalized pointer
5740 SDValue APStore =
5741 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5743 // Load the actual argument out of the pointer VAList
5744 if (NeedFPTrunc) {
5745 // Load the value as an f64.
5746 SDValue WideFP =
5747 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5748 // Round the value down to an f32.
5749 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5750 DAG.getIntPtrConstant(1, DL));
5751 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5752 // Merge the rounded value with the chain output of the load.
5753 return DAG.getMergeValues(Ops, DL);
5756 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5759 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5760 SelectionDAG &DAG) const {
5761 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5762 MFI.setFrameAddressIsTaken(true);
5764 EVT VT = Op.getValueType();
5765 SDLoc DL(Op);
5766 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5767 SDValue FrameAddr =
5768 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5769 while (Depth--)
5770 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5771 MachinePointerInfo());
5773 if (Subtarget->isTargetILP32())
5774 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5775 DAG.getValueType(VT));
5777 return FrameAddr;
5780 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5781 SelectionDAG &DAG) const {
5782 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5784 EVT VT = getPointerTy(DAG.getDataLayout());
5785 SDLoc DL(Op);
5786 int FI = MFI.CreateFixedObject(4, 0, false);
5787 return DAG.getFrameIndex(FI, VT);
5790 #define GET_REGISTER_MATCHER
5791 #include "AArch64GenAsmMatcher.inc"
5793 // FIXME? Maybe this could be a TableGen attribute on some registers and
5794 // this table could be generated automatically from RegInfo.
5795 Register AArch64TargetLowering::
5796 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
5797 Register Reg = MatchRegisterName(RegName);
5798 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5799 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5800 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5801 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5802 Reg = 0;
5804 if (Reg)
5805 return Reg;
5806 report_fatal_error(Twine("Invalid register name \""
5807 + StringRef(RegName) + "\"."));
5810 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5811 SelectionDAG &DAG) const {
5812 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5814 EVT VT = Op.getValueType();
5815 SDLoc DL(Op);
5817 SDValue FrameAddr =
5818 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5819 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5821 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5824 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5825 SelectionDAG &DAG) const {
5826 MachineFunction &MF = DAG.getMachineFunction();
5827 MachineFrameInfo &MFI = MF.getFrameInfo();
5828 MFI.setReturnAddressIsTaken(true);
5830 EVT VT = Op.getValueType();
5831 SDLoc DL(Op);
5832 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5833 if (Depth) {
5834 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5835 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5836 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5837 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5838 MachinePointerInfo());
5841 // Return LR, which contains the return address. Mark it an implicit live-in.
5842 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5843 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5846 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5847 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5848 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5849 SelectionDAG &DAG) const {
5850 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5851 EVT VT = Op.getValueType();
5852 unsigned VTBits = VT.getSizeInBits();
5853 SDLoc dl(Op);
5854 SDValue ShOpLo = Op.getOperand(0);
5855 SDValue ShOpHi = Op.getOperand(1);
5856 SDValue ShAmt = Op.getOperand(2);
5857 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5859 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5861 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5862 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5863 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5865 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5866 // is "undef". We wanted 0, so CSEL it directly.
5867 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5868 ISD::SETEQ, dl, DAG);
5869 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5870 HiBitsForLo =
5871 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5872 HiBitsForLo, CCVal, Cmp);
5874 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5875 DAG.getConstant(VTBits, dl, MVT::i64));
5877 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5878 SDValue LoForNormalShift =
5879 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5881 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5882 dl, DAG);
5883 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5884 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5885 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5886 LoForNormalShift, CCVal, Cmp);
5888 // AArch64 shifts larger than the register width are wrapped rather than
5889 // clamped, so we can't just emit "hi >> x".
5890 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5891 SDValue HiForBigShift =
5892 Opc == ISD::SRA
5893 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5894 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5895 : DAG.getConstant(0, dl, VT);
5896 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5897 HiForNormalShift, CCVal, Cmp);
5899 SDValue Ops[2] = { Lo, Hi };
5900 return DAG.getMergeValues(Ops, dl);
5903 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5904 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5905 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5906 SelectionDAG &DAG) const {
5907 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5908 EVT VT = Op.getValueType();
5909 unsigned VTBits = VT.getSizeInBits();
5910 SDLoc dl(Op);
5911 SDValue ShOpLo = Op.getOperand(0);
5912 SDValue ShOpHi = Op.getOperand(1);
5913 SDValue ShAmt = Op.getOperand(2);
5915 assert(Op.getOpcode() == ISD::SHL_PARTS);
5916 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5917 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5918 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5920 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5921 // is "undef". We wanted 0, so CSEL it directly.
5922 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5923 ISD::SETEQ, dl, DAG);
5924 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5925 LoBitsForHi =
5926 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5927 LoBitsForHi, CCVal, Cmp);
5929 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5930 DAG.getConstant(VTBits, dl, MVT::i64));
5931 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5932 SDValue HiForNormalShift =
5933 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5935 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5937 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5938 dl, DAG);
5939 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5940 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5941 HiForNormalShift, CCVal, Cmp);
5943 // AArch64 shifts of larger than register sizes are wrapped rather than
5944 // clamped, so we can't just emit "lo << a" if a is too big.
5945 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5946 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5947 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5948 LoForNormalShift, CCVal, Cmp);
5950 SDValue Ops[2] = { Lo, Hi };
5951 return DAG.getMergeValues(Ops, dl);
5954 bool AArch64TargetLowering::isOffsetFoldingLegal(
5955 const GlobalAddressSDNode *GA) const {
5956 // Offsets are folded in the DAG combine rather than here so that we can
5957 // intelligently choose an offset based on the uses.
5958 return false;
5961 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5962 bool OptForSize) const {
5963 bool IsLegal = false;
5964 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5965 // 16-bit case when target has full fp16 support.
5966 // FIXME: We should be able to handle f128 as well with a clever lowering.
5967 const APInt ImmInt = Imm.bitcastToAPInt();
5968 if (VT == MVT::f64)
5969 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5970 else if (VT == MVT::f32)
5971 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5972 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5973 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5974 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5975 // generate that fmov.
5977 // If we can not materialize in immediate field for fmov, check if the
5978 // value can be encoded as the immediate operand of a logical instruction.
5979 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5980 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5981 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5982 // however the mov+fmov sequence is always better because of the reduced
5983 // cache pressure. The timings are still the same if you consider
5984 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5985 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5986 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5987 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5988 Insn);
5989 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5990 IsLegal = Insn.size() <= Limit;
5993 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5994 << " imm value: "; Imm.dump(););
5995 return IsLegal;
5998 //===----------------------------------------------------------------------===//
5999 // AArch64 Optimization Hooks
6000 //===----------------------------------------------------------------------===//
6002 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
6003 SDValue Operand, SelectionDAG &DAG,
6004 int &ExtraSteps) {
6005 EVT VT = Operand.getValueType();
6006 if (ST->hasNEON() &&
6007 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
6008 VT == MVT::f32 || VT == MVT::v1f32 ||
6009 VT == MVT::v2f32 || VT == MVT::v4f32)) {
6010 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
6011 // For the reciprocal estimates, convergence is quadratic, so the number
6012 // of digits is doubled after each iteration. In ARMv8, the accuracy of
6013 // the initial estimate is 2^-8. Thus the number of extra steps to refine
6014 // the result for float (23 mantissa bits) is 2 and for double (52
6015 // mantissa bits) is 3.
6016 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
6018 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
6021 return SDValue();
6024 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
6025 SelectionDAG &DAG, int Enabled,
6026 int &ExtraSteps,
6027 bool &UseOneConst,
6028 bool Reciprocal) const {
6029 if (Enabled == ReciprocalEstimate::Enabled ||
6030 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
6031 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
6032 DAG, ExtraSteps)) {
6033 SDLoc DL(Operand);
6034 EVT VT = Operand.getValueType();
6036 SDNodeFlags Flags;
6037 Flags.setAllowReassociation(true);
6039 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
6040 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
6041 for (int i = ExtraSteps; i > 0; --i) {
6042 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
6043 Flags);
6044 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
6045 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6047 if (!Reciprocal) {
6048 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
6049 VT);
6050 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6051 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
6053 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
6054 // Correct the result if the operand is 0.0.
6055 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
6056 VT, Eq, Operand, Estimate);
6059 ExtraSteps = 0;
6060 return Estimate;
6063 return SDValue();
6066 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
6067 SelectionDAG &DAG, int Enabled,
6068 int &ExtraSteps) const {
6069 if (Enabled == ReciprocalEstimate::Enabled)
6070 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
6071 DAG, ExtraSteps)) {
6072 SDLoc DL(Operand);
6073 EVT VT = Operand.getValueType();
6075 SDNodeFlags Flags;
6076 Flags.setAllowReassociation(true);
6078 // Newton reciprocal iteration: E * (2 - X * E)
6079 // AArch64 reciprocal iteration instruction: (2 - M * N)
6080 for (int i = ExtraSteps; i > 0; --i) {
6081 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
6082 Estimate, Flags);
6083 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
6086 ExtraSteps = 0;
6087 return Estimate;
6090 return SDValue();
6093 //===----------------------------------------------------------------------===//
6094 // AArch64 Inline Assembly Support
6095 //===----------------------------------------------------------------------===//
6097 // Table of Constraints
6098 // TODO: This is the current set of constraints supported by ARM for the
6099 // compiler, not all of them may make sense.
6101 // r - A general register
6102 // w - An FP/SIMD register of some size in the range v0-v31
6103 // x - An FP/SIMD register of some size in the range v0-v15
6104 // I - Constant that can be used with an ADD instruction
6105 // J - Constant that can be used with a SUB instruction
6106 // K - Constant that can be used with a 32-bit logical instruction
6107 // L - Constant that can be used with a 64-bit logical instruction
6108 // M - Constant that can be used as a 32-bit MOV immediate
6109 // N - Constant that can be used as a 64-bit MOV immediate
6110 // Q - A memory reference with base register and no offset
6111 // S - A symbolic address
6112 // Y - Floating point constant zero
6113 // Z - Integer constant zero
6115 // Note that general register operands will be output using their 64-bit x
6116 // register name, whatever the size of the variable, unless the asm operand
6117 // is prefixed by the %w modifier. Floating-point and SIMD register operands
6118 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
6119 // %q modifier.
6120 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
6121 // At this point, we have to lower this constraint to something else, so we
6122 // lower it to an "r" or "w". However, by doing this we will force the result
6123 // to be in register, while the X constraint is much more permissive.
6125 // Although we are correct (we are free to emit anything, without
6126 // constraints), we might break use cases that would expect us to be more
6127 // efficient and emit something else.
6128 if (!Subtarget->hasFPARMv8())
6129 return "r";
6131 if (ConstraintVT.isFloatingPoint())
6132 return "w";
6134 if (ConstraintVT.isVector() &&
6135 (ConstraintVT.getSizeInBits() == 64 ||
6136 ConstraintVT.getSizeInBits() == 128))
6137 return "w";
6139 return "r";
6142 enum PredicateConstraint {
6143 Upl,
6144 Upa,
6145 Invalid
6148 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
6149 PredicateConstraint P = PredicateConstraint::Invalid;
6150 if (Constraint == "Upa")
6151 P = PredicateConstraint::Upa;
6152 if (Constraint == "Upl")
6153 P = PredicateConstraint::Upl;
6154 return P;
6157 /// getConstraintType - Given a constraint letter, return the type of
6158 /// constraint it is for this target.
6159 AArch64TargetLowering::ConstraintType
6160 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
6161 if (Constraint.size() == 1) {
6162 switch (Constraint[0]) {
6163 default:
6164 break;
6165 case 'x':
6166 case 'w':
6167 case 'y':
6168 return C_RegisterClass;
6169 // An address with a single base register. Due to the way we
6170 // currently handle addresses it is the same as 'r'.
6171 case 'Q':
6172 return C_Memory;
6173 case 'I':
6174 case 'J':
6175 case 'K':
6176 case 'L':
6177 case 'M':
6178 case 'N':
6179 case 'Y':
6180 case 'Z':
6181 return C_Immediate;
6182 case 'z':
6183 case 'S': // A symbolic address
6184 return C_Other;
6186 } else if (parsePredicateConstraint(Constraint) !=
6187 PredicateConstraint::Invalid)
6188 return C_RegisterClass;
6189 return TargetLowering::getConstraintType(Constraint);
6192 /// Examine constraint type and operand type and determine a weight value.
6193 /// This object must already have been set up with the operand type
6194 /// and the current alternative constraint selected.
6195 TargetLowering::ConstraintWeight
6196 AArch64TargetLowering::getSingleConstraintMatchWeight(
6197 AsmOperandInfo &info, const char *constraint) const {
6198 ConstraintWeight weight = CW_Invalid;
6199 Value *CallOperandVal = info.CallOperandVal;
6200 // If we don't have a value, we can't do a match,
6201 // but allow it at the lowest weight.
6202 if (!CallOperandVal)
6203 return CW_Default;
6204 Type *type = CallOperandVal->getType();
6205 // Look at the constraint type.
6206 switch (*constraint) {
6207 default:
6208 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6209 break;
6210 case 'x':
6211 case 'w':
6212 case 'y':
6213 if (type->isFloatingPointTy() || type->isVectorTy())
6214 weight = CW_Register;
6215 break;
6216 case 'z':
6217 weight = CW_Constant;
6218 break;
6219 case 'U':
6220 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
6221 weight = CW_Register;
6222 break;
6224 return weight;
6227 std::pair<unsigned, const TargetRegisterClass *>
6228 AArch64TargetLowering::getRegForInlineAsmConstraint(
6229 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
6230 if (Constraint.size() == 1) {
6231 switch (Constraint[0]) {
6232 case 'r':
6233 if (VT.getSizeInBits() == 64)
6234 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
6235 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
6236 case 'w':
6237 if (!Subtarget->hasFPARMv8())
6238 break;
6239 if (VT.isScalableVector())
6240 return std::make_pair(0U, &AArch64::ZPRRegClass);
6241 if (VT.getSizeInBits() == 16)
6242 return std::make_pair(0U, &AArch64::FPR16RegClass);
6243 if (VT.getSizeInBits() == 32)
6244 return std::make_pair(0U, &AArch64::FPR32RegClass);
6245 if (VT.getSizeInBits() == 64)
6246 return std::make_pair(0U, &AArch64::FPR64RegClass);
6247 if (VT.getSizeInBits() == 128)
6248 return std::make_pair(0U, &AArch64::FPR128RegClass);
6249 break;
6250 // The instructions that this constraint is designed for can
6251 // only take 128-bit registers so just use that regclass.
6252 case 'x':
6253 if (!Subtarget->hasFPARMv8())
6254 break;
6255 if (VT.isScalableVector())
6256 return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
6257 if (VT.getSizeInBits() == 128)
6258 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
6259 break;
6260 case 'y':
6261 if (!Subtarget->hasFPARMv8())
6262 break;
6263 if (VT.isScalableVector())
6264 return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
6265 break;
6267 } else {
6268 PredicateConstraint PC = parsePredicateConstraint(Constraint);
6269 if (PC != PredicateConstraint::Invalid) {
6270 assert(VT.isScalableVector());
6271 bool restricted = (PC == PredicateConstraint::Upl);
6272 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
6273 : std::make_pair(0U, &AArch64::PPRRegClass);
6276 if (StringRef("{cc}").equals_lower(Constraint))
6277 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
6279 // Use the default implementation in TargetLowering to convert the register
6280 // constraint into a member of a register class.
6281 std::pair<unsigned, const TargetRegisterClass *> Res;
6282 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6284 // Not found as a standard register?
6285 if (!Res.second) {
6286 unsigned Size = Constraint.size();
6287 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6288 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6289 int RegNo;
6290 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6291 if (!Failed && RegNo >= 0 && RegNo <= 31) {
6292 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6293 // By default we'll emit v0-v31 for this unless there's a modifier where
6294 // we'll emit the correct register as well.
6295 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6296 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6297 Res.second = &AArch64::FPR64RegClass;
6298 } else {
6299 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6300 Res.second = &AArch64::FPR128RegClass;
6306 if (Res.second && !Subtarget->hasFPARMv8() &&
6307 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6308 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6309 return std::make_pair(0U, nullptr);
6311 return Res;
6314 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6315 /// vector. If it is invalid, don't add anything to Ops.
6316 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6317 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6318 SelectionDAG &DAG) const {
6319 SDValue Result;
6321 // Currently only support length 1 constraints.
6322 if (Constraint.length() != 1)
6323 return;
6325 char ConstraintLetter = Constraint[0];
6326 switch (ConstraintLetter) {
6327 default:
6328 break;
6330 // This set of constraints deal with valid constants for various instructions.
6331 // Validate and return a target constant for them if we can.
6332 case 'z': {
6333 // 'z' maps to xzr or wzr so it needs an input of 0.
6334 if (!isNullConstant(Op))
6335 return;
6337 if (Op.getValueType() == MVT::i64)
6338 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6339 else
6340 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6341 break;
6343 case 'S': {
6344 // An absolute symbolic address or label reference.
6345 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6346 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6347 GA->getValueType(0));
6348 } else if (const BlockAddressSDNode *BA =
6349 dyn_cast<BlockAddressSDNode>(Op)) {
6350 Result =
6351 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6352 } else if (const ExternalSymbolSDNode *ES =
6353 dyn_cast<ExternalSymbolSDNode>(Op)) {
6354 Result =
6355 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6356 } else
6357 return;
6358 break;
6361 case 'I':
6362 case 'J':
6363 case 'K':
6364 case 'L':
6365 case 'M':
6366 case 'N':
6367 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6368 if (!C)
6369 return;
6371 // Grab the value and do some validation.
6372 uint64_t CVal = C->getZExtValue();
6373 switch (ConstraintLetter) {
6374 // The I constraint applies only to simple ADD or SUB immediate operands:
6375 // i.e. 0 to 4095 with optional shift by 12
6376 // The J constraint applies only to ADD or SUB immediates that would be
6377 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6378 // instruction [or vice versa], in other words -1 to -4095 with optional
6379 // left shift by 12.
6380 case 'I':
6381 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6382 break;
6383 return;
6384 case 'J': {
6385 uint64_t NVal = -C->getSExtValue();
6386 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6387 CVal = C->getSExtValue();
6388 break;
6390 return;
6392 // The K and L constraints apply *only* to logical immediates, including
6393 // what used to be the MOVI alias for ORR (though the MOVI alias has now
6394 // been removed and MOV should be used). So these constraints have to
6395 // distinguish between bit patterns that are valid 32-bit or 64-bit
6396 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6397 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6398 // versa.
6399 case 'K':
6400 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6401 break;
6402 return;
6403 case 'L':
6404 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6405 break;
6406 return;
6407 // The M and N constraints are a superset of K and L respectively, for use
6408 // with the MOV (immediate) alias. As well as the logical immediates they
6409 // also match 32 or 64-bit immediates that can be loaded either using a
6410 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6411 // (M) or 64-bit 0x1234000000000000 (N) etc.
6412 // As a note some of this code is liberally stolen from the asm parser.
6413 case 'M': {
6414 if (!isUInt<32>(CVal))
6415 return;
6416 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6417 break;
6418 if ((CVal & 0xFFFF) == CVal)
6419 break;
6420 if ((CVal & 0xFFFF0000ULL) == CVal)
6421 break;
6422 uint64_t NCVal = ~(uint32_t)CVal;
6423 if ((NCVal & 0xFFFFULL) == NCVal)
6424 break;
6425 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6426 break;
6427 return;
6429 case 'N': {
6430 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6431 break;
6432 if ((CVal & 0xFFFFULL) == CVal)
6433 break;
6434 if ((CVal & 0xFFFF0000ULL) == CVal)
6435 break;
6436 if ((CVal & 0xFFFF00000000ULL) == CVal)
6437 break;
6438 if ((CVal & 0xFFFF000000000000ULL) == CVal)
6439 break;
6440 uint64_t NCVal = ~CVal;
6441 if ((NCVal & 0xFFFFULL) == NCVal)
6442 break;
6443 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6444 break;
6445 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6446 break;
6447 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6448 break;
6449 return;
6451 default:
6452 return;
6455 // All assembler immediates are 64-bit integers.
6456 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6457 break;
6460 if (Result.getNode()) {
6461 Ops.push_back(Result);
6462 return;
6465 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6468 //===----------------------------------------------------------------------===//
6469 // AArch64 Advanced SIMD Support
6470 //===----------------------------------------------------------------------===//
6472 /// WidenVector - Given a value in the V64 register class, produce the
6473 /// equivalent value in the V128 register class.
6474 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6475 EVT VT = V64Reg.getValueType();
6476 unsigned NarrowSize = VT.getVectorNumElements();
6477 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6478 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6479 SDLoc DL(V64Reg);
6481 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6482 V64Reg, DAG.getConstant(0, DL, MVT::i32));
6485 /// getExtFactor - Determine the adjustment factor for the position when
6486 /// generating an "extract from vector registers" instruction.
6487 static unsigned getExtFactor(SDValue &V) {
6488 EVT EltType = V.getValueType().getVectorElementType();
6489 return EltType.getSizeInBits() / 8;
6492 /// NarrowVector - Given a value in the V128 register class, produce the
6493 /// equivalent value in the V64 register class.
6494 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6495 EVT VT = V128Reg.getValueType();
6496 unsigned WideSize = VT.getVectorNumElements();
6497 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6498 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6499 SDLoc DL(V128Reg);
6501 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6504 // Gather data to see if the operation can be modelled as a
6505 // shuffle in combination with VEXTs.
6506 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6507 SelectionDAG &DAG) const {
6508 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6509 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6510 SDLoc dl(Op);
6511 EVT VT = Op.getValueType();
6512 unsigned NumElts = VT.getVectorNumElements();
6514 struct ShuffleSourceInfo {
6515 SDValue Vec;
6516 unsigned MinElt;
6517 unsigned MaxElt;
6519 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6520 // be compatible with the shuffle we intend to construct. As a result
6521 // ShuffleVec will be some sliding window into the original Vec.
6522 SDValue ShuffleVec;
6524 // Code should guarantee that element i in Vec starts at element "WindowBase
6525 // + i * WindowScale in ShuffleVec".
6526 int WindowBase;
6527 int WindowScale;
6529 ShuffleSourceInfo(SDValue Vec)
6530 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6531 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6533 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6536 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6537 // node.
6538 SmallVector<ShuffleSourceInfo, 2> Sources;
6539 for (unsigned i = 0; i < NumElts; ++i) {
6540 SDValue V = Op.getOperand(i);
6541 if (V.isUndef())
6542 continue;
6543 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6544 !isa<ConstantSDNode>(V.getOperand(1))) {
6545 LLVM_DEBUG(
6546 dbgs() << "Reshuffle failed: "
6547 "a shuffle can only come from building a vector from "
6548 "various elements of other vectors, provided their "
6549 "indices are constant\n");
6550 return SDValue();
6553 // Add this element source to the list if it's not already there.
6554 SDValue SourceVec = V.getOperand(0);
6555 auto Source = find(Sources, SourceVec);
6556 if (Source == Sources.end())
6557 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6559 // Update the minimum and maximum lane number seen.
6560 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6561 Source->MinElt = std::min(Source->MinElt, EltNo);
6562 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6565 if (Sources.size() > 2) {
6566 LLVM_DEBUG(
6567 dbgs() << "Reshuffle failed: currently only do something sane when at "
6568 "most two source vectors are involved\n");
6569 return SDValue();
6572 // Find out the smallest element size among result and two sources, and use
6573 // it as element size to build the shuffle_vector.
6574 EVT SmallestEltTy = VT.getVectorElementType();
6575 for (auto &Source : Sources) {
6576 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6577 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6578 SmallestEltTy = SrcEltTy;
6581 unsigned ResMultiplier =
6582 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6583 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6584 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6586 // If the source vector is too wide or too narrow, we may nevertheless be able
6587 // to construct a compatible shuffle either by concatenating it with UNDEF or
6588 // extracting a suitable range of elements.
6589 for (auto &Src : Sources) {
6590 EVT SrcVT = Src.ShuffleVec.getValueType();
6592 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6593 continue;
6595 // This stage of the search produces a source with the same element type as
6596 // the original, but with a total width matching the BUILD_VECTOR output.
6597 EVT EltVT = SrcVT.getVectorElementType();
6598 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6599 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6601 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6602 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6603 // We can pad out the smaller vector for free, so if it's part of a
6604 // shuffle...
6605 Src.ShuffleVec =
6606 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6607 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6608 continue;
6611 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6613 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6614 LLVM_DEBUG(
6615 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6616 return SDValue();
6619 if (Src.MinElt >= NumSrcElts) {
6620 // The extraction can just take the second half
6621 Src.ShuffleVec =
6622 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6623 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6624 Src.WindowBase = -NumSrcElts;
6625 } else if (Src.MaxElt < NumSrcElts) {
6626 // The extraction can just take the first half
6627 Src.ShuffleVec =
6628 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6629 DAG.getConstant(0, dl, MVT::i64));
6630 } else {
6631 // An actual VEXT is needed
6632 SDValue VEXTSrc1 =
6633 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6634 DAG.getConstant(0, dl, MVT::i64));
6635 SDValue VEXTSrc2 =
6636 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6637 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6638 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6640 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6641 VEXTSrc2,
6642 DAG.getConstant(Imm, dl, MVT::i32));
6643 Src.WindowBase = -Src.MinElt;
6647 // Another possible incompatibility occurs from the vector element types. We
6648 // can fix this by bitcasting the source vectors to the same type we intend
6649 // for the shuffle.
6650 for (auto &Src : Sources) {
6651 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6652 if (SrcEltTy == SmallestEltTy)
6653 continue;
6654 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6655 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6656 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6657 Src.WindowBase *= Src.WindowScale;
6660 // Final sanity check before we try to actually produce a shuffle.
6661 LLVM_DEBUG(for (auto Src
6662 : Sources)
6663 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6665 // The stars all align, our next step is to produce the mask for the shuffle.
6666 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6667 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6668 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6669 SDValue Entry = Op.getOperand(i);
6670 if (Entry.isUndef())
6671 continue;
6673 auto Src = find(Sources, Entry.getOperand(0));
6674 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6676 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6677 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6678 // segment.
6679 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6680 int BitsDefined =
6681 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6682 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6684 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6685 // starting at the appropriate offset.
6686 int *LaneMask = &Mask[i * ResMultiplier];
6688 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6689 ExtractBase += NumElts * (Src - Sources.begin());
6690 for (int j = 0; j < LanesDefined; ++j)
6691 LaneMask[j] = ExtractBase + j;
6694 // Final check before we try to produce nonsense...
6695 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6696 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6697 return SDValue();
6700 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6701 for (unsigned i = 0; i < Sources.size(); ++i)
6702 ShuffleOps[i] = Sources[i].ShuffleVec;
6704 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6705 ShuffleOps[1], Mask);
6706 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6708 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6709 dbgs() << "Reshuffle, creating node: "; V.dump(););
6711 return V;
6714 // check if an EXT instruction can handle the shuffle mask when the
6715 // vector sources of the shuffle are the same.
6716 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6717 unsigned NumElts = VT.getVectorNumElements();
6719 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6720 if (M[0] < 0)
6721 return false;
6723 Imm = M[0];
6725 // If this is a VEXT shuffle, the immediate value is the index of the first
6726 // element. The other shuffle indices must be the successive elements after
6727 // the first one.
6728 unsigned ExpectedElt = Imm;
6729 for (unsigned i = 1; i < NumElts; ++i) {
6730 // Increment the expected index. If it wraps around, just follow it
6731 // back to index zero and keep going.
6732 ++ExpectedElt;
6733 if (ExpectedElt == NumElts)
6734 ExpectedElt = 0;
6736 if (M[i] < 0)
6737 continue; // ignore UNDEF indices
6738 if (ExpectedElt != static_cast<unsigned>(M[i]))
6739 return false;
6742 return true;
6745 // check if an EXT instruction can handle the shuffle mask when the
6746 // vector sources of the shuffle are different.
6747 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6748 unsigned &Imm) {
6749 // Look for the first non-undef element.
6750 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6752 // Benefit form APInt to handle overflow when calculating expected element.
6753 unsigned NumElts = VT.getVectorNumElements();
6754 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6755 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6756 // The following shuffle indices must be the successive elements after the
6757 // first real element.
6758 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6759 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6760 if (FirstWrongElt != M.end())
6761 return false;
6763 // The index of an EXT is the first element if it is not UNDEF.
6764 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6765 // value of the first element. E.g.
6766 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6767 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6768 // ExpectedElt is the last mask index plus 1.
6769 Imm = ExpectedElt.getZExtValue();
6771 // There are two difference cases requiring to reverse input vectors.
6772 // For example, for vector <4 x i32> we have the following cases,
6773 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6774 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6775 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6776 // to reverse two input vectors.
6777 if (Imm < NumElts)
6778 ReverseEXT = true;
6779 else
6780 Imm -= NumElts;
6782 return true;
6785 /// isREVMask - Check if a vector shuffle corresponds to a REV
6786 /// instruction with the specified blocksize. (The order of the elements
6787 /// within each block of the vector is reversed.)
6788 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6789 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6790 "Only possible block sizes for REV are: 16, 32, 64");
6792 unsigned EltSz = VT.getScalarSizeInBits();
6793 if (EltSz == 64)
6794 return false;
6796 unsigned NumElts = VT.getVectorNumElements();
6797 unsigned BlockElts = M[0] + 1;
6798 // If the first shuffle index is UNDEF, be optimistic.
6799 if (M[0] < 0)
6800 BlockElts = BlockSize / EltSz;
6802 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6803 return false;
6805 for (unsigned i = 0; i < NumElts; ++i) {
6806 if (M[i] < 0)
6807 continue; // ignore UNDEF indices
6808 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6809 return false;
6812 return true;
6815 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6816 unsigned NumElts = VT.getVectorNumElements();
6817 if (NumElts % 2 != 0)
6818 return false;
6819 WhichResult = (M[0] == 0 ? 0 : 1);
6820 unsigned Idx = WhichResult * NumElts / 2;
6821 for (unsigned i = 0; i != NumElts; i += 2) {
6822 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6823 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6824 return false;
6825 Idx += 1;
6828 return true;
6831 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6832 unsigned NumElts = VT.getVectorNumElements();
6833 WhichResult = (M[0] == 0 ? 0 : 1);
6834 for (unsigned i = 0; i != NumElts; ++i) {
6835 if (M[i] < 0)
6836 continue; // ignore UNDEF indices
6837 if ((unsigned)M[i] != 2 * i + WhichResult)
6838 return false;
6841 return true;
6844 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6845 unsigned NumElts = VT.getVectorNumElements();
6846 if (NumElts % 2 != 0)
6847 return false;
6848 WhichResult = (M[0] == 0 ? 0 : 1);
6849 for (unsigned i = 0; i < NumElts; i += 2) {
6850 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6851 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6852 return false;
6854 return true;
6857 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6858 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6859 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6860 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6861 unsigned NumElts = VT.getVectorNumElements();
6862 if (NumElts % 2 != 0)
6863 return false;
6864 WhichResult = (M[0] == 0 ? 0 : 1);
6865 unsigned Idx = WhichResult * NumElts / 2;
6866 for (unsigned i = 0; i != NumElts; i += 2) {
6867 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6868 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6869 return false;
6870 Idx += 1;
6873 return true;
6876 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6877 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6878 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6879 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6880 unsigned Half = VT.getVectorNumElements() / 2;
6881 WhichResult = (M[0] == 0 ? 0 : 1);
6882 for (unsigned j = 0; j != 2; ++j) {
6883 unsigned Idx = WhichResult;
6884 for (unsigned i = 0; i != Half; ++i) {
6885 int MIdx = M[i + j * Half];
6886 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6887 return false;
6888 Idx += 2;
6892 return true;
6895 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6896 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6897 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6898 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6899 unsigned NumElts = VT.getVectorNumElements();
6900 if (NumElts % 2 != 0)
6901 return false;
6902 WhichResult = (M[0] == 0 ? 0 : 1);
6903 for (unsigned i = 0; i < NumElts; i += 2) {
6904 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6905 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6906 return false;
6908 return true;
6911 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6912 bool &DstIsLeft, int &Anomaly) {
6913 if (M.size() != static_cast<size_t>(NumInputElements))
6914 return false;
6916 int NumLHSMatch = 0, NumRHSMatch = 0;
6917 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6919 for (int i = 0; i < NumInputElements; ++i) {
6920 if (M[i] == -1) {
6921 ++NumLHSMatch;
6922 ++NumRHSMatch;
6923 continue;
6926 if (M[i] == i)
6927 ++NumLHSMatch;
6928 else
6929 LastLHSMismatch = i;
6931 if (M[i] == i + NumInputElements)
6932 ++NumRHSMatch;
6933 else
6934 LastRHSMismatch = i;
6937 if (NumLHSMatch == NumInputElements - 1) {
6938 DstIsLeft = true;
6939 Anomaly = LastLHSMismatch;
6940 return true;
6941 } else if (NumRHSMatch == NumInputElements - 1) {
6942 DstIsLeft = false;
6943 Anomaly = LastRHSMismatch;
6944 return true;
6947 return false;
6950 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6951 if (VT.getSizeInBits() != 128)
6952 return false;
6954 unsigned NumElts = VT.getVectorNumElements();
6956 for (int I = 0, E = NumElts / 2; I != E; I++) {
6957 if (Mask[I] != I)
6958 return false;
6961 int Offset = NumElts / 2;
6962 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6963 if (Mask[I] != I + SplitLHS * Offset)
6964 return false;
6967 return true;
6970 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6971 SDLoc DL(Op);
6972 EVT VT = Op.getValueType();
6973 SDValue V0 = Op.getOperand(0);
6974 SDValue V1 = Op.getOperand(1);
6975 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6977 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6978 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6979 return SDValue();
6981 bool SplitV0 = V0.getValueSizeInBits() == 128;
6983 if (!isConcatMask(Mask, VT, SplitV0))
6984 return SDValue();
6986 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6987 if (SplitV0) {
6988 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6989 DAG.getConstant(0, DL, MVT::i64));
6991 if (V1.getValueSizeInBits() == 128) {
6992 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6993 DAG.getConstant(0, DL, MVT::i64));
6995 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6998 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6999 /// the specified operations to build the shuffle.
7000 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7001 SDValue RHS, SelectionDAG &DAG,
7002 const SDLoc &dl) {
7003 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7004 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
7005 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
7007 enum {
7008 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7009 OP_VREV,
7010 OP_VDUP0,
7011 OP_VDUP1,
7012 OP_VDUP2,
7013 OP_VDUP3,
7014 OP_VEXT1,
7015 OP_VEXT2,
7016 OP_VEXT3,
7017 OP_VUZPL, // VUZP, left result
7018 OP_VUZPR, // VUZP, right result
7019 OP_VZIPL, // VZIP, left result
7020 OP_VZIPR, // VZIP, right result
7021 OP_VTRNL, // VTRN, left result
7022 OP_VTRNR // VTRN, right result
7025 if (OpNum == OP_COPY) {
7026 if (LHSID == (1 * 9 + 2) * 9 + 3)
7027 return LHS;
7028 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
7029 return RHS;
7032 SDValue OpLHS, OpRHS;
7033 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7034 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7035 EVT VT = OpLHS.getValueType();
7037 switch (OpNum) {
7038 default:
7039 llvm_unreachable("Unknown shuffle opcode!");
7040 case OP_VREV:
7041 // VREV divides the vector in half and swaps within the half.
7042 if (VT.getVectorElementType() == MVT::i32 ||
7043 VT.getVectorElementType() == MVT::f32)
7044 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
7045 // vrev <4 x i16> -> REV32
7046 if (VT.getVectorElementType() == MVT::i16 ||
7047 VT.getVectorElementType() == MVT::f16)
7048 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
7049 // vrev <4 x i8> -> REV16
7050 assert(VT.getVectorElementType() == MVT::i8);
7051 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
7052 case OP_VDUP0:
7053 case OP_VDUP1:
7054 case OP_VDUP2:
7055 case OP_VDUP3: {
7056 EVT EltTy = VT.getVectorElementType();
7057 unsigned Opcode;
7058 if (EltTy == MVT::i8)
7059 Opcode = AArch64ISD::DUPLANE8;
7060 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
7061 Opcode = AArch64ISD::DUPLANE16;
7062 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
7063 Opcode = AArch64ISD::DUPLANE32;
7064 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
7065 Opcode = AArch64ISD::DUPLANE64;
7066 else
7067 llvm_unreachable("Invalid vector element type?");
7069 if (VT.getSizeInBits() == 64)
7070 OpLHS = WidenVector(OpLHS, DAG);
7071 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
7072 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
7074 case OP_VEXT1:
7075 case OP_VEXT2:
7076 case OP_VEXT3: {
7077 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
7078 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
7079 DAG.getConstant(Imm, dl, MVT::i32));
7081 case OP_VUZPL:
7082 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
7083 OpRHS);
7084 case OP_VUZPR:
7085 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
7086 OpRHS);
7087 case OP_VZIPL:
7088 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
7089 OpRHS);
7090 case OP_VZIPR:
7091 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
7092 OpRHS);
7093 case OP_VTRNL:
7094 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
7095 OpRHS);
7096 case OP_VTRNR:
7097 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
7098 OpRHS);
7102 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
7103 SelectionDAG &DAG) {
7104 // Check to see if we can use the TBL instruction.
7105 SDValue V1 = Op.getOperand(0);
7106 SDValue V2 = Op.getOperand(1);
7107 SDLoc DL(Op);
7109 EVT EltVT = Op.getValueType().getVectorElementType();
7110 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
7112 SmallVector<SDValue, 8> TBLMask;
7113 for (int Val : ShuffleMask) {
7114 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
7115 unsigned Offset = Byte + Val * BytesPerElt;
7116 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
7120 MVT IndexVT = MVT::v8i8;
7121 unsigned IndexLen = 8;
7122 if (Op.getValueSizeInBits() == 128) {
7123 IndexVT = MVT::v16i8;
7124 IndexLen = 16;
7127 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
7128 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
7130 SDValue Shuffle;
7131 if (V2.getNode()->isUndef()) {
7132 if (IndexLen == 8)
7133 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
7134 Shuffle = DAG.getNode(
7135 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7136 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7137 DAG.getBuildVector(IndexVT, DL,
7138 makeArrayRef(TBLMask.data(), IndexLen)));
7139 } else {
7140 if (IndexLen == 8) {
7141 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
7142 Shuffle = DAG.getNode(
7143 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7144 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
7145 DAG.getBuildVector(IndexVT, DL,
7146 makeArrayRef(TBLMask.data(), IndexLen)));
7147 } else {
7148 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
7149 // cannot currently represent the register constraints on the input
7150 // table registers.
7151 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
7152 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
7153 // IndexLen));
7154 Shuffle = DAG.getNode(
7155 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
7156 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
7157 V2Cst, DAG.getBuildVector(IndexVT, DL,
7158 makeArrayRef(TBLMask.data(), IndexLen)));
7161 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
7164 static unsigned getDUPLANEOp(EVT EltType) {
7165 if (EltType == MVT::i8)
7166 return AArch64ISD::DUPLANE8;
7167 if (EltType == MVT::i16 || EltType == MVT::f16)
7168 return AArch64ISD::DUPLANE16;
7169 if (EltType == MVT::i32 || EltType == MVT::f32)
7170 return AArch64ISD::DUPLANE32;
7171 if (EltType == MVT::i64 || EltType == MVT::f64)
7172 return AArch64ISD::DUPLANE64;
7174 llvm_unreachable("Invalid vector element type?");
7177 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7178 SelectionDAG &DAG) const {
7179 SDLoc dl(Op);
7180 EVT VT = Op.getValueType();
7182 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7184 // Convert shuffles that are directly supported on NEON to target-specific
7185 // DAG nodes, instead of keeping them as shuffles and matching them again
7186 // during code selection. This is more efficient and avoids the possibility
7187 // of inconsistencies between legalization and selection.
7188 ArrayRef<int> ShuffleMask = SVN->getMask();
7190 SDValue V1 = Op.getOperand(0);
7191 SDValue V2 = Op.getOperand(1);
7193 if (SVN->isSplat()) {
7194 int Lane = SVN->getSplatIndex();
7195 // If this is undef splat, generate it via "just" vdup, if possible.
7196 if (Lane == -1)
7197 Lane = 0;
7199 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
7200 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
7201 V1.getOperand(0));
7202 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
7203 // constant. If so, we can just reference the lane's definition directly.
7204 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
7205 !isa<ConstantSDNode>(V1.getOperand(Lane)))
7206 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
7208 // Otherwise, duplicate from the lane of the input vector.
7209 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
7211 // Try to eliminate a bitcasted extract subvector before a DUPLANE.
7212 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
7213 // Match: dup (bitcast (extract_subv X, C)), LaneC
7214 if (BitCast.getOpcode() != ISD::BITCAST ||
7215 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
7216 return false;
7218 // The extract index must align in the destination type. That may not
7219 // happen if the bitcast is from narrow to wide type.
7220 SDValue Extract = BitCast.getOperand(0);
7221 unsigned ExtIdx = Extract.getConstantOperandVal(1);
7222 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
7223 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
7224 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
7225 if (ExtIdxInBits % CastedEltBitWidth != 0)
7226 return false;
7228 // Update the lane value by offsetting with the scaled extract index.
7229 LaneC += ExtIdxInBits / CastedEltBitWidth;
7231 // Determine the casted vector type of the wide vector input.
7232 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
7233 // Examples:
7234 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
7235 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
7236 unsigned SrcVecNumElts =
7237 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
7238 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
7239 SrcVecNumElts);
7240 return true;
7242 MVT CastVT;
7243 if (getScaledOffsetDup(V1, Lane, CastVT)) {
7244 V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0));
7245 } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7246 // The lane is incremented by the index of the extract.
7247 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
7248 Lane += V1.getConstantOperandVal(1);
7249 V1 = V1.getOperand(0);
7250 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
7251 // The lane is decremented if we are splatting from the 2nd operand.
7252 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
7253 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
7254 Lane -= Idx * VT.getVectorNumElements() / 2;
7255 V1 = WidenVector(V1.getOperand(Idx), DAG);
7256 } else if (VT.getSizeInBits() == 64) {
7257 // Widen the operand to 128-bit register with undef.
7258 V1 = WidenVector(V1, DAG);
7260 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
7263 if (isREVMask(ShuffleMask, VT, 64))
7264 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
7265 if (isREVMask(ShuffleMask, VT, 32))
7266 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
7267 if (isREVMask(ShuffleMask, VT, 16))
7268 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
7270 bool ReverseEXT = false;
7271 unsigned Imm;
7272 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
7273 if (ReverseEXT)
7274 std::swap(V1, V2);
7275 Imm *= getExtFactor(V1);
7276 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
7277 DAG.getConstant(Imm, dl, MVT::i32));
7278 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
7279 Imm *= getExtFactor(V1);
7280 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
7281 DAG.getConstant(Imm, dl, MVT::i32));
7284 unsigned WhichResult;
7285 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
7286 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7287 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7289 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
7290 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7291 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7293 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
7294 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7295 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
7298 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7299 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
7300 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7302 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7303 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
7304 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7306 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
7307 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
7308 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
7311 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
7312 return Concat;
7314 bool DstIsLeft;
7315 int Anomaly;
7316 int NumInputElements = V1.getValueType().getVectorNumElements();
7317 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
7318 SDValue DstVec = DstIsLeft ? V1 : V2;
7319 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
7321 SDValue SrcVec = V1;
7322 int SrcLane = ShuffleMask[Anomaly];
7323 if (SrcLane >= NumInputElements) {
7324 SrcVec = V2;
7325 SrcLane -= VT.getVectorNumElements();
7327 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7329 EVT ScalarVT = VT.getVectorElementType();
7331 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7332 ScalarVT = MVT::i32;
7334 return DAG.getNode(
7335 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7336 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7337 DstLaneV);
7340 // If the shuffle is not directly supported and it has 4 elements, use
7341 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7342 unsigned NumElts = VT.getVectorNumElements();
7343 if (NumElts == 4) {
7344 unsigned PFIndexes[4];
7345 for (unsigned i = 0; i != 4; ++i) {
7346 if (ShuffleMask[i] < 0)
7347 PFIndexes[i] = 8;
7348 else
7349 PFIndexes[i] = ShuffleMask[i];
7352 // Compute the index in the perfect shuffle table.
7353 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7354 PFIndexes[2] * 9 + PFIndexes[3];
7355 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7356 unsigned Cost = (PFEntry >> 30);
7358 if (Cost <= 4)
7359 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7362 return GenerateTBL(Op, ShuffleMask, DAG);
7365 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
7366 SelectionDAG &DAG) const {
7367 SDLoc dl(Op);
7368 EVT VT = Op.getValueType();
7369 EVT ElemVT = VT.getScalarType();
7371 SDValue SplatVal = Op.getOperand(0);
7373 // Extend input splat value where needed to fit into a GPR (32b or 64b only)
7374 // FPRs don't have this restriction.
7375 switch (ElemVT.getSimpleVT().SimpleTy) {
7376 case MVT::i8:
7377 case MVT::i16:
7378 case MVT::i32:
7379 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
7380 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7381 case MVT::i64:
7382 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7383 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
7384 case MVT::i1: {
7385 // The general case of i1. There isn't any natural way to do this,
7386 // so we use some trickery with whilelo.
7387 // TODO: Add special cases for splat of constant true/false.
7388 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
7389 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
7390 DAG.getValueType(MVT::i1));
7391 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
7392 MVT::i64);
7393 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
7394 DAG.getConstant(0, dl, MVT::i64), SplatVal);
7396 // TODO: we can support float types, but haven't added patterns yet.
7397 case MVT::f16:
7398 case MVT::f32:
7399 case MVT::f64:
7400 default:
7401 report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
7405 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7406 APInt &UndefBits) {
7407 EVT VT = BVN->getValueType(0);
7408 APInt SplatBits, SplatUndef;
7409 unsigned SplatBitSize;
7410 bool HasAnyUndefs;
7411 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7412 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7414 for (unsigned i = 0; i < NumSplats; ++i) {
7415 CnstBits <<= SplatBitSize;
7416 UndefBits <<= SplatBitSize;
7417 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7418 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7421 return true;
7424 return false;
7427 // Try 64-bit splatted SIMD immediate.
7428 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7429 const APInt &Bits) {
7430 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7431 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7432 EVT VT = Op.getValueType();
7433 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7435 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7436 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7438 SDLoc dl(Op);
7439 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7440 DAG.getConstant(Value, dl, MVT::i32));
7441 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7445 return SDValue();
7448 // Try 32-bit splatted SIMD immediate.
7449 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7450 const APInt &Bits,
7451 const SDValue *LHS = nullptr) {
7452 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7453 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7454 EVT VT = Op.getValueType();
7455 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7456 bool isAdvSIMDModImm = false;
7457 uint64_t Shift;
7459 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7460 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7461 Shift = 0;
7463 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7464 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7465 Shift = 8;
7467 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7468 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7469 Shift = 16;
7471 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7472 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7473 Shift = 24;
7476 if (isAdvSIMDModImm) {
7477 SDLoc dl(Op);
7478 SDValue Mov;
7480 if (LHS)
7481 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7482 DAG.getConstant(Value, dl, MVT::i32),
7483 DAG.getConstant(Shift, dl, MVT::i32));
7484 else
7485 Mov = DAG.getNode(NewOp, dl, MovTy,
7486 DAG.getConstant(Value, dl, MVT::i32),
7487 DAG.getConstant(Shift, dl, MVT::i32));
7489 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7493 return SDValue();
7496 // Try 16-bit splatted SIMD immediate.
7497 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7498 const APInt &Bits,
7499 const SDValue *LHS = nullptr) {
7500 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7501 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7502 EVT VT = Op.getValueType();
7503 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7504 bool isAdvSIMDModImm = false;
7505 uint64_t Shift;
7507 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7508 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7509 Shift = 0;
7511 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7512 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7513 Shift = 8;
7516 if (isAdvSIMDModImm) {
7517 SDLoc dl(Op);
7518 SDValue Mov;
7520 if (LHS)
7521 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7522 DAG.getConstant(Value, dl, MVT::i32),
7523 DAG.getConstant(Shift, dl, MVT::i32));
7524 else
7525 Mov = DAG.getNode(NewOp, dl, MovTy,
7526 DAG.getConstant(Value, dl, MVT::i32),
7527 DAG.getConstant(Shift, dl, MVT::i32));
7529 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7533 return SDValue();
7536 // Try 32-bit splatted SIMD immediate with shifted ones.
7537 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7538 SelectionDAG &DAG, const APInt &Bits) {
7539 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7540 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7541 EVT VT = Op.getValueType();
7542 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7543 bool isAdvSIMDModImm = false;
7544 uint64_t Shift;
7546 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7547 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7548 Shift = 264;
7550 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7551 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7552 Shift = 272;
7555 if (isAdvSIMDModImm) {
7556 SDLoc dl(Op);
7557 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7558 DAG.getConstant(Value, dl, MVT::i32),
7559 DAG.getConstant(Shift, dl, MVT::i32));
7560 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7564 return SDValue();
7567 // Try 8-bit splatted SIMD immediate.
7568 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7569 const APInt &Bits) {
7570 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7571 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7572 EVT VT = Op.getValueType();
7573 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7575 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7576 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7578 SDLoc dl(Op);
7579 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7580 DAG.getConstant(Value, dl, MVT::i32));
7581 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7585 return SDValue();
7588 // Try FP splatted SIMD immediate.
7589 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7590 const APInt &Bits) {
7591 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7592 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7593 EVT VT = Op.getValueType();
7594 bool isWide = (VT.getSizeInBits() == 128);
7595 MVT MovTy;
7596 bool isAdvSIMDModImm = false;
7598 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7599 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7600 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7602 else if (isWide &&
7603 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7604 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7605 MovTy = MVT::v2f64;
7608 if (isAdvSIMDModImm) {
7609 SDLoc dl(Op);
7610 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7611 DAG.getConstant(Value, dl, MVT::i32));
7612 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7616 return SDValue();
7619 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7620 // consists of only the same constant int value, returned in reference arg
7621 // ConstVal
7622 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7623 uint64_t &ConstVal) {
7624 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7625 if (!Bvec)
7626 return false;
7627 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7628 if (!FirstElt)
7629 return false;
7630 EVT VT = Bvec->getValueType(0);
7631 unsigned NumElts = VT.getVectorNumElements();
7632 for (unsigned i = 1; i < NumElts; ++i)
7633 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7634 return false;
7635 ConstVal = FirstElt->getZExtValue();
7636 return true;
7639 static unsigned getIntrinsicID(const SDNode *N) {
7640 unsigned Opcode = N->getOpcode();
7641 switch (Opcode) {
7642 default:
7643 return Intrinsic::not_intrinsic;
7644 case ISD::INTRINSIC_WO_CHAIN: {
7645 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7646 if (IID < Intrinsic::num_intrinsics)
7647 return IID;
7648 return Intrinsic::not_intrinsic;
7653 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7654 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7655 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7656 // Also, logical shift right -> sri, with the same structure.
7657 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7658 EVT VT = N->getValueType(0);
7660 if (!VT.isVector())
7661 return SDValue();
7663 SDLoc DL(N);
7665 // Is the first op an AND?
7666 const SDValue And = N->getOperand(0);
7667 if (And.getOpcode() != ISD::AND)
7668 return SDValue();
7670 // Is the second op an shl or lshr?
7671 SDValue Shift = N->getOperand(1);
7672 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7673 // or AArch64ISD::VLSHR vector, #shift
7674 unsigned ShiftOpc = Shift.getOpcode();
7675 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7676 return SDValue();
7677 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7679 // Is the shift amount constant?
7680 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7681 if (!C2node)
7682 return SDValue();
7684 // Is the and mask vector all constant?
7685 uint64_t C1;
7686 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7687 return SDValue();
7689 // Is C1 == ~C2, taking into account how much one can shift elements of a
7690 // particular size?
7691 uint64_t C2 = C2node->getZExtValue();
7692 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7693 if (C2 > ElemSizeInBits)
7694 return SDValue();
7695 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7696 if ((C1 & ElemMask) != (~C2 & ElemMask))
7697 return SDValue();
7699 SDValue X = And.getOperand(0);
7700 SDValue Y = Shift.getOperand(0);
7702 unsigned Intrin =
7703 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7704 SDValue ResultSLI =
7705 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7706 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7707 Shift.getOperand(1));
7709 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7710 LLVM_DEBUG(N->dump(&DAG));
7711 LLVM_DEBUG(dbgs() << "into: \n");
7712 LLVM_DEBUG(ResultSLI->dump(&DAG));
7714 ++NumShiftInserts;
7715 return ResultSLI;
7718 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7719 SelectionDAG &DAG) const {
7720 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7721 if (EnableAArch64SlrGeneration) {
7722 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7723 return Res;
7726 EVT VT = Op.getValueType();
7728 SDValue LHS = Op.getOperand(0);
7729 BuildVectorSDNode *BVN =
7730 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7731 if (!BVN) {
7732 // OR commutes, so try swapping the operands.
7733 LHS = Op.getOperand(1);
7734 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7736 if (!BVN)
7737 return Op;
7739 APInt DefBits(VT.getSizeInBits(), 0);
7740 APInt UndefBits(VT.getSizeInBits(), 0);
7741 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7742 SDValue NewOp;
7744 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7745 DefBits, &LHS)) ||
7746 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7747 DefBits, &LHS)))
7748 return NewOp;
7750 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7751 UndefBits, &LHS)) ||
7752 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7753 UndefBits, &LHS)))
7754 return NewOp;
7757 // We can always fall back to a non-immediate OR.
7758 return Op;
7761 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7762 // be truncated to fit element width.
7763 static SDValue NormalizeBuildVector(SDValue Op,
7764 SelectionDAG &DAG) {
7765 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7766 SDLoc dl(Op);
7767 EVT VT = Op.getValueType();
7768 EVT EltTy= VT.getVectorElementType();
7770 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7771 return Op;
7773 SmallVector<SDValue, 16> Ops;
7774 for (SDValue Lane : Op->ops()) {
7775 // For integer vectors, type legalization would have promoted the
7776 // operands already. Otherwise, if Op is a floating-point splat
7777 // (with operands cast to integers), then the only possibilities
7778 // are constants and UNDEFs.
7779 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7780 APInt LowBits(EltTy.getSizeInBits(),
7781 CstLane->getZExtValue());
7782 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7783 } else if (Lane.getNode()->isUndef()) {
7784 Lane = DAG.getUNDEF(MVT::i32);
7785 } else {
7786 assert(Lane.getValueType() == MVT::i32 &&
7787 "Unexpected BUILD_VECTOR operand type");
7789 Ops.push_back(Lane);
7791 return DAG.getBuildVector(VT, dl, Ops);
7794 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7795 EVT VT = Op.getValueType();
7797 APInt DefBits(VT.getSizeInBits(), 0);
7798 APInt UndefBits(VT.getSizeInBits(), 0);
7799 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7800 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7801 SDValue NewOp;
7802 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7803 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7804 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7805 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7806 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7807 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7808 return NewOp;
7810 DefBits = ~DefBits;
7811 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7812 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7813 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7814 return NewOp;
7816 DefBits = UndefBits;
7817 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7818 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7819 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7820 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7821 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7822 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7823 return NewOp;
7825 DefBits = ~UndefBits;
7826 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7827 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7828 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7829 return NewOp;
7832 return SDValue();
7835 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7836 SelectionDAG &DAG) const {
7837 EVT VT = Op.getValueType();
7839 // Try to build a simple constant vector.
7840 Op = NormalizeBuildVector(Op, DAG);
7841 if (VT.isInteger()) {
7842 // Certain vector constants, used to express things like logical NOT and
7843 // arithmetic NEG, are passed through unmodified. This allows special
7844 // patterns for these operations to match, which will lower these constants
7845 // to whatever is proven necessary.
7846 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7847 if (BVN->isConstant())
7848 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7849 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7850 APInt Val(BitSize,
7851 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7852 if (Val.isNullValue() || Val.isAllOnesValue())
7853 return Op;
7857 if (SDValue V = ConstantBuildVector(Op, DAG))
7858 return V;
7860 // Scan through the operands to find some interesting properties we can
7861 // exploit:
7862 // 1) If only one value is used, we can use a DUP, or
7863 // 2) if only the low element is not undef, we can just insert that, or
7864 // 3) if only one constant value is used (w/ some non-constant lanes),
7865 // we can splat the constant value into the whole vector then fill
7866 // in the non-constant lanes.
7867 // 4) FIXME: If different constant values are used, but we can intelligently
7868 // select the values we'll be overwriting for the non-constant
7869 // lanes such that we can directly materialize the vector
7870 // some other way (MOVI, e.g.), we can be sneaky.
7871 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7872 SDLoc dl(Op);
7873 unsigned NumElts = VT.getVectorNumElements();
7874 bool isOnlyLowElement = true;
7875 bool usesOnlyOneValue = true;
7876 bool usesOnlyOneConstantValue = true;
7877 bool isConstant = true;
7878 bool AllLanesExtractElt = true;
7879 unsigned NumConstantLanes = 0;
7880 SDValue Value;
7881 SDValue ConstantValue;
7882 for (unsigned i = 0; i < NumElts; ++i) {
7883 SDValue V = Op.getOperand(i);
7884 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7885 AllLanesExtractElt = false;
7886 if (V.isUndef())
7887 continue;
7888 if (i > 0)
7889 isOnlyLowElement = false;
7890 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7891 isConstant = false;
7893 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7894 ++NumConstantLanes;
7895 if (!ConstantValue.getNode())
7896 ConstantValue = V;
7897 else if (ConstantValue != V)
7898 usesOnlyOneConstantValue = false;
7901 if (!Value.getNode())
7902 Value = V;
7903 else if (V != Value)
7904 usesOnlyOneValue = false;
7907 if (!Value.getNode()) {
7908 LLVM_DEBUG(
7909 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7910 return DAG.getUNDEF(VT);
7913 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7914 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7915 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7916 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7917 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7918 "SCALAR_TO_VECTOR node\n");
7919 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7922 if (AllLanesExtractElt) {
7923 SDNode *Vector = nullptr;
7924 bool Even = false;
7925 bool Odd = false;
7926 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7927 // the Odd pattern <1,3,5,...>.
7928 for (unsigned i = 0; i < NumElts; ++i) {
7929 SDValue V = Op.getOperand(i);
7930 const SDNode *N = V.getNode();
7931 if (!isa<ConstantSDNode>(N->getOperand(1)))
7932 break;
7933 SDValue N0 = N->getOperand(0);
7935 // All elements are extracted from the same vector.
7936 if (!Vector) {
7937 Vector = N0.getNode();
7938 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7939 // BUILD_VECTOR.
7940 if (VT.getVectorElementType() !=
7941 N0.getValueType().getVectorElementType())
7942 break;
7943 } else if (Vector != N0.getNode()) {
7944 Odd = false;
7945 Even = false;
7946 break;
7949 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7950 // indices <1,3,5,...>.
7951 uint64_t Val = N->getConstantOperandVal(1);
7952 if (Val == 2 * i) {
7953 Even = true;
7954 continue;
7956 if (Val - 1 == 2 * i) {
7957 Odd = true;
7958 continue;
7961 // Something does not match: abort.
7962 Odd = false;
7963 Even = false;
7964 break;
7966 if (Even || Odd) {
7967 SDValue LHS =
7968 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7969 DAG.getConstant(0, dl, MVT::i64));
7970 SDValue RHS =
7971 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7972 DAG.getConstant(NumElts, dl, MVT::i64));
7974 if (Even && !Odd)
7975 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7976 RHS);
7977 if (Odd && !Even)
7978 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7979 RHS);
7983 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7984 // i32 and try again.
7985 if (usesOnlyOneValue) {
7986 if (!isConstant) {
7987 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7988 Value.getValueType() != VT) {
7989 LLVM_DEBUG(
7990 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7991 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7994 // This is actually a DUPLANExx operation, which keeps everything vectory.
7996 SDValue Lane = Value.getOperand(1);
7997 Value = Value.getOperand(0);
7998 if (Value.getValueSizeInBits() == 64) {
7999 LLVM_DEBUG(
8000 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
8001 "widening it\n");
8002 Value = WidenVector(Value, DAG);
8005 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
8006 return DAG.getNode(Opcode, dl, VT, Value, Lane);
8009 if (VT.getVectorElementType().isFloatingPoint()) {
8010 SmallVector<SDValue, 8> Ops;
8011 EVT EltTy = VT.getVectorElementType();
8012 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
8013 "Unsupported floating-point vector type");
8014 LLVM_DEBUG(
8015 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
8016 "BITCASTS, and try again\n");
8017 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
8018 for (unsigned i = 0; i < NumElts; ++i)
8019 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
8020 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
8021 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
8022 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
8023 Val.dump(););
8024 Val = LowerBUILD_VECTOR(Val, DAG);
8025 if (Val.getNode())
8026 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8030 // If there was only one constant value used and for more than one lane,
8031 // start by splatting that value, then replace the non-constant lanes. This
8032 // is better than the default, which will perform a separate initialization
8033 // for each lane.
8034 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
8035 // Firstly, try to materialize the splat constant.
8036 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
8037 Val = ConstantBuildVector(Vec, DAG);
8038 if (!Val) {
8039 // Otherwise, materialize the constant and splat it.
8040 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
8041 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
8044 // Now insert the non-constant lanes.
8045 for (unsigned i = 0; i < NumElts; ++i) {
8046 SDValue V = Op.getOperand(i);
8047 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8048 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
8049 // Note that type legalization likely mucked about with the VT of the
8050 // source operand, so we may have to convert it here before inserting.
8051 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
8053 return Val;
8056 // This will generate a load from the constant pool.
8057 if (isConstant) {
8058 LLVM_DEBUG(
8059 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
8060 "expansion\n");
8061 return SDValue();
8064 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
8065 if (NumElts >= 4) {
8066 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
8067 return shuffle;
8070 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
8071 // know the default expansion would otherwise fall back on something even
8072 // worse. For a vector with one or two non-undef values, that's
8073 // scalar_to_vector for the elements followed by a shuffle (provided the
8074 // shuffle is valid for the target) and materialization element by element
8075 // on the stack followed by a load for everything else.
8076 if (!isConstant && !usesOnlyOneValue) {
8077 LLVM_DEBUG(
8078 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
8079 "of INSERT_VECTOR_ELT\n");
8081 SDValue Vec = DAG.getUNDEF(VT);
8082 SDValue Op0 = Op.getOperand(0);
8083 unsigned i = 0;
8085 // Use SCALAR_TO_VECTOR for lane zero to
8086 // a) Avoid a RMW dependency on the full vector register, and
8087 // b) Allow the register coalescer to fold away the copy if the
8088 // value is already in an S or D register, and we're forced to emit an
8089 // INSERT_SUBREG that we can't fold anywhere.
8091 // We also allow types like i8 and i16 which are illegal scalar but legal
8092 // vector element types. After type-legalization the inserted value is
8093 // extended (i32) and it is safe to cast them to the vector type by ignoring
8094 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
8095 if (!Op0.isUndef()) {
8096 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
8097 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
8098 ++i;
8100 LLVM_DEBUG(if (i < NumElts) dbgs()
8101 << "Creating nodes for the other vector elements:\n";);
8102 for (; i < NumElts; ++i) {
8103 SDValue V = Op.getOperand(i);
8104 if (V.isUndef())
8105 continue;
8106 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
8107 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
8109 return Vec;
8112 LLVM_DEBUG(
8113 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
8114 "better alternative\n");
8115 return SDValue();
8118 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8119 SelectionDAG &DAG) const {
8120 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
8122 // Check for non-constant or out of range lane.
8123 EVT VT = Op.getOperand(0).getValueType();
8124 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8125 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8126 return SDValue();
8129 // Insertion/extraction are legal for V128 types.
8130 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8131 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8132 VT == MVT::v8f16)
8133 return Op;
8135 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8136 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8137 return SDValue();
8139 // For V64 types, we perform insertion by expanding the value
8140 // to a V128 type and perform the insertion on that.
8141 SDLoc DL(Op);
8142 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8143 EVT WideTy = WideVec.getValueType();
8145 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
8146 Op.getOperand(1), Op.getOperand(2));
8147 // Re-narrow the resultant vector.
8148 return NarrowVector(Node, DAG);
8151 SDValue
8152 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8153 SelectionDAG &DAG) const {
8154 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
8156 // Check for non-constant or out of range lane.
8157 EVT VT = Op.getOperand(0).getValueType();
8158 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8159 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
8160 return SDValue();
8163 // Insertion/extraction are legal for V128 types.
8164 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
8165 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
8166 VT == MVT::v8f16)
8167 return Op;
8169 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
8170 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
8171 return SDValue();
8173 // For V64 types, we perform extraction by expanding the value
8174 // to a V128 type and perform the extraction on that.
8175 SDLoc DL(Op);
8176 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
8177 EVT WideTy = WideVec.getValueType();
8179 EVT ExtrTy = WideTy.getVectorElementType();
8180 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
8181 ExtrTy = MVT::i32;
8183 // For extractions, we just return the result directly.
8184 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
8185 Op.getOperand(1));
8188 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
8189 SelectionDAG &DAG) const {
8190 EVT VT = Op.getOperand(0).getValueType();
8191 SDLoc dl(Op);
8192 // Just in case...
8193 if (!VT.isVector())
8194 return SDValue();
8196 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8197 if (!Cst)
8198 return SDValue();
8199 unsigned Val = Cst->getZExtValue();
8201 unsigned Size = Op.getValueSizeInBits();
8203 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
8204 if (Val == 0)
8205 return Op;
8207 // If this is extracting the upper 64-bits of a 128-bit vector, we match
8208 // that directly.
8209 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
8210 return Op;
8212 return SDValue();
8215 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
8216 if (VT.getVectorNumElements() == 4 &&
8217 (VT.is128BitVector() || VT.is64BitVector())) {
8218 unsigned PFIndexes[4];
8219 for (unsigned i = 0; i != 4; ++i) {
8220 if (M[i] < 0)
8221 PFIndexes[i] = 8;
8222 else
8223 PFIndexes[i] = M[i];
8226 // Compute the index in the perfect shuffle table.
8227 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
8228 PFIndexes[2] * 9 + PFIndexes[3];
8229 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8230 unsigned Cost = (PFEntry >> 30);
8232 if (Cost <= 4)
8233 return true;
8236 bool DummyBool;
8237 int DummyInt;
8238 unsigned DummyUnsigned;
8240 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
8241 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
8242 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
8243 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
8244 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
8245 isZIPMask(M, VT, DummyUnsigned) ||
8246 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
8247 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
8248 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
8249 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
8250 isConcatMask(M, VT, VT.getSizeInBits() == 128));
8253 /// getVShiftImm - Check if this is a valid build_vector for the immediate
8254 /// operand of a vector shift operation, where all the elements of the
8255 /// build_vector must have the same constant integer value.
8256 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8257 // Ignore bit_converts.
8258 while (Op.getOpcode() == ISD::BITCAST)
8259 Op = Op.getOperand(0);
8260 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8261 APInt SplatBits, SplatUndef;
8262 unsigned SplatBitSize;
8263 bool HasAnyUndefs;
8264 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8265 HasAnyUndefs, ElementBits) ||
8266 SplatBitSize > ElementBits)
8267 return false;
8268 Cnt = SplatBits.getSExtValue();
8269 return true;
8272 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8273 /// operand of a vector shift left operation. That value must be in the range:
8274 /// 0 <= Value < ElementBits for a left shift; or
8275 /// 0 <= Value <= ElementBits for a long left shift.
8276 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8277 assert(VT.isVector() && "vector shift count is not a vector type");
8278 int64_t ElementBits = VT.getScalarSizeInBits();
8279 if (!getVShiftImm(Op, ElementBits, Cnt))
8280 return false;
8281 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
8284 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8285 /// operand of a vector shift right operation. The value must be in the range:
8286 /// 1 <= Value <= ElementBits for a right shift; or
8287 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
8288 assert(VT.isVector() && "vector shift count is not a vector type");
8289 int64_t ElementBits = VT.getScalarSizeInBits();
8290 if (!getVShiftImm(Op, ElementBits, Cnt))
8291 return false;
8292 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
8295 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
8296 SelectionDAG &DAG) const {
8297 EVT VT = Op.getValueType();
8298 SDLoc DL(Op);
8299 int64_t Cnt;
8301 if (!Op.getOperand(1).getValueType().isVector())
8302 return Op;
8303 unsigned EltSize = VT.getScalarSizeInBits();
8305 switch (Op.getOpcode()) {
8306 default:
8307 llvm_unreachable("unexpected shift opcode");
8309 case ISD::SHL:
8310 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
8311 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
8312 DAG.getConstant(Cnt, DL, MVT::i32));
8313 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8314 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
8315 MVT::i32),
8316 Op.getOperand(0), Op.getOperand(1));
8317 case ISD::SRA:
8318 case ISD::SRL:
8319 // Right shift immediate
8320 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
8321 unsigned Opc =
8322 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
8323 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
8324 DAG.getConstant(Cnt, DL, MVT::i32));
8327 // Right shift register. Note, there is not a shift right register
8328 // instruction, but the shift left register instruction takes a signed
8329 // value, where negative numbers specify a right shift.
8330 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
8331 : Intrinsic::aarch64_neon_ushl;
8332 // negate the shift amount
8333 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
8334 SDValue NegShiftLeft =
8335 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8336 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
8337 NegShift);
8338 return NegShiftLeft;
8341 return SDValue();
8344 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
8345 AArch64CC::CondCode CC, bool NoNans, EVT VT,
8346 const SDLoc &dl, SelectionDAG &DAG) {
8347 EVT SrcVT = LHS.getValueType();
8348 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
8349 "function only supposed to emit natural comparisons");
8351 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
8352 APInt CnstBits(VT.getSizeInBits(), 0);
8353 APInt UndefBits(VT.getSizeInBits(), 0);
8354 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
8355 bool IsZero = IsCnst && (CnstBits == 0);
8357 if (SrcVT.getVectorElementType().isFloatingPoint()) {
8358 switch (CC) {
8359 default:
8360 return SDValue();
8361 case AArch64CC::NE: {
8362 SDValue Fcmeq;
8363 if (IsZero)
8364 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8365 else
8366 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8367 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8369 case AArch64CC::EQ:
8370 if (IsZero)
8371 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8372 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8373 case AArch64CC::GE:
8374 if (IsZero)
8375 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8376 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8377 case AArch64CC::GT:
8378 if (IsZero)
8379 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8380 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8381 case AArch64CC::LS:
8382 if (IsZero)
8383 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8384 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8385 case AArch64CC::LT:
8386 if (!NoNans)
8387 return SDValue();
8388 // If we ignore NaNs then we can use to the MI implementation.
8389 LLVM_FALLTHROUGH;
8390 case AArch64CC::MI:
8391 if (IsZero)
8392 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8393 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8397 switch (CC) {
8398 default:
8399 return SDValue();
8400 case AArch64CC::NE: {
8401 SDValue Cmeq;
8402 if (IsZero)
8403 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8404 else
8405 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8406 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8408 case AArch64CC::EQ:
8409 if (IsZero)
8410 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8411 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8412 case AArch64CC::GE:
8413 if (IsZero)
8414 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8415 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8416 case AArch64CC::GT:
8417 if (IsZero)
8418 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8419 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8420 case AArch64CC::LE:
8421 if (IsZero)
8422 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8423 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8424 case AArch64CC::LS:
8425 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8426 case AArch64CC::LO:
8427 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8428 case AArch64CC::LT:
8429 if (IsZero)
8430 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8431 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8432 case AArch64CC::HI:
8433 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8434 case AArch64CC::HS:
8435 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8439 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8440 SelectionDAG &DAG) const {
8441 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8442 SDValue LHS = Op.getOperand(0);
8443 SDValue RHS = Op.getOperand(1);
8444 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8445 SDLoc dl(Op);
8447 if (LHS.getValueType().getVectorElementType().isInteger()) {
8448 assert(LHS.getValueType() == RHS.getValueType());
8449 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8450 SDValue Cmp =
8451 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8452 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8455 const bool FullFP16 =
8456 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8458 // Make v4f16 (only) fcmp operations utilise vector instructions
8459 // v8f16 support will be a litle more complicated
8460 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8461 if (LHS.getValueType().getVectorNumElements() == 4) {
8462 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8463 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8464 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8465 DAG.ReplaceAllUsesWith(Op, NewSetcc);
8466 CmpVT = MVT::v4i32;
8467 } else
8468 return SDValue();
8471 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8472 LHS.getValueType().getVectorElementType() != MVT::f128);
8474 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8475 // clean. Some of them require two branches to implement.
8476 AArch64CC::CondCode CC1, CC2;
8477 bool ShouldInvert;
8478 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8480 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8481 SDValue Cmp =
8482 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8483 if (!Cmp.getNode())
8484 return SDValue();
8486 if (CC2 != AArch64CC::AL) {
8487 SDValue Cmp2 =
8488 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8489 if (!Cmp2.getNode())
8490 return SDValue();
8492 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8495 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8497 if (ShouldInvert)
8498 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8500 return Cmp;
8503 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8504 SelectionDAG &DAG) {
8505 SDValue VecOp = ScalarOp.getOperand(0);
8506 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8507 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8508 DAG.getConstant(0, DL, MVT::i64));
8511 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8512 SelectionDAG &DAG) const {
8513 SDLoc dl(Op);
8514 switch (Op.getOpcode()) {
8515 case ISD::VECREDUCE_ADD:
8516 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8517 case ISD::VECREDUCE_SMAX:
8518 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8519 case ISD::VECREDUCE_SMIN:
8520 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8521 case ISD::VECREDUCE_UMAX:
8522 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8523 case ISD::VECREDUCE_UMIN:
8524 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8525 case ISD::VECREDUCE_FMAX: {
8526 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8527 return DAG.getNode(
8528 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8529 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8530 Op.getOperand(0));
8532 case ISD::VECREDUCE_FMIN: {
8533 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8534 return DAG.getNode(
8535 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8536 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8537 Op.getOperand(0));
8539 default:
8540 llvm_unreachable("Unhandled reduction");
8544 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8545 SelectionDAG &DAG) const {
8546 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8547 if (!Subtarget.hasLSE())
8548 return SDValue();
8550 // LSE has an atomic load-add instruction, but not a load-sub.
8551 SDLoc dl(Op);
8552 MVT VT = Op.getSimpleValueType();
8553 SDValue RHS = Op.getOperand(2);
8554 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8555 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8556 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8557 Op.getOperand(0), Op.getOperand(1), RHS,
8558 AN->getMemOperand());
8561 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8562 SelectionDAG &DAG) const {
8563 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8564 if (!Subtarget.hasLSE())
8565 return SDValue();
8567 // LSE has an atomic load-clear instruction, but not a load-and.
8568 SDLoc dl(Op);
8569 MVT VT = Op.getSimpleValueType();
8570 SDValue RHS = Op.getOperand(2);
8571 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8572 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8573 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8574 Op.getOperand(0), Op.getOperand(1), RHS,
8575 AN->getMemOperand());
8578 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8579 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8580 SDLoc dl(Op);
8581 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8582 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8584 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8585 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8586 if (Subtarget->hasCustomCallingConv())
8587 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8589 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8590 DAG.getConstant(4, dl, MVT::i64));
8591 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8592 Chain =
8593 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8594 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8595 DAG.getRegisterMask(Mask), Chain.getValue(1));
8596 // To match the actual intent better, we should read the output from X15 here
8597 // again (instead of potentially spilling it to the stack), but rereading Size
8598 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8599 // here.
8601 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8602 DAG.getConstant(4, dl, MVT::i64));
8603 return Chain;
8606 SDValue
8607 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8608 SelectionDAG &DAG) const {
8609 assert(Subtarget->isTargetWindows() &&
8610 "Only Windows alloca probing supported");
8611 SDLoc dl(Op);
8612 // Get the inputs.
8613 SDNode *Node = Op.getNode();
8614 SDValue Chain = Op.getOperand(0);
8615 SDValue Size = Op.getOperand(1);
8616 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8617 EVT VT = Node->getValueType(0);
8619 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8620 "no-stack-arg-probe")) {
8621 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8622 Chain = SP.getValue(1);
8623 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8624 if (Align)
8625 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8626 DAG.getConstant(-(uint64_t)Align, dl, VT));
8627 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8628 SDValue Ops[2] = {SP, Chain};
8629 return DAG.getMergeValues(Ops, dl);
8632 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8634 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8636 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8637 Chain = SP.getValue(1);
8638 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8639 if (Align)
8640 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8641 DAG.getConstant(-(uint64_t)Align, dl, VT));
8642 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8644 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8645 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8647 SDValue Ops[2] = {SP, Chain};
8648 return DAG.getMergeValues(Ops, dl);
8651 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
8652 SelectionDAG &DAG) const {
8653 EVT VT = Op.getValueType();
8654 assert(VT != MVT::i64 && "Expected illegal VSCALE node");
8656 SDLoc DL(Op);
8657 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
8658 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
8659 DL, VT);
8662 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8663 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8664 /// specified in the intrinsic calls.
8665 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8666 const CallInst &I,
8667 MachineFunction &MF,
8668 unsigned Intrinsic) const {
8669 auto &DL = I.getModule()->getDataLayout();
8670 switch (Intrinsic) {
8671 case Intrinsic::aarch64_neon_ld2:
8672 case Intrinsic::aarch64_neon_ld3:
8673 case Intrinsic::aarch64_neon_ld4:
8674 case Intrinsic::aarch64_neon_ld1x2:
8675 case Intrinsic::aarch64_neon_ld1x3:
8676 case Intrinsic::aarch64_neon_ld1x4:
8677 case Intrinsic::aarch64_neon_ld2lane:
8678 case Intrinsic::aarch64_neon_ld3lane:
8679 case Intrinsic::aarch64_neon_ld4lane:
8680 case Intrinsic::aarch64_neon_ld2r:
8681 case Intrinsic::aarch64_neon_ld3r:
8682 case Intrinsic::aarch64_neon_ld4r: {
8683 Info.opc = ISD::INTRINSIC_W_CHAIN;
8684 // Conservatively set memVT to the entire set of vectors loaded.
8685 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8686 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8687 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8688 Info.offset = 0;
8689 Info.align.reset();
8690 // volatile loads with NEON intrinsics not supported
8691 Info.flags = MachineMemOperand::MOLoad;
8692 return true;
8694 case Intrinsic::aarch64_neon_st2:
8695 case Intrinsic::aarch64_neon_st3:
8696 case Intrinsic::aarch64_neon_st4:
8697 case Intrinsic::aarch64_neon_st1x2:
8698 case Intrinsic::aarch64_neon_st1x3:
8699 case Intrinsic::aarch64_neon_st1x4:
8700 case Intrinsic::aarch64_neon_st2lane:
8701 case Intrinsic::aarch64_neon_st3lane:
8702 case Intrinsic::aarch64_neon_st4lane: {
8703 Info.opc = ISD::INTRINSIC_VOID;
8704 // Conservatively set memVT to the entire set of vectors stored.
8705 unsigned NumElts = 0;
8706 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8707 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8708 if (!ArgTy->isVectorTy())
8709 break;
8710 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8712 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8713 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8714 Info.offset = 0;
8715 Info.align.reset();
8716 // volatile stores with NEON intrinsics not supported
8717 Info.flags = MachineMemOperand::MOStore;
8718 return true;
8720 case Intrinsic::aarch64_ldaxr:
8721 case Intrinsic::aarch64_ldxr: {
8722 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8723 Info.opc = ISD::INTRINSIC_W_CHAIN;
8724 Info.memVT = MVT::getVT(PtrTy->getElementType());
8725 Info.ptrVal = I.getArgOperand(0);
8726 Info.offset = 0;
8727 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8728 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8729 return true;
8731 case Intrinsic::aarch64_stlxr:
8732 case Intrinsic::aarch64_stxr: {
8733 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8734 Info.opc = ISD::INTRINSIC_W_CHAIN;
8735 Info.memVT = MVT::getVT(PtrTy->getElementType());
8736 Info.ptrVal = I.getArgOperand(1);
8737 Info.offset = 0;
8738 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8739 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8740 return true;
8742 case Intrinsic::aarch64_ldaxp:
8743 case Intrinsic::aarch64_ldxp:
8744 Info.opc = ISD::INTRINSIC_W_CHAIN;
8745 Info.memVT = MVT::i128;
8746 Info.ptrVal = I.getArgOperand(0);
8747 Info.offset = 0;
8748 Info.align = Align(16);
8749 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8750 return true;
8751 case Intrinsic::aarch64_stlxp:
8752 case Intrinsic::aarch64_stxp:
8753 Info.opc = ISD::INTRINSIC_W_CHAIN;
8754 Info.memVT = MVT::i128;
8755 Info.ptrVal = I.getArgOperand(2);
8756 Info.offset = 0;
8757 Info.align = Align(16);
8758 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8759 return true;
8760 case Intrinsic::aarch64_sve_ldnt1: {
8761 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8762 Info.opc = ISD::INTRINSIC_W_CHAIN;
8763 Info.memVT = MVT::getVT(PtrTy->getElementType());
8764 Info.ptrVal = I.getArgOperand(1);
8765 Info.offset = 0;
8766 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8767 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
8768 return true;
8770 case Intrinsic::aarch64_sve_stnt1: {
8771 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
8772 Info.opc = ISD::INTRINSIC_W_CHAIN;
8773 Info.memVT = MVT::getVT(PtrTy->getElementType());
8774 Info.ptrVal = I.getArgOperand(2);
8775 Info.offset = 0;
8776 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8777 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
8778 return true;
8780 default:
8781 break;
8784 return false;
8787 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8788 ISD::LoadExtType ExtTy,
8789 EVT NewVT) const {
8790 // TODO: This may be worth removing. Check regression tests for diffs.
8791 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8792 return false;
8794 // If we're reducing the load width in order to avoid having to use an extra
8795 // instruction to do extension then it's probably a good idea.
8796 if (ExtTy != ISD::NON_EXTLOAD)
8797 return true;
8798 // Don't reduce load width if it would prevent us from combining a shift into
8799 // the offset.
8800 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8801 assert(Mem);
8802 const SDValue &Base = Mem->getBasePtr();
8803 if (Base.getOpcode() == ISD::ADD &&
8804 Base.getOperand(1).getOpcode() == ISD::SHL &&
8805 Base.getOperand(1).hasOneUse() &&
8806 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8807 // The shift can be combined if it matches the size of the value being
8808 // loaded (and so reducing the width would make it not match).
8809 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8810 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8811 if (ShiftAmount == Log2_32(LoadBytes))
8812 return false;
8814 // We have no reason to disallow reducing the load width, so allow it.
8815 return true;
8818 // Truncations from 64-bit GPR to 32-bit GPR is free.
8819 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8820 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8821 return false;
8822 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8823 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8824 return NumBits1 > NumBits2;
8826 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8827 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8828 return false;
8829 unsigned NumBits1 = VT1.getSizeInBits();
8830 unsigned NumBits2 = VT2.getSizeInBits();
8831 return NumBits1 > NumBits2;
8834 /// Check if it is profitable to hoist instruction in then/else to if.
8835 /// Not profitable if I and it's user can form a FMA instruction
8836 /// because we prefer FMSUB/FMADD.
8837 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8838 if (I->getOpcode() != Instruction::FMul)
8839 return true;
8841 if (!I->hasOneUse())
8842 return true;
8844 Instruction *User = I->user_back();
8846 if (User &&
8847 !(User->getOpcode() == Instruction::FSub ||
8848 User->getOpcode() == Instruction::FAdd))
8849 return true;
8851 const TargetOptions &Options = getTargetMachine().Options;
8852 const Function *F = I->getFunction();
8853 const DataLayout &DL = F->getParent()->getDataLayout();
8854 Type *Ty = User->getOperand(0)->getType();
8856 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
8857 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
8858 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8859 Options.UnsafeFPMath));
8862 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8863 // 64-bit GPR.
8864 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8865 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8866 return false;
8867 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8868 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8869 return NumBits1 == 32 && NumBits2 == 64;
8871 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8872 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8873 return false;
8874 unsigned NumBits1 = VT1.getSizeInBits();
8875 unsigned NumBits2 = VT2.getSizeInBits();
8876 return NumBits1 == 32 && NumBits2 == 64;
8879 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8880 EVT VT1 = Val.getValueType();
8881 if (isZExtFree(VT1, VT2)) {
8882 return true;
8885 if (Val.getOpcode() != ISD::LOAD)
8886 return false;
8888 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8889 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8890 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8891 VT1.getSizeInBits() <= 32);
8894 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8895 if (isa<FPExtInst>(Ext))
8896 return false;
8898 // Vector types are not free.
8899 if (Ext->getType()->isVectorTy())
8900 return false;
8902 for (const Use &U : Ext->uses()) {
8903 // The extension is free if we can fold it with a left shift in an
8904 // addressing mode or an arithmetic operation: add, sub, and cmp.
8906 // Is there a shift?
8907 const Instruction *Instr = cast<Instruction>(U.getUser());
8909 // Is this a constant shift?
8910 switch (Instr->getOpcode()) {
8911 case Instruction::Shl:
8912 if (!isa<ConstantInt>(Instr->getOperand(1)))
8913 return false;
8914 break;
8915 case Instruction::GetElementPtr: {
8916 gep_type_iterator GTI = gep_type_begin(Instr);
8917 auto &DL = Ext->getModule()->getDataLayout();
8918 std::advance(GTI, U.getOperandNo()-1);
8919 Type *IdxTy = GTI.getIndexedType();
8920 // This extension will end up with a shift because of the scaling factor.
8921 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8922 // Get the shift amount based on the scaling factor:
8923 // log2(sizeof(IdxTy)) - log2(8).
8924 uint64_t ShiftAmt =
8925 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
8926 // Is the constant foldable in the shift of the addressing mode?
8927 // I.e., shift amount is between 1 and 4 inclusive.
8928 if (ShiftAmt == 0 || ShiftAmt > 4)
8929 return false;
8930 break;
8932 case Instruction::Trunc:
8933 // Check if this is a noop.
8934 // trunc(sext ty1 to ty2) to ty1.
8935 if (Instr->getType() == Ext->getOperand(0)->getType())
8936 continue;
8937 LLVM_FALLTHROUGH;
8938 default:
8939 return false;
8942 // At this point we can use the bfm family, so this extension is free
8943 // for that use.
8945 return true;
8948 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8949 /// or upper half of the vector elements.
8950 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8951 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8952 auto *FullVT = cast<VectorType>(FullV->getType());
8953 auto *HalfVT = cast<VectorType>(HalfV->getType());
8954 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8957 auto extractHalf = [](Value *FullV, Value *HalfV) {
8958 auto *FullVT = cast<VectorType>(FullV->getType());
8959 auto *HalfVT = cast<VectorType>(HalfV->getType());
8960 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8963 Constant *M1, *M2;
8964 Value *S1Op1, *S2Op1;
8965 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8966 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8967 return false;
8969 // Check that the operands are half as wide as the result and we extract
8970 // half of the elements of the input vectors.
8971 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8972 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8973 return false;
8975 // Check the mask extracts either the lower or upper half of vector
8976 // elements.
8977 int M1Start = -1;
8978 int M2Start = -1;
8979 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8980 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8981 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8982 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8983 return false;
8985 return true;
8988 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8989 /// of the vector elements.
8990 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8991 auto areExtDoubled = [](Instruction *Ext) {
8992 return Ext->getType()->getScalarSizeInBits() ==
8993 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8996 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8997 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8998 !areExtDoubled(cast<Instruction>(Ext1)) ||
8999 !areExtDoubled(cast<Instruction>(Ext2)))
9000 return false;
9002 return true;
9005 /// Check if sinking \p I's operands to I's basic block is profitable, because
9006 /// the operands can be folded into a target instruction, e.g.
9007 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
9008 bool AArch64TargetLowering::shouldSinkOperands(
9009 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
9010 if (!I->getType()->isVectorTy())
9011 return false;
9013 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
9014 switch (II->getIntrinsicID()) {
9015 case Intrinsic::aarch64_neon_umull:
9016 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
9017 return false;
9018 Ops.push_back(&II->getOperandUse(0));
9019 Ops.push_back(&II->getOperandUse(1));
9020 return true;
9021 default:
9022 return false;
9026 switch (I->getOpcode()) {
9027 case Instruction::Sub:
9028 case Instruction::Add: {
9029 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
9030 return false;
9032 // If the exts' operands extract either the lower or upper elements, we
9033 // can sink them too.
9034 auto Ext1 = cast<Instruction>(I->getOperand(0));
9035 auto Ext2 = cast<Instruction>(I->getOperand(1));
9036 if (areExtractShuffleVectors(Ext1, Ext2)) {
9037 Ops.push_back(&Ext1->getOperandUse(0));
9038 Ops.push_back(&Ext2->getOperandUse(0));
9041 Ops.push_back(&I->getOperandUse(0));
9042 Ops.push_back(&I->getOperandUse(1));
9044 return true;
9046 default:
9047 return false;
9049 return false;
9052 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
9053 unsigned &RequiredAligment) const {
9054 if (!LoadedType.isSimple() ||
9055 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
9056 return false;
9057 // Cyclone supports unaligned accesses.
9058 RequiredAligment = 0;
9059 unsigned NumBits = LoadedType.getSizeInBits();
9060 return NumBits == 32 || NumBits == 64;
9063 /// A helper function for determining the number of interleaved accesses we
9064 /// will generate when lowering accesses of the given type.
9065 unsigned
9066 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
9067 const DataLayout &DL) const {
9068 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
9071 MachineMemOperand::Flags
9072 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
9073 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
9074 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
9075 return MOStridedAccess;
9076 return MachineMemOperand::MONone;
9079 bool AArch64TargetLowering::isLegalInterleavedAccessType(
9080 VectorType *VecTy, const DataLayout &DL) const {
9082 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
9083 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
9085 // Ensure the number of vector elements is greater than 1.
9086 if (VecTy->getNumElements() < 2)
9087 return false;
9089 // Ensure the element type is legal.
9090 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
9091 return false;
9093 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
9094 // 128 will be split into multiple interleaved accesses.
9095 return VecSize == 64 || VecSize % 128 == 0;
9098 /// Lower an interleaved load into a ldN intrinsic.
9100 /// E.g. Lower an interleaved load (Factor = 2):
9101 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
9102 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
9103 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
9105 /// Into:
9106 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
9107 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
9108 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
9109 bool AArch64TargetLowering::lowerInterleavedLoad(
9110 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
9111 ArrayRef<unsigned> Indices, unsigned Factor) const {
9112 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9113 "Invalid interleave factor");
9114 assert(!Shuffles.empty() && "Empty shufflevector input");
9115 assert(Shuffles.size() == Indices.size() &&
9116 "Unmatched number of shufflevectors and indices");
9118 const DataLayout &DL = LI->getModule()->getDataLayout();
9120 VectorType *VecTy = Shuffles[0]->getType();
9122 // Skip if we do not have NEON and skip illegal vector types. We can
9123 // "legalize" wide vector types into multiple interleaved accesses as long as
9124 // the vector types are divisible by 128.
9125 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
9126 return false;
9128 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
9130 // A pointer vector can not be the return type of the ldN intrinsics. Need to
9131 // load integer vectors first and then convert to pointer vectors.
9132 Type *EltTy = VecTy->getVectorElementType();
9133 if (EltTy->isPointerTy())
9134 VecTy =
9135 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
9137 IRBuilder<> Builder(LI);
9139 // The base address of the load.
9140 Value *BaseAddr = LI->getPointerOperand();
9142 if (NumLoads > 1) {
9143 // If we're going to generate more than one load, reset the sub-vector type
9144 // to something legal.
9145 VecTy = VectorType::get(VecTy->getVectorElementType(),
9146 VecTy->getVectorNumElements() / NumLoads);
9148 // We will compute the pointer operand of each load from the original base
9149 // address using GEPs. Cast the base address to a pointer to the scalar
9150 // element type.
9151 BaseAddr = Builder.CreateBitCast(
9152 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
9153 LI->getPointerAddressSpace()));
9156 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
9157 Type *Tys[2] = {VecTy, PtrTy};
9158 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
9159 Intrinsic::aarch64_neon_ld3,
9160 Intrinsic::aarch64_neon_ld4};
9161 Function *LdNFunc =
9162 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
9164 // Holds sub-vectors extracted from the load intrinsic return values. The
9165 // sub-vectors are associated with the shufflevector instructions they will
9166 // replace.
9167 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
9169 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
9171 // If we're generating more than one load, compute the base address of
9172 // subsequent loads as an offset from the previous.
9173 if (LoadCount > 0)
9174 BaseAddr =
9175 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
9176 VecTy->getVectorNumElements() * Factor);
9178 CallInst *LdN = Builder.CreateCall(
9179 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
9181 // Extract and store the sub-vectors returned by the load intrinsic.
9182 for (unsigned i = 0; i < Shuffles.size(); i++) {
9183 ShuffleVectorInst *SVI = Shuffles[i];
9184 unsigned Index = Indices[i];
9186 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
9188 // Convert the integer vector to pointer vector if the element is pointer.
9189 if (EltTy->isPointerTy())
9190 SubVec = Builder.CreateIntToPtr(
9191 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
9192 VecTy->getVectorNumElements()));
9193 SubVecs[SVI].push_back(SubVec);
9197 // Replace uses of the shufflevector instructions with the sub-vectors
9198 // returned by the load intrinsic. If a shufflevector instruction is
9199 // associated with more than one sub-vector, those sub-vectors will be
9200 // concatenated into a single wide vector.
9201 for (ShuffleVectorInst *SVI : Shuffles) {
9202 auto &SubVec = SubVecs[SVI];
9203 auto *WideVec =
9204 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
9205 SVI->replaceAllUsesWith(WideVec);
9208 return true;
9211 /// Lower an interleaved store into a stN intrinsic.
9213 /// E.g. Lower an interleaved store (Factor = 3):
9214 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
9215 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
9216 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
9218 /// Into:
9219 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
9220 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
9221 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
9222 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9224 /// Note that the new shufflevectors will be removed and we'll only generate one
9225 /// st3 instruction in CodeGen.
9227 /// Example for a more general valid mask (Factor 3). Lower:
9228 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
9229 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
9230 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
9232 /// Into:
9233 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
9234 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
9235 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
9236 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
9237 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
9238 ShuffleVectorInst *SVI,
9239 unsigned Factor) const {
9240 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
9241 "Invalid interleave factor");
9243 VectorType *VecTy = SVI->getType();
9244 assert(VecTy->getVectorNumElements() % Factor == 0 &&
9245 "Invalid interleaved store");
9247 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
9248 Type *EltTy = VecTy->getVectorElementType();
9249 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
9251 const DataLayout &DL = SI->getModule()->getDataLayout();
9253 // Skip if we do not have NEON and skip illegal vector types. We can
9254 // "legalize" wide vector types into multiple interleaved accesses as long as
9255 // the vector types are divisible by 128.
9256 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
9257 return false;
9259 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
9261 Value *Op0 = SVI->getOperand(0);
9262 Value *Op1 = SVI->getOperand(1);
9263 IRBuilder<> Builder(SI);
9265 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
9266 // vectors to integer vectors.
9267 if (EltTy->isPointerTy()) {
9268 Type *IntTy = DL.getIntPtrType(EltTy);
9269 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
9271 // Convert to the corresponding integer vector.
9272 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
9273 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
9274 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
9276 SubVecTy = VectorType::get(IntTy, LaneLen);
9279 // The base address of the store.
9280 Value *BaseAddr = SI->getPointerOperand();
9282 if (NumStores > 1) {
9283 // If we're going to generate more than one store, reset the lane length
9284 // and sub-vector type to something legal.
9285 LaneLen /= NumStores;
9286 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
9288 // We will compute the pointer operand of each store from the original base
9289 // address using GEPs. Cast the base address to a pointer to the scalar
9290 // element type.
9291 BaseAddr = Builder.CreateBitCast(
9292 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
9293 SI->getPointerAddressSpace()));
9296 auto Mask = SVI->getShuffleMask();
9298 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
9299 Type *Tys[2] = {SubVecTy, PtrTy};
9300 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
9301 Intrinsic::aarch64_neon_st3,
9302 Intrinsic::aarch64_neon_st4};
9303 Function *StNFunc =
9304 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
9306 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
9308 SmallVector<Value *, 5> Ops;
9310 // Split the shufflevector operands into sub vectors for the new stN call.
9311 for (unsigned i = 0; i < Factor; i++) {
9312 unsigned IdxI = StoreCount * LaneLen * Factor + i;
9313 if (Mask[IdxI] >= 0) {
9314 Ops.push_back(Builder.CreateShuffleVector(
9315 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
9316 } else {
9317 unsigned StartMask = 0;
9318 for (unsigned j = 1; j < LaneLen; j++) {
9319 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
9320 if (Mask[IdxJ * Factor + IdxI] >= 0) {
9321 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
9322 break;
9325 // Note: Filling undef gaps with random elements is ok, since
9326 // those elements were being written anyway (with undefs).
9327 // In the case of all undefs we're defaulting to using elems from 0
9328 // Note: StartMask cannot be negative, it's checked in
9329 // isReInterleaveMask
9330 Ops.push_back(Builder.CreateShuffleVector(
9331 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
9335 // If we generating more than one store, we compute the base address of
9336 // subsequent stores as an offset from the previous.
9337 if (StoreCount > 0)
9338 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
9339 BaseAddr, LaneLen * Factor);
9341 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
9342 Builder.CreateCall(StNFunc, Ops);
9344 return true;
9347 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9348 unsigned AlignCheck) {
9349 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9350 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9353 EVT AArch64TargetLowering::getOptimalMemOpType(
9354 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9355 bool ZeroMemset, bool MemcpyStrSrc,
9356 const AttributeList &FuncAttributes) const {
9357 bool CanImplicitFloat =
9358 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9359 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9360 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9361 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9362 // taken one instruction to materialize the v2i64 zero and one store (with
9363 // restrictive addressing mode). Just do i64 stores.
9364 bool IsSmallMemset = IsMemset && Size < 32;
9365 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9366 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9367 return true;
9368 bool Fast;
9369 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9370 &Fast) &&
9371 Fast;
9374 if (CanUseNEON && IsMemset && !IsSmallMemset &&
9375 AlignmentIsAcceptable(MVT::v2i64, 16))
9376 return MVT::v2i64;
9377 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9378 return MVT::f128;
9379 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9380 return MVT::i64;
9381 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9382 return MVT::i32;
9383 return MVT::Other;
9386 LLT AArch64TargetLowering::getOptimalMemOpLLT(
9387 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
9388 bool ZeroMemset, bool MemcpyStrSrc,
9389 const AttributeList &FuncAttributes) const {
9390 bool CanImplicitFloat =
9391 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
9392 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
9393 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
9394 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
9395 // taken one instruction to materialize the v2i64 zero and one store (with
9396 // restrictive addressing mode). Just do i64 stores.
9397 bool IsSmallMemset = IsMemset && Size < 32;
9398 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9399 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9400 return true;
9401 bool Fast;
9402 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9403 &Fast) &&
9404 Fast;
9407 if (CanUseNEON && IsMemset && !IsSmallMemset &&
9408 AlignmentIsAcceptable(MVT::v2i64, 16))
9409 return LLT::vector(2, 64);
9410 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9411 return LLT::scalar(128);
9412 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9413 return LLT::scalar(64);
9414 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9415 return LLT::scalar(32);
9416 return LLT();
9419 // 12-bit optionally shifted immediates are legal for adds.
9420 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9421 if (Immed == std::numeric_limits<int64_t>::min()) {
9422 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9423 << ": avoid UB for INT64_MIN\n");
9424 return false;
9426 // Same encoding for add/sub, just flip the sign.
9427 Immed = std::abs(Immed);
9428 bool IsLegal = ((Immed >> 12) == 0 ||
9429 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9430 LLVM_DEBUG(dbgs() << "Is " << Immed
9431 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9432 return IsLegal;
9435 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9436 // immediates is the same as for an add or a sub.
9437 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9438 return isLegalAddImmediate(Immed);
9441 /// isLegalAddressingMode - Return true if the addressing mode represented
9442 /// by AM is legal for this target, for a load/store of the specified type.
9443 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9444 const AddrMode &AM, Type *Ty,
9445 unsigned AS, Instruction *I) const {
9446 // AArch64 has five basic addressing modes:
9447 // reg
9448 // reg + 9-bit signed offset
9449 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
9450 // reg1 + reg2
9451 // reg + SIZE_IN_BYTES * reg
9453 // No global is ever allowed as a base.
9454 if (AM.BaseGV)
9455 return false;
9457 // No reg+reg+imm addressing.
9458 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9459 return false;
9461 // FIXME: Update this method to support scalable addressing modes.
9462 if (Ty->isVectorTy() && Ty->getVectorIsScalable())
9463 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
9465 // check reg + imm case:
9466 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9467 uint64_t NumBytes = 0;
9468 if (Ty->isSized()) {
9469 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9470 NumBytes = NumBits / 8;
9471 if (!isPowerOf2_64(NumBits))
9472 NumBytes = 0;
9475 if (!AM.Scale) {
9476 int64_t Offset = AM.BaseOffs;
9478 // 9-bit signed offset
9479 if (isInt<9>(Offset))
9480 return true;
9482 // 12-bit unsigned offset
9483 unsigned shift = Log2_64(NumBytes);
9484 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9485 // Must be a multiple of NumBytes (NumBytes is a power of 2)
9486 (Offset >> shift) << shift == Offset)
9487 return true;
9488 return false;
9491 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9493 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9496 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9497 // Consider splitting large offset of struct or array.
9498 return true;
9501 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9502 const AddrMode &AM, Type *Ty,
9503 unsigned AS) const {
9504 // Scaling factors are not free at all.
9505 // Operands | Rt Latency
9506 // -------------------------------------------
9507 // Rt, [Xn, Xm] | 4
9508 // -------------------------------------------
9509 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
9510 // Rt, [Xn, Wm, <extend> #imm] |
9511 if (isLegalAddressingMode(DL, AM, Ty, AS))
9512 // Scale represents reg2 * scale, thus account for 1 if
9513 // it is not equal to 0 or 1.
9514 return AM.Scale != 0 && AM.Scale != 1;
9515 return -1;
9518 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
9519 const MachineFunction &MF, EVT VT) const {
9520 VT = VT.getScalarType();
9522 if (!VT.isSimple())
9523 return false;
9525 switch (VT.getSimpleVT().SimpleTy) {
9526 case MVT::f32:
9527 case MVT::f64:
9528 return true;
9529 default:
9530 break;
9533 return false;
9536 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
9537 Type *Ty) const {
9538 switch (Ty->getScalarType()->getTypeID()) {
9539 case Type::FloatTyID:
9540 case Type::DoubleTyID:
9541 return true;
9542 default:
9543 return false;
9547 const MCPhysReg *
9548 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9549 // LR is a callee-save register, but we must treat it as clobbered by any call
9550 // site. Hence we include LR in the scratch registers, which are in turn added
9551 // as implicit-defs for stackmaps and patchpoints.
9552 static const MCPhysReg ScratchRegs[] = {
9553 AArch64::X16, AArch64::X17, AArch64::LR, 0
9555 return ScratchRegs;
9558 bool
9559 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9560 CombineLevel Level) const {
9561 N = N->getOperand(0).getNode();
9562 EVT VT = N->getValueType(0);
9563 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9564 // it with shift to let it be lowered to UBFX.
9565 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9566 isa<ConstantSDNode>(N->getOperand(1))) {
9567 uint64_t TruncMask = N->getConstantOperandVal(1);
9568 if (isMask_64(TruncMask) &&
9569 N->getOperand(0).getOpcode() == ISD::SRL &&
9570 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9571 return false;
9573 return true;
9576 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9577 Type *Ty) const {
9578 assert(Ty->isIntegerTy());
9580 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9581 if (BitSize == 0)
9582 return false;
9584 int64_t Val = Imm.getSExtValue();
9585 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9586 return true;
9588 if ((int64_t)Val < 0)
9589 Val = ~Val;
9590 if (BitSize == 32)
9591 Val &= (1LL << 32) - 1;
9593 unsigned LZ = countLeadingZeros((uint64_t)Val);
9594 unsigned Shift = (63 - LZ) / 16;
9595 // MOVZ is free so return true for one or fewer MOVK.
9596 return Shift < 3;
9599 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9600 unsigned Index) const {
9601 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9602 return false;
9604 return (Index == 0 || Index == ResVT.getVectorNumElements());
9607 /// Turn vector tests of the signbit in the form of:
9608 /// xor (sra X, elt_size(X)-1), -1
9609 /// into:
9610 /// cmge X, X, #0
9611 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9612 const AArch64Subtarget *Subtarget) {
9613 EVT VT = N->getValueType(0);
9614 if (!Subtarget->hasNEON() || !VT.isVector())
9615 return SDValue();
9617 // There must be a shift right algebraic before the xor, and the xor must be a
9618 // 'not' operation.
9619 SDValue Shift = N->getOperand(0);
9620 SDValue Ones = N->getOperand(1);
9621 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9622 !ISD::isBuildVectorAllOnes(Ones.getNode()))
9623 return SDValue();
9625 // The shift should be smearing the sign bit across each vector element.
9626 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9627 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9628 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9629 return SDValue();
9631 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9634 // Generate SUBS and CSEL for integer abs.
9635 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9636 EVT VT = N->getValueType(0);
9638 SDValue N0 = N->getOperand(0);
9639 SDValue N1 = N->getOperand(1);
9640 SDLoc DL(N);
9642 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9643 // and change it to SUB and CSEL.
9644 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9645 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9646 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9647 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9648 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9649 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9650 N0.getOperand(0));
9651 // Generate SUBS & CSEL.
9652 SDValue Cmp =
9653 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9654 N0.getOperand(0), DAG.getConstant(0, DL, VT));
9655 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9656 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9657 SDValue(Cmp.getNode(), 1));
9659 return SDValue();
9662 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9663 TargetLowering::DAGCombinerInfo &DCI,
9664 const AArch64Subtarget *Subtarget) {
9665 if (DCI.isBeforeLegalizeOps())
9666 return SDValue();
9668 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9669 return Cmp;
9671 return performIntegerAbsCombine(N, DAG);
9674 SDValue
9675 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9676 SelectionDAG &DAG,
9677 SmallVectorImpl<SDNode *> &Created) const {
9678 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9679 if (isIntDivCheap(N->getValueType(0), Attr))
9680 return SDValue(N,0); // Lower SDIV as SDIV
9682 // fold (sdiv X, pow2)
9683 EVT VT = N->getValueType(0);
9684 if ((VT != MVT::i32 && VT != MVT::i64) ||
9685 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9686 return SDValue();
9688 SDLoc DL(N);
9689 SDValue N0 = N->getOperand(0);
9690 unsigned Lg2 = Divisor.countTrailingZeros();
9691 SDValue Zero = DAG.getConstant(0, DL, VT);
9692 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9694 // Add (N0 < 0) ? Pow2 - 1 : 0;
9695 SDValue CCVal;
9696 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9697 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9698 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9700 Created.push_back(Cmp.getNode());
9701 Created.push_back(Add.getNode());
9702 Created.push_back(CSel.getNode());
9704 // Divide by pow2.
9705 SDValue SRA =
9706 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9708 // If we're dividing by a positive value, we're done. Otherwise, we must
9709 // negate the result.
9710 if (Divisor.isNonNegative())
9711 return SRA;
9713 Created.push_back(SRA.getNode());
9714 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9717 static bool IsSVECntIntrinsic(SDValue S) {
9718 switch(getIntrinsicID(S.getNode())) {
9719 default:
9720 break;
9721 case Intrinsic::aarch64_sve_cntb:
9722 case Intrinsic::aarch64_sve_cnth:
9723 case Intrinsic::aarch64_sve_cntw:
9724 case Intrinsic::aarch64_sve_cntd:
9725 return true;
9727 return false;
9730 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9731 TargetLowering::DAGCombinerInfo &DCI,
9732 const AArch64Subtarget *Subtarget) {
9733 if (DCI.isBeforeLegalizeOps())
9734 return SDValue();
9736 // The below optimizations require a constant RHS.
9737 if (!isa<ConstantSDNode>(N->getOperand(1)))
9738 return SDValue();
9740 SDValue N0 = N->getOperand(0);
9741 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9742 const APInt &ConstValue = C->getAPIntValue();
9744 // Allow the scaling to be folded into the `cnt` instruction by preventing
9745 // the scaling to be obscured here. This makes it easier to pattern match.
9746 if (IsSVECntIntrinsic(N0) ||
9747 (N0->getOpcode() == ISD::TRUNCATE &&
9748 (IsSVECntIntrinsic(N0->getOperand(0)))))
9749 if (ConstValue.sge(1) && ConstValue.sle(16))
9750 return SDValue();
9752 // Multiplication of a power of two plus/minus one can be done more
9753 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9754 // future CPUs have a cheaper MADD instruction, this may need to be
9755 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9756 // 64-bit is 5 cycles, so this is always a win.
9757 // More aggressively, some multiplications N0 * C can be lowered to
9758 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9759 // e.g. 6=3*2=(2+1)*2.
9760 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9761 // which equals to (1+2)*16-(1+2).
9762 // TrailingZeroes is used to test if the mul can be lowered to
9763 // shift+add+shift.
9764 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9765 if (TrailingZeroes) {
9766 // Conservatively do not lower to shift+add+shift if the mul might be
9767 // folded into smul or umul.
9768 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9769 isZeroExtended(N0.getNode(), DAG)))
9770 return SDValue();
9771 // Conservatively do not lower to shift+add+shift if the mul might be
9772 // folded into madd or msub.
9773 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9774 N->use_begin()->getOpcode() == ISD::SUB))
9775 return SDValue();
9777 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9778 // and shift+add+shift.
9779 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9781 unsigned ShiftAmt, AddSubOpc;
9782 // Is the shifted value the LHS operand of the add/sub?
9783 bool ShiftValUseIsN0 = true;
9784 // Do we need to negate the result?
9785 bool NegateResult = false;
9787 if (ConstValue.isNonNegative()) {
9788 // (mul x, 2^N + 1) => (add (shl x, N), x)
9789 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9790 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9791 APInt SCVMinus1 = ShiftedConstValue - 1;
9792 APInt CVPlus1 = ConstValue + 1;
9793 if (SCVMinus1.isPowerOf2()) {
9794 ShiftAmt = SCVMinus1.logBase2();
9795 AddSubOpc = ISD::ADD;
9796 } else if (CVPlus1.isPowerOf2()) {
9797 ShiftAmt = CVPlus1.logBase2();
9798 AddSubOpc = ISD::SUB;
9799 } else
9800 return SDValue();
9801 } else {
9802 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9803 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9804 APInt CVNegPlus1 = -ConstValue + 1;
9805 APInt CVNegMinus1 = -ConstValue - 1;
9806 if (CVNegPlus1.isPowerOf2()) {
9807 ShiftAmt = CVNegPlus1.logBase2();
9808 AddSubOpc = ISD::SUB;
9809 ShiftValUseIsN0 = false;
9810 } else if (CVNegMinus1.isPowerOf2()) {
9811 ShiftAmt = CVNegMinus1.logBase2();
9812 AddSubOpc = ISD::ADD;
9813 NegateResult = true;
9814 } else
9815 return SDValue();
9818 SDLoc DL(N);
9819 EVT VT = N->getValueType(0);
9820 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9821 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9823 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9824 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9825 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9826 assert(!(NegateResult && TrailingZeroes) &&
9827 "NegateResult and TrailingZeroes cannot both be true for now.");
9828 // Negate the result.
9829 if (NegateResult)
9830 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9831 // Shift the result.
9832 if (TrailingZeroes)
9833 return DAG.getNode(ISD::SHL, DL, VT, Res,
9834 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9835 return Res;
9838 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9839 SelectionDAG &DAG) {
9840 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9841 // optimize away operation when it's from a constant.
9843 // The general transformation is:
9844 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9845 // AND(VECTOR_CMP(x,y), constant2)
9846 // constant2 = UNARYOP(constant)
9848 // Early exit if this isn't a vector operation, the operand of the
9849 // unary operation isn't a bitwise AND, or if the sizes of the operations
9850 // aren't the same.
9851 EVT VT = N->getValueType(0);
9852 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9853 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9854 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9855 return SDValue();
9857 // Now check that the other operand of the AND is a constant. We could
9858 // make the transformation for non-constant splats as well, but it's unclear
9859 // that would be a benefit as it would not eliminate any operations, just
9860 // perform one more step in scalar code before moving to the vector unit.
9861 if (BuildVectorSDNode *BV =
9862 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9863 // Bail out if the vector isn't a constant.
9864 if (!BV->isConstant())
9865 return SDValue();
9867 // Everything checks out. Build up the new and improved node.
9868 SDLoc DL(N);
9869 EVT IntVT = BV->getValueType(0);
9870 // Create a new constant of the appropriate type for the transformed
9871 // DAG.
9872 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9873 // The AND node needs bitcasts to/from an integer vector type around it.
9874 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9875 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9876 N->getOperand(0)->getOperand(0), MaskConst);
9877 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9878 return Res;
9881 return SDValue();
9884 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9885 const AArch64Subtarget *Subtarget) {
9886 // First try to optimize away the conversion when it's conditionally from
9887 // a constant. Vectors only.
9888 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9889 return Res;
9891 EVT VT = N->getValueType(0);
9892 if (VT != MVT::f32 && VT != MVT::f64)
9893 return SDValue();
9895 // Only optimize when the source and destination types have the same width.
9896 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9897 return SDValue();
9899 // If the result of an integer load is only used by an integer-to-float
9900 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9901 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9902 SDValue N0 = N->getOperand(0);
9903 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9904 // Do not change the width of a volatile load.
9905 !cast<LoadSDNode>(N0)->isVolatile()) {
9906 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9907 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9908 LN0->getPointerInfo(), LN0->getAlignment(),
9909 LN0->getMemOperand()->getFlags());
9911 // Make sure successors of the original load stay after it by updating them
9912 // to use the new Chain.
9913 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9915 unsigned Opcode =
9916 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9917 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9920 return SDValue();
9923 /// Fold a floating-point multiply by power of two into floating-point to
9924 /// fixed-point conversion.
9925 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9926 TargetLowering::DAGCombinerInfo &DCI,
9927 const AArch64Subtarget *Subtarget) {
9928 if (!Subtarget->hasNEON())
9929 return SDValue();
9931 if (!N->getValueType(0).isSimple())
9932 return SDValue();
9934 SDValue Op = N->getOperand(0);
9935 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9936 Op.getOpcode() != ISD::FMUL)
9937 return SDValue();
9939 SDValue ConstVec = Op->getOperand(1);
9940 if (!isa<BuildVectorSDNode>(ConstVec))
9941 return SDValue();
9943 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9944 uint32_t FloatBits = FloatTy.getSizeInBits();
9945 if (FloatBits != 32 && FloatBits != 64)
9946 return SDValue();
9948 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9949 uint32_t IntBits = IntTy.getSizeInBits();
9950 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9951 return SDValue();
9953 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9954 if (IntBits > FloatBits)
9955 return SDValue();
9957 BitVector UndefElements;
9958 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9959 int32_t Bits = IntBits == 64 ? 64 : 32;
9960 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9961 if (C == -1 || C == 0 || C > Bits)
9962 return SDValue();
9964 MVT ResTy;
9965 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9966 switch (NumLanes) {
9967 default:
9968 return SDValue();
9969 case 2:
9970 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9971 break;
9972 case 4:
9973 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9974 break;
9977 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9978 return SDValue();
9980 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9981 "Illegal vector type after legalization");
9983 SDLoc DL(N);
9984 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9985 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9986 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9987 SDValue FixConv =
9988 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9989 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9990 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9991 // We can handle smaller integers by generating an extra trunc.
9992 if (IntBits < FloatBits)
9993 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9995 return FixConv;
9998 /// Fold a floating-point divide by power of two into fixed-point to
9999 /// floating-point conversion.
10000 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
10001 TargetLowering::DAGCombinerInfo &DCI,
10002 const AArch64Subtarget *Subtarget) {
10003 if (!Subtarget->hasNEON())
10004 return SDValue();
10006 SDValue Op = N->getOperand(0);
10007 unsigned Opc = Op->getOpcode();
10008 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10009 !Op.getOperand(0).getValueType().isSimple() ||
10010 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
10011 return SDValue();
10013 SDValue ConstVec = N->getOperand(1);
10014 if (!isa<BuildVectorSDNode>(ConstVec))
10015 return SDValue();
10017 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10018 int32_t IntBits = IntTy.getSizeInBits();
10019 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
10020 return SDValue();
10022 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10023 int32_t FloatBits = FloatTy.getSizeInBits();
10024 if (FloatBits != 32 && FloatBits != 64)
10025 return SDValue();
10027 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
10028 if (IntBits > FloatBits)
10029 return SDValue();
10031 BitVector UndefElements;
10032 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10033 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
10034 if (C == -1 || C == 0 || C > FloatBits)
10035 return SDValue();
10037 MVT ResTy;
10038 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10039 switch (NumLanes) {
10040 default:
10041 return SDValue();
10042 case 2:
10043 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
10044 break;
10045 case 4:
10046 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
10047 break;
10050 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
10051 return SDValue();
10053 SDLoc DL(N);
10054 SDValue ConvInput = Op.getOperand(0);
10055 bool IsSigned = Opc == ISD::SINT_TO_FP;
10056 if (IntBits < FloatBits)
10057 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
10058 ResTy, ConvInput);
10060 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
10061 : Intrinsic::aarch64_neon_vcvtfxu2fp;
10062 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
10063 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
10064 DAG.getConstant(C, DL, MVT::i32));
10067 /// An EXTR instruction is made up of two shifts, ORed together. This helper
10068 /// searches for and classifies those shifts.
10069 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
10070 bool &FromHi) {
10071 if (N.getOpcode() == ISD::SHL)
10072 FromHi = false;
10073 else if (N.getOpcode() == ISD::SRL)
10074 FromHi = true;
10075 else
10076 return false;
10078 if (!isa<ConstantSDNode>(N.getOperand(1)))
10079 return false;
10081 ShiftAmount = N->getConstantOperandVal(1);
10082 Src = N->getOperand(0);
10083 return true;
10086 /// EXTR instruction extracts a contiguous chunk of bits from two existing
10087 /// registers viewed as a high/low pair. This function looks for the pattern:
10088 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
10089 /// with an EXTR. Can't quite be done in TableGen because the two immediates
10090 /// aren't independent.
10091 static SDValue tryCombineToEXTR(SDNode *N,
10092 TargetLowering::DAGCombinerInfo &DCI) {
10093 SelectionDAG &DAG = DCI.DAG;
10094 SDLoc DL(N);
10095 EVT VT = N->getValueType(0);
10097 assert(N->getOpcode() == ISD::OR && "Unexpected root");
10099 if (VT != MVT::i32 && VT != MVT::i64)
10100 return SDValue();
10102 SDValue LHS;
10103 uint32_t ShiftLHS = 0;
10104 bool LHSFromHi = false;
10105 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
10106 return SDValue();
10108 SDValue RHS;
10109 uint32_t ShiftRHS = 0;
10110 bool RHSFromHi = false;
10111 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
10112 return SDValue();
10114 // If they're both trying to come from the high part of the register, they're
10115 // not really an EXTR.
10116 if (LHSFromHi == RHSFromHi)
10117 return SDValue();
10119 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
10120 return SDValue();
10122 if (LHSFromHi) {
10123 std::swap(LHS, RHS);
10124 std::swap(ShiftLHS, ShiftRHS);
10127 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
10128 DAG.getConstant(ShiftRHS, DL, MVT::i64));
10131 static SDValue tryCombineToBSL(SDNode *N,
10132 TargetLowering::DAGCombinerInfo &DCI) {
10133 EVT VT = N->getValueType(0);
10134 SelectionDAG &DAG = DCI.DAG;
10135 SDLoc DL(N);
10137 if (!VT.isVector())
10138 return SDValue();
10140 SDValue N0 = N->getOperand(0);
10141 if (N0.getOpcode() != ISD::AND)
10142 return SDValue();
10144 SDValue N1 = N->getOperand(1);
10145 if (N1.getOpcode() != ISD::AND)
10146 return SDValue();
10148 // We only have to look for constant vectors here since the general, variable
10149 // case can be handled in TableGen.
10150 unsigned Bits = VT.getScalarSizeInBits();
10151 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
10152 for (int i = 1; i >= 0; --i)
10153 for (int j = 1; j >= 0; --j) {
10154 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
10155 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
10156 if (!BVN0 || !BVN1)
10157 continue;
10159 bool FoundMatch = true;
10160 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
10161 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
10162 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
10163 if (!CN0 || !CN1 ||
10164 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
10165 FoundMatch = false;
10166 break;
10170 if (FoundMatch)
10171 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
10172 N0->getOperand(1 - i), N1->getOperand(1 - j));
10175 return SDValue();
10178 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10179 const AArch64Subtarget *Subtarget) {
10180 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
10181 SelectionDAG &DAG = DCI.DAG;
10182 EVT VT = N->getValueType(0);
10184 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10185 return SDValue();
10187 if (SDValue Res = tryCombineToEXTR(N, DCI))
10188 return Res;
10190 if (SDValue Res = tryCombineToBSL(N, DCI))
10191 return Res;
10193 return SDValue();
10196 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
10197 if (!MemVT.getVectorElementType().isSimple())
10198 return false;
10200 uint64_t MaskForTy = 0ull;
10201 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
10202 case MVT::i8:
10203 MaskForTy = 0xffull;
10204 break;
10205 case MVT::i16:
10206 MaskForTy = 0xffffull;
10207 break;
10208 case MVT::i32:
10209 MaskForTy = 0xffffffffull;
10210 break;
10211 default:
10212 return false;
10213 break;
10216 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
10217 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
10218 return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
10220 return false;
10223 static SDValue performSVEAndCombine(SDNode *N,
10224 TargetLowering::DAGCombinerInfo &DCI) {
10225 if (DCI.isBeforeLegalizeOps())
10226 return SDValue();
10228 SDValue Src = N->getOperand(0);
10229 SDValue Mask = N->getOperand(1);
10231 if (!Src.hasOneUse())
10232 return SDValue();
10234 EVT MemVT;
10236 // SVE load instructions perform an implicit zero-extend, which makes them
10237 // perfect candidates for combining.
10238 switch (Src->getOpcode()) {
10239 case AArch64ISD::LDNF1:
10240 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
10241 break;
10242 case AArch64ISD::GLD1:
10243 case AArch64ISD::GLD1_SCALED:
10244 case AArch64ISD::GLD1_SXTW:
10245 case AArch64ISD::GLD1_SXTW_SCALED:
10246 case AArch64ISD::GLD1_UXTW:
10247 case AArch64ISD::GLD1_UXTW_SCALED:
10248 case AArch64ISD::GLD1_IMM:
10249 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
10250 break;
10251 default:
10252 return SDValue();
10255 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
10256 return Src;
10258 return SDValue();
10261 static SDValue performANDCombine(SDNode *N,
10262 TargetLowering::DAGCombinerInfo &DCI) {
10263 SelectionDAG &DAG = DCI.DAG;
10264 SDValue LHS = N->getOperand(0);
10265 EVT VT = N->getValueType(0);
10266 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
10267 return SDValue();
10269 if (VT.isScalableVector())
10270 return performSVEAndCombine(N, DCI);
10272 BuildVectorSDNode *BVN =
10273 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
10274 if (!BVN)
10275 return SDValue();
10277 // AND does not accept an immediate, so check if we can use a BIC immediate
10278 // instruction instead. We do this here instead of using a (and x, (mvni imm))
10279 // pattern in isel, because some immediates may be lowered to the preferred
10280 // (and x, (movi imm)) form, even though an mvni representation also exists.
10281 APInt DefBits(VT.getSizeInBits(), 0);
10282 APInt UndefBits(VT.getSizeInBits(), 0);
10283 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
10284 SDValue NewOp;
10286 DefBits = ~DefBits;
10287 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10288 DefBits, &LHS)) ||
10289 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10290 DefBits, &LHS)))
10291 return NewOp;
10293 UndefBits = ~UndefBits;
10294 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
10295 UndefBits, &LHS)) ||
10296 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
10297 UndefBits, &LHS)))
10298 return NewOp;
10301 return SDValue();
10304 static SDValue performSRLCombine(SDNode *N,
10305 TargetLowering::DAGCombinerInfo &DCI) {
10306 SelectionDAG &DAG = DCI.DAG;
10307 EVT VT = N->getValueType(0);
10308 if (VT != MVT::i32 && VT != MVT::i64)
10309 return SDValue();
10311 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
10312 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
10313 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
10314 SDValue N0 = N->getOperand(0);
10315 if (N0.getOpcode() == ISD::BSWAP) {
10316 SDLoc DL(N);
10317 SDValue N1 = N->getOperand(1);
10318 SDValue N00 = N0.getOperand(0);
10319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10320 uint64_t ShiftAmt = C->getZExtValue();
10321 if (VT == MVT::i32 && ShiftAmt == 16 &&
10322 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
10323 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10324 if (VT == MVT::i64 && ShiftAmt == 32 &&
10325 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
10326 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
10329 return SDValue();
10332 static SDValue performConcatVectorsCombine(SDNode *N,
10333 TargetLowering::DAGCombinerInfo &DCI,
10334 SelectionDAG &DAG) {
10335 SDLoc dl(N);
10336 EVT VT = N->getValueType(0);
10337 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
10339 // Optimize concat_vectors of truncated vectors, where the intermediate
10340 // type is illegal, to avoid said illegality, e.g.,
10341 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
10342 // (v2i16 (truncate (v2i64)))))
10343 // ->
10344 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
10345 // (v4i32 (bitcast (v2i64))),
10346 // <0, 2, 4, 6>)))
10347 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
10348 // on both input and result type, so we might generate worse code.
10349 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
10350 if (N->getNumOperands() == 2 &&
10351 N0->getOpcode() == ISD::TRUNCATE &&
10352 N1->getOpcode() == ISD::TRUNCATE) {
10353 SDValue N00 = N0->getOperand(0);
10354 SDValue N10 = N1->getOperand(0);
10355 EVT N00VT = N00.getValueType();
10357 if (N00VT == N10.getValueType() &&
10358 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
10359 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
10360 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
10361 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
10362 for (size_t i = 0; i < Mask.size(); ++i)
10363 Mask[i] = i * 2;
10364 return DAG.getNode(ISD::TRUNCATE, dl, VT,
10365 DAG.getVectorShuffle(
10366 MidVT, dl,
10367 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
10368 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
10372 // Wait 'til after everything is legalized to try this. That way we have
10373 // legal vector types and such.
10374 if (DCI.isBeforeLegalizeOps())
10375 return SDValue();
10377 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
10378 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
10379 // canonicalise to that.
10380 if (N0 == N1 && VT.getVectorNumElements() == 2) {
10381 assert(VT.getScalarSizeInBits() == 64);
10382 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
10383 DAG.getConstant(0, dl, MVT::i64));
10386 // Canonicalise concat_vectors so that the right-hand vector has as few
10387 // bit-casts as possible before its real operation. The primary matching
10388 // destination for these operations will be the narrowing "2" instructions,
10389 // which depend on the operation being performed on this right-hand vector.
10390 // For example,
10391 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
10392 // becomes
10393 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
10395 if (N1->getOpcode() != ISD::BITCAST)
10396 return SDValue();
10397 SDValue RHS = N1->getOperand(0);
10398 MVT RHSTy = RHS.getValueType().getSimpleVT();
10399 // If the RHS is not a vector, this is not the pattern we're looking for.
10400 if (!RHSTy.isVector())
10401 return SDValue();
10403 LLVM_DEBUG(
10404 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
10406 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
10407 RHSTy.getVectorNumElements() * 2);
10408 return DAG.getNode(ISD::BITCAST, dl, VT,
10409 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
10410 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
10411 RHS));
10414 static SDValue tryCombineFixedPointConvert(SDNode *N,
10415 TargetLowering::DAGCombinerInfo &DCI,
10416 SelectionDAG &DAG) {
10417 // Wait until after everything is legalized to try this. That way we have
10418 // legal vector types and such.
10419 if (DCI.isBeforeLegalizeOps())
10420 return SDValue();
10421 // Transform a scalar conversion of a value from a lane extract into a
10422 // lane extract of a vector conversion. E.g., from foo1 to foo2:
10423 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
10424 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
10426 // The second form interacts better with instruction selection and the
10427 // register allocator to avoid cross-class register copies that aren't
10428 // coalescable due to a lane reference.
10430 // Check the operand and see if it originates from a lane extract.
10431 SDValue Op1 = N->getOperand(1);
10432 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10433 // Yep, no additional predication needed. Perform the transform.
10434 SDValue IID = N->getOperand(0);
10435 SDValue Shift = N->getOperand(2);
10436 SDValue Vec = Op1.getOperand(0);
10437 SDValue Lane = Op1.getOperand(1);
10438 EVT ResTy = N->getValueType(0);
10439 EVT VecResTy;
10440 SDLoc DL(N);
10442 // The vector width should be 128 bits by the time we get here, even
10443 // if it started as 64 bits (the extract_vector handling will have
10444 // done so).
10445 assert(Vec.getValueSizeInBits() == 128 &&
10446 "unexpected vector size on extract_vector_elt!");
10447 if (Vec.getValueType() == MVT::v4i32)
10448 VecResTy = MVT::v4f32;
10449 else if (Vec.getValueType() == MVT::v2i64)
10450 VecResTy = MVT::v2f64;
10451 else
10452 llvm_unreachable("unexpected vector type!");
10454 SDValue Convert =
10455 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10456 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10458 return SDValue();
10461 // AArch64 high-vector "long" operations are formed by performing the non-high
10462 // version on an extract_subvector of each operand which gets the high half:
10464 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10466 // However, there are cases which don't have an extract_high explicitly, but
10467 // have another operation that can be made compatible with one for free. For
10468 // example:
10470 // (dupv64 scalar) --> (extract_high (dup128 scalar))
10472 // This routine does the actual conversion of such DUPs, once outer routines
10473 // have determined that everything else is in order.
10474 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10475 // similarly here.
10476 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10477 switch (N.getOpcode()) {
10478 case AArch64ISD::DUP:
10479 case AArch64ISD::DUPLANE8:
10480 case AArch64ISD::DUPLANE16:
10481 case AArch64ISD::DUPLANE32:
10482 case AArch64ISD::DUPLANE64:
10483 case AArch64ISD::MOVI:
10484 case AArch64ISD::MOVIshift:
10485 case AArch64ISD::MOVIedit:
10486 case AArch64ISD::MOVImsl:
10487 case AArch64ISD::MVNIshift:
10488 case AArch64ISD::MVNImsl:
10489 break;
10490 default:
10491 // FMOV could be supported, but isn't very useful, as it would only occur
10492 // if you passed a bitcast' floating point immediate to an eligible long
10493 // integer op (addl, smull, ...).
10494 return SDValue();
10497 MVT NarrowTy = N.getSimpleValueType();
10498 if (!NarrowTy.is64BitVector())
10499 return SDValue();
10501 MVT ElementTy = NarrowTy.getVectorElementType();
10502 unsigned NumElems = NarrowTy.getVectorNumElements();
10503 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10505 SDLoc dl(N);
10506 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10507 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10508 DAG.getConstant(NumElems, dl, MVT::i64));
10511 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10512 if (N.getOpcode() == ISD::BITCAST)
10513 N = N.getOperand(0);
10514 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10515 return false;
10516 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10517 N.getOperand(0).getValueType().getVectorNumElements() / 2;
10520 /// Helper structure to keep track of ISD::SET_CC operands.
10521 struct GenericSetCCInfo {
10522 const SDValue *Opnd0;
10523 const SDValue *Opnd1;
10524 ISD::CondCode CC;
10527 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10528 struct AArch64SetCCInfo {
10529 const SDValue *Cmp;
10530 AArch64CC::CondCode CC;
10533 /// Helper structure to keep track of SetCC information.
10534 union SetCCInfo {
10535 GenericSetCCInfo Generic;
10536 AArch64SetCCInfo AArch64;
10539 /// Helper structure to be able to read SetCC information. If set to
10540 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10541 /// GenericSetCCInfo.
10542 struct SetCCInfoAndKind {
10543 SetCCInfo Info;
10544 bool IsAArch64;
10547 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10548 /// an
10549 /// AArch64 lowered one.
10550 /// \p SetCCInfo is filled accordingly.
10551 /// \post SetCCInfo is meanginfull only when this function returns true.
10552 /// \return True when Op is a kind of SET_CC operation.
10553 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10554 // If this is a setcc, this is straight forward.
10555 if (Op.getOpcode() == ISD::SETCC) {
10556 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10557 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10558 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10559 SetCCInfo.IsAArch64 = false;
10560 return true;
10562 // Otherwise, check if this is a matching csel instruction.
10563 // In other words:
10564 // - csel 1, 0, cc
10565 // - csel 0, 1, !cc
10566 if (Op.getOpcode() != AArch64ISD::CSEL)
10567 return false;
10568 // Set the information about the operands.
10569 // TODO: we want the operands of the Cmp not the csel
10570 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10571 SetCCInfo.IsAArch64 = true;
10572 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10573 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10575 // Check that the operands matches the constraints:
10576 // (1) Both operands must be constants.
10577 // (2) One must be 1 and the other must be 0.
10578 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10579 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10581 // Check (1).
10582 if (!TValue || !FValue)
10583 return false;
10585 // Check (2).
10586 if (!TValue->isOne()) {
10587 // Update the comparison when we are interested in !cc.
10588 std::swap(TValue, FValue);
10589 SetCCInfo.Info.AArch64.CC =
10590 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10592 return TValue->isOne() && FValue->isNullValue();
10595 // Returns true if Op is setcc or zext of setcc.
10596 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10597 if (isSetCC(Op, Info))
10598 return true;
10599 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10600 isSetCC(Op->getOperand(0), Info));
10603 // The folding we want to perform is:
10604 // (add x, [zext] (setcc cc ...) )
10605 // -->
10606 // (csel x, (add x, 1), !cc ...)
10608 // The latter will get matched to a CSINC instruction.
10609 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10610 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10611 SDValue LHS = Op->getOperand(0);
10612 SDValue RHS = Op->getOperand(1);
10613 SetCCInfoAndKind InfoAndKind;
10615 // If neither operand is a SET_CC, give up.
10616 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10617 std::swap(LHS, RHS);
10618 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10619 return SDValue();
10622 // FIXME: This could be generatized to work for FP comparisons.
10623 EVT CmpVT = InfoAndKind.IsAArch64
10624 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10625 : InfoAndKind.Info.Generic.Opnd0->getValueType();
10626 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10627 return SDValue();
10629 SDValue CCVal;
10630 SDValue Cmp;
10631 SDLoc dl(Op);
10632 if (InfoAndKind.IsAArch64) {
10633 CCVal = DAG.getConstant(
10634 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10635 MVT::i32);
10636 Cmp = *InfoAndKind.Info.AArch64.Cmp;
10637 } else
10638 Cmp = getAArch64Cmp(
10639 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
10640 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
10641 dl);
10643 EVT VT = Op->getValueType(0);
10644 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10645 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10648 // The basic add/sub long vector instructions have variants with "2" on the end
10649 // which act on the high-half of their inputs. They are normally matched by
10650 // patterns like:
10652 // (add (zeroext (extract_high LHS)),
10653 // (zeroext (extract_high RHS)))
10654 // -> uaddl2 vD, vN, vM
10656 // However, if one of the extracts is something like a duplicate, this
10657 // instruction can still be used profitably. This function puts the DAG into a
10658 // more appropriate form for those patterns to trigger.
10659 static SDValue performAddSubLongCombine(SDNode *N,
10660 TargetLowering::DAGCombinerInfo &DCI,
10661 SelectionDAG &DAG) {
10662 if (DCI.isBeforeLegalizeOps())
10663 return SDValue();
10665 MVT VT = N->getSimpleValueType(0);
10666 if (!VT.is128BitVector()) {
10667 if (N->getOpcode() == ISD::ADD)
10668 return performSetccAddFolding(N, DAG);
10669 return SDValue();
10672 // Make sure both branches are extended in the same way.
10673 SDValue LHS = N->getOperand(0);
10674 SDValue RHS = N->getOperand(1);
10675 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10676 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10677 LHS.getOpcode() != RHS.getOpcode())
10678 return SDValue();
10680 unsigned ExtType = LHS.getOpcode();
10682 // It's not worth doing if at least one of the inputs isn't already an
10683 // extract, but we don't know which it'll be so we have to try both.
10684 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10685 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10686 if (!RHS.getNode())
10687 return SDValue();
10689 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10690 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10691 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10692 if (!LHS.getNode())
10693 return SDValue();
10695 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10698 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10701 // Massage DAGs which we can use the high-half "long" operations on into
10702 // something isel will recognize better. E.g.
10704 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10705 // (aarch64_neon_umull (extract_high (v2i64 vec)))
10706 // (extract_high (v2i64 (dup128 scalar)))))
10708 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10709 TargetLowering::DAGCombinerInfo &DCI,
10710 SelectionDAG &DAG) {
10711 if (DCI.isBeforeLegalizeOps())
10712 return SDValue();
10714 SDValue LHS = N->getOperand(1);
10715 SDValue RHS = N->getOperand(2);
10716 assert(LHS.getValueType().is64BitVector() &&
10717 RHS.getValueType().is64BitVector() &&
10718 "unexpected shape for long operation");
10720 // Either node could be a DUP, but it's not worth doing both of them (you'd
10721 // just as well use the non-high version) so look for a corresponding extract
10722 // operation on the other "wing".
10723 if (isEssentiallyExtractHighSubvector(LHS)) {
10724 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10725 if (!RHS.getNode())
10726 return SDValue();
10727 } else if (isEssentiallyExtractHighSubvector(RHS)) {
10728 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10729 if (!LHS.getNode())
10730 return SDValue();
10733 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10734 N->getOperand(0), LHS, RHS);
10737 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10738 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10739 unsigned ElemBits = ElemTy.getSizeInBits();
10741 int64_t ShiftAmount;
10742 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10743 APInt SplatValue, SplatUndef;
10744 unsigned SplatBitSize;
10745 bool HasAnyUndefs;
10746 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10747 HasAnyUndefs, ElemBits) ||
10748 SplatBitSize != ElemBits)
10749 return SDValue();
10751 ShiftAmount = SplatValue.getSExtValue();
10752 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10753 ShiftAmount = CVN->getSExtValue();
10754 } else
10755 return SDValue();
10757 unsigned Opcode;
10758 bool IsRightShift;
10759 switch (IID) {
10760 default:
10761 llvm_unreachable("Unknown shift intrinsic");
10762 case Intrinsic::aarch64_neon_sqshl:
10763 Opcode = AArch64ISD::SQSHL_I;
10764 IsRightShift = false;
10765 break;
10766 case Intrinsic::aarch64_neon_uqshl:
10767 Opcode = AArch64ISD::UQSHL_I;
10768 IsRightShift = false;
10769 break;
10770 case Intrinsic::aarch64_neon_srshl:
10771 Opcode = AArch64ISD::SRSHR_I;
10772 IsRightShift = true;
10773 break;
10774 case Intrinsic::aarch64_neon_urshl:
10775 Opcode = AArch64ISD::URSHR_I;
10776 IsRightShift = true;
10777 break;
10778 case Intrinsic::aarch64_neon_sqshlu:
10779 Opcode = AArch64ISD::SQSHLU_I;
10780 IsRightShift = false;
10781 break;
10782 case Intrinsic::aarch64_neon_sshl:
10783 case Intrinsic::aarch64_neon_ushl:
10784 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10785 // left shift for positive shift amounts. Below, we only replace the current
10786 // node with VSHL, if this condition is met.
10787 Opcode = AArch64ISD::VSHL;
10788 IsRightShift = false;
10789 break;
10792 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10793 SDLoc dl(N);
10794 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10795 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10796 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10797 SDLoc dl(N);
10798 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10799 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10802 return SDValue();
10805 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10806 // the intrinsics must be legal and take an i32, this means there's almost
10807 // certainly going to be a zext in the DAG which we can eliminate.
10808 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10809 SDValue AndN = N->getOperand(2);
10810 if (AndN.getOpcode() != ISD::AND)
10811 return SDValue();
10813 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10814 if (!CMask || CMask->getZExtValue() != Mask)
10815 return SDValue();
10817 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10818 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10821 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10822 SelectionDAG &DAG) {
10823 SDLoc dl(N);
10824 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10825 DAG.getNode(Opc, dl,
10826 N->getOperand(1).getSimpleValueType(),
10827 N->getOperand(1)),
10828 DAG.getConstant(0, dl, MVT::i64));
10831 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc,
10832 SelectionDAG &DAG) {
10833 SDLoc dl(N);
10834 LLVMContext &Ctx = *DAG.getContext();
10835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10837 EVT VT = N->getValueType(0);
10838 SDValue Pred = N->getOperand(1);
10839 SDValue Data = N->getOperand(2);
10840 EVT DataVT = Data.getValueType();
10842 if (DataVT.getVectorElementType().isScalarInteger() &&
10843 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) {
10844 if (!TLI.isTypeLegal(DataVT))
10845 return SDValue();
10847 EVT OutputVT = EVT::getVectorVT(Ctx, VT,
10848 AArch64::NeonBitsPerVector / VT.getSizeInBits());
10849 SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data);
10850 SDValue Zero = DAG.getConstant(0, dl, MVT::i64);
10851 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero);
10853 return Result;
10856 return SDValue();
10859 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
10860 SDLoc dl(N);
10861 LLVMContext &Ctx = *DAG.getContext();
10862 EVT VT = N->getValueType(0);
10864 assert(VT.isScalableVector() && "Expected a scalable vector.");
10866 // Current lowering only supports the SVE-ACLE types.
10867 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
10868 return SDValue();
10870 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
10871 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
10872 EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true });
10874 // Convert everything to the domain of EXT (i.e bytes).
10875 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
10876 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
10877 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
10878 DAG.getConstant(ElemSize, dl, MVT::i32));
10880 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
10881 return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
10884 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID,
10885 bool Invert,
10886 TargetLowering::DAGCombinerInfo &DCI,
10887 SelectionDAG &DAG) {
10888 if (DCI.isBeforeLegalize())
10889 return SDValue();
10891 SDValue Comparator = N->getOperand(3);
10892 if (Comparator.getOpcode() == AArch64ISD::DUP ||
10893 Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
10894 unsigned IID = getIntrinsicID(N);
10895 EVT VT = N->getValueType(0);
10896 EVT CmpVT = N->getOperand(2).getValueType();
10897 SDValue Pred = N->getOperand(1);
10898 SDValue Imm;
10899 SDLoc DL(N);
10901 switch (IID) {
10902 default:
10903 llvm_unreachable("Called with wrong intrinsic!");
10904 break;
10906 // Signed comparisons
10907 case Intrinsic::aarch64_sve_cmpeq_wide:
10908 case Intrinsic::aarch64_sve_cmpne_wide:
10909 case Intrinsic::aarch64_sve_cmpge_wide:
10910 case Intrinsic::aarch64_sve_cmpgt_wide:
10911 case Intrinsic::aarch64_sve_cmplt_wide:
10912 case Intrinsic::aarch64_sve_cmple_wide: {
10913 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10914 int64_t ImmVal = CN->getSExtValue();
10915 if (ImmVal >= -16 && ImmVal <= 15)
10916 Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10917 else
10918 return SDValue();
10920 break;
10922 // Unsigned comparisons
10923 case Intrinsic::aarch64_sve_cmphs_wide:
10924 case Intrinsic::aarch64_sve_cmphi_wide:
10925 case Intrinsic::aarch64_sve_cmplo_wide:
10926 case Intrinsic::aarch64_sve_cmpls_wide: {
10927 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
10928 uint64_t ImmVal = CN->getZExtValue();
10929 if (ImmVal <= 127)
10930 Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
10931 else
10932 return SDValue();
10934 break;
10938 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
10939 SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64);
10940 SDValue Op0, Op1;
10941 if (Invert) {
10942 Op0 = Splat;
10943 Op1 = N->getOperand(2);
10944 } else {
10945 Op0 = N->getOperand(2);
10946 Op1 = Splat;
10948 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10949 ID, Pred, Op0, Op1);
10952 return SDValue();
10955 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
10956 AArch64CC::CondCode Cond) {
10957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10959 SDLoc DL(Op);
10960 assert(Op.getValueType().isScalableVector() &&
10961 TLI.isTypeLegal(Op.getValueType()) &&
10962 "Expected legal scalable vector type!");
10964 // Ensure target specific opcodes are using legal type.
10965 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
10966 SDValue TVal = DAG.getConstant(1, DL, OutVT);
10967 SDValue FVal = DAG.getConstant(0, DL, OutVT);
10969 // Set condition code (CC) flags.
10970 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
10972 // Convert CC to integer based on requested condition.
10973 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
10974 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
10975 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
10976 return DAG.getZExtOrTrunc(Res, DL, VT);
10979 static SDValue performIntrinsicCombine(SDNode *N,
10980 TargetLowering::DAGCombinerInfo &DCI,
10981 const AArch64Subtarget *Subtarget) {
10982 SelectionDAG &DAG = DCI.DAG;
10983 unsigned IID = getIntrinsicID(N);
10984 switch (IID) {
10985 default:
10986 break;
10987 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10988 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10989 return tryCombineFixedPointConvert(N, DCI, DAG);
10990 case Intrinsic::aarch64_neon_saddv:
10991 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10992 case Intrinsic::aarch64_neon_uaddv:
10993 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10994 case Intrinsic::aarch64_neon_sminv:
10995 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10996 case Intrinsic::aarch64_neon_uminv:
10997 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10998 case Intrinsic::aarch64_neon_smaxv:
10999 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
11000 case Intrinsic::aarch64_neon_umaxv:
11001 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
11002 case Intrinsic::aarch64_neon_fmax:
11003 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
11004 N->getOperand(1), N->getOperand(2));
11005 case Intrinsic::aarch64_neon_fmin:
11006 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
11007 N->getOperand(1), N->getOperand(2));
11008 case Intrinsic::aarch64_neon_fmaxnm:
11009 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
11010 N->getOperand(1), N->getOperand(2));
11011 case Intrinsic::aarch64_neon_fminnm:
11012 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
11013 N->getOperand(1), N->getOperand(2));
11014 case Intrinsic::aarch64_neon_smull:
11015 case Intrinsic::aarch64_neon_umull:
11016 case Intrinsic::aarch64_neon_pmull:
11017 case Intrinsic::aarch64_neon_sqdmull:
11018 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
11019 case Intrinsic::aarch64_neon_sqshl:
11020 case Intrinsic::aarch64_neon_uqshl:
11021 case Intrinsic::aarch64_neon_sqshlu:
11022 case Intrinsic::aarch64_neon_srshl:
11023 case Intrinsic::aarch64_neon_urshl:
11024 case Intrinsic::aarch64_neon_sshl:
11025 case Intrinsic::aarch64_neon_ushl:
11026 return tryCombineShiftImm(IID, N, DAG);
11027 case Intrinsic::aarch64_crc32b:
11028 case Intrinsic::aarch64_crc32cb:
11029 return tryCombineCRC32(0xff, N, DAG);
11030 case Intrinsic::aarch64_crc32h:
11031 case Intrinsic::aarch64_crc32ch:
11032 return tryCombineCRC32(0xffff, N, DAG);
11033 case Intrinsic::aarch64_sve_smaxv:
11034 return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG);
11035 case Intrinsic::aarch64_sve_umaxv:
11036 return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG);
11037 case Intrinsic::aarch64_sve_sminv:
11038 return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG);
11039 case Intrinsic::aarch64_sve_uminv:
11040 return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG);
11041 case Intrinsic::aarch64_sve_orv:
11042 return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG);
11043 case Intrinsic::aarch64_sve_eorv:
11044 return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG);
11045 case Intrinsic::aarch64_sve_andv:
11046 return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG);
11047 case Intrinsic::aarch64_sve_ext:
11048 return LowerSVEIntrinsicEXT(N, DAG);
11049 case Intrinsic::aarch64_sve_cmpeq_wide:
11050 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq,
11051 false, DCI, DAG);
11052 case Intrinsic::aarch64_sve_cmpne_wide:
11053 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne,
11054 false, DCI, DAG);
11055 case Intrinsic::aarch64_sve_cmpge_wide:
11056 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11057 false, DCI, DAG);
11058 case Intrinsic::aarch64_sve_cmpgt_wide:
11059 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11060 false, DCI, DAG);
11061 case Intrinsic::aarch64_sve_cmplt_wide:
11062 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt,
11063 true, DCI, DAG);
11064 case Intrinsic::aarch64_sve_cmple_wide:
11065 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge,
11066 true, DCI, DAG);
11067 case Intrinsic::aarch64_sve_cmphs_wide:
11068 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs,
11069 false, DCI, DAG);
11070 case Intrinsic::aarch64_sve_cmphi_wide:
11071 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi,
11072 false, DCI, DAG);
11073 case Intrinsic::aarch64_sve_cmplo_wide:
11074 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true,
11075 DCI, DAG);
11076 case Intrinsic::aarch64_sve_cmpls_wide:
11077 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true,
11078 DCI, DAG);
11079 case Intrinsic::aarch64_sve_ptest_any:
11080 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11081 AArch64CC::ANY_ACTIVE);
11082 case Intrinsic::aarch64_sve_ptest_first:
11083 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11084 AArch64CC::FIRST_ACTIVE);
11085 case Intrinsic::aarch64_sve_ptest_last:
11086 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
11087 AArch64CC::LAST_ACTIVE);
11089 return SDValue();
11092 static SDValue performExtendCombine(SDNode *N,
11093 TargetLowering::DAGCombinerInfo &DCI,
11094 SelectionDAG &DAG) {
11095 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
11096 // we can convert that DUP into another extract_high (of a bigger DUP), which
11097 // helps the backend to decide that an sabdl2 would be useful, saving a real
11098 // extract_high operation.
11099 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
11100 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
11101 SDNode *ABDNode = N->getOperand(0).getNode();
11102 unsigned IID = getIntrinsicID(ABDNode);
11103 if (IID == Intrinsic::aarch64_neon_sabd ||
11104 IID == Intrinsic::aarch64_neon_uabd) {
11105 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
11106 if (!NewABD.getNode())
11107 return SDValue();
11109 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
11110 NewABD);
11114 // This is effectively a custom type legalization for AArch64.
11116 // Type legalization will split an extend of a small, legal, type to a larger
11117 // illegal type by first splitting the destination type, often creating
11118 // illegal source types, which then get legalized in isel-confusing ways,
11119 // leading to really terrible codegen. E.g.,
11120 // %result = v8i32 sext v8i8 %value
11121 // becomes
11122 // %losrc = extract_subreg %value, ...
11123 // %hisrc = extract_subreg %value, ...
11124 // %lo = v4i32 sext v4i8 %losrc
11125 // %hi = v4i32 sext v4i8 %hisrc
11126 // Things go rapidly downhill from there.
11128 // For AArch64, the [sz]ext vector instructions can only go up one element
11129 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
11130 // take two instructions.
11132 // This implies that the most efficient way to do the extend from v8i8
11133 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
11134 // the normal splitting to happen for the v8i16->v8i32.
11136 // This is pre-legalization to catch some cases where the default
11137 // type legalization will create ill-tempered code.
11138 if (!DCI.isBeforeLegalizeOps())
11139 return SDValue();
11141 // We're only interested in cleaning things up for non-legal vector types
11142 // here. If both the source and destination are legal, things will just
11143 // work naturally without any fiddling.
11144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11145 EVT ResVT = N->getValueType(0);
11146 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
11147 return SDValue();
11148 // If the vector type isn't a simple VT, it's beyond the scope of what
11149 // we're worried about here. Let legalization do its thing and hope for
11150 // the best.
11151 SDValue Src = N->getOperand(0);
11152 EVT SrcVT = Src->getValueType(0);
11153 if (!ResVT.isSimple() || !SrcVT.isSimple())
11154 return SDValue();
11156 // If the source VT is a 64-bit vector, we can play games and get the
11157 // better results we want.
11158 if (SrcVT.getSizeInBits() != 64)
11159 return SDValue();
11161 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
11162 unsigned ElementCount = SrcVT.getVectorNumElements();
11163 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
11164 SDLoc DL(N);
11165 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
11167 // Now split the rest of the operation into two halves, each with a 64
11168 // bit source.
11169 EVT LoVT, HiVT;
11170 SDValue Lo, Hi;
11171 unsigned NumElements = ResVT.getVectorNumElements();
11172 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
11173 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
11174 ResVT.getVectorElementType(), NumElements / 2);
11176 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
11177 LoVT.getVectorNumElements());
11178 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11179 DAG.getConstant(0, DL, MVT::i64));
11180 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
11181 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
11182 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
11183 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
11185 // Now combine the parts back together so we still have a single result
11186 // like the combiner expects.
11187 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
11190 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
11191 SDValue SplatVal, unsigned NumVecElts) {
11192 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
11193 unsigned OrigAlignment = St.getAlignment();
11194 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
11196 // Create scalar stores. This is at least as good as the code sequence for a
11197 // split unaligned store which is a dup.s, ext.b, and two stores.
11198 // Most of the time the three stores should be replaced by store pair
11199 // instructions (stp).
11200 SDLoc DL(&St);
11201 SDValue BasePtr = St.getBasePtr();
11202 uint64_t BaseOffset = 0;
11204 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
11205 SDValue NewST1 =
11206 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
11207 OrigAlignment, St.getMemOperand()->getFlags());
11209 // As this in ISel, we will not merge this add which may degrade results.
11210 if (BasePtr->getOpcode() == ISD::ADD &&
11211 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
11212 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
11213 BasePtr = BasePtr->getOperand(0);
11216 unsigned Offset = EltOffset;
11217 while (--NumVecElts) {
11218 unsigned Alignment = MinAlign(OrigAlignment, Offset);
11219 SDValue OffsetPtr =
11220 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11221 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
11222 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
11223 PtrInfo.getWithOffset(Offset), Alignment,
11224 St.getMemOperand()->getFlags());
11225 Offset += EltOffset;
11227 return NewST1;
11230 // Returns an SVE type that ContentTy can be trivially sign or zero extended
11231 // into.
11232 static MVT getSVEContainerType(EVT ContentTy) {
11233 assert(ContentTy.isSimple() && "No SVE containers for extended types");
11235 switch (ContentTy.getSimpleVT().SimpleTy) {
11236 default:
11237 llvm_unreachable("No known SVE container for this MVT type");
11238 case MVT::nxv2i8:
11239 case MVT::nxv2i16:
11240 case MVT::nxv2i32:
11241 case MVT::nxv2i64:
11242 case MVT::nxv2f32:
11243 case MVT::nxv2f64:
11244 return MVT::nxv2i64;
11245 case MVT::nxv4i8:
11246 case MVT::nxv4i16:
11247 case MVT::nxv4i32:
11248 case MVT::nxv4f32:
11249 return MVT::nxv4i32;
11250 case MVT::nxv8i8:
11251 case MVT::nxv8i16:
11252 case MVT::nxv8f16:
11253 return MVT::nxv8i16;
11254 case MVT::nxv16i8:
11255 return MVT::nxv16i8;
11259 static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
11260 SDLoc DL(N);
11261 EVT VT = N->getValueType(0);
11262 EVT PtrTy = N->getOperand(3).getValueType();
11264 EVT LoadVT = VT;
11265 if (VT.isFloatingPoint())
11266 LoadVT = VT.changeTypeToInteger();
11268 auto *MINode = cast<MemIntrinsicSDNode>(N);
11269 SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
11270 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
11271 MINode->getOperand(3), DAG.getUNDEF(PtrTy),
11272 MINode->getOperand(2), PassThru,
11273 MINode->getMemoryVT(), MINode->getMemOperand(),
11274 ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
11276 if (VT.isFloatingPoint()) {
11277 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
11278 return DAG.getMergeValues(Ops, DL);
11281 return L;
11284 static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
11285 SDLoc DL(N);
11287 SDValue Data = N->getOperand(2);
11288 EVT DataVT = Data.getValueType();
11289 EVT PtrTy = N->getOperand(4).getValueType();
11291 if (DataVT.isFloatingPoint())
11292 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
11294 auto *MINode = cast<MemIntrinsicSDNode>(N);
11295 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
11296 DAG.getUNDEF(PtrTy), MINode->getOperand(3),
11297 MINode->getMemoryVT(), MINode->getMemOperand(),
11298 ISD::UNINDEXED, false, false);
11301 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG) {
11302 SDLoc DL(N);
11303 EVT VT = N->getValueType(0);
11305 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
11306 return SDValue();
11308 EVT ContainerVT = VT;
11309 if (ContainerVT.isInteger())
11310 ContainerVT = getSVEContainerType(ContainerVT);
11312 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
11313 SDValue Ops[] = { N->getOperand(0), // Chain
11314 N->getOperand(2), // Pg
11315 N->getOperand(3), // Base
11316 DAG.getValueType(VT) };
11318 SDValue Load = DAG.getNode(AArch64ISD::LDNF1, DL, VTs, Ops);
11319 SDValue LoadChain = SDValue(Load.getNode(), 1);
11321 if (ContainerVT.isInteger() && (VT != ContainerVT))
11322 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
11324 return DAG.getMergeValues({ Load, LoadChain }, DL);
11327 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
11328 /// load store optimizer pass will merge them to store pair stores. This should
11329 /// be better than a movi to create the vector zero followed by a vector store
11330 /// if the zero constant is not re-used, since one instructions and one register
11331 /// live range will be removed.
11333 /// For example, the final generated code should be:
11335 /// stp xzr, xzr, [x0]
11337 /// instead of:
11339 /// movi v0.2d, #0
11340 /// str q0, [x0]
11342 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11343 SDValue StVal = St.getValue();
11344 EVT VT = StVal.getValueType();
11346 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
11347 // 2, 3 or 4 i32 elements.
11348 int NumVecElts = VT.getVectorNumElements();
11349 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
11350 VT.getVectorElementType().getSizeInBits() == 64) ||
11351 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
11352 VT.getVectorElementType().getSizeInBits() == 32)))
11353 return SDValue();
11355 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
11356 return SDValue();
11358 // If the zero constant has more than one use then the vector store could be
11359 // better since the constant mov will be amortized and stp q instructions
11360 // should be able to be formed.
11361 if (!StVal.hasOneUse())
11362 return SDValue();
11364 // If the store is truncating then it's going down to i16 or smaller, which
11365 // means it can be implemented in a single store anyway.
11366 if (St.isTruncatingStore())
11367 return SDValue();
11369 // If the immediate offset of the address operand is too large for the stp
11370 // instruction, then bail out.
11371 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
11372 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
11373 if (Offset < -512 || Offset > 504)
11374 return SDValue();
11377 for (int I = 0; I < NumVecElts; ++I) {
11378 SDValue EltVal = StVal.getOperand(I);
11379 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
11380 return SDValue();
11383 // Use a CopyFromReg WZR/XZR here to prevent
11384 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
11385 SDLoc DL(&St);
11386 unsigned ZeroReg;
11387 EVT ZeroVT;
11388 if (VT.getVectorElementType().getSizeInBits() == 32) {
11389 ZeroReg = AArch64::WZR;
11390 ZeroVT = MVT::i32;
11391 } else {
11392 ZeroReg = AArch64::XZR;
11393 ZeroVT = MVT::i64;
11395 SDValue SplatVal =
11396 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
11397 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11400 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
11401 /// value. The load store optimizer pass will merge them to store pair stores.
11402 /// This has better performance than a splat of the scalar followed by a split
11403 /// vector store. Even if the stores are not merged it is four stores vs a dup,
11404 /// followed by an ext.b and two stores.
11405 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
11406 SDValue StVal = St.getValue();
11407 EVT VT = StVal.getValueType();
11409 // Don't replace floating point stores, they possibly won't be transformed to
11410 // stp because of the store pair suppress pass.
11411 if (VT.isFloatingPoint())
11412 return SDValue();
11414 // We can express a splat as store pair(s) for 2 or 4 elements.
11415 unsigned NumVecElts = VT.getVectorNumElements();
11416 if (NumVecElts != 4 && NumVecElts != 2)
11417 return SDValue();
11419 // If the store is truncating then it's going down to i16 or smaller, which
11420 // means it can be implemented in a single store anyway.
11421 if (St.isTruncatingStore())
11422 return SDValue();
11424 // Check that this is a splat.
11425 // Make sure that each of the relevant vector element locations are inserted
11426 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
11427 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
11428 SDValue SplatVal;
11429 for (unsigned I = 0; I < NumVecElts; ++I) {
11430 // Check for insert vector elements.
11431 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
11432 return SDValue();
11434 // Check that same value is inserted at each vector element.
11435 if (I == 0)
11436 SplatVal = StVal.getOperand(1);
11437 else if (StVal.getOperand(1) != SplatVal)
11438 return SDValue();
11440 // Check insert element index.
11441 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
11442 if (!CIndex)
11443 return SDValue();
11444 uint64_t IndexVal = CIndex->getZExtValue();
11445 if (IndexVal >= NumVecElts)
11446 return SDValue();
11447 IndexNotInserted.reset(IndexVal);
11449 StVal = StVal.getOperand(0);
11451 // Check that all vector element locations were inserted to.
11452 if (IndexNotInserted.any())
11453 return SDValue();
11455 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
11458 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
11459 SelectionDAG &DAG,
11460 const AArch64Subtarget *Subtarget) {
11462 StoreSDNode *S = cast<StoreSDNode>(N);
11463 if (S->isVolatile() || S->isIndexed())
11464 return SDValue();
11466 SDValue StVal = S->getValue();
11467 EVT VT = StVal.getValueType();
11468 if (!VT.isVector())
11469 return SDValue();
11471 // If we get a splat of zeros, convert this vector store to a store of
11472 // scalars. They will be merged into store pairs of xzr thereby removing one
11473 // instruction and one register.
11474 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
11475 return ReplacedZeroSplat;
11477 // FIXME: The logic for deciding if an unaligned store should be split should
11478 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
11479 // a call to that function here.
11481 if (!Subtarget->isMisaligned128StoreSlow())
11482 return SDValue();
11484 // Don't split at -Oz.
11485 if (DAG.getMachineFunction().getFunction().hasMinSize())
11486 return SDValue();
11488 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
11489 // those up regresses performance on micro-benchmarks and olden/bh.
11490 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
11491 return SDValue();
11493 // Split unaligned 16B stores. They are terrible for performance.
11494 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
11495 // extensions can use this to mark that it does not want splitting to happen
11496 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
11497 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
11498 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
11499 S->getAlignment() <= 2)
11500 return SDValue();
11502 // If we get a splat of a scalar convert this vector store to a store of
11503 // scalars. They will be merged into store pairs thereby removing two
11504 // instructions.
11505 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
11506 return ReplacedSplat;
11508 SDLoc DL(S);
11510 // Split VT into two.
11511 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
11512 unsigned NumElts = HalfVT.getVectorNumElements();
11513 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11514 DAG.getConstant(0, DL, MVT::i64));
11515 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
11516 DAG.getConstant(NumElts, DL, MVT::i64));
11517 SDValue BasePtr = S->getBasePtr();
11518 SDValue NewST1 =
11519 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
11520 S->getAlignment(), S->getMemOperand()->getFlags());
11521 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
11522 DAG.getConstant(8, DL, MVT::i64));
11523 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
11524 S->getPointerInfo(), S->getAlignment(),
11525 S->getMemOperand()->getFlags());
11528 /// Target-specific DAG combine function for post-increment LD1 (lane) and
11529 /// post-increment LD1R.
11530 static SDValue performPostLD1Combine(SDNode *N,
11531 TargetLowering::DAGCombinerInfo &DCI,
11532 bool IsLaneOp) {
11533 if (DCI.isBeforeLegalizeOps())
11534 return SDValue();
11536 SelectionDAG &DAG = DCI.DAG;
11537 EVT VT = N->getValueType(0);
11539 unsigned LoadIdx = IsLaneOp ? 1 : 0;
11540 SDNode *LD = N->getOperand(LoadIdx).getNode();
11541 // If it is not LOAD, can not do such combine.
11542 if (LD->getOpcode() != ISD::LOAD)
11543 return SDValue();
11545 // The vector lane must be a constant in the LD1LANE opcode.
11546 SDValue Lane;
11547 if (IsLaneOp) {
11548 Lane = N->getOperand(2);
11549 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
11550 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
11551 return SDValue();
11554 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
11555 EVT MemVT = LoadSDN->getMemoryVT();
11556 // Check if memory operand is the same type as the vector element.
11557 if (MemVT != VT.getVectorElementType())
11558 return SDValue();
11560 // Check if there are other uses. If so, do not combine as it will introduce
11561 // an extra load.
11562 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
11563 ++UI) {
11564 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
11565 continue;
11566 if (*UI != N)
11567 return SDValue();
11570 SDValue Addr = LD->getOperand(1);
11571 SDValue Vector = N->getOperand(0);
11572 // Search for a use of the address operand that is an increment.
11573 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
11574 Addr.getNode()->use_end(); UI != UE; ++UI) {
11575 SDNode *User = *UI;
11576 if (User->getOpcode() != ISD::ADD
11577 || UI.getUse().getResNo() != Addr.getResNo())
11578 continue;
11580 // If the increment is a constant, it must match the memory ref size.
11581 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11582 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11583 uint32_t IncVal = CInc->getZExtValue();
11584 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
11585 if (IncVal != NumBytes)
11586 continue;
11587 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11590 // To avoid cycle construction make sure that neither the load nor the add
11591 // are predecessors to each other or the Vector.
11592 SmallPtrSet<const SDNode *, 32> Visited;
11593 SmallVector<const SDNode *, 16> Worklist;
11594 Visited.insert(Addr.getNode());
11595 Worklist.push_back(User);
11596 Worklist.push_back(LD);
11597 Worklist.push_back(Vector.getNode());
11598 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
11599 SDNode::hasPredecessorHelper(User, Visited, Worklist))
11600 continue;
11602 SmallVector<SDValue, 8> Ops;
11603 Ops.push_back(LD->getOperand(0)); // Chain
11604 if (IsLaneOp) {
11605 Ops.push_back(Vector); // The vector to be inserted
11606 Ops.push_back(Lane); // The lane to be inserted in the vector
11608 Ops.push_back(Addr);
11609 Ops.push_back(Inc);
11611 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
11612 SDVTList SDTys = DAG.getVTList(Tys);
11613 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
11614 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
11615 MemVT,
11616 LoadSDN->getMemOperand());
11618 // Update the uses.
11619 SDValue NewResults[] = {
11620 SDValue(LD, 0), // The result of load
11621 SDValue(UpdN.getNode(), 2) // Chain
11623 DCI.CombineTo(LD, NewResults);
11624 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
11625 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
11627 break;
11629 return SDValue();
11632 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
11633 /// address translation.
11634 static bool performTBISimplification(SDValue Addr,
11635 TargetLowering::DAGCombinerInfo &DCI,
11636 SelectionDAG &DAG) {
11637 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
11638 KnownBits Known;
11639 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11640 !DCI.isBeforeLegalizeOps());
11641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11642 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
11643 DCI.CommitTargetLoweringOpt(TLO);
11644 return true;
11646 return false;
11649 static SDValue performSTORECombine(SDNode *N,
11650 TargetLowering::DAGCombinerInfo &DCI,
11651 SelectionDAG &DAG,
11652 const AArch64Subtarget *Subtarget) {
11653 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
11654 return Split;
11656 if (Subtarget->supportsAddressTopByteIgnored() &&
11657 performTBISimplification(N->getOperand(2), DCI, DAG))
11658 return SDValue(N, 0);
11660 return SDValue();
11664 /// Target-specific DAG combine function for NEON load/store intrinsics
11665 /// to merge base address updates.
11666 static SDValue performNEONPostLDSTCombine(SDNode *N,
11667 TargetLowering::DAGCombinerInfo &DCI,
11668 SelectionDAG &DAG) {
11669 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11670 return SDValue();
11672 unsigned AddrOpIdx = N->getNumOperands() - 1;
11673 SDValue Addr = N->getOperand(AddrOpIdx);
11675 // Search for a use of the address operand that is an increment.
11676 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11677 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11678 SDNode *User = *UI;
11679 if (User->getOpcode() != ISD::ADD ||
11680 UI.getUse().getResNo() != Addr.getResNo())
11681 continue;
11683 // Check that the add is independent of the load/store. Otherwise, folding
11684 // it would create a cycle.
11685 SmallPtrSet<const SDNode *, 32> Visited;
11686 SmallVector<const SDNode *, 16> Worklist;
11687 Visited.insert(Addr.getNode());
11688 Worklist.push_back(N);
11689 Worklist.push_back(User);
11690 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11691 SDNode::hasPredecessorHelper(User, Visited, Worklist))
11692 continue;
11694 // Find the new opcode for the updating load/store.
11695 bool IsStore = false;
11696 bool IsLaneOp = false;
11697 bool IsDupOp = false;
11698 unsigned NewOpc = 0;
11699 unsigned NumVecs = 0;
11700 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11701 switch (IntNo) {
11702 default: llvm_unreachable("unexpected intrinsic for Neon base update");
11703 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
11704 NumVecs = 2; break;
11705 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
11706 NumVecs = 3; break;
11707 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
11708 NumVecs = 4; break;
11709 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
11710 NumVecs = 2; IsStore = true; break;
11711 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
11712 NumVecs = 3; IsStore = true; break;
11713 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
11714 NumVecs = 4; IsStore = true; break;
11715 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
11716 NumVecs = 2; break;
11717 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
11718 NumVecs = 3; break;
11719 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
11720 NumVecs = 4; break;
11721 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
11722 NumVecs = 2; IsStore = true; break;
11723 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
11724 NumVecs = 3; IsStore = true; break;
11725 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
11726 NumVecs = 4; IsStore = true; break;
11727 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
11728 NumVecs = 2; IsDupOp = true; break;
11729 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
11730 NumVecs = 3; IsDupOp = true; break;
11731 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
11732 NumVecs = 4; IsDupOp = true; break;
11733 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
11734 NumVecs = 2; IsLaneOp = true; break;
11735 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
11736 NumVecs = 3; IsLaneOp = true; break;
11737 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
11738 NumVecs = 4; IsLaneOp = true; break;
11739 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
11740 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11741 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
11742 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11743 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
11744 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11747 EVT VecTy;
11748 if (IsStore)
11749 VecTy = N->getOperand(2).getValueType();
11750 else
11751 VecTy = N->getValueType(0);
11753 // If the increment is a constant, it must match the memory ref size.
11754 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11755 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11756 uint32_t IncVal = CInc->getZExtValue();
11757 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11758 if (IsLaneOp || IsDupOp)
11759 NumBytes /= VecTy.getVectorNumElements();
11760 if (IncVal != NumBytes)
11761 continue;
11762 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11764 SmallVector<SDValue, 8> Ops;
11765 Ops.push_back(N->getOperand(0)); // Incoming chain
11766 // Load lane and store have vector list as input.
11767 if (IsLaneOp || IsStore)
11768 for (unsigned i = 2; i < AddrOpIdx; ++i)
11769 Ops.push_back(N->getOperand(i));
11770 Ops.push_back(Addr); // Base register
11771 Ops.push_back(Inc);
11773 // Return Types.
11774 EVT Tys[6];
11775 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11776 unsigned n;
11777 for (n = 0; n < NumResultVecs; ++n)
11778 Tys[n] = VecTy;
11779 Tys[n++] = MVT::i64; // Type of write back register
11780 Tys[n] = MVT::Other; // Type of the chain
11781 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11783 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11784 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11785 MemInt->getMemoryVT(),
11786 MemInt->getMemOperand());
11788 // Update the uses.
11789 std::vector<SDValue> NewResults;
11790 for (unsigned i = 0; i < NumResultVecs; ++i) {
11791 NewResults.push_back(SDValue(UpdN.getNode(), i));
11793 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11794 DCI.CombineTo(N, NewResults);
11795 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11797 break;
11799 return SDValue();
11802 // Checks to see if the value is the prescribed width and returns information
11803 // about its extension mode.
11804 static
11805 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11806 ExtType = ISD::NON_EXTLOAD;
11807 switch(V.getNode()->getOpcode()) {
11808 default:
11809 return false;
11810 case ISD::LOAD: {
11811 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11812 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11813 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11814 ExtType = LoadNode->getExtensionType();
11815 return true;
11817 return false;
11819 case ISD::AssertSext: {
11820 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11821 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11822 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11823 ExtType = ISD::SEXTLOAD;
11824 return true;
11826 return false;
11828 case ISD::AssertZext: {
11829 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11830 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11831 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11832 ExtType = ISD::ZEXTLOAD;
11833 return true;
11835 return false;
11837 case ISD::Constant:
11838 case ISD::TargetConstant: {
11839 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11840 1LL << (width - 1);
11844 return true;
11847 // This function does a whole lot of voodoo to determine if the tests are
11848 // equivalent without and with a mask. Essentially what happens is that given a
11849 // DAG resembling:
11851 // +-------------+ +-------------+ +-------------+ +-------------+
11852 // | Input | | AddConstant | | CompConstant| | CC |
11853 // +-------------+ +-------------+ +-------------+ +-------------+
11854 // | | | |
11855 // V V | +----------+
11856 // +-------------+ +----+ | |
11857 // | ADD | |0xff| | |
11858 // +-------------+ +----+ | |
11859 // | | | |
11860 // V V | |
11861 // +-------------+ | |
11862 // | AND | | |
11863 // +-------------+ | |
11864 // | | |
11865 // +-----+ | |
11866 // | | |
11867 // V V V
11868 // +-------------+
11869 // | CMP |
11870 // +-------------+
11872 // The AND node may be safely removed for some combinations of inputs. In
11873 // particular we need to take into account the extension type of the Input,
11874 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
11875 // width of the input (this can work for any width inputs, the above graph is
11876 // specific to 8 bits.
11878 // The specific equations were worked out by generating output tables for each
11879 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11880 // problem was simplified by working with 4 bit inputs, which means we only
11881 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11882 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11883 // patterns present in both extensions (0,7). For every distinct set of
11884 // AddConstant and CompConstants bit patterns we can consider the masked and
11885 // unmasked versions to be equivalent if the result of this function is true for
11886 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11888 // sub w8, w0, w1
11889 // and w10, w8, #0x0f
11890 // cmp w8, w2
11891 // cset w9, AArch64CC
11892 // cmp w10, w2
11893 // cset w11, AArch64CC
11894 // cmp w9, w11
11895 // cset w0, eq
11896 // ret
11898 // Since the above function shows when the outputs are equivalent it defines
11899 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11900 // would be expensive to run during compiles. The equations below were written
11901 // in a test harness that confirmed they gave equivalent outputs to the above
11902 // for all inputs function, so they can be used determine if the removal is
11903 // legal instead.
11905 // isEquivalentMaskless() is the code for testing if the AND can be removed
11906 // factored out of the DAG recognition as the DAG can take several forms.
11908 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11909 ISD::LoadExtType ExtType, int AddConstant,
11910 int CompConstant) {
11911 // By being careful about our equations and only writing the in term
11912 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11913 // make them generally applicable to all bit widths.
11914 int MaxUInt = (1 << width);
11916 // For the purposes of these comparisons sign extending the type is
11917 // equivalent to zero extending the add and displacing it by half the integer
11918 // width. Provided we are careful and make sure our equations are valid over
11919 // the whole range we can just adjust the input and avoid writing equations
11920 // for sign extended inputs.
11921 if (ExtType == ISD::SEXTLOAD)
11922 AddConstant -= (1 << (width-1));
11924 switch(CC) {
11925 case AArch64CC::LE:
11926 case AArch64CC::GT:
11927 if ((AddConstant == 0) ||
11928 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11929 (AddConstant >= 0 && CompConstant < 0) ||
11930 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11931 return true;
11932 break;
11933 case AArch64CC::LT:
11934 case AArch64CC::GE:
11935 if ((AddConstant == 0) ||
11936 (AddConstant >= 0 && CompConstant <= 0) ||
11937 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11938 return true;
11939 break;
11940 case AArch64CC::HI:
11941 case AArch64CC::LS:
11942 if ((AddConstant >= 0 && CompConstant < 0) ||
11943 (AddConstant <= 0 && CompConstant >= -1 &&
11944 CompConstant < AddConstant + MaxUInt))
11945 return true;
11946 break;
11947 case AArch64CC::PL:
11948 case AArch64CC::MI:
11949 if ((AddConstant == 0) ||
11950 (AddConstant > 0 && CompConstant <= 0) ||
11951 (AddConstant < 0 && CompConstant <= AddConstant))
11952 return true;
11953 break;
11954 case AArch64CC::LO:
11955 case AArch64CC::HS:
11956 if ((AddConstant >= 0 && CompConstant <= 0) ||
11957 (AddConstant <= 0 && CompConstant >= 0 &&
11958 CompConstant <= AddConstant + MaxUInt))
11959 return true;
11960 break;
11961 case AArch64CC::EQ:
11962 case AArch64CC::NE:
11963 if ((AddConstant > 0 && CompConstant < 0) ||
11964 (AddConstant < 0 && CompConstant >= 0 &&
11965 CompConstant < AddConstant + MaxUInt) ||
11966 (AddConstant >= 0 && CompConstant >= 0 &&
11967 CompConstant >= AddConstant) ||
11968 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11969 return true;
11970 break;
11971 case AArch64CC::VS:
11972 case AArch64CC::VC:
11973 case AArch64CC::AL:
11974 case AArch64CC::NV:
11975 return true;
11976 case AArch64CC::Invalid:
11977 break;
11980 return false;
11983 static
11984 SDValue performCONDCombine(SDNode *N,
11985 TargetLowering::DAGCombinerInfo &DCI,
11986 SelectionDAG &DAG, unsigned CCIndex,
11987 unsigned CmpIndex) {
11988 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11989 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11990 unsigned CondOpcode = SubsNode->getOpcode();
11992 if (CondOpcode != AArch64ISD::SUBS)
11993 return SDValue();
11995 // There is a SUBS feeding this condition. Is it fed by a mask we can
11996 // use?
11998 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11999 unsigned MaskBits = 0;
12001 if (AndNode->getOpcode() != ISD::AND)
12002 return SDValue();
12004 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
12005 uint32_t CNV = CN->getZExtValue();
12006 if (CNV == 255)
12007 MaskBits = 8;
12008 else if (CNV == 65535)
12009 MaskBits = 16;
12012 if (!MaskBits)
12013 return SDValue();
12015 SDValue AddValue = AndNode->getOperand(0);
12017 if (AddValue.getOpcode() != ISD::ADD)
12018 return SDValue();
12020 // The basic dag structure is correct, grab the inputs and validate them.
12022 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
12023 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
12024 SDValue SubsInputValue = SubsNode->getOperand(1);
12026 // The mask is present and the provenance of all the values is a smaller type,
12027 // lets see if the mask is superfluous.
12029 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
12030 !isa<ConstantSDNode>(SubsInputValue.getNode()))
12031 return SDValue();
12033 ISD::LoadExtType ExtType;
12035 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
12036 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
12037 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
12038 return SDValue();
12040 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
12041 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
12042 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
12043 return SDValue();
12045 // The AND is not necessary, remove it.
12047 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
12048 SubsNode->getValueType(1));
12049 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
12051 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
12052 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
12054 return SDValue(N, 0);
12057 // Optimize compare with zero and branch.
12058 static SDValue performBRCONDCombine(SDNode *N,
12059 TargetLowering::DAGCombinerInfo &DCI,
12060 SelectionDAG &DAG) {
12061 MachineFunction &MF = DAG.getMachineFunction();
12062 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
12063 // will not be produced, as they are conditional branch instructions that do
12064 // not set flags.
12065 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
12066 return SDValue();
12068 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
12069 N = NV.getNode();
12070 SDValue Chain = N->getOperand(0);
12071 SDValue Dest = N->getOperand(1);
12072 SDValue CCVal = N->getOperand(2);
12073 SDValue Cmp = N->getOperand(3);
12075 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
12076 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
12077 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
12078 return SDValue();
12080 unsigned CmpOpc = Cmp.getOpcode();
12081 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
12082 return SDValue();
12084 // Only attempt folding if there is only one use of the flag and no use of the
12085 // value.
12086 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
12087 return SDValue();
12089 SDValue LHS = Cmp.getOperand(0);
12090 SDValue RHS = Cmp.getOperand(1);
12092 assert(LHS.getValueType() == RHS.getValueType() &&
12093 "Expected the value type to be the same for both operands!");
12094 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
12095 return SDValue();
12097 if (isNullConstant(LHS))
12098 std::swap(LHS, RHS);
12100 if (!isNullConstant(RHS))
12101 return SDValue();
12103 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
12104 LHS.getOpcode() == ISD::SRL)
12105 return SDValue();
12107 // Fold the compare into the branch instruction.
12108 SDValue BR;
12109 if (CC == AArch64CC::EQ)
12110 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12111 else
12112 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
12114 // Do not add new nodes to DAG combiner worklist.
12115 DCI.CombineTo(N, BR, false);
12117 return SDValue();
12120 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
12121 // as well as whether the test should be inverted. This code is required to
12122 // catch these cases (as opposed to standard dag combines) because
12123 // AArch64ISD::TBZ is matched during legalization.
12124 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
12125 SelectionDAG &DAG) {
12127 if (!Op->hasOneUse())
12128 return Op;
12130 // We don't handle undef/constant-fold cases below, as they should have
12131 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
12132 // etc.)
12134 // (tbz (trunc x), b) -> (tbz x, b)
12135 // This case is just here to enable more of the below cases to be caught.
12136 if (Op->getOpcode() == ISD::TRUNCATE &&
12137 Bit < Op->getValueType(0).getSizeInBits()) {
12138 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12141 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
12142 if (Op->getOpcode() == ISD::ANY_EXTEND &&
12143 Bit < Op->getOperand(0).getValueSizeInBits()) {
12144 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12147 if (Op->getNumOperands() != 2)
12148 return Op;
12150 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12151 if (!C)
12152 return Op;
12154 switch (Op->getOpcode()) {
12155 default:
12156 return Op;
12158 // (tbz (and x, m), b) -> (tbz x, b)
12159 case ISD::AND:
12160 if ((C->getZExtValue() >> Bit) & 1)
12161 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12162 return Op;
12164 // (tbz (shl x, c), b) -> (tbz x, b-c)
12165 case ISD::SHL:
12166 if (C->getZExtValue() <= Bit &&
12167 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12168 Bit = Bit - C->getZExtValue();
12169 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12171 return Op;
12173 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
12174 case ISD::SRA:
12175 Bit = Bit + C->getZExtValue();
12176 if (Bit >= Op->getValueType(0).getSizeInBits())
12177 Bit = Op->getValueType(0).getSizeInBits() - 1;
12178 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12180 // (tbz (srl x, c), b) -> (tbz x, b+c)
12181 case ISD::SRL:
12182 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
12183 Bit = Bit + C->getZExtValue();
12184 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12186 return Op;
12188 // (tbz (xor x, -1), b) -> (tbnz x, b)
12189 case ISD::XOR:
12190 if ((C->getZExtValue() >> Bit) & 1)
12191 Invert = !Invert;
12192 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
12196 // Optimize test single bit zero/non-zero and branch.
12197 static SDValue performTBZCombine(SDNode *N,
12198 TargetLowering::DAGCombinerInfo &DCI,
12199 SelectionDAG &DAG) {
12200 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12201 bool Invert = false;
12202 SDValue TestSrc = N->getOperand(1);
12203 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
12205 if (TestSrc == NewTestSrc)
12206 return SDValue();
12208 unsigned NewOpc = N->getOpcode();
12209 if (Invert) {
12210 if (NewOpc == AArch64ISD::TBZ)
12211 NewOpc = AArch64ISD::TBNZ;
12212 else {
12213 assert(NewOpc == AArch64ISD::TBNZ);
12214 NewOpc = AArch64ISD::TBZ;
12218 SDLoc DL(N);
12219 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
12220 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
12223 // vselect (v1i1 setcc) ->
12224 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
12225 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
12226 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
12227 // such VSELECT.
12228 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
12229 SDValue N0 = N->getOperand(0);
12230 EVT CCVT = N0.getValueType();
12232 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
12233 CCVT.getVectorElementType() != MVT::i1)
12234 return SDValue();
12236 EVT ResVT = N->getValueType(0);
12237 EVT CmpVT = N0.getOperand(0).getValueType();
12238 // Only combine when the result type is of the same size as the compared
12239 // operands.
12240 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
12241 return SDValue();
12243 SDValue IfTrue = N->getOperand(1);
12244 SDValue IfFalse = N->getOperand(2);
12245 SDValue SetCC =
12246 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
12247 N0.getOperand(0), N0.getOperand(1),
12248 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12249 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
12250 IfTrue, IfFalse);
12253 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
12254 /// the compare-mask instructions rather than going via NZCV, even if LHS and
12255 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
12256 /// with a vector one followed by a DUP shuffle on the result.
12257 static SDValue performSelectCombine(SDNode *N,
12258 TargetLowering::DAGCombinerInfo &DCI) {
12259 SelectionDAG &DAG = DCI.DAG;
12260 SDValue N0 = N->getOperand(0);
12261 EVT ResVT = N->getValueType(0);
12263 if (N0.getOpcode() != ISD::SETCC)
12264 return SDValue();
12266 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
12267 // scalar SetCCResultType. We also don't expect vectors, because we assume
12268 // that selects fed by vector SETCCs are canonicalized to VSELECT.
12269 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
12270 "Scalar-SETCC feeding SELECT has unexpected result type!");
12272 // If NumMaskElts == 0, the comparison is larger than select result. The
12273 // largest real NEON comparison is 64-bits per lane, which means the result is
12274 // at most 32-bits and an illegal vector. Just bail out for now.
12275 EVT SrcVT = N0.getOperand(0).getValueType();
12277 // Don't try to do this optimization when the setcc itself has i1 operands.
12278 // There are no legal vectors of i1, so this would be pointless.
12279 if (SrcVT == MVT::i1)
12280 return SDValue();
12282 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
12283 if (!ResVT.isVector() || NumMaskElts == 0)
12284 return SDValue();
12286 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
12287 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
12289 // Also bail out if the vector CCVT isn't the same size as ResVT.
12290 // This can happen if the SETCC operand size doesn't divide the ResVT size
12291 // (e.g., f64 vs v3f32).
12292 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
12293 return SDValue();
12295 // Make sure we didn't create illegal types, if we're not supposed to.
12296 assert(DCI.isBeforeLegalize() ||
12297 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
12299 // First perform a vector comparison, where lane 0 is the one we're interested
12300 // in.
12301 SDLoc DL(N0);
12302 SDValue LHS =
12303 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
12304 SDValue RHS =
12305 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
12306 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
12308 // Now duplicate the comparison mask we want across all other lanes.
12309 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
12310 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
12311 Mask = DAG.getNode(ISD::BITCAST, DL,
12312 ResVT.changeVectorElementTypeToInteger(), Mask);
12314 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
12317 /// Get rid of unnecessary NVCASTs (that don't change the type).
12318 static SDValue performNVCASTCombine(SDNode *N) {
12319 if (N->getValueType(0) == N->getOperand(0).getValueType())
12320 return N->getOperand(0);
12322 return SDValue();
12325 // If all users of the globaladdr are of the form (globaladdr + constant), find
12326 // the smallest constant, fold it into the globaladdr's offset and rewrite the
12327 // globaladdr as (globaladdr + constant) - constant.
12328 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
12329 const AArch64Subtarget *Subtarget,
12330 const TargetMachine &TM) {
12331 auto *GN = cast<GlobalAddressSDNode>(N);
12332 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
12333 AArch64II::MO_NO_FLAG)
12334 return SDValue();
12336 uint64_t MinOffset = -1ull;
12337 for (SDNode *N : GN->uses()) {
12338 if (N->getOpcode() != ISD::ADD)
12339 return SDValue();
12340 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
12341 if (!C)
12342 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12343 if (!C)
12344 return SDValue();
12345 MinOffset = std::min(MinOffset, C->getZExtValue());
12347 uint64_t Offset = MinOffset + GN->getOffset();
12349 // Require that the new offset is larger than the existing one. Otherwise, we
12350 // can end up oscillating between two possible DAGs, for example,
12351 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
12352 if (Offset <= uint64_t(GN->getOffset()))
12353 return SDValue();
12355 // Check whether folding this offset is legal. It must not go out of bounds of
12356 // the referenced object to avoid violating the code model, and must be
12357 // smaller than 2^21 because this is the largest offset expressible in all
12358 // object formats.
12360 // This check also prevents us from folding negative offsets, which will end
12361 // up being treated in the same way as large positive ones. They could also
12362 // cause code model violations, and aren't really common enough to matter.
12363 if (Offset >= (1 << 21))
12364 return SDValue();
12366 const GlobalValue *GV = GN->getGlobal();
12367 Type *T = GV->getValueType();
12368 if (!T->isSized() ||
12369 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
12370 return SDValue();
12372 SDLoc DL(GN);
12373 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
12374 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
12375 DAG.getConstant(MinOffset, DL, MVT::i64));
12378 static SDValue performST1ScatterCombine(SDNode *N, SelectionDAG &DAG,
12379 unsigned Opcode,
12380 bool OnlyPackedOffsets = true) {
12381 const SDValue Src = N->getOperand(2);
12382 const EVT SrcVT = Src->getValueType(0);
12383 assert(SrcVT.isScalableVector() &&
12384 "Scatter stores are only possible for SVE vectors");
12386 SDLoc DL(N);
12387 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
12389 // Make sure that source data will fit into an SVE register
12390 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12391 return SDValue();
12393 // For FPs, ACLE only supports _packed_ single and double precision types.
12394 if (SrcElVT.isFloatingPoint())
12395 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
12396 return SDValue();
12398 // Depending on the addressing mode, this is either a pointer or a vector of
12399 // pointers (that fits into one register)
12400 SDValue Base = N->getOperand(4);
12401 // Depending on the addressing mode, this is either a single offset or a
12402 // vector of offsets (that fits into one register)
12403 SDValue Offset = N->getOperand(5);
12405 // SST1_IMM requires that the offset is an immediate:
12406 // * multiple of #SizeInBytes
12407 // * in the range [0, 31 x #SizeInBytes]
12408 // where #SizeInBytes is the size in bytes of the stored
12409 // items. For immediates outside that range and non-immediate scalar offsets use
12410 // SST1 or SST1_UXTW instead.
12411 if (Opcode == AArch64ISD::SST1_IMM) {
12412 uint64_t MaxIndex = 31;
12413 uint64_t SrcElSize = SrcElVT.getStoreSize().getKnownMinSize();
12415 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12416 if (nullptr == OffsetConst ||
12417 OffsetConst->getZExtValue() > MaxIndex * SrcElSize ||
12418 OffsetConst->getZExtValue() % SrcElSize) {
12419 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12420 Opcode = AArch64ISD::SST1_UXTW;
12421 else
12422 Opcode = AArch64ISD::SST1;
12424 std::swap(Base, Offset);
12428 auto &TLI = DAG.getTargetLoweringInfo();
12429 if (!TLI.isTypeLegal(Base.getValueType()))
12430 return SDValue();
12432 // Some scatter store variants allow unpacked offsets, but only as nxv2i32
12433 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12434 // nxv2i64. Legalize accordingly.
12435 if (!OnlyPackedOffsets &&
12436 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12437 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12439 if (!TLI.isTypeLegal(Offset.getValueType()))
12440 return SDValue();
12442 // Source value type that is representable in hardware
12443 EVT HwSrcVt = getSVEContainerType(SrcVT);
12445 // Keep the original type of the input data to store - this is needed to
12446 // differentiate between ST1B, ST1H, ST1W and ST1D. For FP values we want the
12447 // integer equivalent, so just use HwSrcVt.
12448 SDValue InputVT = DAG.getValueType(SrcVT);
12449 if (SrcVT.isFloatingPoint())
12450 InputVT = DAG.getValueType(HwSrcVt);
12452 SDVTList VTs = DAG.getVTList(MVT::Other);
12453 SDValue SrcNew;
12455 if (Src.getValueType().isFloatingPoint())
12456 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
12457 else
12458 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
12460 SDValue Ops[] = {N->getOperand(0), // Chain
12461 SrcNew,
12462 N->getOperand(3), // Pg
12463 Base,
12464 Offset,
12465 InputVT};
12467 return DAG.getNode(Opcode, DL, VTs, Ops);
12470 static SDValue performLD1GatherCombine(SDNode *N, SelectionDAG &DAG,
12471 unsigned Opcode,
12472 bool OnlyPackedOffsets = true) {
12473 EVT RetVT = N->getValueType(0);
12474 assert(RetVT.isScalableVector() &&
12475 "Gather loads are only possible for SVE vectors");
12476 SDLoc DL(N);
12478 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
12479 return SDValue();
12481 // Depending on the addressing mode, this is either a pointer or a vector of
12482 // pointers (that fits into one register)
12483 SDValue Base = N->getOperand(3);
12484 // Depending on the addressing mode, this is either a single offset or a
12485 // vector of offsets (that fits into one register)
12486 SDValue Offset = N->getOperand(4);
12488 // GLD1_IMM requires that the offset is an immediate:
12489 // * multiple of #SizeInBytes
12490 // * in the range [0, 31 x #SizeInBytes]
12491 // where #SizeInBytes is the size in bytes of the loaded items. For immediates
12492 // outside that range and non-immediate scalar offsets use GLD1 or GLD1_UXTW
12493 // instead.
12494 if (Opcode == AArch64ISD::GLD1_IMM) {
12495 uint64_t MaxIndex = 31;
12496 uint64_t RetElSize = RetVT.getVectorElementType()
12497 .getSimpleVT()
12498 .getStoreSize()
12499 .getKnownMinSize();
12501 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
12502 if (nullptr == OffsetConst ||
12503 OffsetConst->getZExtValue() > MaxIndex * RetElSize ||
12504 OffsetConst->getZExtValue() % RetElSize) {
12505 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
12506 Opcode = AArch64ISD::GLD1_UXTW;
12507 else
12508 Opcode = AArch64ISD::GLD1;
12510 std::swap(Base, Offset);
12514 auto &TLI = DAG.getTargetLoweringInfo();
12515 if (!TLI.isTypeLegal(Base.getValueType()))
12516 return SDValue();
12518 // Some gather load variants allow unpacked offsets, but only as nxv2i32
12519 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
12520 // nxv2i64. Legalize accordingly.
12521 if (!OnlyPackedOffsets &&
12522 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
12523 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
12525 // Return value type that is representable in hardware
12526 EVT HwRetVt = getSVEContainerType(RetVT);
12528 // Keep the original output value type around - this will better inform
12529 // optimisations (e.g. instruction folding when load is followed by
12530 // zext/sext). This will only be used for ints, so the value for FPs
12531 // doesn't matter.
12532 SDValue OutVT = DAG.getValueType(RetVT);
12533 if (RetVT.isFloatingPoint())
12534 OutVT = DAG.getValueType(HwRetVt);
12536 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
12537 SDValue Ops[] = {N->getOperand(0), // Chain
12538 N->getOperand(2), // Pg
12539 Base, Offset, OutVT};
12541 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
12542 SDValue LoadChain = SDValue(Load.getNode(), 1);
12544 if (RetVT.isInteger() && (RetVT != HwRetVt))
12545 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
12547 // If the original return value was FP, bitcast accordingly. Doing it here
12548 // means that we can avoid adding TableGen patterns for FPs.
12549 if (RetVT.isFloatingPoint())
12550 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
12552 return DAG.getMergeValues({Load, LoadChain}, DL);
12556 static SDValue
12557 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
12558 SelectionDAG &DAG) {
12559 if (DCI.isBeforeLegalizeOps())
12560 return SDValue();
12562 SDValue Src = N->getOperand(0);
12563 unsigned Opc = Src->getOpcode();
12565 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
12566 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
12567 unsigned NewOpc;
12568 unsigned MemVTOpNum = 4;
12569 switch (Opc) {
12570 case AArch64ISD::LDNF1:
12571 NewOpc = AArch64ISD::LDNF1S;
12572 MemVTOpNum = 3;
12573 break;
12574 case AArch64ISD::GLD1:
12575 NewOpc = AArch64ISD::GLD1S;
12576 break;
12577 case AArch64ISD::GLD1_SCALED:
12578 NewOpc = AArch64ISD::GLD1S_SCALED;
12579 break;
12580 case AArch64ISD::GLD1_SXTW:
12581 NewOpc = AArch64ISD::GLD1S_SXTW;
12582 break;
12583 case AArch64ISD::GLD1_SXTW_SCALED:
12584 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED;
12585 break;
12586 case AArch64ISD::GLD1_UXTW:
12587 NewOpc = AArch64ISD::GLD1S_UXTW;
12588 break;
12589 case AArch64ISD::GLD1_UXTW_SCALED:
12590 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED;
12591 break;
12592 case AArch64ISD::GLD1_IMM:
12593 NewOpc = AArch64ISD::GLD1S_IMM;
12594 break;
12595 default:
12596 return SDValue();
12599 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
12600 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
12602 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
12603 return SDValue();
12605 EVT DstVT = N->getValueType(0);
12606 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
12608 SmallVector<SDValue, 5> Ops;
12609 for (unsigned I = 0; I < Src->getNumOperands(); ++I)
12610 Ops.push_back(Src->getOperand(I));
12612 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
12613 DCI.CombineTo(N, ExtLoad);
12614 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
12616 // Return N so it doesn't get rechecked
12617 return SDValue(N, 0);
12620 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
12621 DAGCombinerInfo &DCI) const {
12622 SelectionDAG &DAG = DCI.DAG;
12623 switch (N->getOpcode()) {
12624 default:
12625 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
12626 break;
12627 case ISD::ADD:
12628 case ISD::SUB:
12629 return performAddSubLongCombine(N, DCI, DAG);
12630 case ISD::XOR:
12631 return performXorCombine(N, DAG, DCI, Subtarget);
12632 case ISD::MUL:
12633 return performMulCombine(N, DAG, DCI, Subtarget);
12634 case ISD::SINT_TO_FP:
12635 case ISD::UINT_TO_FP:
12636 return performIntToFpCombine(N, DAG, Subtarget);
12637 case ISD::FP_TO_SINT:
12638 case ISD::FP_TO_UINT:
12639 return performFpToIntCombine(N, DAG, DCI, Subtarget);
12640 case ISD::FDIV:
12641 return performFDivCombine(N, DAG, DCI, Subtarget);
12642 case ISD::OR:
12643 return performORCombine(N, DCI, Subtarget);
12644 case ISD::AND:
12645 return performANDCombine(N, DCI);
12646 case ISD::SRL:
12647 return performSRLCombine(N, DCI);
12648 case ISD::INTRINSIC_WO_CHAIN:
12649 return performIntrinsicCombine(N, DCI, Subtarget);
12650 case ISD::ANY_EXTEND:
12651 case ISD::ZERO_EXTEND:
12652 case ISD::SIGN_EXTEND:
12653 return performExtendCombine(N, DCI, DAG);
12654 case ISD::SIGN_EXTEND_INREG:
12655 return performSignExtendInRegCombine(N, DCI, DAG);
12656 case ISD::CONCAT_VECTORS:
12657 return performConcatVectorsCombine(N, DCI, DAG);
12658 case ISD::SELECT:
12659 return performSelectCombine(N, DCI);
12660 case ISD::VSELECT:
12661 return performVSelectCombine(N, DCI.DAG);
12662 case ISD::LOAD:
12663 if (performTBISimplification(N->getOperand(1), DCI, DAG))
12664 return SDValue(N, 0);
12665 break;
12666 case ISD::STORE:
12667 return performSTORECombine(N, DCI, DAG, Subtarget);
12668 case AArch64ISD::BRCOND:
12669 return performBRCONDCombine(N, DCI, DAG);
12670 case AArch64ISD::TBNZ:
12671 case AArch64ISD::TBZ:
12672 return performTBZCombine(N, DCI, DAG);
12673 case AArch64ISD::CSEL:
12674 return performCONDCombine(N, DCI, DAG, 2, 3);
12675 case AArch64ISD::DUP:
12676 return performPostLD1Combine(N, DCI, false);
12677 case AArch64ISD::NVCAST:
12678 return performNVCASTCombine(N);
12679 case ISD::INSERT_VECTOR_ELT:
12680 return performPostLD1Combine(N, DCI, true);
12681 case ISD::INTRINSIC_VOID:
12682 case ISD::INTRINSIC_W_CHAIN:
12683 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12684 case Intrinsic::aarch64_neon_ld2:
12685 case Intrinsic::aarch64_neon_ld3:
12686 case Intrinsic::aarch64_neon_ld4:
12687 case Intrinsic::aarch64_neon_ld1x2:
12688 case Intrinsic::aarch64_neon_ld1x3:
12689 case Intrinsic::aarch64_neon_ld1x4:
12690 case Intrinsic::aarch64_neon_ld2lane:
12691 case Intrinsic::aarch64_neon_ld3lane:
12692 case Intrinsic::aarch64_neon_ld4lane:
12693 case Intrinsic::aarch64_neon_ld2r:
12694 case Intrinsic::aarch64_neon_ld3r:
12695 case Intrinsic::aarch64_neon_ld4r:
12696 case Intrinsic::aarch64_neon_st2:
12697 case Intrinsic::aarch64_neon_st3:
12698 case Intrinsic::aarch64_neon_st4:
12699 case Intrinsic::aarch64_neon_st1x2:
12700 case Intrinsic::aarch64_neon_st1x3:
12701 case Intrinsic::aarch64_neon_st1x4:
12702 case Intrinsic::aarch64_neon_st2lane:
12703 case Intrinsic::aarch64_neon_st3lane:
12704 case Intrinsic::aarch64_neon_st4lane:
12705 return performNEONPostLDSTCombine(N, DCI, DAG);
12706 case Intrinsic::aarch64_sve_ldnt1:
12707 return performLDNT1Combine(N, DAG);
12708 case Intrinsic::aarch64_sve_ldnf1:
12709 return performLDNF1Combine(N, DAG);
12710 case Intrinsic::aarch64_sve_stnt1:
12711 return performSTNT1Combine(N, DAG);
12712 case Intrinsic::aarch64_sve_ld1_gather:
12713 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1);
12714 case Intrinsic::aarch64_sve_ld1_gather_index:
12715 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SCALED);
12716 case Intrinsic::aarch64_sve_ld1_gather_sxtw:
12717 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW,
12718 /*OnlyPackedOffsets=*/false);
12719 case Intrinsic::aarch64_sve_ld1_gather_uxtw:
12720 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW,
12721 /*OnlyPackedOffsets=*/false);
12722 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
12723 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED,
12724 /*OnlyPackedOffsets=*/false);
12725 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
12726 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED,
12727 /*OnlyPackedOffsets=*/false);
12728 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
12729 return performLD1GatherCombine(N, DAG, AArch64ISD::GLD1_IMM);
12730 case Intrinsic::aarch64_sve_st1_scatter:
12731 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1);
12732 case Intrinsic::aarch64_sve_st1_scatter_index:
12733 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SCALED);
12734 case Intrinsic::aarch64_sve_st1_scatter_sxtw:
12735 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW,
12736 /*OnlyPackedOffsets=*/false);
12737 case Intrinsic::aarch64_sve_st1_scatter_uxtw:
12738 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW,
12739 /*OnlyPackedOffsets=*/false);
12740 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
12741 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED,
12742 /*OnlyPackedOffsets=*/false);
12743 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
12744 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED,
12745 /*OnlyPackedOffsets=*/false);
12746 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
12747 return performST1ScatterCombine(N, DAG, AArch64ISD::SST1_IMM);
12748 default:
12749 break;
12751 break;
12752 case ISD::GlobalAddress:
12753 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
12755 return SDValue();
12758 // Check if the return value is used as only a return value, as otherwise
12759 // we can't perform a tail-call. In particular, we need to check for
12760 // target ISD nodes that are returns and any other "odd" constructs
12761 // that the generic analysis code won't necessarily catch.
12762 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
12763 SDValue &Chain) const {
12764 if (N->getNumValues() != 1)
12765 return false;
12766 if (!N->hasNUsesOfValue(1, 0))
12767 return false;
12769 SDValue TCChain = Chain;
12770 SDNode *Copy = *N->use_begin();
12771 if (Copy->getOpcode() == ISD::CopyToReg) {
12772 // If the copy has a glue operand, we conservatively assume it isn't safe to
12773 // perform a tail call.
12774 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
12775 MVT::Glue)
12776 return false;
12777 TCChain = Copy->getOperand(0);
12778 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
12779 return false;
12781 bool HasRet = false;
12782 for (SDNode *Node : Copy->uses()) {
12783 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
12784 return false;
12785 HasRet = true;
12788 if (!HasRet)
12789 return false;
12791 Chain = TCChain;
12792 return true;
12795 // Return whether the an instruction can potentially be optimized to a tail
12796 // call. This will cause the optimizers to attempt to move, or duplicate,
12797 // return instructions to help enable tail call optimizations for this
12798 // instruction.
12799 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
12800 return CI->isTailCall();
12803 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
12804 SDValue &Offset,
12805 ISD::MemIndexedMode &AM,
12806 bool &IsInc,
12807 SelectionDAG &DAG) const {
12808 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
12809 return false;
12811 Base = Op->getOperand(0);
12812 // All of the indexed addressing mode instructions take a signed
12813 // 9 bit immediate offset.
12814 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
12815 int64_t RHSC = RHS->getSExtValue();
12816 if (Op->getOpcode() == ISD::SUB)
12817 RHSC = -(uint64_t)RHSC;
12818 if (!isInt<9>(RHSC))
12819 return false;
12820 IsInc = (Op->getOpcode() == ISD::ADD);
12821 Offset = Op->getOperand(1);
12822 return true;
12824 return false;
12827 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12828 SDValue &Offset,
12829 ISD::MemIndexedMode &AM,
12830 SelectionDAG &DAG) const {
12831 EVT VT;
12832 SDValue Ptr;
12833 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12834 VT = LD->getMemoryVT();
12835 Ptr = LD->getBasePtr();
12836 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12837 VT = ST->getMemoryVT();
12838 Ptr = ST->getBasePtr();
12839 } else
12840 return false;
12842 bool IsInc;
12843 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
12844 return false;
12845 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
12846 return true;
12849 bool AArch64TargetLowering::getPostIndexedAddressParts(
12850 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
12851 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
12852 EVT VT;
12853 SDValue Ptr;
12854 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12855 VT = LD->getMemoryVT();
12856 Ptr = LD->getBasePtr();
12857 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12858 VT = ST->getMemoryVT();
12859 Ptr = ST->getBasePtr();
12860 } else
12861 return false;
12863 bool IsInc;
12864 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
12865 return false;
12866 // Post-indexing updates the base, so it's not a valid transform
12867 // if that's not the same as the load's pointer.
12868 if (Ptr != Base)
12869 return false;
12870 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
12871 return true;
12874 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
12875 SelectionDAG &DAG) {
12876 SDLoc DL(N);
12877 SDValue Op = N->getOperand(0);
12879 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
12880 return;
12882 Op = SDValue(
12883 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
12884 DAG.getUNDEF(MVT::i32), Op,
12885 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
12887 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
12888 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
12891 static void ReplaceReductionResults(SDNode *N,
12892 SmallVectorImpl<SDValue> &Results,
12893 SelectionDAG &DAG, unsigned InterOp,
12894 unsigned AcrossOp) {
12895 EVT LoVT, HiVT;
12896 SDValue Lo, Hi;
12897 SDLoc dl(N);
12898 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
12899 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
12900 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
12901 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
12902 Results.push_back(SplitVal);
12905 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
12906 SDLoc DL(N);
12907 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
12908 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
12909 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
12910 DAG.getConstant(64, DL, MVT::i64)));
12911 return std::make_pair(Lo, Hi);
12914 // Create an even/odd pair of X registers holding integer value V.
12915 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
12916 SDLoc dl(V.getNode());
12917 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
12918 SDValue VHi = DAG.getAnyExtOrTrunc(
12919 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
12920 dl, MVT::i64);
12921 if (DAG.getDataLayout().isBigEndian())
12922 std::swap (VLo, VHi);
12923 SDValue RegClass =
12924 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
12925 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
12926 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
12927 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
12928 return SDValue(
12929 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
12932 static void ReplaceCMP_SWAP_128Results(SDNode *N,
12933 SmallVectorImpl<SDValue> &Results,
12934 SelectionDAG &DAG,
12935 const AArch64Subtarget *Subtarget) {
12936 assert(N->getValueType(0) == MVT::i128 &&
12937 "AtomicCmpSwap on types less than 128 should be legal");
12939 if (Subtarget->hasLSE()) {
12940 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
12941 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
12942 SDValue Ops[] = {
12943 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
12944 createGPRPairNode(DAG, N->getOperand(3)), // Store value
12945 N->getOperand(1), // Ptr
12946 N->getOperand(0), // Chain in
12949 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12951 unsigned Opcode;
12952 switch (MemOp->getOrdering()) {
12953 case AtomicOrdering::Monotonic:
12954 Opcode = AArch64::CASPX;
12955 break;
12956 case AtomicOrdering::Acquire:
12957 Opcode = AArch64::CASPAX;
12958 break;
12959 case AtomicOrdering::Release:
12960 Opcode = AArch64::CASPLX;
12961 break;
12962 case AtomicOrdering::AcquireRelease:
12963 case AtomicOrdering::SequentiallyConsistent:
12964 Opcode = AArch64::CASPALX;
12965 break;
12966 default:
12967 llvm_unreachable("Unexpected ordering!");
12970 MachineSDNode *CmpSwap = DAG.getMachineNode(
12971 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
12972 DAG.setNodeMemRefs(CmpSwap, {MemOp});
12974 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
12975 if (DAG.getDataLayout().isBigEndian())
12976 std::swap(SubReg1, SubReg2);
12977 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
12978 SDValue(CmpSwap, 0)));
12979 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
12980 SDValue(CmpSwap, 0)));
12981 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
12982 return;
12985 auto Desired = splitInt128(N->getOperand(2), DAG);
12986 auto New = splitInt128(N->getOperand(3), DAG);
12987 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
12988 New.first, New.second, N->getOperand(0)};
12989 SDNode *CmpSwap = DAG.getMachineNode(
12990 AArch64::CMP_SWAP_128, SDLoc(N),
12991 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
12993 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
12994 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
12996 Results.push_back(SDValue(CmpSwap, 0));
12997 Results.push_back(SDValue(CmpSwap, 1));
12998 Results.push_back(SDValue(CmpSwap, 3));
13001 void AArch64TargetLowering::ReplaceNodeResults(
13002 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
13003 switch (N->getOpcode()) {
13004 default:
13005 llvm_unreachable("Don't know how to custom expand this");
13006 case ISD::BITCAST:
13007 ReplaceBITCASTResults(N, Results, DAG);
13008 return;
13009 case ISD::VECREDUCE_ADD:
13010 case ISD::VECREDUCE_SMAX:
13011 case ISD::VECREDUCE_SMIN:
13012 case ISD::VECREDUCE_UMAX:
13013 case ISD::VECREDUCE_UMIN:
13014 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
13015 return;
13017 case AArch64ISD::SADDV:
13018 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
13019 return;
13020 case AArch64ISD::UADDV:
13021 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
13022 return;
13023 case AArch64ISD::SMINV:
13024 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
13025 return;
13026 case AArch64ISD::UMINV:
13027 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
13028 return;
13029 case AArch64ISD::SMAXV:
13030 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
13031 return;
13032 case AArch64ISD::UMAXV:
13033 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
13034 return;
13035 case ISD::FP_TO_UINT:
13036 case ISD::FP_TO_SINT:
13037 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
13038 // Let normal code take care of it by not adding anything to Results.
13039 return;
13040 case ISD::ATOMIC_CMP_SWAP:
13041 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
13042 return;
13043 case ISD::LOAD: {
13044 assert(SDValue(N, 0).getValueType() == MVT::i128 &&
13045 "unexpected load's value type");
13046 LoadSDNode *LoadNode = cast<LoadSDNode>(N);
13047 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
13048 // Non-volatile loads are optimized later in AArch64's load/store
13049 // optimizer.
13050 return;
13053 SDValue Result = DAG.getMemIntrinsicNode(
13054 AArch64ISD::LDP, SDLoc(N),
13055 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
13056 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
13057 LoadNode->getMemOperand());
13059 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
13060 Result.getValue(0), Result.getValue(1));
13061 Results.append({Pair, Result.getValue(2) /* Chain */});
13062 return;
13064 case ISD::INTRINSIC_WO_CHAIN: {
13065 EVT VT = N->getValueType(0);
13066 assert((VT == MVT::i8 || VT == MVT::i16) &&
13067 "custom lowering for unexpected type");
13069 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
13070 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13071 switch (IntID) {
13072 default:
13073 return;
13074 case Intrinsic::aarch64_sve_clasta_n: {
13075 SDLoc DL(N);
13076 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13077 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
13078 N->getOperand(1), Op2, N->getOperand(3));
13079 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13080 return;
13082 case Intrinsic::aarch64_sve_clastb_n: {
13083 SDLoc DL(N);
13084 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
13085 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
13086 N->getOperand(1), Op2, N->getOperand(3));
13087 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13088 return;
13090 case Intrinsic::aarch64_sve_lasta: {
13091 SDLoc DL(N);
13092 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
13093 N->getOperand(1), N->getOperand(2));
13094 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13095 return;
13097 case Intrinsic::aarch64_sve_lastb: {
13098 SDLoc DL(N);
13099 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
13100 N->getOperand(1), N->getOperand(2));
13101 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
13102 return;
13109 bool AArch64TargetLowering::useLoadStackGuardNode() const {
13110 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
13111 return TargetLowering::useLoadStackGuardNode();
13112 return true;
13115 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
13116 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13117 // reciprocal if there are three or more FDIVs.
13118 return 3;
13121 TargetLoweringBase::LegalizeTypeAction
13122 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
13123 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
13124 // v4i16, v2i32 instead of to promote.
13125 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
13126 VT == MVT::v1f32)
13127 return TypeWidenVector;
13129 return TargetLoweringBase::getPreferredVectorAction(VT);
13132 // Loads and stores less than 128-bits are already atomic; ones above that
13133 // are doomed anyway, so defer to the default libcall and blame the OS when
13134 // things go wrong.
13135 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13136 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13137 return Size == 128;
13140 // Loads and stores less than 128-bits are already atomic; ones above that
13141 // are doomed anyway, so defer to the default libcall and blame the OS when
13142 // things go wrong.
13143 TargetLowering::AtomicExpansionKind
13144 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13145 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13146 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
13149 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
13150 TargetLowering::AtomicExpansionKind
13151 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13152 if (AI->isFloatingPointOperation())
13153 return AtomicExpansionKind::CmpXChg;
13155 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13156 if (Size > 128) return AtomicExpansionKind::None;
13157 // Nand not supported in LSE.
13158 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
13159 // Leave 128 bits to LLSC.
13160 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
13163 TargetLowering::AtomicExpansionKind
13164 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
13165 AtomicCmpXchgInst *AI) const {
13166 // If subtarget has LSE, leave cmpxchg intact for codegen.
13167 if (Subtarget->hasLSE())
13168 return AtomicExpansionKind::None;
13169 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13170 // implement cmpxchg without spilling. If the address being exchanged is also
13171 // on the stack and close enough to the spill slot, this can lead to a
13172 // situation where the monitor always gets cleared and the atomic operation
13173 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13174 if (getTargetMachine().getOptLevel() == 0)
13175 return AtomicExpansionKind::None;
13176 return AtomicExpansionKind::LLSC;
13179 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13180 AtomicOrdering Ord) const {
13181 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13182 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13183 bool IsAcquire = isAcquireOrStronger(Ord);
13185 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
13186 // intrinsic must return {i64, i64} and we have to recombine them into a
13187 // single i128 here.
13188 if (ValTy->getPrimitiveSizeInBits() == 128) {
13189 Intrinsic::ID Int =
13190 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
13191 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
13193 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13194 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
13196 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13197 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13198 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13199 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13200 return Builder.CreateOr(
13201 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
13204 Type *Tys[] = { Addr->getType() };
13205 Intrinsic::ID Int =
13206 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
13207 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
13209 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
13211 const DataLayout &DL = M->getDataLayout();
13212 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
13213 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
13215 return Builder.CreateBitCast(Trunc, EltTy);
13218 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13219 IRBuilder<> &Builder) const {
13220 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13221 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
13224 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
13225 Value *Val, Value *Addr,
13226 AtomicOrdering Ord) const {
13227 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13228 bool IsRelease = isReleaseOrStronger(Ord);
13230 // Since the intrinsics must have legal type, the i128 intrinsics take two
13231 // parameters: "i64, i64". We must marshal Val into the appropriate form
13232 // before the call.
13233 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
13234 Intrinsic::ID Int =
13235 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
13236 Function *Stxr = Intrinsic::getDeclaration(M, Int);
13237 Type *Int64Ty = Type::getInt64Ty(M->getContext());
13239 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
13240 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
13241 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13242 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
13245 Intrinsic::ID Int =
13246 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
13247 Type *Tys[] = { Addr->getType() };
13248 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
13250 const DataLayout &DL = M->getDataLayout();
13251 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
13252 Val = Builder.CreateBitCast(Val, IntValTy);
13254 return Builder.CreateCall(Stxr,
13255 {Builder.CreateZExtOrBitCast(
13256 Val, Stxr->getFunctionType()->getParamType(0)),
13257 Addr});
13260 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
13261 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13262 return Ty->isArrayTy();
13265 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
13266 EVT) const {
13267 return false;
13270 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
13271 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
13272 Function *ThreadPointerFunc =
13273 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
13274 return IRB.CreatePointerCast(
13275 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
13276 Offset),
13277 IRB.getInt8PtrTy()->getPointerTo(0));
13280 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
13281 // Android provides a fixed TLS slot for the stack cookie. See the definition
13282 // of TLS_SLOT_STACK_GUARD in
13283 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13284 if (Subtarget->isTargetAndroid())
13285 return UseTlsOffset(IRB, 0x28);
13287 // Fuchsia is similar.
13288 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
13289 if (Subtarget->isTargetFuchsia())
13290 return UseTlsOffset(IRB, -0x10);
13292 return TargetLowering::getIRStackGuard(IRB);
13295 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
13296 // MSVC CRT provides functionalities for stack protection.
13297 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
13298 // MSVC CRT has a global variable holding security cookie.
13299 M.getOrInsertGlobal("__security_cookie",
13300 Type::getInt8PtrTy(M.getContext()));
13302 // MSVC CRT has a function to validate security cookie.
13303 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
13304 "__security_check_cookie", Type::getVoidTy(M.getContext()),
13305 Type::getInt8PtrTy(M.getContext()));
13306 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
13307 F->setCallingConv(CallingConv::Win64);
13308 F->addAttribute(1, Attribute::AttrKind::InReg);
13310 return;
13312 TargetLowering::insertSSPDeclarations(M);
13315 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
13316 // MSVC CRT has a global variable holding security cookie.
13317 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13318 return M.getGlobalVariable("__security_cookie");
13319 return TargetLowering::getSDagStackGuard(M);
13322 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
13323 // MSVC CRT has a function to validate security cookie.
13324 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
13325 return M.getFunction("__security_check_cookie");
13326 return TargetLowering::getSSPStackGuardCheck(M);
13329 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
13330 // Android provides a fixed TLS slot for the SafeStack pointer. See the
13331 // definition of TLS_SLOT_SAFESTACK in
13332 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
13333 if (Subtarget->isTargetAndroid())
13334 return UseTlsOffset(IRB, 0x48);
13336 // Fuchsia is similar.
13337 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
13338 if (Subtarget->isTargetFuchsia())
13339 return UseTlsOffset(IRB, -0x8);
13341 return TargetLowering::getSafeStackPointerLocation(IRB);
13344 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
13345 const Instruction &AndI) const {
13346 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
13347 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
13348 // may be beneficial to sink in other cases, but we would have to check that
13349 // the cmp would not get folded into the br to form a cbz for these to be
13350 // beneficial.
13351 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
13352 if (!Mask)
13353 return false;
13354 return Mask->getValue().isPowerOf2();
13357 bool AArch64TargetLowering::
13358 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13359 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
13360 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
13361 SelectionDAG &DAG) const {
13362 // Does baseline recommend not to perform the fold by default?
13363 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
13364 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
13365 return false;
13366 // Else, if this is a vector shift, prefer 'shl'.
13367 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
13370 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
13371 SDNode *N) const {
13372 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
13373 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
13374 return false;
13375 return true;
13378 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13379 // Update IsSplitCSR in AArch64unctionInfo.
13380 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
13381 AFI->setIsSplitCSR(true);
13384 void AArch64TargetLowering::insertCopiesSplitCSR(
13385 MachineBasicBlock *Entry,
13386 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13387 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
13388 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13389 if (!IStart)
13390 return;
13392 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13393 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13394 MachineBasicBlock::iterator MBBI = Entry->begin();
13395 for (const MCPhysReg *I = IStart; *I; ++I) {
13396 const TargetRegisterClass *RC = nullptr;
13397 if (AArch64::GPR64RegClass.contains(*I))
13398 RC = &AArch64::GPR64RegClass;
13399 else if (AArch64::FPR64RegClass.contains(*I))
13400 RC = &AArch64::FPR64RegClass;
13401 else
13402 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13404 Register NewVR = MRI->createVirtualRegister(RC);
13405 // Create copy from CSR to a virtual register.
13406 // FIXME: this currently does not emit CFI pseudo-instructions, it works
13407 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13408 // nounwind. If we want to generalize this later, we may need to emit
13409 // CFI pseudo-instructions.
13410 assert(Entry->getParent()->getFunction().hasFnAttribute(
13411 Attribute::NoUnwind) &&
13412 "Function should be nounwind in insertCopiesSplitCSR!");
13413 Entry->addLiveIn(*I);
13414 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13415 .addReg(*I);
13417 // Insert the copy-back instructions right before the terminator.
13418 for (auto *Exit : Exits)
13419 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13420 TII->get(TargetOpcode::COPY), *I)
13421 .addReg(NewVR);
13425 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
13426 // Integer division on AArch64 is expensive. However, when aggressively
13427 // optimizing for code size, we prefer to use a div instruction, as it is
13428 // usually smaller than the alternative sequence.
13429 // The exception to this is vector division. Since AArch64 doesn't have vector
13430 // integer division, leaving the division as-is is a loss even in terms of
13431 // size, because it will have to be scalarized, while the alternative code
13432 // sequence can be performed in vector form.
13433 bool OptSize =
13434 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
13435 return OptSize && !VT.isVector();
13438 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
13439 // We want inc-of-add for scalars and sub-of-not for vectors.
13440 return VT.isScalarInteger();
13443 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
13444 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
13447 unsigned
13448 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
13449 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
13450 return getPointerTy(DL).getSizeInBits();
13452 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
13455 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
13456 MF.getFrameInfo().computeMaxCallFrameSize(MF);
13457 TargetLoweringBase::finalizeLowering(MF);
13460 // Unlike X86, we let frame lowering assign offsets to all catch objects.
13461 bool AArch64TargetLowering::needsFixedCatchObjects() const {
13462 return false;