[Alignment][NFC] Optimize alignTo
[llvm-complete.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
blobee62b6dfe36b6d1fb7bd64a922a3842c84638dd3
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 "AArch64ExpandImm.h"
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/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/Module.h"
62 #include "llvm/IR/OperandTraits.h"
63 #include "llvm/IR/PatternMatch.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/IR/Use.h"
66 #include "llvm/IR/Value.h"
67 #include "llvm/MC/MCRegisterInfo.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/KnownBits.h"
75 #include "llvm/Support/MachineValueType.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Target/TargetMachine.h"
79 #include "llvm/Target/TargetOptions.h"
80 #include <algorithm>
81 #include <bitset>
82 #include <cassert>
83 #include <cctype>
84 #include <cstdint>
85 #include <cstdlib>
86 #include <iterator>
87 #include <limits>
88 #include <tuple>
89 #include <utility>
90 #include <vector>
92 using namespace llvm;
93 using namespace llvm::PatternMatch;
95 #define DEBUG_TYPE "aarch64-lower"
97 STATISTIC(NumTailCalls, "Number of tail calls");
98 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
99 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
101 static cl::opt<bool>
102 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
103 cl::desc("Allow AArch64 SLI/SRI formation"),
104 cl::init(false));
106 // FIXME: The necessary dtprel relocations don't seem to be supported
107 // well in the GNU bfd and gold linkers at the moment. Therefore, by
108 // default, for now, fall back to GeneralDynamic code generation.
109 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
110 "aarch64-elf-ldtls-generation", cl::Hidden,
111 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
112 cl::init(false));
114 static cl::opt<bool>
115 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
116 cl::desc("Enable AArch64 logical imm instruction "
117 "optimization"),
118 cl::init(true));
120 /// Value type used for condition codes.
121 static const MVT MVT_CC = MVT::i32;
123 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
124 const AArch64Subtarget &STI)
125 : TargetLowering(TM), Subtarget(&STI) {
126 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
127 // we have to make something up. Arbitrarily, choose ZeroOrOne.
128 setBooleanContents(ZeroOrOneBooleanContent);
129 // When comparing vectors the result sets the different elements in the
130 // vector to all-one or all-zero.
131 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
133 // Set up the register classes.
134 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
135 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
137 if (Subtarget->hasFPARMv8()) {
138 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
139 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
140 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
141 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
144 if (Subtarget->hasNEON()) {
145 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
146 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
147 // Someone set us up the NEON.
148 addDRTypeForNEON(MVT::v2f32);
149 addDRTypeForNEON(MVT::v8i8);
150 addDRTypeForNEON(MVT::v4i16);
151 addDRTypeForNEON(MVT::v2i32);
152 addDRTypeForNEON(MVT::v1i64);
153 addDRTypeForNEON(MVT::v1f64);
154 addDRTypeForNEON(MVT::v4f16);
156 addQRTypeForNEON(MVT::v4f32);
157 addQRTypeForNEON(MVT::v2f64);
158 addQRTypeForNEON(MVT::v16i8);
159 addQRTypeForNEON(MVT::v8i16);
160 addQRTypeForNEON(MVT::v4i32);
161 addQRTypeForNEON(MVT::v2i64);
162 addQRTypeForNEON(MVT::v8f16);
165 if (Subtarget->hasSVE()) {
166 // Add legal sve predicate types
167 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
168 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
169 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
170 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
172 // Add legal sve data types
173 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
174 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
175 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
176 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
178 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
179 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
180 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
181 addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
184 addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
185 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
188 // Compute derived properties from the register classes
189 computeRegisterProperties(Subtarget->getRegisterInfo());
191 // Provide all sorts of operation actions
192 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
193 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
194 setOperationAction(ISD::SETCC, MVT::i32, Custom);
195 setOperationAction(ISD::SETCC, MVT::i64, Custom);
196 setOperationAction(ISD::SETCC, MVT::f16, Custom);
197 setOperationAction(ISD::SETCC, MVT::f32, Custom);
198 setOperationAction(ISD::SETCC, MVT::f64, Custom);
199 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
200 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
201 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
202 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
203 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
204 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
205 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
206 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
207 setOperationAction(ISD::SELECT, MVT::i32, Custom);
208 setOperationAction(ISD::SELECT, MVT::i64, Custom);
209 setOperationAction(ISD::SELECT, MVT::f16, Custom);
210 setOperationAction(ISD::SELECT, MVT::f32, Custom);
211 setOperationAction(ISD::SELECT, MVT::f64, Custom);
212 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
213 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
214 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
215 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
216 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
217 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
218 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
220 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
221 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
222 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
224 setOperationAction(ISD::FREM, MVT::f32, Expand);
225 setOperationAction(ISD::FREM, MVT::f64, Expand);
226 setOperationAction(ISD::FREM, MVT::f80, Expand);
228 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
230 // Custom lowering hooks are needed for XOR
231 // to fold it into CSINC/CSINV.
232 setOperationAction(ISD::XOR, MVT::i32, Custom);
233 setOperationAction(ISD::XOR, MVT::i64, Custom);
235 // Virtually no operation on f128 is legal, but LLVM can't expand them when
236 // there's a valid register class, so we need custom operations in most cases.
237 setOperationAction(ISD::FABS, MVT::f128, Expand);
238 setOperationAction(ISD::FADD, MVT::f128, Custom);
239 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
240 setOperationAction(ISD::FCOS, MVT::f128, Expand);
241 setOperationAction(ISD::FDIV, MVT::f128, Custom);
242 setOperationAction(ISD::FMA, MVT::f128, Expand);
243 setOperationAction(ISD::FMUL, MVT::f128, Custom);
244 setOperationAction(ISD::FNEG, MVT::f128, Expand);
245 setOperationAction(ISD::FPOW, MVT::f128, Expand);
246 setOperationAction(ISD::FREM, MVT::f128, Expand);
247 setOperationAction(ISD::FRINT, MVT::f128, Expand);
248 setOperationAction(ISD::FSIN, MVT::f128, Expand);
249 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
250 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
251 setOperationAction(ISD::FSUB, MVT::f128, Custom);
252 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
253 setOperationAction(ISD::SETCC, MVT::f128, Custom);
254 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
255 setOperationAction(ISD::SELECT, MVT::f128, Custom);
256 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
257 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
259 // Lowering for many of the conversions is actually specified by the non-f128
260 // type. The LowerXXX function will be trivial when f128 isn't involved.
261 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
262 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
264 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
265 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
266 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
267 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
268 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
269 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
270 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
272 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
273 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
274 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
276 // Variable arguments.
277 setOperationAction(ISD::VASTART, MVT::Other, Custom);
278 setOperationAction(ISD::VAARG, MVT::Other, Custom);
279 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
280 setOperationAction(ISD::VAEND, MVT::Other, Expand);
282 // Variable-sized objects.
283 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
284 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
286 if (Subtarget->isTargetWindows())
287 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
288 else
289 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
291 // Constant pool entries
292 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
294 // BlockAddress
295 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
297 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
298 setOperationAction(ISD::ADDC, MVT::i32, Custom);
299 setOperationAction(ISD::ADDE, MVT::i32, Custom);
300 setOperationAction(ISD::SUBC, MVT::i32, Custom);
301 setOperationAction(ISD::SUBE, MVT::i32, Custom);
302 setOperationAction(ISD::ADDC, MVT::i64, Custom);
303 setOperationAction(ISD::ADDE, MVT::i64, Custom);
304 setOperationAction(ISD::SUBC, MVT::i64, Custom);
305 setOperationAction(ISD::SUBE, MVT::i64, Custom);
307 // AArch64 lacks both left-rotate and popcount instructions.
308 setOperationAction(ISD::ROTL, MVT::i32, Expand);
309 setOperationAction(ISD::ROTL, MVT::i64, Expand);
310 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
311 setOperationAction(ISD::ROTL, VT, Expand);
312 setOperationAction(ISD::ROTR, VT, Expand);
315 // AArch64 doesn't have {U|S}MUL_LOHI.
316 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
317 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
319 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
320 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
322 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
323 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
324 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
325 setOperationAction(ISD::SDIVREM, VT, Expand);
326 setOperationAction(ISD::UDIVREM, VT, Expand);
328 setOperationAction(ISD::SREM, MVT::i32, Expand);
329 setOperationAction(ISD::SREM, MVT::i64, Expand);
330 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
331 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
332 setOperationAction(ISD::UREM, MVT::i32, Expand);
333 setOperationAction(ISD::UREM, MVT::i64, Expand);
335 // Custom lower Add/Sub/Mul with overflow.
336 setOperationAction(ISD::SADDO, MVT::i32, Custom);
337 setOperationAction(ISD::SADDO, MVT::i64, Custom);
338 setOperationAction(ISD::UADDO, MVT::i32, Custom);
339 setOperationAction(ISD::UADDO, MVT::i64, Custom);
340 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
341 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
342 setOperationAction(ISD::USUBO, MVT::i32, Custom);
343 setOperationAction(ISD::USUBO, MVT::i64, Custom);
344 setOperationAction(ISD::SMULO, MVT::i32, Custom);
345 setOperationAction(ISD::SMULO, MVT::i64, Custom);
346 setOperationAction(ISD::UMULO, MVT::i32, Custom);
347 setOperationAction(ISD::UMULO, MVT::i64, Custom);
349 setOperationAction(ISD::FSIN, MVT::f32, Expand);
350 setOperationAction(ISD::FSIN, MVT::f64, Expand);
351 setOperationAction(ISD::FCOS, MVT::f32, Expand);
352 setOperationAction(ISD::FCOS, MVT::f64, Expand);
353 setOperationAction(ISD::FPOW, MVT::f32, Expand);
354 setOperationAction(ISD::FPOW, MVT::f64, Expand);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
357 if (Subtarget->hasFullFP16())
358 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
359 else
360 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
362 setOperationAction(ISD::FREM, MVT::f16, Promote);
363 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
364 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
365 setOperationAction(ISD::FPOW, MVT::f16, Promote);
366 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
367 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
368 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
369 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
370 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
371 setOperationAction(ISD::FCOS, MVT::f16, Promote);
372 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
373 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
374 setOperationAction(ISD::FSIN, MVT::f16, Promote);
375 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
376 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
377 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
378 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
380 setOperationAction(ISD::FEXP, MVT::f16, Promote);
381 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
382 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
383 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
384 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
385 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
386 setOperationAction(ISD::FLOG, MVT::f16, Promote);
387 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
388 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
389 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
390 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
391 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
392 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
393 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
394 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
396 if (!Subtarget->hasFullFP16()) {
397 setOperationAction(ISD::SELECT, MVT::f16, Promote);
398 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
399 setOperationAction(ISD::SETCC, MVT::f16, Promote);
400 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
401 setOperationAction(ISD::FADD, MVT::f16, Promote);
402 setOperationAction(ISD::FSUB, MVT::f16, Promote);
403 setOperationAction(ISD::FMUL, MVT::f16, Promote);
404 setOperationAction(ISD::FDIV, MVT::f16, Promote);
405 setOperationAction(ISD::FMA, MVT::f16, Promote);
406 setOperationAction(ISD::FNEG, MVT::f16, Promote);
407 setOperationAction(ISD::FABS, MVT::f16, Promote);
408 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
409 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
410 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
411 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
412 setOperationAction(ISD::FRINT, MVT::f16, Promote);
413 setOperationAction(ISD::FROUND, MVT::f16, Promote);
414 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
415 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
416 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
417 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
418 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
420 // promote v4f16 to v4f32 when that is known to be safe.
421 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
422 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
423 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
424 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
425 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
426 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
427 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
428 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
429 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
430 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
431 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
432 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
434 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
435 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
436 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
437 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
438 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
439 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
440 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
441 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
442 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
443 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
444 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
445 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
446 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
447 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
448 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
450 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
451 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
452 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
453 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
454 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
455 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
456 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
457 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
458 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
459 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
460 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
461 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
462 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
463 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
464 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
465 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
466 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
467 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
468 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
469 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
472 // AArch64 has implementations of a lot of rounding-like FP operations.
473 for (MVT Ty : {MVT::f32, MVT::f64}) {
474 setOperationAction(ISD::FFLOOR, Ty, Legal);
475 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
476 setOperationAction(ISD::FCEIL, Ty, Legal);
477 setOperationAction(ISD::FRINT, Ty, Legal);
478 setOperationAction(ISD::FTRUNC, Ty, Legal);
479 setOperationAction(ISD::FROUND, Ty, Legal);
480 setOperationAction(ISD::FMINNUM, Ty, Legal);
481 setOperationAction(ISD::FMAXNUM, Ty, Legal);
482 setOperationAction(ISD::FMINIMUM, Ty, Legal);
483 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
484 setOperationAction(ISD::LROUND, Ty, Legal);
485 setOperationAction(ISD::LLROUND, Ty, Legal);
486 setOperationAction(ISD::LRINT, Ty, Legal);
487 setOperationAction(ISD::LLRINT, Ty, Legal);
490 if (Subtarget->hasFullFP16()) {
491 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
492 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
493 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
494 setOperationAction(ISD::FRINT, MVT::f16, Legal);
495 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
496 setOperationAction(ISD::FROUND, MVT::f16, Legal);
497 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
498 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
499 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
500 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
503 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
505 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
507 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
514 // This requires the Performance Monitors extension.
515 if (Subtarget->hasPerfMon())
516 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
518 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
519 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
520 // Issue __sincos_stret if available.
521 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
522 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
523 } else {
524 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
525 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
528 // Make floating-point constants legal for the large code model, so they don't
529 // become loads from the constant pool.
530 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
531 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
532 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
535 // AArch64 does not have floating-point extending loads, i1 sign-extending
536 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
537 for (MVT VT : MVT::fp_valuetypes()) {
538 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
539 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
540 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
541 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
543 for (MVT VT : MVT::integer_valuetypes())
544 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
546 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
547 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
548 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
549 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
550 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
551 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
552 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
554 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
555 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
557 // Indexed loads and stores are supported.
558 for (unsigned im = (unsigned)ISD::PRE_INC;
559 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
560 setIndexedLoadAction(im, MVT::i8, Legal);
561 setIndexedLoadAction(im, MVT::i16, Legal);
562 setIndexedLoadAction(im, MVT::i32, Legal);
563 setIndexedLoadAction(im, MVT::i64, Legal);
564 setIndexedLoadAction(im, MVT::f64, Legal);
565 setIndexedLoadAction(im, MVT::f32, Legal);
566 setIndexedLoadAction(im, MVT::f16, Legal);
567 setIndexedStoreAction(im, MVT::i8, Legal);
568 setIndexedStoreAction(im, MVT::i16, Legal);
569 setIndexedStoreAction(im, MVT::i32, Legal);
570 setIndexedStoreAction(im, MVT::i64, Legal);
571 setIndexedStoreAction(im, MVT::f64, Legal);
572 setIndexedStoreAction(im, MVT::f32, Legal);
573 setIndexedStoreAction(im, MVT::f16, Legal);
576 // Trap.
577 setOperationAction(ISD::TRAP, MVT::Other, Legal);
578 if (Subtarget->isTargetWindows())
579 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
581 // We combine OR nodes for bitfield operations.
582 setTargetDAGCombine(ISD::OR);
583 // Try to create BICs for vector ANDs.
584 setTargetDAGCombine(ISD::AND);
586 // Vector add and sub nodes may conceal a high-half opportunity.
587 // Also, try to fold ADD into CSINC/CSINV..
588 setTargetDAGCombine(ISD::ADD);
589 setTargetDAGCombine(ISD::SUB);
590 setTargetDAGCombine(ISD::SRL);
591 setTargetDAGCombine(ISD::XOR);
592 setTargetDAGCombine(ISD::SINT_TO_FP);
593 setTargetDAGCombine(ISD::UINT_TO_FP);
595 setTargetDAGCombine(ISD::FP_TO_SINT);
596 setTargetDAGCombine(ISD::FP_TO_UINT);
597 setTargetDAGCombine(ISD::FDIV);
599 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
601 setTargetDAGCombine(ISD::ANY_EXTEND);
602 setTargetDAGCombine(ISD::ZERO_EXTEND);
603 setTargetDAGCombine(ISD::SIGN_EXTEND);
604 setTargetDAGCombine(ISD::BITCAST);
605 setTargetDAGCombine(ISD::CONCAT_VECTORS);
606 setTargetDAGCombine(ISD::STORE);
607 if (Subtarget->supportsAddressTopByteIgnored())
608 setTargetDAGCombine(ISD::LOAD);
610 setTargetDAGCombine(ISD::MUL);
612 setTargetDAGCombine(ISD::SELECT);
613 setTargetDAGCombine(ISD::VSELECT);
615 setTargetDAGCombine(ISD::INTRINSIC_VOID);
616 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
617 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
619 setTargetDAGCombine(ISD::GlobalAddress);
621 // In case of strict alignment, avoid an excessive number of byte wide stores.
622 MaxStoresPerMemsetOptSize = 8;
623 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
624 ? MaxStoresPerMemsetOptSize : 32;
626 MaxGluedStoresPerMemcpy = 4;
627 MaxStoresPerMemcpyOptSize = 4;
628 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
629 ? MaxStoresPerMemcpyOptSize : 16;
631 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
633 MaxLoadsPerMemcmpOptSize = 4;
634 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
635 ? MaxLoadsPerMemcmpOptSize : 8;
637 setStackPointerRegisterToSaveRestore(AArch64::SP);
639 setSchedulingPreference(Sched::Hybrid);
641 EnableExtLdPromotion = true;
643 // Set required alignment.
644 setMinFunctionAlignment(Align(4));
645 // Set preferred alignments.
646 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
647 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
649 // Only change the limit for entries in a jump table if specified by
650 // the sub target, but not at the command line.
651 unsigned MaxJT = STI.getMaximumJumpTableSize();
652 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
653 setMaximumJumpTableSize(MaxJT);
655 setHasExtractBitsInsn(true);
657 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
659 if (Subtarget->hasNEON()) {
660 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
661 // silliness like this:
662 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
663 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
664 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
665 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
666 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
667 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
668 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
669 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
670 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
671 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
672 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
673 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
674 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
675 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
676 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
677 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
678 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
679 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
680 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
681 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
682 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
683 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
684 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
685 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
686 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
688 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
689 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
690 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
691 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
692 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
694 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
696 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
697 // elements smaller than i32, so promote the input to i32 first.
698 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
699 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
700 // i8 vector elements also need promotion to i32 for v8i8
701 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
702 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
703 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
704 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
705 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
706 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
707 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
708 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
709 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
710 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
711 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
713 if (Subtarget->hasFullFP16()) {
714 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
715 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
716 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
717 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
718 } else {
719 // when AArch64 doesn't have fullfp16 support, promote the input
720 // to i32 first.
721 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
722 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
723 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
724 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
727 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
728 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
730 // AArch64 doesn't have MUL.2d:
731 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
732 // Custom handling for some quad-vector types to detect MULL.
733 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
734 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
735 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
737 // Vector reductions
738 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
739 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
740 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
741 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
742 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
743 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
744 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
746 for (MVT VT : { MVT::v4f16, MVT::v2f32,
747 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
748 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
749 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
752 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
753 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
754 // Likewise, narrowing and extending vector loads/stores aren't handled
755 // directly.
756 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
757 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
759 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
760 setOperationAction(ISD::MULHS, VT, Legal);
761 setOperationAction(ISD::MULHU, VT, Legal);
762 } else {
763 setOperationAction(ISD::MULHS, VT, Expand);
764 setOperationAction(ISD::MULHU, VT, Expand);
766 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
767 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
769 setOperationAction(ISD::BSWAP, VT, Expand);
770 setOperationAction(ISD::CTTZ, VT, Expand);
772 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
773 setTruncStoreAction(VT, InnerVT, Expand);
774 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
775 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
776 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
780 // AArch64 has implementations of a lot of rounding-like FP operations.
781 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
782 setOperationAction(ISD::FFLOOR, Ty, Legal);
783 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
784 setOperationAction(ISD::FCEIL, Ty, Legal);
785 setOperationAction(ISD::FRINT, Ty, Legal);
786 setOperationAction(ISD::FTRUNC, Ty, Legal);
787 setOperationAction(ISD::FROUND, Ty, Legal);
790 if (Subtarget->hasFullFP16()) {
791 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
792 setOperationAction(ISD::FFLOOR, Ty, Legal);
793 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
794 setOperationAction(ISD::FCEIL, Ty, Legal);
795 setOperationAction(ISD::FRINT, Ty, Legal);
796 setOperationAction(ISD::FTRUNC, Ty, Legal);
797 setOperationAction(ISD::FROUND, Ty, Legal);
801 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
804 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
807 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
808 assert(VT.isVector() && "VT should be a vector type");
810 if (VT.isFloatingPoint()) {
811 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
812 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
813 setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
816 // Mark vector float intrinsics as expand.
817 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
818 setOperationAction(ISD::FSIN, VT, Expand);
819 setOperationAction(ISD::FCOS, VT, Expand);
820 setOperationAction(ISD::FPOW, VT, Expand);
821 setOperationAction(ISD::FLOG, VT, Expand);
822 setOperationAction(ISD::FLOG2, VT, Expand);
823 setOperationAction(ISD::FLOG10, VT, Expand);
824 setOperationAction(ISD::FEXP, VT, Expand);
825 setOperationAction(ISD::FEXP2, VT, Expand);
827 // But we do support custom-lowering for FCOPYSIGN.
828 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
833 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
834 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
835 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
836 setOperationAction(ISD::SRA, VT, Custom);
837 setOperationAction(ISD::SRL, VT, Custom);
838 setOperationAction(ISD::SHL, VT, Custom);
839 setOperationAction(ISD::OR, VT, Custom);
840 setOperationAction(ISD::SETCC, VT, Custom);
841 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
843 setOperationAction(ISD::SELECT, VT, Expand);
844 setOperationAction(ISD::SELECT_CC, VT, Expand);
845 setOperationAction(ISD::VSELECT, VT, Expand);
846 for (MVT InnerVT : MVT::all_valuetypes())
847 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
849 // CNT supports only B element sizes, then use UADDLP to widen.
850 if (VT != MVT::v8i8 && VT != MVT::v16i8)
851 setOperationAction(ISD::CTPOP, VT, Custom);
853 setOperationAction(ISD::UDIV, VT, Expand);
854 setOperationAction(ISD::SDIV, VT, Expand);
855 setOperationAction(ISD::UREM, VT, Expand);
856 setOperationAction(ISD::SREM, VT, Expand);
857 setOperationAction(ISD::FREM, VT, Expand);
859 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
860 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
862 if (!VT.isFloatingPoint())
863 setOperationAction(ISD::ABS, VT, Legal);
865 // [SU][MIN|MAX] are available for all NEON types apart from i64.
866 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
867 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
868 setOperationAction(Opcode, VT, Legal);
870 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
871 if (VT.isFloatingPoint() &&
872 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
873 for (unsigned Opcode :
874 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
875 setOperationAction(Opcode, VT, Legal);
877 if (Subtarget->isLittleEndian()) {
878 for (unsigned im = (unsigned)ISD::PRE_INC;
879 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
880 setIndexedLoadAction(im, VT, Legal);
881 setIndexedStoreAction(im, VT, Legal);
886 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
887 addRegisterClass(VT, &AArch64::FPR64RegClass);
888 addTypeForNEON(VT, MVT::v2i32);
891 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
892 addRegisterClass(VT, &AArch64::FPR128RegClass);
893 addTypeForNEON(VT, MVT::v4i32);
896 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
897 EVT VT) const {
898 if (!VT.isVector())
899 return MVT::i32;
900 return VT.changeVectorElementTypeToInteger();
903 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
904 const APInt &Demanded,
905 TargetLowering::TargetLoweringOpt &TLO,
906 unsigned NewOpc) {
907 uint64_t OldImm = Imm, NewImm, Enc;
908 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
910 // Return if the immediate is already all zeros, all ones, a bimm32 or a
911 // bimm64.
912 if (Imm == 0 || Imm == Mask ||
913 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
914 return false;
916 unsigned EltSize = Size;
917 uint64_t DemandedBits = Demanded.getZExtValue();
919 // Clear bits that are not demanded.
920 Imm &= DemandedBits;
922 while (true) {
923 // The goal here is to set the non-demanded bits in a way that minimizes
924 // the number of switching between 0 and 1. In order to achieve this goal,
925 // we set the non-demanded bits to the value of the preceding demanded bits.
926 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
927 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
928 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
929 // The final result is 0b11000011.
930 uint64_t NonDemandedBits = ~DemandedBits;
931 uint64_t InvertedImm = ~Imm & DemandedBits;
932 uint64_t RotatedImm =
933 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
934 NonDemandedBits;
935 uint64_t Sum = RotatedImm + NonDemandedBits;
936 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
937 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
938 NewImm = (Imm | Ones) & Mask;
940 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
941 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
942 // we halve the element size and continue the search.
943 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
944 break;
946 // We cannot shrink the element size any further if it is 2-bits.
947 if (EltSize == 2)
948 return false;
950 EltSize /= 2;
951 Mask >>= EltSize;
952 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
954 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
955 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
956 return false;
958 // Merge the upper and lower halves of Imm and DemandedBits.
959 Imm |= Hi;
960 DemandedBits |= DemandedBitsHi;
963 ++NumOptimizedImms;
965 // Replicate the element across the register width.
966 while (EltSize < Size) {
967 NewImm |= NewImm << EltSize;
968 EltSize *= 2;
971 (void)OldImm;
972 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
973 "demanded bits should never be altered");
974 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
976 // Create the new constant immediate node.
977 EVT VT = Op.getValueType();
978 SDLoc DL(Op);
979 SDValue New;
981 // If the new constant immediate is all-zeros or all-ones, let the target
982 // independent DAG combine optimize this node.
983 if (NewImm == 0 || NewImm == OrigMask) {
984 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
985 TLO.DAG.getConstant(NewImm, DL, VT));
986 // Otherwise, create a machine node so that target independent DAG combine
987 // doesn't undo this optimization.
988 } else {
989 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
990 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
991 New = SDValue(
992 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
995 return TLO.CombineTo(Op, New);
998 bool AArch64TargetLowering::targetShrinkDemandedConstant(
999 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
1000 // Delay this optimization to as late as possible.
1001 if (!TLO.LegalOps)
1002 return false;
1004 if (!EnableOptimizeLogicalImm)
1005 return false;
1007 EVT VT = Op.getValueType();
1008 if (VT.isVector())
1009 return false;
1011 unsigned Size = VT.getSizeInBits();
1012 assert((Size == 32 || Size == 64) &&
1013 "i32 or i64 is expected after legalization.");
1015 // Exit early if we demand all bits.
1016 if (Demanded.countPopulation() == Size)
1017 return false;
1019 unsigned NewOpc;
1020 switch (Op.getOpcode()) {
1021 default:
1022 return false;
1023 case ISD::AND:
1024 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
1025 break;
1026 case ISD::OR:
1027 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
1028 break;
1029 case ISD::XOR:
1030 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
1031 break;
1033 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
1034 if (!C)
1035 return false;
1036 uint64_t Imm = C->getZExtValue();
1037 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
1040 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1041 /// Mask are known to be either zero or one and return them Known.
1042 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1043 const SDValue Op, KnownBits &Known,
1044 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
1045 switch (Op.getOpcode()) {
1046 default:
1047 break;
1048 case AArch64ISD::CSEL: {
1049 KnownBits Known2;
1050 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
1051 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
1052 Known.Zero &= Known2.Zero;
1053 Known.One &= Known2.One;
1054 break;
1056 case AArch64ISD::LOADgot:
1057 case AArch64ISD::ADDlow: {
1058 if (!Subtarget->isTargetILP32())
1059 break;
1060 // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
1061 Known.Zero = APInt::getHighBitsSet(64, 32);
1062 break;
1064 case ISD::INTRINSIC_W_CHAIN: {
1065 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1066 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1067 switch (IntID) {
1068 default: return;
1069 case Intrinsic::aarch64_ldaxr:
1070 case Intrinsic::aarch64_ldxr: {
1071 unsigned BitWidth = Known.getBitWidth();
1072 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1073 unsigned MemBits = VT.getScalarSizeInBits();
1074 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1075 return;
1078 break;
1080 case ISD::INTRINSIC_WO_CHAIN:
1081 case ISD::INTRINSIC_VOID: {
1082 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1083 switch (IntNo) {
1084 default:
1085 break;
1086 case Intrinsic::aarch64_neon_umaxv:
1087 case Intrinsic::aarch64_neon_uminv: {
1088 // Figure out the datatype of the vector operand. The UMINV instruction
1089 // will zero extend the result, so we can mark as known zero all the
1090 // bits larger than the element datatype. 32-bit or larget doesn't need
1091 // this as those are legal types and will be handled by isel directly.
1092 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1093 unsigned BitWidth = Known.getBitWidth();
1094 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1095 assert(BitWidth >= 8 && "Unexpected width!");
1096 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1097 Known.Zero |= Mask;
1098 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1099 assert(BitWidth >= 16 && "Unexpected width!");
1100 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1101 Known.Zero |= Mask;
1103 break;
1104 } break;
1110 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1111 EVT) const {
1112 return MVT::i64;
1115 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1116 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1117 bool *Fast) const {
1118 if (Subtarget->requiresStrictAlign())
1119 return false;
1121 if (Fast) {
1122 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1123 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1124 // See comments in performSTORECombine() for more details about
1125 // these conditions.
1127 // Code that uses clang vector extensions can mark that it
1128 // wants unaligned accesses to be treated as fast by
1129 // underspecifying alignment to be 1 or 2.
1130 Align <= 2 ||
1132 // Disregard v2i64. Memcpy lowering produces those and splitting
1133 // them regresses performance on micro-benchmarks and olden/bh.
1134 VT == MVT::v2i64;
1136 return true;
1139 // Same as above but handling LLTs instead.
1140 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1141 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1142 bool *Fast) const {
1143 if (Subtarget->requiresStrictAlign())
1144 return false;
1146 if (Fast) {
1147 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1148 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1149 Ty.getSizeInBytes() != 16 ||
1150 // See comments in performSTORECombine() for more details about
1151 // these conditions.
1153 // Code that uses clang vector extensions can mark that it
1154 // wants unaligned accesses to be treated as fast by
1155 // underspecifying alignment to be 1 or 2.
1156 Align <= 2 ||
1158 // Disregard v2i64. Memcpy lowering produces those and splitting
1159 // them regresses performance on micro-benchmarks and olden/bh.
1160 Ty == LLT::vector(2, 64);
1162 return true;
1165 FastISel *
1166 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1167 const TargetLibraryInfo *libInfo) const {
1168 return AArch64::createFastISel(funcInfo, libInfo);
1171 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1172 switch ((AArch64ISD::NodeType)Opcode) {
1173 case AArch64ISD::FIRST_NUMBER: break;
1174 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1175 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1176 case AArch64ISD::ADR: return "AArch64ISD::ADR";
1177 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1178 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1179 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1180 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1181 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1182 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1183 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1184 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1185 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1186 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1187 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1188 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1189 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1190 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1191 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1192 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1193 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1194 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1195 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1196 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1197 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1198 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1199 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1200 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1201 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1202 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1203 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1204 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1205 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1206 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1207 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1208 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1209 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1210 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1211 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1212 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1213 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1214 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1215 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1216 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1217 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1218 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1219 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1220 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1221 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1222 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1223 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1224 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1225 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1226 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1227 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1228 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1229 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1230 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1231 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1232 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1233 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1234 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1235 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1236 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1237 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1238 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1239 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1240 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1241 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1242 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1243 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1244 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1245 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1246 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1247 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1248 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1249 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1250 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1251 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1252 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1253 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1254 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1255 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1256 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1257 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1258 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1259 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1260 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1261 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1262 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1263 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1264 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1265 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1266 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1267 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1268 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1269 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1270 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1271 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1272 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1273 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1274 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1275 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1276 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1277 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1278 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1279 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1280 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1281 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1282 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1283 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1284 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1285 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1286 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1287 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1288 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1289 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1290 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1291 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1292 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1293 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1294 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1295 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1296 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1297 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1298 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1299 case AArch64ISD::STG: return "AArch64ISD::STG";
1300 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1301 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1302 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
1304 return nullptr;
1307 MachineBasicBlock *
1308 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1309 MachineBasicBlock *MBB) const {
1310 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1311 // phi node:
1313 // OrigBB:
1314 // [... previous instrs leading to comparison ...]
1315 // b.ne TrueBB
1316 // b EndBB
1317 // TrueBB:
1318 // ; Fallthrough
1319 // EndBB:
1320 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1322 MachineFunction *MF = MBB->getParent();
1323 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1324 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1325 DebugLoc DL = MI.getDebugLoc();
1326 MachineFunction::iterator It = ++MBB->getIterator();
1328 Register DestReg = MI.getOperand(0).getReg();
1329 Register IfTrueReg = MI.getOperand(1).getReg();
1330 Register IfFalseReg = MI.getOperand(2).getReg();
1331 unsigned CondCode = MI.getOperand(3).getImm();
1332 bool NZCVKilled = MI.getOperand(4).isKill();
1334 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1335 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1336 MF->insert(It, TrueBB);
1337 MF->insert(It, EndBB);
1339 // Transfer rest of current basic-block to EndBB
1340 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1341 MBB->end());
1342 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1344 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1345 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1346 MBB->addSuccessor(TrueBB);
1347 MBB->addSuccessor(EndBB);
1349 // TrueBB falls through to the end.
1350 TrueBB->addSuccessor(EndBB);
1352 if (!NZCVKilled) {
1353 TrueBB->addLiveIn(AArch64::NZCV);
1354 EndBB->addLiveIn(AArch64::NZCV);
1357 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1358 .addReg(IfTrueReg)
1359 .addMBB(TrueBB)
1360 .addReg(IfFalseReg)
1361 .addMBB(MBB);
1363 MI.eraseFromParent();
1364 return EndBB;
1367 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1368 MachineInstr &MI, MachineBasicBlock *BB) const {
1369 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1370 BB->getParent()->getFunction().getPersonalityFn())) &&
1371 "SEH does not use catchret!");
1372 return BB;
1375 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1376 MachineInstr &MI, MachineBasicBlock *BB) const {
1377 MI.eraseFromParent();
1378 return BB;
1381 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1382 MachineInstr &MI, MachineBasicBlock *BB) const {
1383 switch (MI.getOpcode()) {
1384 default:
1385 #ifndef NDEBUG
1386 MI.dump();
1387 #endif
1388 llvm_unreachable("Unexpected instruction for custom inserter!");
1390 case AArch64::F128CSEL:
1391 return EmitF128CSEL(MI, BB);
1393 case TargetOpcode::STACKMAP:
1394 case TargetOpcode::PATCHPOINT:
1395 return emitPatchPoint(MI, BB);
1397 case AArch64::CATCHRET:
1398 return EmitLoweredCatchRet(MI, BB);
1399 case AArch64::CATCHPAD:
1400 return EmitLoweredCatchPad(MI, BB);
1404 //===----------------------------------------------------------------------===//
1405 // AArch64 Lowering private implementation.
1406 //===----------------------------------------------------------------------===//
1408 //===----------------------------------------------------------------------===//
1409 // Lowering Code
1410 //===----------------------------------------------------------------------===//
1412 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1413 /// CC
1414 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1415 switch (CC) {
1416 default:
1417 llvm_unreachable("Unknown condition code!");
1418 case ISD::SETNE:
1419 return AArch64CC::NE;
1420 case ISD::SETEQ:
1421 return AArch64CC::EQ;
1422 case ISD::SETGT:
1423 return AArch64CC::GT;
1424 case ISD::SETGE:
1425 return AArch64CC::GE;
1426 case ISD::SETLT:
1427 return AArch64CC::LT;
1428 case ISD::SETLE:
1429 return AArch64CC::LE;
1430 case ISD::SETUGT:
1431 return AArch64CC::HI;
1432 case ISD::SETUGE:
1433 return AArch64CC::HS;
1434 case ISD::SETULT:
1435 return AArch64CC::LO;
1436 case ISD::SETULE:
1437 return AArch64CC::LS;
1441 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1442 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1443 AArch64CC::CondCode &CondCode,
1444 AArch64CC::CondCode &CondCode2) {
1445 CondCode2 = AArch64CC::AL;
1446 switch (CC) {
1447 default:
1448 llvm_unreachable("Unknown FP condition!");
1449 case ISD::SETEQ:
1450 case ISD::SETOEQ:
1451 CondCode = AArch64CC::EQ;
1452 break;
1453 case ISD::SETGT:
1454 case ISD::SETOGT:
1455 CondCode = AArch64CC::GT;
1456 break;
1457 case ISD::SETGE:
1458 case ISD::SETOGE:
1459 CondCode = AArch64CC::GE;
1460 break;
1461 case ISD::SETOLT:
1462 CondCode = AArch64CC::MI;
1463 break;
1464 case ISD::SETOLE:
1465 CondCode = AArch64CC::LS;
1466 break;
1467 case ISD::SETONE:
1468 CondCode = AArch64CC::MI;
1469 CondCode2 = AArch64CC::GT;
1470 break;
1471 case ISD::SETO:
1472 CondCode = AArch64CC::VC;
1473 break;
1474 case ISD::SETUO:
1475 CondCode = AArch64CC::VS;
1476 break;
1477 case ISD::SETUEQ:
1478 CondCode = AArch64CC::EQ;
1479 CondCode2 = AArch64CC::VS;
1480 break;
1481 case ISD::SETUGT:
1482 CondCode = AArch64CC::HI;
1483 break;
1484 case ISD::SETUGE:
1485 CondCode = AArch64CC::PL;
1486 break;
1487 case ISD::SETLT:
1488 case ISD::SETULT:
1489 CondCode = AArch64CC::LT;
1490 break;
1491 case ISD::SETLE:
1492 case ISD::SETULE:
1493 CondCode = AArch64CC::LE;
1494 break;
1495 case ISD::SETNE:
1496 case ISD::SETUNE:
1497 CondCode = AArch64CC::NE;
1498 break;
1502 /// Convert a DAG fp condition code to an AArch64 CC.
1503 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1504 /// should be AND'ed instead of OR'ed.
1505 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1506 AArch64CC::CondCode &CondCode,
1507 AArch64CC::CondCode &CondCode2) {
1508 CondCode2 = AArch64CC::AL;
1509 switch (CC) {
1510 default:
1511 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1512 assert(CondCode2 == AArch64CC::AL);
1513 break;
1514 case ISD::SETONE:
1515 // (a one b)
1516 // == ((a olt b) || (a ogt b))
1517 // == ((a ord b) && (a une b))
1518 CondCode = AArch64CC::VC;
1519 CondCode2 = AArch64CC::NE;
1520 break;
1521 case ISD::SETUEQ:
1522 // (a ueq b)
1523 // == ((a uno b) || (a oeq b))
1524 // == ((a ule b) && (a uge b))
1525 CondCode = AArch64CC::PL;
1526 CondCode2 = AArch64CC::LE;
1527 break;
1531 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1532 /// CC usable with the vector instructions. Fewer operations are available
1533 /// without a real NZCV register, so we have to use less efficient combinations
1534 /// to get the same effect.
1535 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1536 AArch64CC::CondCode &CondCode,
1537 AArch64CC::CondCode &CondCode2,
1538 bool &Invert) {
1539 Invert = false;
1540 switch (CC) {
1541 default:
1542 // Mostly the scalar mappings work fine.
1543 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1544 break;
1545 case ISD::SETUO:
1546 Invert = true;
1547 LLVM_FALLTHROUGH;
1548 case ISD::SETO:
1549 CondCode = AArch64CC::MI;
1550 CondCode2 = AArch64CC::GE;
1551 break;
1552 case ISD::SETUEQ:
1553 case ISD::SETULT:
1554 case ISD::SETULE:
1555 case ISD::SETUGT:
1556 case ISD::SETUGE:
1557 // All of the compare-mask comparisons are ordered, but we can switch
1558 // between the two by a double inversion. E.g. ULE == !OGT.
1559 Invert = true;
1560 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1561 break;
1565 static bool isLegalArithImmed(uint64_t C) {
1566 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1567 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1568 LLVM_DEBUG(dbgs() << "Is imm " << C
1569 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1570 return IsLegal;
1573 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1574 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1575 // can be set differently by this operation. It comes down to whether
1576 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1577 // everything is fine. If not then the optimization is wrong. Thus general
1578 // comparisons are only valid if op2 != 0.
1580 // So, finally, the only LLVM-native comparisons that don't mention C and V
1581 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1582 // the absence of information about op2.
1583 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1584 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1585 (CC == ISD::SETEQ || CC == ISD::SETNE);
1588 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1589 const SDLoc &dl, SelectionDAG &DAG) {
1590 EVT VT = LHS.getValueType();
1591 const bool FullFP16 =
1592 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1594 if (VT.isFloatingPoint()) {
1595 assert(VT != MVT::f128);
1596 if (VT == MVT::f16 && !FullFP16) {
1597 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1598 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1599 VT = MVT::f32;
1601 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1604 // The CMP instruction is just an alias for SUBS, and representing it as
1605 // SUBS means that it's possible to get CSE with subtract operations.
1606 // A later phase can perform the optimization of setting the destination
1607 // register to WZR/XZR if it ends up being unused.
1608 unsigned Opcode = AArch64ISD::SUBS;
1610 if (isCMN(RHS, CC)) {
1611 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1612 Opcode = AArch64ISD::ADDS;
1613 RHS = RHS.getOperand(1);
1614 } else if (isCMN(LHS, CC)) {
1615 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1616 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1617 Opcode = AArch64ISD::ADDS;
1618 LHS = LHS.getOperand(1);
1619 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1620 !isUnsignedIntSetCC(CC)) {
1621 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1622 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1623 // of the signed comparisons.
1624 Opcode = AArch64ISD::ANDS;
1625 RHS = LHS.getOperand(1);
1626 LHS = LHS.getOperand(0);
1629 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1630 .getValue(1);
1633 /// \defgroup AArch64CCMP CMP;CCMP matching
1635 /// These functions deal with the formation of CMP;CCMP;... sequences.
1636 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1637 /// a comparison. They set the NZCV flags to a predefined value if their
1638 /// predicate is false. This allows to express arbitrary conjunctions, for
1639 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1640 /// expressed as:
1641 /// cmp A
1642 /// ccmp B, inv(CB), CA
1643 /// check for CB flags
1645 /// This naturally lets us implement chains of AND operations with SETCC
1646 /// operands. And we can even implement some other situations by transforming
1647 /// them:
1648 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1649 /// negating the flags used in a CCMP/FCCMP operations.
1650 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1651 /// by negating the flags we test for afterwards. i.e.
1652 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1653 /// - Note that we can only ever negate all previously processed results.
1654 /// What we can not implement by flipping the flags to test is a negation
1655 /// of two sub-trees (because the negation affects all sub-trees emitted so
1656 /// far, so the 2nd sub-tree we emit would also affect the first).
1657 /// With those tools we can implement some OR operations:
1658 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1659 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1660 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1661 /// elimination rules from earlier to implement the whole thing as a
1662 /// CCMP/FCCMP chain.
1664 /// As complete example:
1665 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1666 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1667 /// can be reassociated to:
1668 /// or (and (setCC (cmp C)) setCD (cmp D))
1669 // (or (setCA (cmp A)) (setCB (cmp B)))
1670 /// can be transformed to:
1671 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1672 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1673 /// which can be implemented as:
1674 /// cmp C
1675 /// ccmp D, inv(CD), CC
1676 /// ccmp A, CA, inv(CD)
1677 /// ccmp B, CB, inv(CA)
1678 /// check for CB flags
1680 /// A counterexample is "or (and A B) (and C D)" which translates to
1681 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1682 /// can only implement 1 of the inner (not) operations, but not both!
1683 /// @{
1685 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1686 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1687 ISD::CondCode CC, SDValue CCOp,
1688 AArch64CC::CondCode Predicate,
1689 AArch64CC::CondCode OutCC,
1690 const SDLoc &DL, SelectionDAG &DAG) {
1691 unsigned Opcode = 0;
1692 const bool FullFP16 =
1693 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1695 if (LHS.getValueType().isFloatingPoint()) {
1696 assert(LHS.getValueType() != MVT::f128);
1697 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1698 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1699 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1701 Opcode = AArch64ISD::FCCMP;
1702 } else if (RHS.getOpcode() == ISD::SUB) {
1703 SDValue SubOp0 = RHS.getOperand(0);
1704 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1705 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1706 Opcode = AArch64ISD::CCMN;
1707 RHS = RHS.getOperand(1);
1710 if (Opcode == 0)
1711 Opcode = AArch64ISD::CCMP;
1713 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1714 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1715 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1716 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1717 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1720 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1721 /// expressed as a conjunction. See \ref AArch64CCMP.
1722 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1723 /// changing the conditions on the SETCC tests.
1724 /// (this means we can call emitConjunctionRec() with
1725 /// Negate==true on this sub-tree)
1726 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1727 /// cannot do the negation naturally. We are required to
1728 /// emit the subtree first in this case.
1729 /// \param WillNegate Is true if are called when the result of this
1730 /// subexpression must be negated. This happens when the
1731 /// outer expression is an OR. We can use this fact to know
1732 /// that we have a double negation (or (or ...) ...) that
1733 /// can be implemented for free.
1734 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1735 bool &MustBeFirst, bool WillNegate,
1736 unsigned Depth = 0) {
1737 if (!Val.hasOneUse())
1738 return false;
1739 unsigned Opcode = Val->getOpcode();
1740 if (Opcode == ISD::SETCC) {
1741 if (Val->getOperand(0).getValueType() == MVT::f128)
1742 return false;
1743 CanNegate = true;
1744 MustBeFirst = false;
1745 return true;
1747 // Protect against exponential runtime and stack overflow.
1748 if (Depth > 6)
1749 return false;
1750 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1751 bool IsOR = Opcode == ISD::OR;
1752 SDValue O0 = Val->getOperand(0);
1753 SDValue O1 = Val->getOperand(1);
1754 bool CanNegateL;
1755 bool MustBeFirstL;
1756 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1757 return false;
1758 bool CanNegateR;
1759 bool MustBeFirstR;
1760 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1761 return false;
1763 if (MustBeFirstL && MustBeFirstR)
1764 return false;
1766 if (IsOR) {
1767 // For an OR expression we need to be able to naturally negate at least
1768 // one side or we cannot do the transformation at all.
1769 if (!CanNegateL && !CanNegateR)
1770 return false;
1771 // If we the result of the OR will be negated and we can naturally negate
1772 // the leafs, then this sub-tree as a whole negates naturally.
1773 CanNegate = WillNegate && CanNegateL && CanNegateR;
1774 // If we cannot naturally negate the whole sub-tree, then this must be
1775 // emitted first.
1776 MustBeFirst = !CanNegate;
1777 } else {
1778 assert(Opcode == ISD::AND && "Must be OR or AND");
1779 // We cannot naturally negate an AND operation.
1780 CanNegate = false;
1781 MustBeFirst = MustBeFirstL || MustBeFirstR;
1783 return true;
1785 return false;
1788 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1789 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1790 /// Tries to transform the given i1 producing node @p Val to a series compare
1791 /// and conditional compare operations. @returns an NZCV flags producing node
1792 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1793 /// transformation was not possible.
1794 /// \p Negate is true if we want this sub-tree being negated just by changing
1795 /// SETCC conditions.
1796 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1797 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1798 AArch64CC::CondCode Predicate) {
1799 // We're at a tree leaf, produce a conditional comparison operation.
1800 unsigned Opcode = Val->getOpcode();
1801 if (Opcode == ISD::SETCC) {
1802 SDValue LHS = Val->getOperand(0);
1803 SDValue RHS = Val->getOperand(1);
1804 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1805 bool isInteger = LHS.getValueType().isInteger();
1806 if (Negate)
1807 CC = getSetCCInverse(CC, isInteger);
1808 SDLoc DL(Val);
1809 // Determine OutCC and handle FP special case.
1810 if (isInteger) {
1811 OutCC = changeIntCCToAArch64CC(CC);
1812 } else {
1813 assert(LHS.getValueType().isFloatingPoint());
1814 AArch64CC::CondCode ExtraCC;
1815 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1816 // Some floating point conditions can't be tested with a single condition
1817 // code. Construct an additional comparison in this case.
1818 if (ExtraCC != AArch64CC::AL) {
1819 SDValue ExtraCmp;
1820 if (!CCOp.getNode())
1821 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1822 else
1823 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1824 ExtraCC, DL, DAG);
1825 CCOp = ExtraCmp;
1826 Predicate = ExtraCC;
1830 // Produce a normal comparison if we are first in the chain
1831 if (!CCOp)
1832 return emitComparison(LHS, RHS, CC, DL, DAG);
1833 // Otherwise produce a ccmp.
1834 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1835 DAG);
1837 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1839 bool IsOR = Opcode == ISD::OR;
1841 SDValue LHS = Val->getOperand(0);
1842 bool CanNegateL;
1843 bool MustBeFirstL;
1844 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1845 assert(ValidL && "Valid conjunction/disjunction tree");
1846 (void)ValidL;
1848 SDValue RHS = Val->getOperand(1);
1849 bool CanNegateR;
1850 bool MustBeFirstR;
1851 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1852 assert(ValidR && "Valid conjunction/disjunction tree");
1853 (void)ValidR;
1855 // Swap sub-tree that must come first to the right side.
1856 if (MustBeFirstL) {
1857 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1858 std::swap(LHS, RHS);
1859 std::swap(CanNegateL, CanNegateR);
1860 std::swap(MustBeFirstL, MustBeFirstR);
1863 bool NegateR;
1864 bool NegateAfterR;
1865 bool NegateL;
1866 bool NegateAfterAll;
1867 if (Opcode == ISD::OR) {
1868 // Swap the sub-tree that we can negate naturally to the left.
1869 if (!CanNegateL) {
1870 assert(CanNegateR && "at least one side must be negatable");
1871 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1872 assert(!Negate);
1873 std::swap(LHS, RHS);
1874 NegateR = false;
1875 NegateAfterR = true;
1876 } else {
1877 // Negate the left sub-tree if possible, otherwise negate the result.
1878 NegateR = CanNegateR;
1879 NegateAfterR = !CanNegateR;
1881 NegateL = true;
1882 NegateAfterAll = !Negate;
1883 } else {
1884 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1885 assert(!Negate && "Valid conjunction/disjunction tree");
1887 NegateL = false;
1888 NegateR = false;
1889 NegateAfterR = false;
1890 NegateAfterAll = false;
1893 // Emit sub-trees.
1894 AArch64CC::CondCode RHSCC;
1895 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1896 if (NegateAfterR)
1897 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1898 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1899 if (NegateAfterAll)
1900 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1901 return CmpL;
1904 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1905 /// In some cases this is even possible with OR operations in the expression.
1906 /// See \ref AArch64CCMP.
1907 /// \see emitConjunctionRec().
1908 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1909 AArch64CC::CondCode &OutCC) {
1910 bool DummyCanNegate;
1911 bool DummyMustBeFirst;
1912 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1913 return SDValue();
1915 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1918 /// @}
1920 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1921 /// extension operations.
1922 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1923 auto isSupportedExtend = [&](SDValue V) {
1924 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1925 return true;
1927 if (V.getOpcode() == ISD::AND)
1928 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1929 uint64_t Mask = MaskCst->getZExtValue();
1930 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1933 return false;
1936 if (!Op.hasOneUse())
1937 return 0;
1939 if (isSupportedExtend(Op))
1940 return 1;
1942 unsigned Opc = Op.getOpcode();
1943 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1944 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1945 uint64_t Shift = ShiftCst->getZExtValue();
1946 if (isSupportedExtend(Op.getOperand(0)))
1947 return (Shift <= 4) ? 2 : 1;
1948 EVT VT = Op.getValueType();
1949 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1950 return 1;
1953 return 0;
1956 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1957 SDValue &AArch64cc, SelectionDAG &DAG,
1958 const SDLoc &dl) {
1959 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1960 EVT VT = RHS.getValueType();
1961 uint64_t C = RHSC->getZExtValue();
1962 if (!isLegalArithImmed(C)) {
1963 // Constant does not fit, try adjusting it by one?
1964 switch (CC) {
1965 default:
1966 break;
1967 case ISD::SETLT:
1968 case ISD::SETGE:
1969 if ((VT == MVT::i32 && C != 0x80000000 &&
1970 isLegalArithImmed((uint32_t)(C - 1))) ||
1971 (VT == MVT::i64 && C != 0x80000000ULL &&
1972 isLegalArithImmed(C - 1ULL))) {
1973 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1974 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1975 RHS = DAG.getConstant(C, dl, VT);
1977 break;
1978 case ISD::SETULT:
1979 case ISD::SETUGE:
1980 if ((VT == MVT::i32 && C != 0 &&
1981 isLegalArithImmed((uint32_t)(C - 1))) ||
1982 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1983 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1984 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1985 RHS = DAG.getConstant(C, dl, VT);
1987 break;
1988 case ISD::SETLE:
1989 case ISD::SETGT:
1990 if ((VT == MVT::i32 && C != INT32_MAX &&
1991 isLegalArithImmed((uint32_t)(C + 1))) ||
1992 (VT == MVT::i64 && C != INT64_MAX &&
1993 isLegalArithImmed(C + 1ULL))) {
1994 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1995 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1996 RHS = DAG.getConstant(C, dl, VT);
1998 break;
1999 case ISD::SETULE:
2000 case ISD::SETUGT:
2001 if ((VT == MVT::i32 && C != UINT32_MAX &&
2002 isLegalArithImmed((uint32_t)(C + 1))) ||
2003 (VT == MVT::i64 && C != UINT64_MAX &&
2004 isLegalArithImmed(C + 1ULL))) {
2005 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2006 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
2007 RHS = DAG.getConstant(C, dl, VT);
2009 break;
2014 // Comparisons are canonicalized so that the RHS operand is simpler than the
2015 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2016 // can fold some shift+extend operations on the RHS operand, so swap the
2017 // operands if that can be done.
2019 // For example:
2020 // lsl w13, w11, #1
2021 // cmp w13, w12
2022 // can be turned into:
2023 // cmp w12, w11, lsl #1
2024 if (!isa<ConstantSDNode>(RHS) ||
2025 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2026 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2028 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2029 std::swap(LHS, RHS);
2030 CC = ISD::getSetCCSwappedOperands(CC);
2034 SDValue Cmp;
2035 AArch64CC::CondCode AArch64CC;
2036 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2037 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2039 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2040 // For the i8 operand, the largest immediate is 255, so this can be easily
2041 // encoded in the compare instruction. For the i16 operand, however, the
2042 // largest immediate cannot be encoded in the compare.
2043 // Therefore, use a sign extending load and cmn to avoid materializing the
2044 // -1 constant. For example,
2045 // movz w1, #65535
2046 // ldrh w0, [x0, #0]
2047 // cmp w0, w1
2048 // >
2049 // ldrsh w0, [x0, #0]
2050 // cmn w0, #1
2051 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2052 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2053 // ensure both the LHS and RHS are truly zero extended and to make sure the
2054 // transformation is profitable.
2055 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2056 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2057 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2058 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2059 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2060 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2061 SDValue SExt =
2062 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2063 DAG.getValueType(MVT::i16));
2064 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2065 RHS.getValueType()),
2066 CC, dl, DAG);
2067 AArch64CC = changeIntCCToAArch64CC(CC);
2071 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2072 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2073 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2074 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2079 if (!Cmp) {
2080 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2081 AArch64CC = changeIntCCToAArch64CC(CC);
2083 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2084 return Cmp;
2087 static std::pair<SDValue, SDValue>
2088 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2089 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2090 "Unsupported value type");
2091 SDValue Value, Overflow;
2092 SDLoc DL(Op);
2093 SDValue LHS = Op.getOperand(0);
2094 SDValue RHS = Op.getOperand(1);
2095 unsigned Opc = 0;
2096 switch (Op.getOpcode()) {
2097 default:
2098 llvm_unreachable("Unknown overflow instruction!");
2099 case ISD::SADDO:
2100 Opc = AArch64ISD::ADDS;
2101 CC = AArch64CC::VS;
2102 break;
2103 case ISD::UADDO:
2104 Opc = AArch64ISD::ADDS;
2105 CC = AArch64CC::HS;
2106 break;
2107 case ISD::SSUBO:
2108 Opc = AArch64ISD::SUBS;
2109 CC = AArch64CC::VS;
2110 break;
2111 case ISD::USUBO:
2112 Opc = AArch64ISD::SUBS;
2113 CC = AArch64CC::LO;
2114 break;
2115 // Multiply needs a little bit extra work.
2116 case ISD::SMULO:
2117 case ISD::UMULO: {
2118 CC = AArch64CC::NE;
2119 bool IsSigned = Op.getOpcode() == ISD::SMULO;
2120 if (Op.getValueType() == MVT::i32) {
2121 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2122 // For a 32 bit multiply with overflow check we want the instruction
2123 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2124 // need to generate the following pattern:
2125 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2126 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2127 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2128 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2129 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2130 DAG.getConstant(0, DL, MVT::i64));
2131 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2132 // operation. We need to clear out the upper 32 bits, because we used a
2133 // widening multiply that wrote all 64 bits. In the end this should be a
2134 // noop.
2135 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2136 if (IsSigned) {
2137 // The signed overflow check requires more than just a simple check for
2138 // any bit set in the upper 32 bits of the result. These bits could be
2139 // just the sign bits of a negative number. To perform the overflow
2140 // check we have to arithmetic shift right the 32nd bit of the result by
2141 // 31 bits. Then we compare the result to the upper 32 bits.
2142 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2143 DAG.getConstant(32, DL, MVT::i64));
2144 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2145 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2146 DAG.getConstant(31, DL, MVT::i64));
2147 // It is important that LowerBits is last, otherwise the arithmetic
2148 // shift will not be folded into the compare (SUBS).
2149 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2150 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2151 .getValue(1);
2152 } else {
2153 // The overflow check for unsigned multiply is easy. We only need to
2154 // check if any of the upper 32 bits are set. This can be done with a
2155 // CMP (shifted register). For that we need to generate the following
2156 // pattern:
2157 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2158 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2159 DAG.getConstant(32, DL, MVT::i64));
2160 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2161 Overflow =
2162 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2163 DAG.getConstant(0, DL, MVT::i64),
2164 UpperBits).getValue(1);
2166 break;
2168 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2169 // For the 64 bit multiply
2170 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2171 if (IsSigned) {
2172 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2173 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2174 DAG.getConstant(63, DL, MVT::i64));
2175 // It is important that LowerBits is last, otherwise the arithmetic
2176 // shift will not be folded into the compare (SUBS).
2177 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2178 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2179 .getValue(1);
2180 } else {
2181 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2182 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2183 Overflow =
2184 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2185 DAG.getConstant(0, DL, MVT::i64),
2186 UpperBits).getValue(1);
2188 break;
2190 } // switch (...)
2192 if (Opc) {
2193 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2195 // Emit the AArch64 operation with overflow check.
2196 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2197 Overflow = Value.getValue(1);
2199 return std::make_pair(Value, Overflow);
2202 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2203 RTLIB::Libcall Call) const {
2204 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2205 MakeLibCallOptions CallOptions;
2206 return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
2209 // Returns true if the given Op is the overflow flag result of an overflow
2210 // intrinsic operation.
2211 static bool isOverflowIntrOpRes(SDValue Op) {
2212 unsigned Opc = Op.getOpcode();
2213 return (Op.getResNo() == 1 &&
2214 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2215 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2218 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2219 SDValue Sel = Op.getOperand(0);
2220 SDValue Other = Op.getOperand(1);
2221 SDLoc dl(Sel);
2223 // If the operand is an overflow checking operation, invert the condition
2224 // code and kill the Not operation. I.e., transform:
2225 // (xor (overflow_op_bool, 1))
2226 // -->
2227 // (csel 1, 0, invert(cc), overflow_op_bool)
2228 // ... which later gets transformed to just a cset instruction with an
2229 // inverted condition code, rather than a cset + eor sequence.
2230 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2231 // Only lower legal XALUO ops.
2232 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2233 return SDValue();
2235 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2236 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2237 AArch64CC::CondCode CC;
2238 SDValue Value, Overflow;
2239 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2240 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2241 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2242 CCVal, Overflow);
2244 // If neither operand is a SELECT_CC, give up.
2245 if (Sel.getOpcode() != ISD::SELECT_CC)
2246 std::swap(Sel, Other);
2247 if (Sel.getOpcode() != ISD::SELECT_CC)
2248 return Op;
2250 // The folding we want to perform is:
2251 // (xor x, (select_cc a, b, cc, 0, -1) )
2252 // -->
2253 // (csel x, (xor x, -1), cc ...)
2255 // The latter will get matched to a CSINV instruction.
2257 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2258 SDValue LHS = Sel.getOperand(0);
2259 SDValue RHS = Sel.getOperand(1);
2260 SDValue TVal = Sel.getOperand(2);
2261 SDValue FVal = Sel.getOperand(3);
2263 // FIXME: This could be generalized to non-integer comparisons.
2264 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2265 return Op;
2267 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2268 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2270 // The values aren't constants, this isn't the pattern we're looking for.
2271 if (!CFVal || !CTVal)
2272 return Op;
2274 // We can commute the SELECT_CC by inverting the condition. This
2275 // might be needed to make this fit into a CSINV pattern.
2276 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2277 std::swap(TVal, FVal);
2278 std::swap(CTVal, CFVal);
2279 CC = ISD::getSetCCInverse(CC, true);
2282 // If the constants line up, perform the transform!
2283 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2284 SDValue CCVal;
2285 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2287 FVal = Other;
2288 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2289 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2291 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2292 CCVal, Cmp);
2295 return Op;
2298 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2299 EVT VT = Op.getValueType();
2301 // Let legalize expand this if it isn't a legal type yet.
2302 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2303 return SDValue();
2305 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2307 unsigned Opc;
2308 bool ExtraOp = false;
2309 switch (Op.getOpcode()) {
2310 default:
2311 llvm_unreachable("Invalid code");
2312 case ISD::ADDC:
2313 Opc = AArch64ISD::ADDS;
2314 break;
2315 case ISD::SUBC:
2316 Opc = AArch64ISD::SUBS;
2317 break;
2318 case ISD::ADDE:
2319 Opc = AArch64ISD::ADCS;
2320 ExtraOp = true;
2321 break;
2322 case ISD::SUBE:
2323 Opc = AArch64ISD::SBCS;
2324 ExtraOp = true;
2325 break;
2328 if (!ExtraOp)
2329 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2330 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2331 Op.getOperand(2));
2334 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2335 // Let legalize expand this if it isn't a legal type yet.
2336 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2337 return SDValue();
2339 SDLoc dl(Op);
2340 AArch64CC::CondCode CC;
2341 // The actual operation that sets the overflow or carry flag.
2342 SDValue Value, Overflow;
2343 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2345 // We use 0 and 1 as false and true values.
2346 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2347 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2349 // We use an inverted condition, because the conditional select is inverted
2350 // too. This will allow it to be selected to a single instruction:
2351 // CSINC Wd, WZR, WZR, invert(cond).
2352 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2353 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2354 CCVal, Overflow);
2356 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2357 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2360 // Prefetch operands are:
2361 // 1: Address to prefetch
2362 // 2: bool isWrite
2363 // 3: int locality (0 = no locality ... 3 = extreme locality)
2364 // 4: bool isDataCache
2365 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2366 SDLoc DL(Op);
2367 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2368 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2369 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2371 bool IsStream = !Locality;
2372 // When the locality number is set
2373 if (Locality) {
2374 // The front-end should have filtered out the out-of-range values
2375 assert(Locality <= 3 && "Prefetch locality out-of-range");
2376 // The locality degree is the opposite of the cache speed.
2377 // Put the number the other way around.
2378 // The encoding starts at 0 for level 1
2379 Locality = 3 - Locality;
2382 // built the mask value encoding the expected behavior.
2383 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2384 (!IsData << 3) | // IsDataCache bit
2385 (Locality << 1) | // Cache level bits
2386 (unsigned)IsStream; // Stream bit
2387 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2388 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2391 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2392 SelectionDAG &DAG) const {
2393 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2395 RTLIB::Libcall LC;
2396 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2398 return LowerF128Call(Op, DAG, LC);
2401 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2402 SelectionDAG &DAG) const {
2403 if (Op.getOperand(0).getValueType() != MVT::f128) {
2404 // It's legal except when f128 is involved
2405 return Op;
2408 RTLIB::Libcall LC;
2409 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2411 // FP_ROUND node has a second operand indicating whether it is known to be
2412 // precise. That doesn't take part in the LibCall so we can't directly use
2413 // LowerF128Call.
2414 SDValue SrcVal = Op.getOperand(0);
2415 MakeLibCallOptions CallOptions;
2416 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
2417 SDLoc(Op)).first;
2420 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2421 SelectionDAG &DAG) const {
2422 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2423 // Any additional optimization in this function should be recorded
2424 // in the cost tables.
2425 EVT InVT = Op.getOperand(0).getValueType();
2426 EVT VT = Op.getValueType();
2427 unsigned NumElts = InVT.getVectorNumElements();
2429 // f16 conversions are promoted to f32 when full fp16 is not supported.
2430 if (InVT.getVectorElementType() == MVT::f16 &&
2431 !Subtarget->hasFullFP16()) {
2432 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2433 SDLoc dl(Op);
2434 return DAG.getNode(
2435 Op.getOpcode(), dl, Op.getValueType(),
2436 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2439 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2440 SDLoc dl(Op);
2441 SDValue Cv =
2442 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2443 Op.getOperand(0));
2444 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2447 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2448 SDLoc dl(Op);
2449 MVT ExtVT =
2450 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2451 VT.getVectorNumElements());
2452 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2453 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2456 // Type changing conversions are illegal.
2457 return Op;
2460 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2461 SelectionDAG &DAG) const {
2462 if (Op.getOperand(0).getValueType().isVector())
2463 return LowerVectorFP_TO_INT(Op, DAG);
2465 // f16 conversions are promoted to f32 when full fp16 is not supported.
2466 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2467 !Subtarget->hasFullFP16()) {
2468 SDLoc dl(Op);
2469 return DAG.getNode(
2470 Op.getOpcode(), dl, Op.getValueType(),
2471 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2474 if (Op.getOperand(0).getValueType() != MVT::f128) {
2475 // It's legal except when f128 is involved
2476 return Op;
2479 RTLIB::Libcall LC;
2480 if (Op.getOpcode() == ISD::FP_TO_SINT)
2481 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2482 else
2483 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2485 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2486 MakeLibCallOptions CallOptions;
2487 return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
2490 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2491 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2492 // Any additional optimization in this function should be recorded
2493 // in the cost tables.
2494 EVT VT = Op.getValueType();
2495 SDLoc dl(Op);
2496 SDValue In = Op.getOperand(0);
2497 EVT InVT = In.getValueType();
2499 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2500 MVT CastVT =
2501 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2502 InVT.getVectorNumElements());
2503 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2504 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2507 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2508 unsigned CastOpc =
2509 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2510 EVT CastVT = VT.changeVectorElementTypeToInteger();
2511 In = DAG.getNode(CastOpc, dl, CastVT, In);
2512 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2515 return Op;
2518 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2519 SelectionDAG &DAG) const {
2520 if (Op.getValueType().isVector())
2521 return LowerVectorINT_TO_FP(Op, DAG);
2523 // f16 conversions are promoted to f32 when full fp16 is not supported.
2524 if (Op.getValueType() == MVT::f16 &&
2525 !Subtarget->hasFullFP16()) {
2526 SDLoc dl(Op);
2527 return DAG.getNode(
2528 ISD::FP_ROUND, dl, MVT::f16,
2529 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2530 DAG.getIntPtrConstant(0, dl));
2533 // i128 conversions are libcalls.
2534 if (Op.getOperand(0).getValueType() == MVT::i128)
2535 return SDValue();
2537 // Other conversions are legal, unless it's to the completely software-based
2538 // fp128.
2539 if (Op.getValueType() != MVT::f128)
2540 return Op;
2542 RTLIB::Libcall LC;
2543 if (Op.getOpcode() == ISD::SINT_TO_FP)
2544 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2545 else
2546 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2548 return LowerF128Call(Op, DAG, LC);
2551 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2552 SelectionDAG &DAG) const {
2553 // For iOS, we want to call an alternative entry point: __sincos_stret,
2554 // which returns the values in two S / D registers.
2555 SDLoc dl(Op);
2556 SDValue Arg = Op.getOperand(0);
2557 EVT ArgVT = Arg.getValueType();
2558 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2560 ArgListTy Args;
2561 ArgListEntry Entry;
2563 Entry.Node = Arg;
2564 Entry.Ty = ArgTy;
2565 Entry.IsSExt = false;
2566 Entry.IsZExt = false;
2567 Args.push_back(Entry);
2569 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2570 : RTLIB::SINCOS_STRET_F32;
2571 const char *LibcallName = getLibcallName(LC);
2572 SDValue Callee =
2573 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2575 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2576 TargetLowering::CallLoweringInfo CLI(DAG);
2577 CLI.setDebugLoc(dl)
2578 .setChain(DAG.getEntryNode())
2579 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2581 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2582 return CallResult.first;
2585 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2586 if (Op.getValueType() != MVT::f16)
2587 return SDValue();
2589 assert(Op.getOperand(0).getValueType() == MVT::i16);
2590 SDLoc DL(Op);
2592 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2593 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2594 return SDValue(
2595 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2596 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2600 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2601 if (OrigVT.getSizeInBits() >= 64)
2602 return OrigVT;
2604 assert(OrigVT.isSimple() && "Expecting a simple value type");
2606 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2607 switch (OrigSimpleTy) {
2608 default: llvm_unreachable("Unexpected Vector Type");
2609 case MVT::v2i8:
2610 case MVT::v2i16:
2611 return MVT::v2i32;
2612 case MVT::v4i8:
2613 return MVT::v4i16;
2617 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2618 const EVT &OrigTy,
2619 const EVT &ExtTy,
2620 unsigned ExtOpcode) {
2621 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2622 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2623 // 64-bits we need to insert a new extension so that it will be 64-bits.
2624 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2625 if (OrigTy.getSizeInBits() >= 64)
2626 return N;
2628 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2629 EVT NewVT = getExtensionTo64Bits(OrigTy);
2631 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2634 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2635 bool isSigned) {
2636 EVT VT = N->getValueType(0);
2638 if (N->getOpcode() != ISD::BUILD_VECTOR)
2639 return false;
2641 for (const SDValue &Elt : N->op_values()) {
2642 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2643 unsigned EltSize = VT.getScalarSizeInBits();
2644 unsigned HalfSize = EltSize / 2;
2645 if (isSigned) {
2646 if (!isIntN(HalfSize, C->getSExtValue()))
2647 return false;
2648 } else {
2649 if (!isUIntN(HalfSize, C->getZExtValue()))
2650 return false;
2652 continue;
2654 return false;
2657 return true;
2660 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2661 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2662 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2663 N->getOperand(0)->getValueType(0),
2664 N->getValueType(0),
2665 N->getOpcode());
2667 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2668 EVT VT = N->getValueType(0);
2669 SDLoc dl(N);
2670 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2671 unsigned NumElts = VT.getVectorNumElements();
2672 MVT TruncVT = MVT::getIntegerVT(EltSize);
2673 SmallVector<SDValue, 8> Ops;
2674 for (unsigned i = 0; i != NumElts; ++i) {
2675 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2676 const APInt &CInt = C->getAPIntValue();
2677 // Element types smaller than 32 bits are not legal, so use i32 elements.
2678 // The values are implicitly truncated so sext vs. zext doesn't matter.
2679 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2681 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2684 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2685 return N->getOpcode() == ISD::SIGN_EXTEND ||
2686 isExtendedBUILD_VECTOR(N, DAG, true);
2689 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2690 return N->getOpcode() == ISD::ZERO_EXTEND ||
2691 isExtendedBUILD_VECTOR(N, DAG, false);
2694 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2695 unsigned Opcode = N->getOpcode();
2696 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2697 SDNode *N0 = N->getOperand(0).getNode();
2698 SDNode *N1 = N->getOperand(1).getNode();
2699 return N0->hasOneUse() && N1->hasOneUse() &&
2700 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2702 return false;
2705 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2706 unsigned Opcode = N->getOpcode();
2707 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2708 SDNode *N0 = N->getOperand(0).getNode();
2709 SDNode *N1 = N->getOperand(1).getNode();
2710 return N0->hasOneUse() && N1->hasOneUse() &&
2711 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2713 return false;
2716 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2717 SelectionDAG &DAG) const {
2718 // The rounding mode is in bits 23:22 of the FPSCR.
2719 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2720 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2721 // so that the shift + and get folded into a bitfield extract.
2722 SDLoc dl(Op);
2724 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2725 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2726 MVT::i64));
2727 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2728 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2729 DAG.getConstant(1U << 22, dl, MVT::i32));
2730 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2731 DAG.getConstant(22, dl, MVT::i32));
2732 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2733 DAG.getConstant(3, dl, MVT::i32));
2736 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2737 // Multiplications are only custom-lowered for 128-bit vectors so that
2738 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2739 EVT VT = Op.getValueType();
2740 assert(VT.is128BitVector() && VT.isInteger() &&
2741 "unexpected type for custom-lowering ISD::MUL");
2742 SDNode *N0 = Op.getOperand(0).getNode();
2743 SDNode *N1 = Op.getOperand(1).getNode();
2744 unsigned NewOpc = 0;
2745 bool isMLA = false;
2746 bool isN0SExt = isSignExtended(N0, DAG);
2747 bool isN1SExt = isSignExtended(N1, DAG);
2748 if (isN0SExt && isN1SExt)
2749 NewOpc = AArch64ISD::SMULL;
2750 else {
2751 bool isN0ZExt = isZeroExtended(N0, DAG);
2752 bool isN1ZExt = isZeroExtended(N1, DAG);
2753 if (isN0ZExt && isN1ZExt)
2754 NewOpc = AArch64ISD::UMULL;
2755 else if (isN1SExt || isN1ZExt) {
2756 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2757 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2758 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2759 NewOpc = AArch64ISD::SMULL;
2760 isMLA = true;
2761 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2762 NewOpc = AArch64ISD::UMULL;
2763 isMLA = true;
2764 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2765 std::swap(N0, N1);
2766 NewOpc = AArch64ISD::UMULL;
2767 isMLA = true;
2771 if (!NewOpc) {
2772 if (VT == MVT::v2i64)
2773 // Fall through to expand this. It is not legal.
2774 return SDValue();
2775 else
2776 // Other vector multiplications are legal.
2777 return Op;
2781 // Legalize to a S/UMULL instruction
2782 SDLoc DL(Op);
2783 SDValue Op0;
2784 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2785 if (!isMLA) {
2786 Op0 = skipExtensionForVectorMULL(N0, DAG);
2787 assert(Op0.getValueType().is64BitVector() &&
2788 Op1.getValueType().is64BitVector() &&
2789 "unexpected types for extended operands to VMULL");
2790 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2792 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2793 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2794 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2795 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2796 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2797 EVT Op1VT = Op1.getValueType();
2798 return DAG.getNode(N0->getOpcode(), DL, VT,
2799 DAG.getNode(NewOpc, DL, VT,
2800 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2801 DAG.getNode(NewOpc, DL, VT,
2802 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2805 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2806 SelectionDAG &DAG) const {
2807 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2808 SDLoc dl(Op);
2809 switch (IntNo) {
2810 default: return SDValue(); // Don't custom lower most intrinsics.
2811 case Intrinsic::thread_pointer: {
2812 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2813 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2815 case Intrinsic::aarch64_neon_abs: {
2816 EVT Ty = Op.getValueType();
2817 if (Ty == MVT::i64) {
2818 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2819 Op.getOperand(1));
2820 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2821 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2822 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2823 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2824 } else {
2825 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2828 case Intrinsic::aarch64_neon_smax:
2829 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2830 Op.getOperand(1), Op.getOperand(2));
2831 case Intrinsic::aarch64_neon_umax:
2832 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2833 Op.getOperand(1), Op.getOperand(2));
2834 case Intrinsic::aarch64_neon_smin:
2835 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2836 Op.getOperand(1), Op.getOperand(2));
2837 case Intrinsic::aarch64_neon_umin:
2838 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2839 Op.getOperand(1), Op.getOperand(2));
2841 case Intrinsic::localaddress: {
2842 const auto &MF = DAG.getMachineFunction();
2843 const auto *RegInfo = Subtarget->getRegisterInfo();
2844 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2845 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2846 Op.getSimpleValueType());
2849 case Intrinsic::eh_recoverfp: {
2850 // FIXME: This needs to be implemented to correctly handle highly aligned
2851 // stack objects. For now we simply return the incoming FP. Refer D53541
2852 // for more details.
2853 SDValue FnOp = Op.getOperand(1);
2854 SDValue IncomingFPOp = Op.getOperand(2);
2855 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2856 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2857 if (!Fn)
2858 report_fatal_error(
2859 "llvm.eh.recoverfp must take a function as the first argument");
2860 return IncomingFPOp;
2865 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2866 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2867 EVT VT, EVT MemVT,
2868 SelectionDAG &DAG) {
2869 assert(VT.isVector() && "VT should be a vector type");
2870 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2872 SDValue Value = ST->getValue();
2874 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2875 // the word lane which represent the v4i8 subvector. It optimizes the store
2876 // to:
2878 // xtn v0.8b, v0.8h
2879 // str s0, [x0]
2881 SDValue Undef = DAG.getUNDEF(MVT::i16);
2882 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2883 {Undef, Undef, Undef, Undef});
2885 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2886 Value, UndefVec);
2887 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2889 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2890 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2891 Trunc, DAG.getConstant(0, DL, MVT::i64));
2893 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2894 ST->getBasePtr(), ST->getMemOperand());
2897 // Custom lowering for any store, vector or scalar and/or default or with
2898 // a truncate operations. Currently only custom lower truncate operation
2899 // from vector v4i16 to v4i8.
2900 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2901 SelectionDAG &DAG) const {
2902 SDLoc Dl(Op);
2903 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2904 assert (StoreNode && "Can only custom lower store nodes");
2906 SDValue Value = StoreNode->getValue();
2908 EVT VT = Value.getValueType();
2909 EVT MemVT = StoreNode->getMemoryVT();
2911 assert (VT.isVector() && "Can only custom lower vector store types");
2913 unsigned AS = StoreNode->getAddressSpace();
2914 unsigned Align = StoreNode->getAlignment();
2915 if (Align < MemVT.getStoreSize() &&
2916 !allowsMisalignedMemoryAccesses(
2917 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
2918 return scalarizeVectorStore(StoreNode, DAG);
2921 if (StoreNode->isTruncatingStore()) {
2922 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2925 return SDValue();
2928 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2929 SelectionDAG &DAG) const {
2930 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2931 LLVM_DEBUG(Op.dump());
2933 switch (Op.getOpcode()) {
2934 default:
2935 llvm_unreachable("unimplemented operand");
2936 return SDValue();
2937 case ISD::BITCAST:
2938 return LowerBITCAST(Op, DAG);
2939 case ISD::GlobalAddress:
2940 return LowerGlobalAddress(Op, DAG);
2941 case ISD::GlobalTLSAddress:
2942 return LowerGlobalTLSAddress(Op, DAG);
2943 case ISD::SETCC:
2944 return LowerSETCC(Op, DAG);
2945 case ISD::BR_CC:
2946 return LowerBR_CC(Op, DAG);
2947 case ISD::SELECT:
2948 return LowerSELECT(Op, DAG);
2949 case ISD::SELECT_CC:
2950 return LowerSELECT_CC(Op, DAG);
2951 case ISD::JumpTable:
2952 return LowerJumpTable(Op, DAG);
2953 case ISD::BR_JT:
2954 return LowerBR_JT(Op, DAG);
2955 case ISD::ConstantPool:
2956 return LowerConstantPool(Op, DAG);
2957 case ISD::BlockAddress:
2958 return LowerBlockAddress(Op, DAG);
2959 case ISD::VASTART:
2960 return LowerVASTART(Op, DAG);
2961 case ISD::VACOPY:
2962 return LowerVACOPY(Op, DAG);
2963 case ISD::VAARG:
2964 return LowerVAARG(Op, DAG);
2965 case ISD::ADDC:
2966 case ISD::ADDE:
2967 case ISD::SUBC:
2968 case ISD::SUBE:
2969 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2970 case ISD::SADDO:
2971 case ISD::UADDO:
2972 case ISD::SSUBO:
2973 case ISD::USUBO:
2974 case ISD::SMULO:
2975 case ISD::UMULO:
2976 return LowerXALUO(Op, DAG);
2977 case ISD::FADD:
2978 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2979 case ISD::FSUB:
2980 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2981 case ISD::FMUL:
2982 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2983 case ISD::FDIV:
2984 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2985 case ISD::FP_ROUND:
2986 return LowerFP_ROUND(Op, DAG);
2987 case ISD::FP_EXTEND:
2988 return LowerFP_EXTEND(Op, DAG);
2989 case ISD::FRAMEADDR:
2990 return LowerFRAMEADDR(Op, DAG);
2991 case ISD::SPONENTRY:
2992 return LowerSPONENTRY(Op, DAG);
2993 case ISD::RETURNADDR:
2994 return LowerRETURNADDR(Op, DAG);
2995 case ISD::ADDROFRETURNADDR:
2996 return LowerADDROFRETURNADDR(Op, DAG);
2997 case ISD::INSERT_VECTOR_ELT:
2998 return LowerINSERT_VECTOR_ELT(Op, DAG);
2999 case ISD::EXTRACT_VECTOR_ELT:
3000 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3001 case ISD::BUILD_VECTOR:
3002 return LowerBUILD_VECTOR(Op, DAG);
3003 case ISD::VECTOR_SHUFFLE:
3004 return LowerVECTOR_SHUFFLE(Op, DAG);
3005 case ISD::EXTRACT_SUBVECTOR:
3006 return LowerEXTRACT_SUBVECTOR(Op, DAG);
3007 case ISD::SRA:
3008 case ISD::SRL:
3009 case ISD::SHL:
3010 return LowerVectorSRA_SRL_SHL(Op, DAG);
3011 case ISD::SHL_PARTS:
3012 return LowerShiftLeftParts(Op, DAG);
3013 case ISD::SRL_PARTS:
3014 case ISD::SRA_PARTS:
3015 return LowerShiftRightParts(Op, DAG);
3016 case ISD::CTPOP:
3017 return LowerCTPOP(Op, DAG);
3018 case ISD::FCOPYSIGN:
3019 return LowerFCOPYSIGN(Op, DAG);
3020 case ISD::OR:
3021 return LowerVectorOR(Op, DAG);
3022 case ISD::XOR:
3023 return LowerXOR(Op, DAG);
3024 case ISD::PREFETCH:
3025 return LowerPREFETCH(Op, DAG);
3026 case ISD::SINT_TO_FP:
3027 case ISD::UINT_TO_FP:
3028 return LowerINT_TO_FP(Op, DAG);
3029 case ISD::FP_TO_SINT:
3030 case ISD::FP_TO_UINT:
3031 return LowerFP_TO_INT(Op, DAG);
3032 case ISD::FSINCOS:
3033 return LowerFSINCOS(Op, DAG);
3034 case ISD::FLT_ROUNDS_:
3035 return LowerFLT_ROUNDS_(Op, DAG);
3036 case ISD::MUL:
3037 return LowerMUL(Op, DAG);
3038 case ISD::INTRINSIC_WO_CHAIN:
3039 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3040 case ISD::STORE:
3041 return LowerSTORE(Op, DAG);
3042 case ISD::VECREDUCE_ADD:
3043 case ISD::VECREDUCE_SMAX:
3044 case ISD::VECREDUCE_SMIN:
3045 case ISD::VECREDUCE_UMAX:
3046 case ISD::VECREDUCE_UMIN:
3047 case ISD::VECREDUCE_FMAX:
3048 case ISD::VECREDUCE_FMIN:
3049 return LowerVECREDUCE(Op, DAG);
3050 case ISD::ATOMIC_LOAD_SUB:
3051 return LowerATOMIC_LOAD_SUB(Op, DAG);
3052 case ISD::ATOMIC_LOAD_AND:
3053 return LowerATOMIC_LOAD_AND(Op, DAG);
3054 case ISD::DYNAMIC_STACKALLOC:
3055 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3059 //===----------------------------------------------------------------------===//
3060 // Calling Convention Implementation
3061 //===----------------------------------------------------------------------===//
3063 /// Selects the correct CCAssignFn for a given CallingConvention value.
3064 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3065 bool IsVarArg) const {
3066 switch (CC) {
3067 default:
3068 report_fatal_error("Unsupported calling convention.");
3069 case CallingConv::WebKit_JS:
3070 return CC_AArch64_WebKit_JS;
3071 case CallingConv::GHC:
3072 return CC_AArch64_GHC;
3073 case CallingConv::C:
3074 case CallingConv::Fast:
3075 case CallingConv::PreserveMost:
3076 case CallingConv::CXX_FAST_TLS:
3077 case CallingConv::Swift:
3078 if (Subtarget->isTargetWindows() && IsVarArg)
3079 return CC_AArch64_Win64_VarArg;
3080 if (!Subtarget->isTargetDarwin())
3081 return CC_AArch64_AAPCS;
3082 if (!IsVarArg)
3083 return CC_AArch64_DarwinPCS;
3084 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
3085 : CC_AArch64_DarwinPCS_VarArg;
3086 case CallingConv::Win64:
3087 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3088 case CallingConv::AArch64_VectorCall:
3089 return CC_AArch64_AAPCS;
3093 CCAssignFn *
3094 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3095 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3096 : RetCC_AArch64_AAPCS;
3099 SDValue AArch64TargetLowering::LowerFormalArguments(
3100 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3101 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3102 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3103 MachineFunction &MF = DAG.getMachineFunction();
3104 MachineFrameInfo &MFI = MF.getFrameInfo();
3105 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3107 // Assign locations to all of the incoming arguments.
3108 SmallVector<CCValAssign, 16> ArgLocs;
3109 DenseMap<unsigned, SDValue> CopiedRegs;
3110 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3111 *DAG.getContext());
3113 // At this point, Ins[].VT may already be promoted to i32. To correctly
3114 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3115 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3116 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3117 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3118 // LocVT.
3119 unsigned NumArgs = Ins.size();
3120 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3121 unsigned CurArgIdx = 0;
3122 for (unsigned i = 0; i != NumArgs; ++i) {
3123 MVT ValVT = Ins[i].VT;
3124 if (Ins[i].isOrigArg()) {
3125 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3126 CurArgIdx = Ins[i].getOrigArgIndex();
3128 // Get type of the original argument.
3129 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3130 /*AllowUnknown*/ true);
3131 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3132 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3133 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3134 ValVT = MVT::i8;
3135 else if (ActualMVT == MVT::i16)
3136 ValVT = MVT::i16;
3138 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3139 bool Res =
3140 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3141 assert(!Res && "Call operand has unhandled type");
3142 (void)Res;
3144 assert(ArgLocs.size() == Ins.size());
3145 SmallVector<SDValue, 16> ArgValues;
3146 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3147 CCValAssign &VA = ArgLocs[i];
3149 if (Ins[i].Flags.isByVal()) {
3150 // Byval is used for HFAs in the PCS, but the system should work in a
3151 // non-compliant manner for larger structs.
3152 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3153 int Size = Ins[i].Flags.getByValSize();
3154 unsigned NumRegs = (Size + 7) / 8;
3156 // FIXME: This works on big-endian for composite byvals, which are the common
3157 // case. It should also work for fundamental types too.
3158 unsigned FrameIdx =
3159 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3160 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3161 InVals.push_back(FrameIdxN);
3163 continue;
3166 SDValue ArgValue;
3167 if (VA.isRegLoc()) {
3168 // Arguments stored in registers.
3169 EVT RegVT = VA.getLocVT();
3170 const TargetRegisterClass *RC;
3172 if (RegVT == MVT::i32)
3173 RC = &AArch64::GPR32RegClass;
3174 else if (RegVT == MVT::i64)
3175 RC = &AArch64::GPR64RegClass;
3176 else if (RegVT == MVT::f16)
3177 RC = &AArch64::FPR16RegClass;
3178 else if (RegVT == MVT::f32)
3179 RC = &AArch64::FPR32RegClass;
3180 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3181 RC = &AArch64::FPR64RegClass;
3182 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3183 RC = &AArch64::FPR128RegClass;
3184 else if (RegVT.isScalableVector() &&
3185 RegVT.getVectorElementType() == MVT::i1)
3186 RC = &AArch64::PPRRegClass;
3187 else if (RegVT.isScalableVector())
3188 RC = &AArch64::ZPRRegClass;
3189 else
3190 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3192 // Transform the arguments in physical registers into virtual ones.
3193 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3194 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3196 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3197 // to 64 bits. Insert an assert[sz]ext to capture this, then
3198 // truncate to the right size.
3199 switch (VA.getLocInfo()) {
3200 default:
3201 llvm_unreachable("Unknown loc info!");
3202 case CCValAssign::Full:
3203 break;
3204 case CCValAssign::Indirect:
3205 assert(VA.getValVT().isScalableVector() &&
3206 "Only scalable vectors can be passed indirectly");
3207 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3208 case CCValAssign::BCvt:
3209 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3210 break;
3211 case CCValAssign::AExt:
3212 case CCValAssign::SExt:
3213 case CCValAssign::ZExt:
3214 break;
3215 case CCValAssign::AExtUpper:
3216 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
3217 DAG.getConstant(32, DL, RegVT));
3218 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
3219 break;
3221 } else { // VA.isRegLoc()
3222 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3223 unsigned ArgOffset = VA.getLocMemOffset();
3224 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3226 uint32_t BEAlign = 0;
3227 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3228 !Ins[i].Flags.isInConsecutiveRegs())
3229 BEAlign = 8 - ArgSize;
3231 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3233 // Create load nodes to retrieve arguments from the stack.
3234 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3236 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3237 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3238 MVT MemVT = VA.getValVT();
3240 switch (VA.getLocInfo()) {
3241 default:
3242 break;
3243 case CCValAssign::Trunc:
3244 case CCValAssign::BCvt:
3245 MemVT = VA.getLocVT();
3246 break;
3247 case CCValAssign::Indirect:
3248 assert(VA.getValVT().isScalableVector() &&
3249 "Only scalable vectors can be passed indirectly");
3250 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3251 case CCValAssign::SExt:
3252 ExtType = ISD::SEXTLOAD;
3253 break;
3254 case CCValAssign::ZExt:
3255 ExtType = ISD::ZEXTLOAD;
3256 break;
3257 case CCValAssign::AExt:
3258 ExtType = ISD::EXTLOAD;
3259 break;
3262 ArgValue = DAG.getExtLoad(
3263 ExtType, DL, VA.getLocVT(), Chain, FIN,
3264 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3265 MemVT);
3268 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
3269 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
3270 ArgValue, DAG.getValueType(MVT::i32));
3271 InVals.push_back(ArgValue);
3274 // varargs
3275 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3276 if (isVarArg) {
3277 if (!Subtarget->isTargetDarwin() || IsWin64) {
3278 // The AAPCS variadic function ABI is identical to the non-variadic
3279 // one. As a result there may be more arguments in registers and we should
3280 // save them for future reference.
3281 // Win64 variadic functions also pass arguments in registers, but all float
3282 // arguments are passed in integer registers.
3283 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3286 // This will point to the next argument passed via stack.
3287 unsigned StackOffset = CCInfo.getNextStackOffset();
3288 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
3289 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
3290 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3292 if (MFI.hasMustTailInVarArgFunc()) {
3293 SmallVector<MVT, 2> RegParmTypes;
3294 RegParmTypes.push_back(MVT::i64);
3295 RegParmTypes.push_back(MVT::f128);
3296 // Compute the set of forwarded registers. The rest are scratch.
3297 SmallVectorImpl<ForwardedRegister> &Forwards =
3298 FuncInfo->getForwardedMustTailRegParms();
3299 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3300 CC_AArch64_AAPCS);
3302 // Conservatively forward X8, since it might be used for aggregate return.
3303 if (!CCInfo.isAllocated(AArch64::X8)) {
3304 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3305 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3310 // On Windows, InReg pointers must be returned, so record the pointer in a
3311 // virtual register at the start of the function so it can be returned in the
3312 // epilogue.
3313 if (IsWin64) {
3314 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3315 if (Ins[I].Flags.isInReg()) {
3316 assert(!FuncInfo->getSRetReturnReg());
3318 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3319 Register Reg =
3320 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3321 FuncInfo->setSRetReturnReg(Reg);
3323 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3324 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3325 break;
3330 unsigned StackArgSize = CCInfo.getNextStackOffset();
3331 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3332 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3333 // This is a non-standard ABI so by fiat I say we're allowed to make full
3334 // use of the stack area to be popped, which must be aligned to 16 bytes in
3335 // any case:
3336 StackArgSize = alignTo(StackArgSize, 16);
3338 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3339 // a multiple of 16.
3340 FuncInfo->setArgumentStackToRestore(StackArgSize);
3342 // This realignment carries over to the available bytes below. Our own
3343 // callers will guarantee the space is free by giving an aligned value to
3344 // CALLSEQ_START.
3346 // Even if we're not expected to free up the space, it's useful to know how
3347 // much is there while considering tail calls (because we can reuse it).
3348 FuncInfo->setBytesInStackArgArea(StackArgSize);
3350 if (Subtarget->hasCustomCallingConv())
3351 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3353 return Chain;
3356 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3357 SelectionDAG &DAG,
3358 const SDLoc &DL,
3359 SDValue &Chain) const {
3360 MachineFunction &MF = DAG.getMachineFunction();
3361 MachineFrameInfo &MFI = MF.getFrameInfo();
3362 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3363 auto PtrVT = getPointerTy(DAG.getDataLayout());
3364 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3366 SmallVector<SDValue, 8> MemOps;
3368 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3369 AArch64::X3, AArch64::X4, AArch64::X5,
3370 AArch64::X6, AArch64::X7 };
3371 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3372 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3374 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3375 int GPRIdx = 0;
3376 if (GPRSaveSize != 0) {
3377 if (IsWin64) {
3378 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3379 if (GPRSaveSize & 15)
3380 // The extra size here, if triggered, will always be 8.
3381 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3382 } else
3383 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3385 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3387 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3388 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3389 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3390 SDValue Store = DAG.getStore(
3391 Val.getValue(1), DL, Val, FIN,
3392 IsWin64
3393 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3394 GPRIdx,
3395 (i - FirstVariadicGPR) * 8)
3396 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3397 MemOps.push_back(Store);
3398 FIN =
3399 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3402 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3403 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3405 if (Subtarget->hasFPARMv8() && !IsWin64) {
3406 static const MCPhysReg FPRArgRegs[] = {
3407 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3408 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3409 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3410 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3412 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3413 int FPRIdx = 0;
3414 if (FPRSaveSize != 0) {
3415 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3417 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3419 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3420 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3421 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3423 SDValue Store = DAG.getStore(
3424 Val.getValue(1), DL, Val, FIN,
3425 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3426 MemOps.push_back(Store);
3427 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3428 DAG.getConstant(16, DL, PtrVT));
3431 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3432 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3435 if (!MemOps.empty()) {
3436 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3440 /// LowerCallResult - Lower the result values of a call into the
3441 /// appropriate copies out of appropriate physical registers.
3442 SDValue AArch64TargetLowering::LowerCallResult(
3443 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3444 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3445 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3446 SDValue ThisVal) const {
3447 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3448 ? RetCC_AArch64_WebKit_JS
3449 : RetCC_AArch64_AAPCS;
3450 // Assign locations to each value returned by this call.
3451 SmallVector<CCValAssign, 16> RVLocs;
3452 DenseMap<unsigned, SDValue> CopiedRegs;
3453 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3454 *DAG.getContext());
3455 CCInfo.AnalyzeCallResult(Ins, RetCC);
3457 // Copy all of the result registers out of their specified physreg.
3458 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3459 CCValAssign VA = RVLocs[i];
3461 // Pass 'this' value directly from the argument to return value, to avoid
3462 // reg unit interference
3463 if (i == 0 && isThisReturn) {
3464 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3465 "unexpected return calling convention register assignment");
3466 InVals.push_back(ThisVal);
3467 continue;
3470 // Avoid copying a physreg twice since RegAllocFast is incompetent and only
3471 // allows one use of a physreg per block.
3472 SDValue Val = CopiedRegs.lookup(VA.getLocReg());
3473 if (!Val) {
3474 Val =
3475 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3476 Chain = Val.getValue(1);
3477 InFlag = Val.getValue(2);
3478 CopiedRegs[VA.getLocReg()] = Val;
3481 switch (VA.getLocInfo()) {
3482 default:
3483 llvm_unreachable("Unknown loc info!");
3484 case CCValAssign::Full:
3485 break;
3486 case CCValAssign::BCvt:
3487 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3488 break;
3489 case CCValAssign::AExtUpper:
3490 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
3491 DAG.getConstant(32, DL, VA.getLocVT()));
3492 LLVM_FALLTHROUGH;
3493 case CCValAssign::AExt:
3494 LLVM_FALLTHROUGH;
3495 case CCValAssign::ZExt:
3496 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
3497 break;
3500 InVals.push_back(Val);
3503 return Chain;
3506 /// Return true if the calling convention is one that we can guarantee TCO for.
3507 static bool canGuaranteeTCO(CallingConv::ID CC) {
3508 return CC == CallingConv::Fast;
3511 /// Return true if we might ever do TCO for calls with this calling convention.
3512 static bool mayTailCallThisCC(CallingConv::ID CC) {
3513 switch (CC) {
3514 case CallingConv::C:
3515 case CallingConv::PreserveMost:
3516 case CallingConv::Swift:
3517 return true;
3518 default:
3519 return canGuaranteeTCO(CC);
3523 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3524 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3525 const SmallVectorImpl<ISD::OutputArg> &Outs,
3526 const SmallVectorImpl<SDValue> &OutVals,
3527 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3528 if (!mayTailCallThisCC(CalleeCC))
3529 return false;
3531 MachineFunction &MF = DAG.getMachineFunction();
3532 const Function &CallerF = MF.getFunction();
3533 CallingConv::ID CallerCC = CallerF.getCallingConv();
3534 bool CCMatch = CallerCC == CalleeCC;
3536 // Byval parameters hand the function a pointer directly into the stack area
3537 // we want to reuse during a tail call. Working around this *is* possible (see
3538 // X86) but less efficient and uglier in LowerCall.
3539 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3540 e = CallerF.arg_end();
3541 i != e; ++i) {
3542 if (i->hasByValAttr())
3543 return false;
3545 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3546 // In this case, it is necessary to save/restore X0 in the callee. Tail
3547 // call opt interferes with this. So we disable tail call opt when the
3548 // caller has an argument with "inreg" attribute.
3550 // FIXME: Check whether the callee also has an "inreg" argument.
3551 if (i->hasInRegAttr())
3552 return false;
3555 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3556 return canGuaranteeTCO(CalleeCC) && CCMatch;
3558 // Externally-defined functions with weak linkage should not be
3559 // tail-called on AArch64 when the OS does not support dynamic
3560 // pre-emption of symbols, as the AAELF spec requires normal calls
3561 // to undefined weak functions to be replaced with a NOP or jump to the
3562 // next instruction. The behaviour of branch instructions in this
3563 // situation (as used for tail calls) is implementation-defined, so we
3564 // cannot rely on the linker replacing the tail call with a return.
3565 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3566 const GlobalValue *GV = G->getGlobal();
3567 const Triple &TT = getTargetMachine().getTargetTriple();
3568 if (GV->hasExternalWeakLinkage() &&
3569 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3570 return false;
3573 // Now we search for cases where we can use a tail call without changing the
3574 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3575 // concept.
3577 // I want anyone implementing a new calling convention to think long and hard
3578 // about this assert.
3579 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3580 "Unexpected variadic calling convention");
3582 LLVMContext &C = *DAG.getContext();
3583 if (isVarArg && !Outs.empty()) {
3584 // At least two cases here: if caller is fastcc then we can't have any
3585 // memory arguments (we'd be expected to clean up the stack afterwards). If
3586 // caller is C then we could potentially use its argument area.
3588 // FIXME: for now we take the most conservative of these in both cases:
3589 // disallow all variadic memory operands.
3590 SmallVector<CCValAssign, 16> ArgLocs;
3591 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3593 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3594 for (const CCValAssign &ArgLoc : ArgLocs)
3595 if (!ArgLoc.isRegLoc())
3596 return false;
3599 // Check that the call results are passed in the same way.
3600 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3601 CCAssignFnForCall(CalleeCC, isVarArg),
3602 CCAssignFnForCall(CallerCC, isVarArg)))
3603 return false;
3604 // The callee has to preserve all registers the caller needs to preserve.
3605 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3606 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3607 if (!CCMatch) {
3608 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3609 if (Subtarget->hasCustomCallingConv()) {
3610 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3611 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3613 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3614 return false;
3617 // Nothing more to check if the callee is taking no arguments
3618 if (Outs.empty())
3619 return true;
3621 SmallVector<CCValAssign, 16> ArgLocs;
3622 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3624 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3626 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3628 // If the stack arguments for this call do not fit into our own save area then
3629 // the call cannot be made tail.
3630 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3631 return false;
3633 const MachineRegisterInfo &MRI = MF.getRegInfo();
3634 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3635 return false;
3637 return true;
3640 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3641 SelectionDAG &DAG,
3642 MachineFrameInfo &MFI,
3643 int ClobberedFI) const {
3644 SmallVector<SDValue, 8> ArgChains;
3645 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3646 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3648 // Include the original chain at the beginning of the list. When this is
3649 // used by target LowerCall hooks, this helps legalize find the
3650 // CALLSEQ_BEGIN node.
3651 ArgChains.push_back(Chain);
3653 // Add a chain value for each stack argument corresponding
3654 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3655 UE = DAG.getEntryNode().getNode()->use_end();
3656 U != UE; ++U)
3657 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3658 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3659 if (FI->getIndex() < 0) {
3660 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3661 int64_t InLastByte = InFirstByte;
3662 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3664 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3665 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3666 ArgChains.push_back(SDValue(L, 1));
3669 // Build a tokenfactor for all the chains.
3670 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3673 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3674 bool TailCallOpt) const {
3675 return CallCC == CallingConv::Fast && TailCallOpt;
3678 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3679 /// and add input and output parameter nodes.
3680 SDValue
3681 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3682 SmallVectorImpl<SDValue> &InVals) const {
3683 SelectionDAG &DAG = CLI.DAG;
3684 SDLoc &DL = CLI.DL;
3685 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3686 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3687 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3688 SDValue Chain = CLI.Chain;
3689 SDValue Callee = CLI.Callee;
3690 bool &IsTailCall = CLI.IsTailCall;
3691 CallingConv::ID CallConv = CLI.CallConv;
3692 bool IsVarArg = CLI.IsVarArg;
3694 MachineFunction &MF = DAG.getMachineFunction();
3695 MachineFunction::CallSiteInfo CSInfo;
3696 bool IsThisReturn = false;
3698 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3699 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3700 bool IsSibCall = false;
3702 if (IsTailCall) {
3703 // Check if it's really possible to do a tail call.
3704 IsTailCall = isEligibleForTailCallOptimization(
3705 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3706 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3707 report_fatal_error("failed to perform tail call elimination on a call "
3708 "site marked musttail");
3710 // A sibling call is one where we're under the usual C ABI and not planning
3711 // to change that but can still do a tail call:
3712 if (!TailCallOpt && IsTailCall)
3713 IsSibCall = true;
3715 if (IsTailCall)
3716 ++NumTailCalls;
3719 // Analyze operands of the call, assigning locations to each operand.
3720 SmallVector<CCValAssign, 16> ArgLocs;
3721 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3722 *DAG.getContext());
3724 if (IsVarArg) {
3725 // Handle fixed and variable vector arguments differently.
3726 // Variable vector arguments always go into memory.
3727 unsigned NumArgs = Outs.size();
3729 for (unsigned i = 0; i != NumArgs; ++i) {
3730 MVT ArgVT = Outs[i].VT;
3731 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3732 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3733 /*IsVarArg=*/ !Outs[i].IsFixed);
3734 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3735 assert(!Res && "Call operand has unhandled type");
3736 (void)Res;
3738 } else {
3739 // At this point, Outs[].VT may already be promoted to i32. To correctly
3740 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3741 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3742 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3743 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3744 // LocVT.
3745 unsigned NumArgs = Outs.size();
3746 for (unsigned i = 0; i != NumArgs; ++i) {
3747 MVT ValVT = Outs[i].VT;
3748 // Get type of the original argument.
3749 EVT ActualVT = getValueType(DAG.getDataLayout(),
3750 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3751 /*AllowUnknown*/ true);
3752 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3753 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3754 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3755 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3756 ValVT = MVT::i8;
3757 else if (ActualMVT == MVT::i16)
3758 ValVT = MVT::i16;
3760 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3761 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3762 assert(!Res && "Call operand has unhandled type");
3763 (void)Res;
3767 // Get a count of how many bytes are to be pushed on the stack.
3768 unsigned NumBytes = CCInfo.getNextStackOffset();
3770 if (IsSibCall) {
3771 // Since we're not changing the ABI to make this a tail call, the memory
3772 // operands are already available in the caller's incoming argument space.
3773 NumBytes = 0;
3776 // FPDiff is the byte offset of the call's argument area from the callee's.
3777 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3778 // by this amount for a tail call. In a sibling call it must be 0 because the
3779 // caller will deallocate the entire stack and the callee still expects its
3780 // arguments to begin at SP+0. Completely unused for non-tail calls.
3781 int FPDiff = 0;
3783 if (IsTailCall && !IsSibCall) {
3784 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3786 // Since callee will pop argument stack as a tail call, we must keep the
3787 // popped size 16-byte aligned.
3788 NumBytes = alignTo(NumBytes, 16);
3790 // FPDiff will be negative if this tail call requires more space than we
3791 // would automatically have in our incoming argument space. Positive if we
3792 // can actually shrink the stack.
3793 FPDiff = NumReusableBytes - NumBytes;
3795 // The stack pointer must be 16-byte aligned at all times it's used for a
3796 // memory operation, which in practice means at *all* times and in
3797 // particular across call boundaries. Therefore our own arguments started at
3798 // a 16-byte aligned SP and the delta applied for the tail call should
3799 // satisfy the same constraint.
3800 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3803 // Adjust the stack pointer for the new arguments...
3804 // These operations are automatically eliminated by the prolog/epilog pass
3805 if (!IsSibCall)
3806 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3808 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3809 getPointerTy(DAG.getDataLayout()));
3811 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3812 SmallSet<unsigned, 8> RegsUsed;
3813 SmallVector<SDValue, 8> MemOpChains;
3814 auto PtrVT = getPointerTy(DAG.getDataLayout());
3816 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3817 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3818 for (const auto &F : Forwards) {
3819 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3820 RegsToPass.emplace_back(F.PReg, Val);
3824 // Walk the register/memloc assignments, inserting copies/loads.
3825 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3826 ++i, ++realArgIdx) {
3827 CCValAssign &VA = ArgLocs[i];
3828 SDValue Arg = OutVals[realArgIdx];
3829 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3831 // Promote the value if needed.
3832 switch (VA.getLocInfo()) {
3833 default:
3834 llvm_unreachable("Unknown loc info!");
3835 case CCValAssign::Full:
3836 break;
3837 case CCValAssign::SExt:
3838 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3839 break;
3840 case CCValAssign::ZExt:
3841 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3842 break;
3843 case CCValAssign::AExt:
3844 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3845 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3846 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3847 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3849 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3850 break;
3851 case CCValAssign::AExtUpper:
3852 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
3853 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3854 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
3855 DAG.getConstant(32, DL, VA.getLocVT()));
3856 break;
3857 case CCValAssign::BCvt:
3858 Arg = DAG.getBitcast(VA.getLocVT(), Arg);
3859 break;
3860 case CCValAssign::Trunc:
3861 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
3862 break;
3863 case CCValAssign::FPExt:
3864 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3865 break;
3866 case CCValAssign::Indirect:
3867 assert(VA.getValVT().isScalableVector() &&
3868 "Only scalable vectors can be passed indirectly");
3869 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3872 if (VA.isRegLoc()) {
3873 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3874 Outs[0].VT == MVT::i64) {
3875 assert(VA.getLocVT() == MVT::i64 &&
3876 "unexpected calling convention register assignment");
3877 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3878 "unexpected use of 'returned'");
3879 IsThisReturn = true;
3881 if (RegsUsed.count(VA.getLocReg())) {
3882 // If this register has already been used then we're trying to pack
3883 // parts of an [N x i32] into an X-register. The extension type will
3884 // take care of putting the two halves in the right place but we have to
3885 // combine them.
3886 SDValue &Bits =
3887 std::find_if(RegsToPass.begin(), RegsToPass.end(),
3888 [=](const std::pair<unsigned, SDValue> &Elt) {
3889 return Elt.first == VA.getLocReg();
3891 ->second;
3892 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
3893 // Call site info is used for function's parameter entry value
3894 // tracking. For now we track only simple cases when parameter
3895 // is transferred through whole register.
3896 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(),
3897 [&VA](MachineFunction::ArgRegPair ArgReg) {
3898 return ArgReg.Reg == VA.getLocReg();
3900 CSInfo.end());
3901 } else {
3902 RegsToPass.emplace_back(VA.getLocReg(), Arg);
3903 RegsUsed.insert(VA.getLocReg());
3904 const TargetOptions &Options = DAG.getTarget().Options;
3905 if (Options.EnableDebugEntryValues)
3906 CSInfo.emplace_back(VA.getLocReg(), i);
3908 } else {
3909 assert(VA.isMemLoc());
3911 SDValue DstAddr;
3912 MachinePointerInfo DstInfo;
3914 // FIXME: This works on big-endian for composite byvals, which are the
3915 // common case. It should also work for fundamental types too.
3916 uint32_t BEAlign = 0;
3917 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3918 : VA.getValVT().getSizeInBits();
3919 OpSize = (OpSize + 7) / 8;
3920 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3921 !Flags.isInConsecutiveRegs()) {
3922 if (OpSize < 8)
3923 BEAlign = 8 - OpSize;
3925 unsigned LocMemOffset = VA.getLocMemOffset();
3926 int32_t Offset = LocMemOffset + BEAlign;
3927 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3928 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3930 if (IsTailCall) {
3931 Offset = Offset + FPDiff;
3932 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3934 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3935 DstInfo =
3936 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3938 // Make sure any stack arguments overlapping with where we're storing
3939 // are loaded before this eventual operation. Otherwise they'll be
3940 // clobbered.
3941 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3942 } else {
3943 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3945 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3946 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3947 LocMemOffset);
3950 if (Outs[i].Flags.isByVal()) {
3951 SDValue SizeNode =
3952 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3953 SDValue Cpy = DAG.getMemcpy(
3954 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3955 /*isVol = */ false, /*AlwaysInline = */ false,
3956 /*isTailCall = */ false,
3957 DstInfo, MachinePointerInfo());
3959 MemOpChains.push_back(Cpy);
3960 } else {
3961 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3962 // promoted to a legal register type i32, we should truncate Arg back to
3963 // i1/i8/i16.
3964 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3965 VA.getValVT() == MVT::i16)
3966 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3968 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3969 MemOpChains.push_back(Store);
3974 if (!MemOpChains.empty())
3975 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3977 // Build a sequence of copy-to-reg nodes chained together with token chain
3978 // and flag operands which copy the outgoing args into the appropriate regs.
3979 SDValue InFlag;
3980 for (auto &RegToPass : RegsToPass) {
3981 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3982 RegToPass.second, InFlag);
3983 InFlag = Chain.getValue(1);
3986 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3987 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3988 // node so that legalize doesn't hack it.
3989 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3990 auto GV = G->getGlobal();
3991 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3992 AArch64II::MO_GOT) {
3993 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3994 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3995 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3996 assert(Subtarget->isTargetWindows() &&
3997 "Windows is the only supported COFF target");
3998 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3999 } else {
4000 const GlobalValue *GV = G->getGlobal();
4001 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
4003 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4004 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4005 Subtarget->isTargetMachO()) {
4006 const char *Sym = S->getSymbol();
4007 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
4008 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
4009 } else {
4010 const char *Sym = S->getSymbol();
4011 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
4015 // We don't usually want to end the call-sequence here because we would tidy
4016 // the frame up *after* the call, however in the ABI-changing tail-call case
4017 // we've carefully laid out the parameters so that when sp is reset they'll be
4018 // in the correct location.
4019 if (IsTailCall && !IsSibCall) {
4020 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4021 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
4022 InFlag = Chain.getValue(1);
4025 std::vector<SDValue> Ops;
4026 Ops.push_back(Chain);
4027 Ops.push_back(Callee);
4029 if (IsTailCall) {
4030 // Each tail call may have to adjust the stack by a different amount, so
4031 // this information must travel along with the operation for eventual
4032 // consumption by emitEpilogue.
4033 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
4036 // Add argument registers to the end of the list so that they are known live
4037 // into the call.
4038 for (auto &RegToPass : RegsToPass)
4039 Ops.push_back(DAG.getRegister(RegToPass.first,
4040 RegToPass.second.getValueType()));
4042 // Check callee args/returns for SVE registers and set calling convention
4043 // accordingly.
4044 if (CallConv == CallingConv::C) {
4045 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
4046 return Out.VT.isScalableVector();
4048 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
4049 return In.VT.isScalableVector();
4052 if (CalleeInSVE || CalleeOutSVE)
4053 CallConv = CallingConv::AArch64_SVE_VectorCall;
4056 // Add a register mask operand representing the call-preserved registers.
4057 const uint32_t *Mask;
4058 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4059 if (IsThisReturn) {
4060 // For 'this' returns, use the X0-preserving mask if applicable
4061 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
4062 if (!Mask) {
4063 IsThisReturn = false;
4064 Mask = TRI->getCallPreservedMask(MF, CallConv);
4066 } else
4067 Mask = TRI->getCallPreservedMask(MF, CallConv);
4069 if (Subtarget->hasCustomCallingConv())
4070 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4072 if (TRI->isAnyArgRegReserved(MF))
4073 TRI->emitReservedArgRegCallError(MF);
4075 assert(Mask && "Missing call preserved mask for calling convention");
4076 Ops.push_back(DAG.getRegisterMask(Mask));
4078 if (InFlag.getNode())
4079 Ops.push_back(InFlag);
4081 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4083 // If we're doing a tall call, use a TC_RETURN here rather than an
4084 // actual call instruction.
4085 if (IsTailCall) {
4086 MF.getFrameInfo().setHasTailCall();
4087 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4088 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4089 return Ret;
4092 // Returns a chain and a flag for retval copy to use.
4093 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4094 InFlag = Chain.getValue(1);
4095 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4097 uint64_t CalleePopBytes =
4098 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4100 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4101 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4102 InFlag, DL);
4103 if (!Ins.empty())
4104 InFlag = Chain.getValue(1);
4106 // Handle result values, copying them out of physregs into vregs that we
4107 // return.
4108 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4109 InVals, IsThisReturn,
4110 IsThisReturn ? OutVals[0] : SDValue());
4113 bool AArch64TargetLowering::CanLowerReturn(
4114 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4115 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4116 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4117 ? RetCC_AArch64_WebKit_JS
4118 : RetCC_AArch64_AAPCS;
4119 SmallVector<CCValAssign, 16> RVLocs;
4120 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4121 return CCInfo.CheckReturn(Outs, RetCC);
4124 SDValue
4125 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4126 bool isVarArg,
4127 const SmallVectorImpl<ISD::OutputArg> &Outs,
4128 const SmallVectorImpl<SDValue> &OutVals,
4129 const SDLoc &DL, SelectionDAG &DAG) const {
4130 auto &MF = DAG.getMachineFunction();
4131 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4133 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4134 ? RetCC_AArch64_WebKit_JS
4135 : RetCC_AArch64_AAPCS;
4136 SmallVector<CCValAssign, 16> RVLocs;
4137 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4138 *DAG.getContext());
4139 CCInfo.AnalyzeReturn(Outs, RetCC);
4141 // Copy the result values into the output registers.
4142 SDValue Flag;
4143 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
4144 SmallSet<unsigned, 4> RegsUsed;
4145 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4146 ++i, ++realRVLocIdx) {
4147 CCValAssign &VA = RVLocs[i];
4148 assert(VA.isRegLoc() && "Can only return in registers!");
4149 SDValue Arg = OutVals[realRVLocIdx];
4151 switch (VA.getLocInfo()) {
4152 default:
4153 llvm_unreachable("Unknown loc info!");
4154 case CCValAssign::Full:
4155 if (Outs[i].ArgVT == MVT::i1) {
4156 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4157 // value. This is strictly redundant on Darwin (which uses "zeroext
4158 // i1"), but will be optimised out before ISel.
4159 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4160 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4162 break;
4163 case CCValAssign::BCvt:
4164 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4165 break;
4166 case CCValAssign::AExt:
4167 case CCValAssign::ZExt:
4168 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4169 break;
4170 case CCValAssign::AExtUpper:
4171 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
4172 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
4173 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
4174 DAG.getConstant(32, DL, VA.getLocVT()));
4175 break;
4178 if (RegsUsed.count(VA.getLocReg())) {
4179 SDValue &Bits =
4180 std::find_if(RetVals.begin(), RetVals.end(),
4181 [=](const std::pair<unsigned, SDValue> &Elt) {
4182 return Elt.first == VA.getLocReg();
4184 ->second;
4185 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
4186 } else {
4187 RetVals.emplace_back(VA.getLocReg(), Arg);
4188 RegsUsed.insert(VA.getLocReg());
4192 SmallVector<SDValue, 4> RetOps(1, Chain);
4193 for (auto &RetVal : RetVals) {
4194 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
4195 Flag = Chain.getValue(1);
4196 RetOps.push_back(
4197 DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
4200 // Windows AArch64 ABIs require that for returning structs by value we copy
4201 // the sret argument into X0 for the return.
4202 // We saved the argument into a virtual register in the entry block,
4203 // so now we copy the value out and into X0.
4204 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4205 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4206 getPointerTy(MF.getDataLayout()));
4208 unsigned RetValReg = AArch64::X0;
4209 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4210 Flag = Chain.getValue(1);
4212 RetOps.push_back(
4213 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4216 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4217 const MCPhysReg *I =
4218 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4219 if (I) {
4220 for (; *I; ++I) {
4221 if (AArch64::GPR64RegClass.contains(*I))
4222 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4223 else if (AArch64::FPR64RegClass.contains(*I))
4224 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4225 else
4226 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4230 RetOps[0] = Chain; // Update chain.
4232 // Add the flag if we have it.
4233 if (Flag.getNode())
4234 RetOps.push_back(Flag);
4236 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4239 //===----------------------------------------------------------------------===//
4240 // Other Lowering Code
4241 //===----------------------------------------------------------------------===//
4243 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4244 SelectionDAG &DAG,
4245 unsigned Flag) const {
4246 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4247 N->getOffset(), Flag);
4250 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4251 SelectionDAG &DAG,
4252 unsigned Flag) const {
4253 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4256 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4257 SelectionDAG &DAG,
4258 unsigned Flag) const {
4259 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4260 N->getOffset(), Flag);
4263 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4264 SelectionDAG &DAG,
4265 unsigned Flag) const {
4266 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4269 // (loadGOT sym)
4270 template <class NodeTy>
4271 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4272 unsigned Flags) const {
4273 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4274 SDLoc DL(N);
4275 EVT Ty = getPointerTy(DAG.getDataLayout());
4276 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4277 // FIXME: Once remat is capable of dealing with instructions with register
4278 // operands, expand this into two nodes instead of using a wrapper node.
4279 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4282 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4283 template <class NodeTy>
4284 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4285 unsigned Flags) const {
4286 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4287 SDLoc DL(N);
4288 EVT Ty = getPointerTy(DAG.getDataLayout());
4289 const unsigned char MO_NC = AArch64II::MO_NC;
4290 return DAG.getNode(
4291 AArch64ISD::WrapperLarge, DL, Ty,
4292 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4293 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4294 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4295 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4298 // (addlow (adrp %hi(sym)) %lo(sym))
4299 template <class NodeTy>
4300 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4301 unsigned Flags) const {
4302 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4303 SDLoc DL(N);
4304 EVT Ty = getPointerTy(DAG.getDataLayout());
4305 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4306 SDValue Lo = getTargetNode(N, Ty, DAG,
4307 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4308 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4309 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4312 // (adr sym)
4313 template <class NodeTy>
4314 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4315 unsigned Flags) const {
4316 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4317 SDLoc DL(N);
4318 EVT Ty = getPointerTy(DAG.getDataLayout());
4319 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4320 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4323 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4324 SelectionDAG &DAG) const {
4325 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4326 const GlobalValue *GV = GN->getGlobal();
4327 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4329 if (OpFlags != AArch64II::MO_NO_FLAG)
4330 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4331 "unexpected offset in global node");
4333 // This also catches the large code model case for Darwin, and tiny code
4334 // model with got relocations.
4335 if ((OpFlags & AArch64II::MO_GOT) != 0) {
4336 return getGOT(GN, DAG, OpFlags);
4339 SDValue Result;
4340 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4341 Result = getAddrLarge(GN, DAG, OpFlags);
4342 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4343 Result = getAddrTiny(GN, DAG, OpFlags);
4344 } else {
4345 Result = getAddr(GN, DAG, OpFlags);
4347 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4348 SDLoc DL(GN);
4349 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4350 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4351 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4352 return Result;
4355 /// Convert a TLS address reference into the correct sequence of loads
4356 /// and calls to compute the variable's address (for Darwin, currently) and
4357 /// return an SDValue containing the final node.
4359 /// Darwin only has one TLS scheme which must be capable of dealing with the
4360 /// fully general situation, in the worst case. This means:
4361 /// + "extern __thread" declaration.
4362 /// + Defined in a possibly unknown dynamic library.
4364 /// The general system is that each __thread variable has a [3 x i64] descriptor
4365 /// which contains information used by the runtime to calculate the address. The
4366 /// only part of this the compiler needs to know about is the first xword, which
4367 /// contains a function pointer that must be called with the address of the
4368 /// entire descriptor in "x0".
4370 /// Since this descriptor may be in a different unit, in general even the
4371 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4372 /// is:
4373 /// adrp x0, _var@TLVPPAGE
4374 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4375 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4376 /// ; the function pointer
4377 /// blr x1 ; Uses descriptor address in x0
4378 /// ; Address of _var is now in x0.
4380 /// If the address of _var's descriptor *is* known to the linker, then it can
4381 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4382 /// a slight efficiency gain.
4383 SDValue
4384 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4385 SelectionDAG &DAG) const {
4386 assert(Subtarget->isTargetDarwin() &&
4387 "This function expects a Darwin target");
4389 SDLoc DL(Op);
4390 MVT PtrVT = getPointerTy(DAG.getDataLayout());
4391 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
4392 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4394 SDValue TLVPAddr =
4395 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4396 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4398 // The first entry in the descriptor is a function pointer that we must call
4399 // to obtain the address of the variable.
4400 SDValue Chain = DAG.getEntryNode();
4401 SDValue FuncTLVGet = DAG.getLoad(
4402 PtrMemVT, DL, Chain, DescAddr,
4403 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4404 /* Alignment = */ PtrMemVT.getSizeInBits() / 8,
4405 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4406 Chain = FuncTLVGet.getValue(1);
4408 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
4409 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
4411 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4412 MFI.setAdjustsStack(true);
4414 // TLS calls preserve all registers except those that absolutely must be
4415 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4416 // silly).
4417 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4418 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4419 if (Subtarget->hasCustomCallingConv())
4420 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4422 // Finally, we can make the call. This is just a degenerate version of a
4423 // normal AArch64 call node: x0 takes the address of the descriptor, and
4424 // returns the address of the variable in this thread.
4425 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4426 Chain =
4427 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4428 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4429 DAG.getRegisterMask(Mask), Chain.getValue(1));
4430 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4433 /// When accessing thread-local variables under either the general-dynamic or
4434 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4435 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4436 /// is a function pointer to carry out the resolution.
4438 /// The sequence is:
4439 /// adrp x0, :tlsdesc:var
4440 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4441 /// add x0, x0, #:tlsdesc_lo12:var
4442 /// .tlsdesccall var
4443 /// blr x1
4444 /// (TPIDR_EL0 offset now in x0)
4446 /// The above sequence must be produced unscheduled, to enable the linker to
4447 /// optimize/relax this sequence.
4448 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4449 /// above sequence, and expanded really late in the compilation flow, to ensure
4450 /// the sequence is produced as per above.
4451 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4452 const SDLoc &DL,
4453 SelectionDAG &DAG) const {
4454 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4456 SDValue Chain = DAG.getEntryNode();
4457 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4459 Chain =
4460 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4461 SDValue Glue = Chain.getValue(1);
4463 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4466 SDValue
4467 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4468 SelectionDAG &DAG) const {
4469 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4470 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4471 report_fatal_error("ELF TLS only supported in small memory model");
4472 // Different choices can be made for the maximum size of the TLS area for a
4473 // module. For the small address model, the default TLS size is 16MiB and the
4474 // maximum TLS size is 4GiB.
4475 // FIXME: add -mtls-size command line option and make it control the 16MiB
4476 // vs. 4GiB code sequence generation.
4477 // FIXME: add tiny codemodel support. We currently generate the same code as
4478 // small, which may be larger than needed.
4479 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4481 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4483 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4484 if (Model == TLSModel::LocalDynamic)
4485 Model = TLSModel::GeneralDynamic;
4488 SDValue TPOff;
4489 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4490 SDLoc DL(Op);
4491 const GlobalValue *GV = GA->getGlobal();
4493 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4495 if (Model == TLSModel::LocalExec) {
4496 SDValue HiVar = DAG.getTargetGlobalAddress(
4497 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4498 SDValue LoVar = DAG.getTargetGlobalAddress(
4499 GV, DL, PtrVT, 0,
4500 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4502 SDValue TPWithOff_lo =
4503 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4504 HiVar,
4505 DAG.getTargetConstant(0, DL, MVT::i32)),
4507 SDValue TPWithOff =
4508 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4509 LoVar,
4510 DAG.getTargetConstant(0, DL, MVT::i32)),
4512 return TPWithOff;
4513 } else if (Model == TLSModel::InitialExec) {
4514 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4515 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4516 } else if (Model == TLSModel::LocalDynamic) {
4517 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4518 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4519 // the beginning of the module's TLS region, followed by a DTPREL offset
4520 // calculation.
4522 // These accesses will need deduplicating if there's more than one.
4523 AArch64FunctionInfo *MFI =
4524 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4525 MFI->incNumLocalDynamicTLSAccesses();
4527 // The call needs a relocation too for linker relaxation. It doesn't make
4528 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4529 // the address.
4530 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4531 AArch64II::MO_TLS);
4533 // Now we can calculate the offset from TPIDR_EL0 to this module's
4534 // thread-local area.
4535 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4537 // Now use :dtprel_whatever: operations to calculate this variable's offset
4538 // in its thread-storage area.
4539 SDValue HiVar = DAG.getTargetGlobalAddress(
4540 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4541 SDValue LoVar = DAG.getTargetGlobalAddress(
4542 GV, DL, MVT::i64, 0,
4543 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4545 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4546 DAG.getTargetConstant(0, DL, MVT::i32)),
4548 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4549 DAG.getTargetConstant(0, DL, MVT::i32)),
4551 } else if (Model == TLSModel::GeneralDynamic) {
4552 // The call needs a relocation too for linker relaxation. It doesn't make
4553 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4554 // the address.
4555 SDValue SymAddr =
4556 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4558 // Finally we can make a call to calculate the offset from tpidr_el0.
4559 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4560 } else
4561 llvm_unreachable("Unsupported ELF TLS access model");
4563 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4566 SDValue
4567 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4568 SelectionDAG &DAG) const {
4569 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4571 SDValue Chain = DAG.getEntryNode();
4572 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4573 SDLoc DL(Op);
4575 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4577 // Load the ThreadLocalStoragePointer from the TEB
4578 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4579 SDValue TLSArray =
4580 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4581 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4582 Chain = TLSArray.getValue(1);
4584 // Load the TLS index from the C runtime;
4585 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4586 // This also does the same as LOADgot, but using a generic i32 load,
4587 // while LOADgot only loads i64.
4588 SDValue TLSIndexHi =
4589 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4590 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4591 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4592 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4593 SDValue TLSIndex =
4594 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4595 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4596 Chain = TLSIndex.getValue(1);
4598 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4599 // offset into the TLSArray.
4600 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4601 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4602 DAG.getConstant(3, DL, PtrVT));
4603 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4604 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4605 MachinePointerInfo());
4606 Chain = TLS.getValue(1);
4608 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4609 const GlobalValue *GV = GA->getGlobal();
4610 SDValue TGAHi = DAG.getTargetGlobalAddress(
4611 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4612 SDValue TGALo = DAG.getTargetGlobalAddress(
4613 GV, DL, PtrVT, 0,
4614 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4616 // Add the offset from the start of the .tls section (section base).
4617 SDValue Addr =
4618 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4619 DAG.getTargetConstant(0, DL, MVT::i32)),
4621 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4622 return Addr;
4625 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4626 SelectionDAG &DAG) const {
4627 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4628 if (DAG.getTarget().useEmulatedTLS())
4629 return LowerToTLSEmulatedModel(GA, DAG);
4631 if (Subtarget->isTargetDarwin())
4632 return LowerDarwinGlobalTLSAddress(Op, DAG);
4633 if (Subtarget->isTargetELF())
4634 return LowerELFGlobalTLSAddress(Op, DAG);
4635 if (Subtarget->isTargetWindows())
4636 return LowerWindowsGlobalTLSAddress(Op, DAG);
4638 llvm_unreachable("Unexpected platform trying to use TLS");
4641 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4642 SDValue Chain = Op.getOperand(0);
4643 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4644 SDValue LHS = Op.getOperand(2);
4645 SDValue RHS = Op.getOperand(3);
4646 SDValue Dest = Op.getOperand(4);
4647 SDLoc dl(Op);
4649 MachineFunction &MF = DAG.getMachineFunction();
4650 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4651 // will not be produced, as they are conditional branch instructions that do
4652 // not set flags.
4653 bool ProduceNonFlagSettingCondBr =
4654 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4656 // Handle f128 first, since lowering it will result in comparing the return
4657 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4658 // is expecting to deal with.
4659 if (LHS.getValueType() == MVT::f128) {
4660 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4662 // If softenSetCCOperands returned a scalar, we need to compare the result
4663 // against zero to select between true and false values.
4664 if (!RHS.getNode()) {
4665 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4666 CC = ISD::SETNE;
4670 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4671 // instruction.
4672 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4673 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4674 // Only lower legal XALUO ops.
4675 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4676 return SDValue();
4678 // The actual operation with overflow check.
4679 AArch64CC::CondCode OFCC;
4680 SDValue Value, Overflow;
4681 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4683 if (CC == ISD::SETNE)
4684 OFCC = getInvertedCondCode(OFCC);
4685 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4687 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4688 Overflow);
4691 if (LHS.getValueType().isInteger()) {
4692 assert((LHS.getValueType() == RHS.getValueType()) &&
4693 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4695 // If the RHS of the comparison is zero, we can potentially fold this
4696 // to a specialized branch.
4697 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4698 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4699 if (CC == ISD::SETEQ) {
4700 // See if we can use a TBZ to fold in an AND as well.
4701 // TBZ has a smaller branch displacement than CBZ. If the offset is
4702 // out of bounds, a late MI-layer pass rewrites branches.
4703 // 403.gcc is an example that hits this case.
4704 if (LHS.getOpcode() == ISD::AND &&
4705 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4706 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4707 SDValue Test = LHS.getOperand(0);
4708 uint64_t Mask = LHS.getConstantOperandVal(1);
4709 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4710 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4711 Dest);
4714 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4715 } else if (CC == ISD::SETNE) {
4716 // See if we can use a TBZ to fold in an AND as well.
4717 // TBZ has a smaller branch displacement than CBZ. If the offset is
4718 // out of bounds, a late MI-layer pass rewrites branches.
4719 // 403.gcc is an example that hits this case.
4720 if (LHS.getOpcode() == ISD::AND &&
4721 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4722 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4723 SDValue Test = LHS.getOperand(0);
4724 uint64_t Mask = LHS.getConstantOperandVal(1);
4725 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4726 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4727 Dest);
4730 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4731 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4732 // Don't combine AND since emitComparison converts the AND to an ANDS
4733 // (a.k.a. TST) and the test in the test bit and branch instruction
4734 // becomes redundant. This would also increase register pressure.
4735 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4736 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4737 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4740 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4741 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4742 // Don't combine AND since emitComparison converts the AND to an ANDS
4743 // (a.k.a. TST) and the test in the test bit and branch instruction
4744 // becomes redundant. This would also increase register pressure.
4745 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4746 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4747 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4750 SDValue CCVal;
4751 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4752 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4753 Cmp);
4756 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4757 LHS.getValueType() == MVT::f64);
4759 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4760 // clean. Some of them require two branches to implement.
4761 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4762 AArch64CC::CondCode CC1, CC2;
4763 changeFPCCToAArch64CC(CC, CC1, CC2);
4764 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4765 SDValue BR1 =
4766 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4767 if (CC2 != AArch64CC::AL) {
4768 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4769 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4770 Cmp);
4773 return BR1;
4776 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4777 SelectionDAG &DAG) const {
4778 EVT VT = Op.getValueType();
4779 SDLoc DL(Op);
4781 SDValue In1 = Op.getOperand(0);
4782 SDValue In2 = Op.getOperand(1);
4783 EVT SrcVT = In2.getValueType();
4785 if (SrcVT.bitsLT(VT))
4786 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4787 else if (SrcVT.bitsGT(VT))
4788 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4790 EVT VecVT;
4791 uint64_t EltMask;
4792 SDValue VecVal1, VecVal2;
4794 auto setVecVal = [&] (int Idx) {
4795 if (!VT.isVector()) {
4796 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4797 DAG.getUNDEF(VecVT), In1);
4798 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4799 DAG.getUNDEF(VecVT), In2);
4800 } else {
4801 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4802 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4806 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4807 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4808 EltMask = 0x80000000ULL;
4809 setVecVal(AArch64::ssub);
4810 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4811 VecVT = MVT::v2i64;
4813 // We want to materialize a mask with the high bit set, but the AdvSIMD
4814 // immediate moves cannot materialize that in a single instruction for
4815 // 64-bit elements. Instead, materialize zero and then negate it.
4816 EltMask = 0;
4818 setVecVal(AArch64::dsub);
4819 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4820 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4821 EltMask = 0x8000ULL;
4822 setVecVal(AArch64::hsub);
4823 } else {
4824 llvm_unreachable("Invalid type for copysign!");
4827 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4829 // If we couldn't materialize the mask above, then the mask vector will be
4830 // the zero vector, and we need to negate it here.
4831 if (VT == MVT::f64 || VT == MVT::v2f64) {
4832 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4833 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4834 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4837 SDValue Sel =
4838 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4840 if (VT == MVT::f16)
4841 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4842 if (VT == MVT::f32)
4843 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4844 else if (VT == MVT::f64)
4845 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4846 else
4847 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4850 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4851 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4852 Attribute::NoImplicitFloat))
4853 return SDValue();
4855 if (!Subtarget->hasNEON())
4856 return SDValue();
4858 // While there is no integer popcount instruction, it can
4859 // be more efficiently lowered to the following sequence that uses
4860 // AdvSIMD registers/instructions as long as the copies to/from
4861 // the AdvSIMD registers are cheap.
4862 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4863 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4864 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4865 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4866 SDValue Val = Op.getOperand(0);
4867 SDLoc DL(Op);
4868 EVT VT = Op.getValueType();
4870 if (VT == MVT::i32 || VT == MVT::i64) {
4871 if (VT == MVT::i32)
4872 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4873 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4875 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4876 SDValue UaddLV = DAG.getNode(
4877 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4878 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4880 if (VT == MVT::i64)
4881 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4882 return UaddLV;
4885 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4886 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4887 "Unexpected type for custom ctpop lowering");
4889 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4890 Val = DAG.getBitcast(VT8Bit, Val);
4891 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4893 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4894 unsigned EltSize = 8;
4895 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4896 while (EltSize != VT.getScalarSizeInBits()) {
4897 EltSize *= 2;
4898 NumElts /= 2;
4899 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4900 Val = DAG.getNode(
4901 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4902 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4905 return Val;
4908 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4910 if (Op.getValueType().isVector())
4911 return LowerVSETCC(Op, DAG);
4913 SDValue LHS = Op.getOperand(0);
4914 SDValue RHS = Op.getOperand(1);
4915 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4916 SDLoc dl(Op);
4918 // We chose ZeroOrOneBooleanContents, so use zero and one.
4919 EVT VT = Op.getValueType();
4920 SDValue TVal = DAG.getConstant(1, dl, VT);
4921 SDValue FVal = DAG.getConstant(0, dl, VT);
4923 // Handle f128 first, since one possible outcome is a normal integer
4924 // comparison which gets picked up by the next if statement.
4925 if (LHS.getValueType() == MVT::f128) {
4926 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4928 // If softenSetCCOperands returned a scalar, use it.
4929 if (!RHS.getNode()) {
4930 assert(LHS.getValueType() == Op.getValueType() &&
4931 "Unexpected setcc expansion!");
4932 return LHS;
4936 if (LHS.getValueType().isInteger()) {
4937 SDValue CCVal;
4938 SDValue Cmp =
4939 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4941 // Note that we inverted the condition above, so we reverse the order of
4942 // the true and false operands here. This will allow the setcc to be
4943 // matched to a single CSINC instruction.
4944 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4947 // Now we know we're dealing with FP values.
4948 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4949 LHS.getValueType() == MVT::f64);
4951 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4952 // and do the comparison.
4953 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4955 AArch64CC::CondCode CC1, CC2;
4956 changeFPCCToAArch64CC(CC, CC1, CC2);
4957 if (CC2 == AArch64CC::AL) {
4958 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4959 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4961 // Note that we inverted the condition above, so we reverse the order of
4962 // the true and false operands here. This will allow the setcc to be
4963 // matched to a single CSINC instruction.
4964 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4965 } else {
4966 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4967 // totally clean. Some of them require two CSELs to implement. As is in
4968 // this case, we emit the first CSEL and then emit a second using the output
4969 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4971 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4972 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4973 SDValue CS1 =
4974 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4976 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4977 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4981 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4982 SDValue RHS, SDValue TVal,
4983 SDValue FVal, const SDLoc &dl,
4984 SelectionDAG &DAG) const {
4985 // Handle f128 first, because it will result in a comparison of some RTLIB
4986 // call result against zero.
4987 if (LHS.getValueType() == MVT::f128) {
4988 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4990 // If softenSetCCOperands returned a scalar, we need to compare the result
4991 // against zero to select between true and false values.
4992 if (!RHS.getNode()) {
4993 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4994 CC = ISD::SETNE;
4998 // Also handle f16, for which we need to do a f32 comparison.
4999 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
5000 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
5001 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
5004 // Next, handle integers.
5005 if (LHS.getValueType().isInteger()) {
5006 assert((LHS.getValueType() == RHS.getValueType()) &&
5007 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
5009 unsigned Opcode = AArch64ISD::CSEL;
5011 // If both the TVal and the FVal are constants, see if we can swap them in
5012 // order to for a CSINV or CSINC out of them.
5013 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
5014 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
5016 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
5017 std::swap(TVal, FVal);
5018 std::swap(CTVal, CFVal);
5019 CC = ISD::getSetCCInverse(CC, true);
5020 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
5021 std::swap(TVal, FVal);
5022 std::swap(CTVal, CFVal);
5023 CC = ISD::getSetCCInverse(CC, true);
5024 } else if (TVal.getOpcode() == ISD::XOR) {
5025 // If TVal is a NOT we want to swap TVal and FVal so that we can match
5026 // with a CSINV rather than a CSEL.
5027 if (isAllOnesConstant(TVal.getOperand(1))) {
5028 std::swap(TVal, FVal);
5029 std::swap(CTVal, CFVal);
5030 CC = ISD::getSetCCInverse(CC, true);
5032 } else if (TVal.getOpcode() == ISD::SUB) {
5033 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
5034 // that we can match with a CSNEG rather than a CSEL.
5035 if (isNullConstant(TVal.getOperand(0))) {
5036 std::swap(TVal, FVal);
5037 std::swap(CTVal, CFVal);
5038 CC = ISD::getSetCCInverse(CC, true);
5040 } else if (CTVal && CFVal) {
5041 const int64_t TrueVal = CTVal->getSExtValue();
5042 const int64_t FalseVal = CFVal->getSExtValue();
5043 bool Swap = false;
5045 // If both TVal and FVal are constants, see if FVal is the
5046 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
5047 // instead of a CSEL in that case.
5048 if (TrueVal == ~FalseVal) {
5049 Opcode = AArch64ISD::CSINV;
5050 } else if (TrueVal == -FalseVal) {
5051 Opcode = AArch64ISD::CSNEG;
5052 } else if (TVal.getValueType() == MVT::i32) {
5053 // If our operands are only 32-bit wide, make sure we use 32-bit
5054 // arithmetic for the check whether we can use CSINC. This ensures that
5055 // the addition in the check will wrap around properly in case there is
5056 // an overflow (which would not be the case if we do the check with
5057 // 64-bit arithmetic).
5058 const uint32_t TrueVal32 = CTVal->getZExtValue();
5059 const uint32_t FalseVal32 = CFVal->getZExtValue();
5061 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
5062 Opcode = AArch64ISD::CSINC;
5064 if (TrueVal32 > FalseVal32) {
5065 Swap = true;
5068 // 64-bit check whether we can use CSINC.
5069 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
5070 Opcode = AArch64ISD::CSINC;
5072 if (TrueVal > FalseVal) {
5073 Swap = true;
5077 // Swap TVal and FVal if necessary.
5078 if (Swap) {
5079 std::swap(TVal, FVal);
5080 std::swap(CTVal, CFVal);
5081 CC = ISD::getSetCCInverse(CC, true);
5084 if (Opcode != AArch64ISD::CSEL) {
5085 // Drop FVal since we can get its value by simply inverting/negating
5086 // TVal.
5087 FVal = TVal;
5091 // Avoid materializing a constant when possible by reusing a known value in
5092 // a register. However, don't perform this optimization if the known value
5093 // is one, zero or negative one in the case of a CSEL. We can always
5094 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
5095 // FVal, respectively.
5096 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
5097 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
5098 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
5099 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5100 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5101 // "a != C ? x : a" to avoid materializing C.
5102 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5103 TVal = LHS;
5104 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5105 FVal = LHS;
5106 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5107 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5108 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5109 // avoid materializing C.
5110 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5111 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5112 Opcode = AArch64ISD::CSINV;
5113 TVal = LHS;
5114 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5118 SDValue CCVal;
5119 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5120 EVT VT = TVal.getValueType();
5121 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5124 // Now we know we're dealing with FP values.
5125 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5126 LHS.getValueType() == MVT::f64);
5127 assert(LHS.getValueType() == RHS.getValueType());
5128 EVT VT = TVal.getValueType();
5129 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5131 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5132 // clean. Some of them require two CSELs to implement.
5133 AArch64CC::CondCode CC1, CC2;
5134 changeFPCCToAArch64CC(CC, CC1, CC2);
5136 if (DAG.getTarget().Options.UnsafeFPMath) {
5137 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5138 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5139 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5140 if (RHSVal && RHSVal->isZero()) {
5141 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5142 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5144 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5145 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5146 TVal = LHS;
5147 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5148 CFVal && CFVal->isZero() &&
5149 FVal.getValueType() == LHS.getValueType())
5150 FVal = LHS;
5154 // Emit first, and possibly only, CSEL.
5155 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5156 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5158 // If we need a second CSEL, emit it, using the output of the first as the
5159 // RHS. We're effectively OR'ing the two CC's together.
5160 if (CC2 != AArch64CC::AL) {
5161 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5162 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5165 // Otherwise, return the output of the first CSEL.
5166 return CS1;
5169 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5170 SelectionDAG &DAG) const {
5171 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5172 SDValue LHS = Op.getOperand(0);
5173 SDValue RHS = Op.getOperand(1);
5174 SDValue TVal = Op.getOperand(2);
5175 SDValue FVal = Op.getOperand(3);
5176 SDLoc DL(Op);
5177 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5180 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5181 SelectionDAG &DAG) const {
5182 SDValue CCVal = Op->getOperand(0);
5183 SDValue TVal = Op->getOperand(1);
5184 SDValue FVal = Op->getOperand(2);
5185 SDLoc DL(Op);
5187 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5188 // instruction.
5189 if (isOverflowIntrOpRes(CCVal)) {
5190 // Only lower legal XALUO ops.
5191 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5192 return SDValue();
5194 AArch64CC::CondCode OFCC;
5195 SDValue Value, Overflow;
5196 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5197 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5199 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5200 CCVal, Overflow);
5203 // Lower it the same way as we would lower a SELECT_CC node.
5204 ISD::CondCode CC;
5205 SDValue LHS, RHS;
5206 if (CCVal.getOpcode() == ISD::SETCC) {
5207 LHS = CCVal.getOperand(0);
5208 RHS = CCVal.getOperand(1);
5209 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5210 } else {
5211 LHS = CCVal;
5212 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5213 CC = ISD::SETNE;
5215 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5218 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5219 SelectionDAG &DAG) const {
5220 // Jump table entries as PC relative offsets. No additional tweaking
5221 // is necessary here. Just get the address of the jump table.
5222 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5224 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5225 !Subtarget->isTargetMachO()) {
5226 return getAddrLarge(JT, DAG);
5227 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5228 return getAddrTiny(JT, DAG);
5230 return getAddr(JT, DAG);
5233 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5234 SelectionDAG &DAG) const {
5235 // Jump table entries as PC relative offsets. No additional tweaking
5236 // is necessary here. Just get the address of the jump table.
5237 SDLoc DL(Op);
5238 SDValue JT = Op.getOperand(1);
5239 SDValue Entry = Op.getOperand(2);
5240 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5242 SDNode *Dest =
5243 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5244 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5245 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5246 SDValue(Dest, 0));
5249 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5250 SelectionDAG &DAG) const {
5251 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5253 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5254 // Use the GOT for the large code model on iOS.
5255 if (Subtarget->isTargetMachO()) {
5256 return getGOT(CP, DAG);
5258 return getAddrLarge(CP, DAG);
5259 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5260 return getAddrTiny(CP, DAG);
5261 } else {
5262 return getAddr(CP, DAG);
5266 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5267 SelectionDAG &DAG) const {
5268 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5269 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5270 !Subtarget->isTargetMachO()) {
5271 return getAddrLarge(BA, DAG);
5272 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5273 return getAddrTiny(BA, DAG);
5275 return getAddr(BA, DAG);
5278 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5279 SelectionDAG &DAG) const {
5280 AArch64FunctionInfo *FuncInfo =
5281 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5283 SDLoc DL(Op);
5284 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5285 getPointerTy(DAG.getDataLayout()));
5286 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
5287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5288 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5289 MachinePointerInfo(SV));
5292 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5293 SelectionDAG &DAG) const {
5294 AArch64FunctionInfo *FuncInfo =
5295 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5297 SDLoc DL(Op);
5298 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5299 ? FuncInfo->getVarArgsGPRIndex()
5300 : FuncInfo->getVarArgsStackIndex(),
5301 getPointerTy(DAG.getDataLayout()));
5302 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5303 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5304 MachinePointerInfo(SV));
5307 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5308 SelectionDAG &DAG) const {
5309 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5310 // Standard, section B.3.
5311 MachineFunction &MF = DAG.getMachineFunction();
5312 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5313 auto PtrVT = getPointerTy(DAG.getDataLayout());
5314 SDLoc DL(Op);
5316 SDValue Chain = Op.getOperand(0);
5317 SDValue VAList = Op.getOperand(1);
5318 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5319 SmallVector<SDValue, 4> MemOps;
5321 // void *__stack at offset 0
5322 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5323 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5324 MachinePointerInfo(SV), /* Alignment = */ 8));
5326 // void *__gr_top at offset 8
5327 int GPRSize = FuncInfo->getVarArgsGPRSize();
5328 if (GPRSize > 0) {
5329 SDValue GRTop, GRTopAddr;
5331 GRTopAddr =
5332 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5334 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5335 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5336 DAG.getConstant(GPRSize, DL, PtrVT));
5338 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5339 MachinePointerInfo(SV, 8),
5340 /* Alignment = */ 8));
5343 // void *__vr_top at offset 16
5344 int FPRSize = FuncInfo->getVarArgsFPRSize();
5345 if (FPRSize > 0) {
5346 SDValue VRTop, VRTopAddr;
5347 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5348 DAG.getConstant(16, DL, PtrVT));
5350 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5351 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5352 DAG.getConstant(FPRSize, DL, PtrVT));
5354 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5355 MachinePointerInfo(SV, 16),
5356 /* Alignment = */ 8));
5359 // int __gr_offs at offset 24
5360 SDValue GROffsAddr =
5361 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5362 MemOps.push_back(DAG.getStore(
5363 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5364 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5366 // int __vr_offs at offset 28
5367 SDValue VROffsAddr =
5368 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5369 MemOps.push_back(DAG.getStore(
5370 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5371 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5373 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5376 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5377 SelectionDAG &DAG) const {
5378 MachineFunction &MF = DAG.getMachineFunction();
5380 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5381 return LowerWin64_VASTART(Op, DAG);
5382 else if (Subtarget->isTargetDarwin())
5383 return LowerDarwin_VASTART(Op, DAG);
5384 else
5385 return LowerAAPCS_VASTART(Op, DAG);
5388 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5389 SelectionDAG &DAG) const {
5390 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5391 // pointer.
5392 SDLoc DL(Op);
5393 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
5394 unsigned VaListSize = (Subtarget->isTargetDarwin() ||
5395 Subtarget->isTargetWindows()) ? PtrSize : 32;
5396 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5397 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5399 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
5400 DAG.getConstant(VaListSize, DL, MVT::i32), PtrSize,
5401 false, false, false, MachinePointerInfo(DestSV),
5402 MachinePointerInfo(SrcSV));
5405 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5406 assert(Subtarget->isTargetDarwin() &&
5407 "automatic va_arg instruction only works on Darwin");
5409 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5410 EVT VT = Op.getValueType();
5411 SDLoc DL(Op);
5412 SDValue Chain = Op.getOperand(0);
5413 SDValue Addr = Op.getOperand(1);
5414 unsigned Align = Op.getConstantOperandVal(3);
5415 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
5416 auto PtrVT = getPointerTy(DAG.getDataLayout());
5417 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
5418 SDValue VAList =
5419 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
5420 Chain = VAList.getValue(1);
5421 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
5423 if (Align > MinSlotSize) {
5424 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5425 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5426 DAG.getConstant(Align - 1, DL, PtrVT));
5427 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5428 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5431 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5432 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5434 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5435 // up to 64 bits. At the very least, we have to increase the striding of the
5436 // vaargs list to match this, and for FP values we need to introduce
5437 // FP_ROUND nodes as well.
5438 if (VT.isInteger() && !VT.isVector())
5439 ArgSize = std::max(ArgSize, MinSlotSize);
5440 bool NeedFPTrunc = false;
5441 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5442 ArgSize = 8;
5443 NeedFPTrunc = true;
5446 // Increment the pointer, VAList, to the next vaarg
5447 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5448 DAG.getConstant(ArgSize, DL, PtrVT));
5449 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
5451 // Store the incremented VAList to the legalized pointer
5452 SDValue APStore =
5453 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5455 // Load the actual argument out of the pointer VAList
5456 if (NeedFPTrunc) {
5457 // Load the value as an f64.
5458 SDValue WideFP =
5459 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5460 // Round the value down to an f32.
5461 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5462 DAG.getIntPtrConstant(1, DL));
5463 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5464 // Merge the rounded value with the chain output of the load.
5465 return DAG.getMergeValues(Ops, DL);
5468 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5471 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5472 SelectionDAG &DAG) const {
5473 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5474 MFI.setFrameAddressIsTaken(true);
5476 EVT VT = Op.getValueType();
5477 SDLoc DL(Op);
5478 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5479 SDValue FrameAddr =
5480 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
5481 while (Depth--)
5482 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5483 MachinePointerInfo());
5485 if (Subtarget->isTargetILP32())
5486 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
5487 DAG.getValueType(VT));
5489 return FrameAddr;
5492 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5493 SelectionDAG &DAG) const {
5494 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5496 EVT VT = getPointerTy(DAG.getDataLayout());
5497 SDLoc DL(Op);
5498 int FI = MFI.CreateFixedObject(4, 0, false);
5499 return DAG.getFrameIndex(FI, VT);
5502 #define GET_REGISTER_MATCHER
5503 #include "AArch64GenAsmMatcher.inc"
5505 // FIXME? Maybe this could be a TableGen attribute on some registers and
5506 // this table could be generated automatically from RegInfo.
5507 Register AArch64TargetLowering::
5508 getRegisterByName(const char* RegName, EVT VT, const MachineFunction &MF) const {
5509 Register Reg = MatchRegisterName(RegName);
5510 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5511 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5512 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5513 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5514 Reg = 0;
5516 if (Reg)
5517 return Reg;
5518 report_fatal_error(Twine("Invalid register name \""
5519 + StringRef(RegName) + "\"."));
5522 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5523 SelectionDAG &DAG) const {
5524 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5526 EVT VT = Op.getValueType();
5527 SDLoc DL(Op);
5529 SDValue FrameAddr =
5530 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5531 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5533 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5536 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5537 SelectionDAG &DAG) const {
5538 MachineFunction &MF = DAG.getMachineFunction();
5539 MachineFrameInfo &MFI = MF.getFrameInfo();
5540 MFI.setReturnAddressIsTaken(true);
5542 EVT VT = Op.getValueType();
5543 SDLoc DL(Op);
5544 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5545 if (Depth) {
5546 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5547 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5548 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5549 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5550 MachinePointerInfo());
5553 // Return LR, which contains the return address. Mark it an implicit live-in.
5554 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5555 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5558 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5559 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5560 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5561 SelectionDAG &DAG) const {
5562 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5563 EVT VT = Op.getValueType();
5564 unsigned VTBits = VT.getSizeInBits();
5565 SDLoc dl(Op);
5566 SDValue ShOpLo = Op.getOperand(0);
5567 SDValue ShOpHi = Op.getOperand(1);
5568 SDValue ShAmt = Op.getOperand(2);
5569 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5571 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5573 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5574 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5575 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5577 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5578 // is "undef". We wanted 0, so CSEL it directly.
5579 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5580 ISD::SETEQ, dl, DAG);
5581 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5582 HiBitsForLo =
5583 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5584 HiBitsForLo, CCVal, Cmp);
5586 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5587 DAG.getConstant(VTBits, dl, MVT::i64));
5589 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5590 SDValue LoForNormalShift =
5591 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5593 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5594 dl, DAG);
5595 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5596 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5597 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5598 LoForNormalShift, CCVal, Cmp);
5600 // AArch64 shifts larger than the register width are wrapped rather than
5601 // clamped, so we can't just emit "hi >> x".
5602 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5603 SDValue HiForBigShift =
5604 Opc == ISD::SRA
5605 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5606 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5607 : DAG.getConstant(0, dl, VT);
5608 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5609 HiForNormalShift, CCVal, Cmp);
5611 SDValue Ops[2] = { Lo, Hi };
5612 return DAG.getMergeValues(Ops, dl);
5615 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5616 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5617 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5618 SelectionDAG &DAG) const {
5619 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5620 EVT VT = Op.getValueType();
5621 unsigned VTBits = VT.getSizeInBits();
5622 SDLoc dl(Op);
5623 SDValue ShOpLo = Op.getOperand(0);
5624 SDValue ShOpHi = Op.getOperand(1);
5625 SDValue ShAmt = Op.getOperand(2);
5627 assert(Op.getOpcode() == ISD::SHL_PARTS);
5628 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5629 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5630 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5632 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5633 // is "undef". We wanted 0, so CSEL it directly.
5634 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5635 ISD::SETEQ, dl, DAG);
5636 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5637 LoBitsForHi =
5638 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5639 LoBitsForHi, CCVal, Cmp);
5641 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5642 DAG.getConstant(VTBits, dl, MVT::i64));
5643 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5644 SDValue HiForNormalShift =
5645 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5647 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5649 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5650 dl, DAG);
5651 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5652 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5653 HiForNormalShift, CCVal, Cmp);
5655 // AArch64 shifts of larger than register sizes are wrapped rather than
5656 // clamped, so we can't just emit "lo << a" if a is too big.
5657 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5658 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5659 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5660 LoForNormalShift, CCVal, Cmp);
5662 SDValue Ops[2] = { Lo, Hi };
5663 return DAG.getMergeValues(Ops, dl);
5666 bool AArch64TargetLowering::isOffsetFoldingLegal(
5667 const GlobalAddressSDNode *GA) const {
5668 // Offsets are folded in the DAG combine rather than here so that we can
5669 // intelligently choose an offset based on the uses.
5670 return false;
5673 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5674 bool OptForSize) const {
5675 bool IsLegal = false;
5676 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5677 // 16-bit case when target has full fp16 support.
5678 // FIXME: We should be able to handle f128 as well with a clever lowering.
5679 const APInt ImmInt = Imm.bitcastToAPInt();
5680 if (VT == MVT::f64)
5681 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5682 else if (VT == MVT::f32)
5683 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5684 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5685 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5686 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5687 // generate that fmov.
5689 // If we can not materialize in immediate field for fmov, check if the
5690 // value can be encoded as the immediate operand of a logical instruction.
5691 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5692 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5693 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5694 // however the mov+fmov sequence is always better because of the reduced
5695 // cache pressure. The timings are still the same if you consider
5696 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5697 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5698 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5699 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5700 Insn);
5701 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5702 IsLegal = Insn.size() <= Limit;
5705 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5706 << " imm value: "; Imm.dump(););
5707 return IsLegal;
5710 //===----------------------------------------------------------------------===//
5711 // AArch64 Optimization Hooks
5712 //===----------------------------------------------------------------------===//
5714 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5715 SDValue Operand, SelectionDAG &DAG,
5716 int &ExtraSteps) {
5717 EVT VT = Operand.getValueType();
5718 if (ST->hasNEON() &&
5719 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5720 VT == MVT::f32 || VT == MVT::v1f32 ||
5721 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5722 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5723 // For the reciprocal estimates, convergence is quadratic, so the number
5724 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5725 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5726 // the result for float (23 mantissa bits) is 2 and for double (52
5727 // mantissa bits) is 3.
5728 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5730 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5733 return SDValue();
5736 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5737 SelectionDAG &DAG, int Enabled,
5738 int &ExtraSteps,
5739 bool &UseOneConst,
5740 bool Reciprocal) const {
5741 if (Enabled == ReciprocalEstimate::Enabled ||
5742 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5743 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5744 DAG, ExtraSteps)) {
5745 SDLoc DL(Operand);
5746 EVT VT = Operand.getValueType();
5748 SDNodeFlags Flags;
5749 Flags.setAllowReassociation(true);
5751 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5752 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5753 for (int i = ExtraSteps; i > 0; --i) {
5754 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5755 Flags);
5756 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5757 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5759 if (!Reciprocal) {
5760 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5761 VT);
5762 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5763 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5765 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5766 // Correct the result if the operand is 0.0.
5767 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5768 VT, Eq, Operand, Estimate);
5771 ExtraSteps = 0;
5772 return Estimate;
5775 return SDValue();
5778 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5779 SelectionDAG &DAG, int Enabled,
5780 int &ExtraSteps) const {
5781 if (Enabled == ReciprocalEstimate::Enabled)
5782 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5783 DAG, ExtraSteps)) {
5784 SDLoc DL(Operand);
5785 EVT VT = Operand.getValueType();
5787 SDNodeFlags Flags;
5788 Flags.setAllowReassociation(true);
5790 // Newton reciprocal iteration: E * (2 - X * E)
5791 // AArch64 reciprocal iteration instruction: (2 - M * N)
5792 for (int i = ExtraSteps; i > 0; --i) {
5793 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5794 Estimate, Flags);
5795 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5798 ExtraSteps = 0;
5799 return Estimate;
5802 return SDValue();
5805 //===----------------------------------------------------------------------===//
5806 // AArch64 Inline Assembly Support
5807 //===----------------------------------------------------------------------===//
5809 // Table of Constraints
5810 // TODO: This is the current set of constraints supported by ARM for the
5811 // compiler, not all of them may make sense.
5813 // r - A general register
5814 // w - An FP/SIMD register of some size in the range v0-v31
5815 // x - An FP/SIMD register of some size in the range v0-v15
5816 // I - Constant that can be used with an ADD instruction
5817 // J - Constant that can be used with a SUB instruction
5818 // K - Constant that can be used with a 32-bit logical instruction
5819 // L - Constant that can be used with a 64-bit logical instruction
5820 // M - Constant that can be used as a 32-bit MOV immediate
5821 // N - Constant that can be used as a 64-bit MOV immediate
5822 // Q - A memory reference with base register and no offset
5823 // S - A symbolic address
5824 // Y - Floating point constant zero
5825 // Z - Integer constant zero
5827 // Note that general register operands will be output using their 64-bit x
5828 // register name, whatever the size of the variable, unless the asm operand
5829 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5830 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5831 // %q modifier.
5832 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5833 // At this point, we have to lower this constraint to something else, so we
5834 // lower it to an "r" or "w". However, by doing this we will force the result
5835 // to be in register, while the X constraint is much more permissive.
5837 // Although we are correct (we are free to emit anything, without
5838 // constraints), we might break use cases that would expect us to be more
5839 // efficient and emit something else.
5840 if (!Subtarget->hasFPARMv8())
5841 return "r";
5843 if (ConstraintVT.isFloatingPoint())
5844 return "w";
5846 if (ConstraintVT.isVector() &&
5847 (ConstraintVT.getSizeInBits() == 64 ||
5848 ConstraintVT.getSizeInBits() == 128))
5849 return "w";
5851 return "r";
5854 enum PredicateConstraint {
5855 Upl,
5856 Upa,
5857 Invalid
5860 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
5861 PredicateConstraint P = PredicateConstraint::Invalid;
5862 if (Constraint == "Upa")
5863 P = PredicateConstraint::Upa;
5864 if (Constraint == "Upl")
5865 P = PredicateConstraint::Upl;
5866 return P;
5869 /// getConstraintType - Given a constraint letter, return the type of
5870 /// constraint it is for this target.
5871 AArch64TargetLowering::ConstraintType
5872 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5873 if (Constraint.size() == 1) {
5874 switch (Constraint[0]) {
5875 default:
5876 break;
5877 case 'x':
5878 case 'w':
5879 case 'y':
5880 return C_RegisterClass;
5881 // An address with a single base register. Due to the way we
5882 // currently handle addresses it is the same as 'r'.
5883 case 'Q':
5884 return C_Memory;
5885 case 'I':
5886 case 'J':
5887 case 'K':
5888 case 'L':
5889 case 'M':
5890 case 'N':
5891 case 'Y':
5892 case 'Z':
5893 return C_Immediate;
5894 case 'z':
5895 case 'S': // A symbolic address
5896 return C_Other;
5898 } else if (parsePredicateConstraint(Constraint) !=
5899 PredicateConstraint::Invalid)
5900 return C_RegisterClass;
5901 return TargetLowering::getConstraintType(Constraint);
5904 /// Examine constraint type and operand type and determine a weight value.
5905 /// This object must already have been set up with the operand type
5906 /// and the current alternative constraint selected.
5907 TargetLowering::ConstraintWeight
5908 AArch64TargetLowering::getSingleConstraintMatchWeight(
5909 AsmOperandInfo &info, const char *constraint) const {
5910 ConstraintWeight weight = CW_Invalid;
5911 Value *CallOperandVal = info.CallOperandVal;
5912 // If we don't have a value, we can't do a match,
5913 // but allow it at the lowest weight.
5914 if (!CallOperandVal)
5915 return CW_Default;
5916 Type *type = CallOperandVal->getType();
5917 // Look at the constraint type.
5918 switch (*constraint) {
5919 default:
5920 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5921 break;
5922 case 'x':
5923 case 'w':
5924 case 'y':
5925 if (type->isFloatingPointTy() || type->isVectorTy())
5926 weight = CW_Register;
5927 break;
5928 case 'z':
5929 weight = CW_Constant;
5930 break;
5931 case 'U':
5932 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
5933 weight = CW_Register;
5934 break;
5936 return weight;
5939 std::pair<unsigned, const TargetRegisterClass *>
5940 AArch64TargetLowering::getRegForInlineAsmConstraint(
5941 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5942 if (Constraint.size() == 1) {
5943 switch (Constraint[0]) {
5944 case 'r':
5945 if (VT.getSizeInBits() == 64)
5946 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5947 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5948 case 'w':
5949 if (!Subtarget->hasFPARMv8())
5950 break;
5951 if (VT.isScalableVector())
5952 return std::make_pair(0U, &AArch64::ZPRRegClass);
5953 if (VT.getSizeInBits() == 16)
5954 return std::make_pair(0U, &AArch64::FPR16RegClass);
5955 if (VT.getSizeInBits() == 32)
5956 return std::make_pair(0U, &AArch64::FPR32RegClass);
5957 if (VT.getSizeInBits() == 64)
5958 return std::make_pair(0U, &AArch64::FPR64RegClass);
5959 if (VT.getSizeInBits() == 128)
5960 return std::make_pair(0U, &AArch64::FPR128RegClass);
5961 break;
5962 // The instructions that this constraint is designed for can
5963 // only take 128-bit registers so just use that regclass.
5964 case 'x':
5965 if (!Subtarget->hasFPARMv8())
5966 break;
5967 if (VT.isScalableVector())
5968 return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
5969 if (VT.getSizeInBits() == 128)
5970 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5971 break;
5972 case 'y':
5973 if (!Subtarget->hasFPARMv8())
5974 break;
5975 if (VT.isScalableVector())
5976 return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
5977 break;
5979 } else {
5980 PredicateConstraint PC = parsePredicateConstraint(Constraint);
5981 if (PC != PredicateConstraint::Invalid) {
5982 assert(VT.isScalableVector());
5983 bool restricted = (PC == PredicateConstraint::Upl);
5984 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
5985 : std::make_pair(0U, &AArch64::PPRRegClass);
5988 if (StringRef("{cc}").equals_lower(Constraint))
5989 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5991 // Use the default implementation in TargetLowering to convert the register
5992 // constraint into a member of a register class.
5993 std::pair<unsigned, const TargetRegisterClass *> Res;
5994 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5996 // Not found as a standard register?
5997 if (!Res.second) {
5998 unsigned Size = Constraint.size();
5999 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
6000 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
6001 int RegNo;
6002 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
6003 if (!Failed && RegNo >= 0 && RegNo <= 31) {
6004 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
6005 // By default we'll emit v0-v31 for this unless there's a modifier where
6006 // we'll emit the correct register as well.
6007 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
6008 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
6009 Res.second = &AArch64::FPR64RegClass;
6010 } else {
6011 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
6012 Res.second = &AArch64::FPR128RegClass;
6018 if (Res.second && !Subtarget->hasFPARMv8() &&
6019 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
6020 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
6021 return std::make_pair(0U, nullptr);
6023 return Res;
6026 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6027 /// vector. If it is invalid, don't add anything to Ops.
6028 void AArch64TargetLowering::LowerAsmOperandForConstraint(
6029 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
6030 SelectionDAG &DAG) const {
6031 SDValue Result;
6033 // Currently only support length 1 constraints.
6034 if (Constraint.length() != 1)
6035 return;
6037 char ConstraintLetter = Constraint[0];
6038 switch (ConstraintLetter) {
6039 default:
6040 break;
6042 // This set of constraints deal with valid constants for various instructions.
6043 // Validate and return a target constant for them if we can.
6044 case 'z': {
6045 // 'z' maps to xzr or wzr so it needs an input of 0.
6046 if (!isNullConstant(Op))
6047 return;
6049 if (Op.getValueType() == MVT::i64)
6050 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
6051 else
6052 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
6053 break;
6055 case 'S': {
6056 // An absolute symbolic address or label reference.
6057 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
6058 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
6059 GA->getValueType(0));
6060 } else if (const BlockAddressSDNode *BA =
6061 dyn_cast<BlockAddressSDNode>(Op)) {
6062 Result =
6063 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
6064 } else if (const ExternalSymbolSDNode *ES =
6065 dyn_cast<ExternalSymbolSDNode>(Op)) {
6066 Result =
6067 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
6068 } else
6069 return;
6070 break;
6073 case 'I':
6074 case 'J':
6075 case 'K':
6076 case 'L':
6077 case 'M':
6078 case 'N':
6079 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
6080 if (!C)
6081 return;
6083 // Grab the value and do some validation.
6084 uint64_t CVal = C->getZExtValue();
6085 switch (ConstraintLetter) {
6086 // The I constraint applies only to simple ADD or SUB immediate operands:
6087 // i.e. 0 to 4095 with optional shift by 12
6088 // The J constraint applies only to ADD or SUB immediates that would be
6089 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
6090 // instruction [or vice versa], in other words -1 to -4095 with optional
6091 // left shift by 12.
6092 case 'I':
6093 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
6094 break;
6095 return;
6096 case 'J': {
6097 uint64_t NVal = -C->getSExtValue();
6098 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
6099 CVal = C->getSExtValue();
6100 break;
6102 return;
6104 // The K and L constraints apply *only* to logical immediates, including
6105 // what used to be the MOVI alias for ORR (though the MOVI alias has now
6106 // been removed and MOV should be used). So these constraints have to
6107 // distinguish between bit patterns that are valid 32-bit or 64-bit
6108 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
6109 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
6110 // versa.
6111 case 'K':
6112 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6113 break;
6114 return;
6115 case 'L':
6116 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6117 break;
6118 return;
6119 // The M and N constraints are a superset of K and L respectively, for use
6120 // with the MOV (immediate) alias. As well as the logical immediates they
6121 // also match 32 or 64-bit immediates that can be loaded either using a
6122 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
6123 // (M) or 64-bit 0x1234000000000000 (N) etc.
6124 // As a note some of this code is liberally stolen from the asm parser.
6125 case 'M': {
6126 if (!isUInt<32>(CVal))
6127 return;
6128 if (AArch64_AM::isLogicalImmediate(CVal, 32))
6129 break;
6130 if ((CVal & 0xFFFF) == CVal)
6131 break;
6132 if ((CVal & 0xFFFF0000ULL) == CVal)
6133 break;
6134 uint64_t NCVal = ~(uint32_t)CVal;
6135 if ((NCVal & 0xFFFFULL) == NCVal)
6136 break;
6137 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6138 break;
6139 return;
6141 case 'N': {
6142 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6143 break;
6144 if ((CVal & 0xFFFFULL) == CVal)
6145 break;
6146 if ((CVal & 0xFFFF0000ULL) == CVal)
6147 break;
6148 if ((CVal & 0xFFFF00000000ULL) == CVal)
6149 break;
6150 if ((CVal & 0xFFFF000000000000ULL) == CVal)
6151 break;
6152 uint64_t NCVal = ~CVal;
6153 if ((NCVal & 0xFFFFULL) == NCVal)
6154 break;
6155 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6156 break;
6157 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6158 break;
6159 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6160 break;
6161 return;
6163 default:
6164 return;
6167 // All assembler immediates are 64-bit integers.
6168 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6169 break;
6172 if (Result.getNode()) {
6173 Ops.push_back(Result);
6174 return;
6177 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6180 //===----------------------------------------------------------------------===//
6181 // AArch64 Advanced SIMD Support
6182 //===----------------------------------------------------------------------===//
6184 /// WidenVector - Given a value in the V64 register class, produce the
6185 /// equivalent value in the V128 register class.
6186 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6187 EVT VT = V64Reg.getValueType();
6188 unsigned NarrowSize = VT.getVectorNumElements();
6189 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6190 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6191 SDLoc DL(V64Reg);
6193 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6194 V64Reg, DAG.getConstant(0, DL, MVT::i32));
6197 /// getExtFactor - Determine the adjustment factor for the position when
6198 /// generating an "extract from vector registers" instruction.
6199 static unsigned getExtFactor(SDValue &V) {
6200 EVT EltType = V.getValueType().getVectorElementType();
6201 return EltType.getSizeInBits() / 8;
6204 /// NarrowVector - Given a value in the V128 register class, produce the
6205 /// equivalent value in the V64 register class.
6206 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6207 EVT VT = V128Reg.getValueType();
6208 unsigned WideSize = VT.getVectorNumElements();
6209 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6210 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6211 SDLoc DL(V128Reg);
6213 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6216 // Gather data to see if the operation can be modelled as a
6217 // shuffle in combination with VEXTs.
6218 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6219 SelectionDAG &DAG) const {
6220 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6221 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6222 SDLoc dl(Op);
6223 EVT VT = Op.getValueType();
6224 unsigned NumElts = VT.getVectorNumElements();
6226 struct ShuffleSourceInfo {
6227 SDValue Vec;
6228 unsigned MinElt;
6229 unsigned MaxElt;
6231 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6232 // be compatible with the shuffle we intend to construct. As a result
6233 // ShuffleVec will be some sliding window into the original Vec.
6234 SDValue ShuffleVec;
6236 // Code should guarantee that element i in Vec starts at element "WindowBase
6237 // + i * WindowScale in ShuffleVec".
6238 int WindowBase;
6239 int WindowScale;
6241 ShuffleSourceInfo(SDValue Vec)
6242 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6243 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6245 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6248 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6249 // node.
6250 SmallVector<ShuffleSourceInfo, 2> Sources;
6251 for (unsigned i = 0; i < NumElts; ++i) {
6252 SDValue V = Op.getOperand(i);
6253 if (V.isUndef())
6254 continue;
6255 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6256 !isa<ConstantSDNode>(V.getOperand(1))) {
6257 LLVM_DEBUG(
6258 dbgs() << "Reshuffle failed: "
6259 "a shuffle can only come from building a vector from "
6260 "various elements of other vectors, provided their "
6261 "indices are constant\n");
6262 return SDValue();
6265 // Add this element source to the list if it's not already there.
6266 SDValue SourceVec = V.getOperand(0);
6267 auto Source = find(Sources, SourceVec);
6268 if (Source == Sources.end())
6269 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6271 // Update the minimum and maximum lane number seen.
6272 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6273 Source->MinElt = std::min(Source->MinElt, EltNo);
6274 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6277 if (Sources.size() > 2) {
6278 LLVM_DEBUG(
6279 dbgs() << "Reshuffle failed: currently only do something sane when at "
6280 "most two source vectors are involved\n");
6281 return SDValue();
6284 // Find out the smallest element size among result and two sources, and use
6285 // it as element size to build the shuffle_vector.
6286 EVT SmallestEltTy = VT.getVectorElementType();
6287 for (auto &Source : Sources) {
6288 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6289 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6290 SmallestEltTy = SrcEltTy;
6293 unsigned ResMultiplier =
6294 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6295 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6296 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6298 // If the source vector is too wide or too narrow, we may nevertheless be able
6299 // to construct a compatible shuffle either by concatenating it with UNDEF or
6300 // extracting a suitable range of elements.
6301 for (auto &Src : Sources) {
6302 EVT SrcVT = Src.ShuffleVec.getValueType();
6304 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6305 continue;
6307 // This stage of the search produces a source with the same element type as
6308 // the original, but with a total width matching the BUILD_VECTOR output.
6309 EVT EltVT = SrcVT.getVectorElementType();
6310 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6311 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6313 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6314 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6315 // We can pad out the smaller vector for free, so if it's part of a
6316 // shuffle...
6317 Src.ShuffleVec =
6318 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6319 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6320 continue;
6323 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6325 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6326 LLVM_DEBUG(
6327 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6328 return SDValue();
6331 if (Src.MinElt >= NumSrcElts) {
6332 // The extraction can just take the second half
6333 Src.ShuffleVec =
6334 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6335 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6336 Src.WindowBase = -NumSrcElts;
6337 } else if (Src.MaxElt < NumSrcElts) {
6338 // The extraction can just take the first half
6339 Src.ShuffleVec =
6340 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6341 DAG.getConstant(0, dl, MVT::i64));
6342 } else {
6343 // An actual VEXT is needed
6344 SDValue VEXTSrc1 =
6345 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6346 DAG.getConstant(0, dl, MVT::i64));
6347 SDValue VEXTSrc2 =
6348 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6349 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6350 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6352 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6353 VEXTSrc2,
6354 DAG.getConstant(Imm, dl, MVT::i32));
6355 Src.WindowBase = -Src.MinElt;
6359 // Another possible incompatibility occurs from the vector element types. We
6360 // can fix this by bitcasting the source vectors to the same type we intend
6361 // for the shuffle.
6362 for (auto &Src : Sources) {
6363 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6364 if (SrcEltTy == SmallestEltTy)
6365 continue;
6366 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6367 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6368 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6369 Src.WindowBase *= Src.WindowScale;
6372 // Final sanity check before we try to actually produce a shuffle.
6373 LLVM_DEBUG(for (auto Src
6374 : Sources)
6375 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6377 // The stars all align, our next step is to produce the mask for the shuffle.
6378 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6379 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6380 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6381 SDValue Entry = Op.getOperand(i);
6382 if (Entry.isUndef())
6383 continue;
6385 auto Src = find(Sources, Entry.getOperand(0));
6386 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6388 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6389 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6390 // segment.
6391 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6392 int BitsDefined =
6393 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6394 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6396 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6397 // starting at the appropriate offset.
6398 int *LaneMask = &Mask[i * ResMultiplier];
6400 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6401 ExtractBase += NumElts * (Src - Sources.begin());
6402 for (int j = 0; j < LanesDefined; ++j)
6403 LaneMask[j] = ExtractBase + j;
6406 // Final check before we try to produce nonsense...
6407 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6408 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6409 return SDValue();
6412 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6413 for (unsigned i = 0; i < Sources.size(); ++i)
6414 ShuffleOps[i] = Sources[i].ShuffleVec;
6416 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6417 ShuffleOps[1], Mask);
6418 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6420 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6421 dbgs() << "Reshuffle, creating node: "; V.dump(););
6423 return V;
6426 // check if an EXT instruction can handle the shuffle mask when the
6427 // vector sources of the shuffle are the same.
6428 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6429 unsigned NumElts = VT.getVectorNumElements();
6431 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6432 if (M[0] < 0)
6433 return false;
6435 Imm = M[0];
6437 // If this is a VEXT shuffle, the immediate value is the index of the first
6438 // element. The other shuffle indices must be the successive elements after
6439 // the first one.
6440 unsigned ExpectedElt = Imm;
6441 for (unsigned i = 1; i < NumElts; ++i) {
6442 // Increment the expected index. If it wraps around, just follow it
6443 // back to index zero and keep going.
6444 ++ExpectedElt;
6445 if (ExpectedElt == NumElts)
6446 ExpectedElt = 0;
6448 if (M[i] < 0)
6449 continue; // ignore UNDEF indices
6450 if (ExpectedElt != static_cast<unsigned>(M[i]))
6451 return false;
6454 return true;
6457 // check if an EXT instruction can handle the shuffle mask when the
6458 // vector sources of the shuffle are different.
6459 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6460 unsigned &Imm) {
6461 // Look for the first non-undef element.
6462 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6464 // Benefit form APInt to handle overflow when calculating expected element.
6465 unsigned NumElts = VT.getVectorNumElements();
6466 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6467 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6468 // The following shuffle indices must be the successive elements after the
6469 // first real element.
6470 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6471 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6472 if (FirstWrongElt != M.end())
6473 return false;
6475 // The index of an EXT is the first element if it is not UNDEF.
6476 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6477 // value of the first element. E.g.
6478 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6479 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6480 // ExpectedElt is the last mask index plus 1.
6481 Imm = ExpectedElt.getZExtValue();
6483 // There are two difference cases requiring to reverse input vectors.
6484 // For example, for vector <4 x i32> we have the following cases,
6485 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6486 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6487 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6488 // to reverse two input vectors.
6489 if (Imm < NumElts)
6490 ReverseEXT = true;
6491 else
6492 Imm -= NumElts;
6494 return true;
6497 /// isREVMask - Check if a vector shuffle corresponds to a REV
6498 /// instruction with the specified blocksize. (The order of the elements
6499 /// within each block of the vector is reversed.)
6500 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6501 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6502 "Only possible block sizes for REV are: 16, 32, 64");
6504 unsigned EltSz = VT.getScalarSizeInBits();
6505 if (EltSz == 64)
6506 return false;
6508 unsigned NumElts = VT.getVectorNumElements();
6509 unsigned BlockElts = M[0] + 1;
6510 // If the first shuffle index is UNDEF, be optimistic.
6511 if (M[0] < 0)
6512 BlockElts = BlockSize / EltSz;
6514 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6515 return false;
6517 for (unsigned i = 0; i < NumElts; ++i) {
6518 if (M[i] < 0)
6519 continue; // ignore UNDEF indices
6520 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6521 return false;
6524 return true;
6527 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6528 unsigned NumElts = VT.getVectorNumElements();
6529 if (NumElts % 2 != 0)
6530 return false;
6531 WhichResult = (M[0] == 0 ? 0 : 1);
6532 unsigned Idx = WhichResult * NumElts / 2;
6533 for (unsigned i = 0; i != NumElts; i += 2) {
6534 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6535 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6536 return false;
6537 Idx += 1;
6540 return true;
6543 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6544 unsigned NumElts = VT.getVectorNumElements();
6545 WhichResult = (M[0] == 0 ? 0 : 1);
6546 for (unsigned i = 0; i != NumElts; ++i) {
6547 if (M[i] < 0)
6548 continue; // ignore UNDEF indices
6549 if ((unsigned)M[i] != 2 * i + WhichResult)
6550 return false;
6553 return true;
6556 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6557 unsigned NumElts = VT.getVectorNumElements();
6558 if (NumElts % 2 != 0)
6559 return false;
6560 WhichResult = (M[0] == 0 ? 0 : 1);
6561 for (unsigned i = 0; i < NumElts; i += 2) {
6562 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6563 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6564 return false;
6566 return true;
6569 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6570 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6571 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6572 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6573 unsigned NumElts = VT.getVectorNumElements();
6574 if (NumElts % 2 != 0)
6575 return false;
6576 WhichResult = (M[0] == 0 ? 0 : 1);
6577 unsigned Idx = WhichResult * NumElts / 2;
6578 for (unsigned i = 0; i != NumElts; i += 2) {
6579 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6580 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6581 return false;
6582 Idx += 1;
6585 return true;
6588 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6589 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6590 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6591 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6592 unsigned Half = VT.getVectorNumElements() / 2;
6593 WhichResult = (M[0] == 0 ? 0 : 1);
6594 for (unsigned j = 0; j != 2; ++j) {
6595 unsigned Idx = WhichResult;
6596 for (unsigned i = 0; i != Half; ++i) {
6597 int MIdx = M[i + j * Half];
6598 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6599 return false;
6600 Idx += 2;
6604 return true;
6607 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6608 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6609 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6610 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6611 unsigned NumElts = VT.getVectorNumElements();
6612 if (NumElts % 2 != 0)
6613 return false;
6614 WhichResult = (M[0] == 0 ? 0 : 1);
6615 for (unsigned i = 0; i < NumElts; i += 2) {
6616 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6617 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6618 return false;
6620 return true;
6623 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6624 bool &DstIsLeft, int &Anomaly) {
6625 if (M.size() != static_cast<size_t>(NumInputElements))
6626 return false;
6628 int NumLHSMatch = 0, NumRHSMatch = 0;
6629 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6631 for (int i = 0; i < NumInputElements; ++i) {
6632 if (M[i] == -1) {
6633 ++NumLHSMatch;
6634 ++NumRHSMatch;
6635 continue;
6638 if (M[i] == i)
6639 ++NumLHSMatch;
6640 else
6641 LastLHSMismatch = i;
6643 if (M[i] == i + NumInputElements)
6644 ++NumRHSMatch;
6645 else
6646 LastRHSMismatch = i;
6649 if (NumLHSMatch == NumInputElements - 1) {
6650 DstIsLeft = true;
6651 Anomaly = LastLHSMismatch;
6652 return true;
6653 } else if (NumRHSMatch == NumInputElements - 1) {
6654 DstIsLeft = false;
6655 Anomaly = LastRHSMismatch;
6656 return true;
6659 return false;
6662 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6663 if (VT.getSizeInBits() != 128)
6664 return false;
6666 unsigned NumElts = VT.getVectorNumElements();
6668 for (int I = 0, E = NumElts / 2; I != E; I++) {
6669 if (Mask[I] != I)
6670 return false;
6673 int Offset = NumElts / 2;
6674 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6675 if (Mask[I] != I + SplitLHS * Offset)
6676 return false;
6679 return true;
6682 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6683 SDLoc DL(Op);
6684 EVT VT = Op.getValueType();
6685 SDValue V0 = Op.getOperand(0);
6686 SDValue V1 = Op.getOperand(1);
6687 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6689 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6690 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6691 return SDValue();
6693 bool SplitV0 = V0.getValueSizeInBits() == 128;
6695 if (!isConcatMask(Mask, VT, SplitV0))
6696 return SDValue();
6698 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6699 if (SplitV0) {
6700 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6701 DAG.getConstant(0, DL, MVT::i64));
6703 if (V1.getValueSizeInBits() == 128) {
6704 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6705 DAG.getConstant(0, DL, MVT::i64));
6707 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6710 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6711 /// the specified operations to build the shuffle.
6712 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6713 SDValue RHS, SelectionDAG &DAG,
6714 const SDLoc &dl) {
6715 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6716 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6717 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6719 enum {
6720 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6721 OP_VREV,
6722 OP_VDUP0,
6723 OP_VDUP1,
6724 OP_VDUP2,
6725 OP_VDUP3,
6726 OP_VEXT1,
6727 OP_VEXT2,
6728 OP_VEXT3,
6729 OP_VUZPL, // VUZP, left result
6730 OP_VUZPR, // VUZP, right result
6731 OP_VZIPL, // VZIP, left result
6732 OP_VZIPR, // VZIP, right result
6733 OP_VTRNL, // VTRN, left result
6734 OP_VTRNR // VTRN, right result
6737 if (OpNum == OP_COPY) {
6738 if (LHSID == (1 * 9 + 2) * 9 + 3)
6739 return LHS;
6740 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6741 return RHS;
6744 SDValue OpLHS, OpRHS;
6745 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6746 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6747 EVT VT = OpLHS.getValueType();
6749 switch (OpNum) {
6750 default:
6751 llvm_unreachable("Unknown shuffle opcode!");
6752 case OP_VREV:
6753 // VREV divides the vector in half and swaps within the half.
6754 if (VT.getVectorElementType() == MVT::i32 ||
6755 VT.getVectorElementType() == MVT::f32)
6756 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6757 // vrev <4 x i16> -> REV32
6758 if (VT.getVectorElementType() == MVT::i16 ||
6759 VT.getVectorElementType() == MVT::f16)
6760 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6761 // vrev <4 x i8> -> REV16
6762 assert(VT.getVectorElementType() == MVT::i8);
6763 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6764 case OP_VDUP0:
6765 case OP_VDUP1:
6766 case OP_VDUP2:
6767 case OP_VDUP3: {
6768 EVT EltTy = VT.getVectorElementType();
6769 unsigned Opcode;
6770 if (EltTy == MVT::i8)
6771 Opcode = AArch64ISD::DUPLANE8;
6772 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6773 Opcode = AArch64ISD::DUPLANE16;
6774 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6775 Opcode = AArch64ISD::DUPLANE32;
6776 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6777 Opcode = AArch64ISD::DUPLANE64;
6778 else
6779 llvm_unreachable("Invalid vector element type?");
6781 if (VT.getSizeInBits() == 64)
6782 OpLHS = WidenVector(OpLHS, DAG);
6783 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6784 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6786 case OP_VEXT1:
6787 case OP_VEXT2:
6788 case OP_VEXT3: {
6789 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6790 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6791 DAG.getConstant(Imm, dl, MVT::i32));
6793 case OP_VUZPL:
6794 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6795 OpRHS);
6796 case OP_VUZPR:
6797 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6798 OpRHS);
6799 case OP_VZIPL:
6800 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6801 OpRHS);
6802 case OP_VZIPR:
6803 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6804 OpRHS);
6805 case OP_VTRNL:
6806 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6807 OpRHS);
6808 case OP_VTRNR:
6809 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6810 OpRHS);
6814 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6815 SelectionDAG &DAG) {
6816 // Check to see if we can use the TBL instruction.
6817 SDValue V1 = Op.getOperand(0);
6818 SDValue V2 = Op.getOperand(1);
6819 SDLoc DL(Op);
6821 EVT EltVT = Op.getValueType().getVectorElementType();
6822 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6824 SmallVector<SDValue, 8> TBLMask;
6825 for (int Val : ShuffleMask) {
6826 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6827 unsigned Offset = Byte + Val * BytesPerElt;
6828 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6832 MVT IndexVT = MVT::v8i8;
6833 unsigned IndexLen = 8;
6834 if (Op.getValueSizeInBits() == 128) {
6835 IndexVT = MVT::v16i8;
6836 IndexLen = 16;
6839 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6840 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6842 SDValue Shuffle;
6843 if (V2.getNode()->isUndef()) {
6844 if (IndexLen == 8)
6845 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6846 Shuffle = DAG.getNode(
6847 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6848 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6849 DAG.getBuildVector(IndexVT, DL,
6850 makeArrayRef(TBLMask.data(), IndexLen)));
6851 } else {
6852 if (IndexLen == 8) {
6853 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6854 Shuffle = DAG.getNode(
6855 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6856 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6857 DAG.getBuildVector(IndexVT, DL,
6858 makeArrayRef(TBLMask.data(), IndexLen)));
6859 } else {
6860 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6861 // cannot currently represent the register constraints on the input
6862 // table registers.
6863 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6864 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6865 // IndexLen));
6866 Shuffle = DAG.getNode(
6867 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6868 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6869 V2Cst, DAG.getBuildVector(IndexVT, DL,
6870 makeArrayRef(TBLMask.data(), IndexLen)));
6873 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6876 static unsigned getDUPLANEOp(EVT EltType) {
6877 if (EltType == MVT::i8)
6878 return AArch64ISD::DUPLANE8;
6879 if (EltType == MVT::i16 || EltType == MVT::f16)
6880 return AArch64ISD::DUPLANE16;
6881 if (EltType == MVT::i32 || EltType == MVT::f32)
6882 return AArch64ISD::DUPLANE32;
6883 if (EltType == MVT::i64 || EltType == MVT::f64)
6884 return AArch64ISD::DUPLANE64;
6886 llvm_unreachable("Invalid vector element type?");
6889 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6890 SelectionDAG &DAG) const {
6891 SDLoc dl(Op);
6892 EVT VT = Op.getValueType();
6894 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6896 // Convert shuffles that are directly supported on NEON to target-specific
6897 // DAG nodes, instead of keeping them as shuffles and matching them again
6898 // during code selection. This is more efficient and avoids the possibility
6899 // of inconsistencies between legalization and selection.
6900 ArrayRef<int> ShuffleMask = SVN->getMask();
6902 SDValue V1 = Op.getOperand(0);
6903 SDValue V2 = Op.getOperand(1);
6905 if (SVN->isSplat()) {
6906 int Lane = SVN->getSplatIndex();
6907 // If this is undef splat, generate it via "just" vdup, if possible.
6908 if (Lane == -1)
6909 Lane = 0;
6911 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6912 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6913 V1.getOperand(0));
6914 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6915 // constant. If so, we can just reference the lane's definition directly.
6916 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6917 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6918 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6920 // Otherwise, duplicate from the lane of the input vector.
6921 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6923 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6924 // to make a vector of the same size as this SHUFFLE. We can ignore the
6925 // extract entirely, and canonicalise the concat using WidenVector.
6926 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6927 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6928 V1 = V1.getOperand(0);
6929 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6930 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6931 Lane -= Idx * VT.getVectorNumElements() / 2;
6932 V1 = WidenVector(V1.getOperand(Idx), DAG);
6933 } else if (VT.getSizeInBits() == 64)
6934 V1 = WidenVector(V1, DAG);
6936 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6939 if (isREVMask(ShuffleMask, VT, 64))
6940 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6941 if (isREVMask(ShuffleMask, VT, 32))
6942 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6943 if (isREVMask(ShuffleMask, VT, 16))
6944 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6946 bool ReverseEXT = false;
6947 unsigned Imm;
6948 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6949 if (ReverseEXT)
6950 std::swap(V1, V2);
6951 Imm *= getExtFactor(V1);
6952 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6953 DAG.getConstant(Imm, dl, MVT::i32));
6954 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6955 Imm *= getExtFactor(V1);
6956 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6957 DAG.getConstant(Imm, dl, MVT::i32));
6960 unsigned WhichResult;
6961 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6962 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6963 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6965 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6966 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6967 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6969 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6970 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6971 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6974 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6975 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6976 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6978 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6979 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6980 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6982 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6983 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6984 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6987 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6988 return Concat;
6990 bool DstIsLeft;
6991 int Anomaly;
6992 int NumInputElements = V1.getValueType().getVectorNumElements();
6993 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6994 SDValue DstVec = DstIsLeft ? V1 : V2;
6995 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6997 SDValue SrcVec = V1;
6998 int SrcLane = ShuffleMask[Anomaly];
6999 if (SrcLane >= NumInputElements) {
7000 SrcVec = V2;
7001 SrcLane -= VT.getVectorNumElements();
7003 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
7005 EVT ScalarVT = VT.getVectorElementType();
7007 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
7008 ScalarVT = MVT::i32;
7010 return DAG.getNode(
7011 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7012 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
7013 DstLaneV);
7016 // If the shuffle is not directly supported and it has 4 elements, use
7017 // the PerfectShuffle-generated table to synthesize it from other shuffles.
7018 unsigned NumElts = VT.getVectorNumElements();
7019 if (NumElts == 4) {
7020 unsigned PFIndexes[4];
7021 for (unsigned i = 0; i != 4; ++i) {
7022 if (ShuffleMask[i] < 0)
7023 PFIndexes[i] = 8;
7024 else
7025 PFIndexes[i] = ShuffleMask[i];
7028 // Compute the index in the perfect shuffle table.
7029 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7030 PFIndexes[2] * 9 + PFIndexes[3];
7031 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7032 unsigned Cost = (PFEntry >> 30);
7034 if (Cost <= 4)
7035 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7038 return GenerateTBL(Op, ShuffleMask, DAG);
7041 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
7042 APInt &UndefBits) {
7043 EVT VT = BVN->getValueType(0);
7044 APInt SplatBits, SplatUndef;
7045 unsigned SplatBitSize;
7046 bool HasAnyUndefs;
7047 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7048 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
7050 for (unsigned i = 0; i < NumSplats; ++i) {
7051 CnstBits <<= SplatBitSize;
7052 UndefBits <<= SplatBitSize;
7053 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
7054 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
7057 return true;
7060 return false;
7063 // Try 64-bit splatted SIMD immediate.
7064 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7065 const APInt &Bits) {
7066 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7067 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7068 EVT VT = Op.getValueType();
7069 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
7071 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
7072 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
7074 SDLoc dl(Op);
7075 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7076 DAG.getConstant(Value, dl, MVT::i32));
7077 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7081 return SDValue();
7084 // Try 32-bit splatted SIMD immediate.
7085 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7086 const APInt &Bits,
7087 const SDValue *LHS = nullptr) {
7088 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7089 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7090 EVT VT = Op.getValueType();
7091 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7092 bool isAdvSIMDModImm = false;
7093 uint64_t Shift;
7095 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
7096 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
7097 Shift = 0;
7099 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
7100 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
7101 Shift = 8;
7103 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
7104 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
7105 Shift = 16;
7107 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
7108 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
7109 Shift = 24;
7112 if (isAdvSIMDModImm) {
7113 SDLoc dl(Op);
7114 SDValue Mov;
7116 if (LHS)
7117 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7118 DAG.getConstant(Value, dl, MVT::i32),
7119 DAG.getConstant(Shift, dl, MVT::i32));
7120 else
7121 Mov = DAG.getNode(NewOp, dl, MovTy,
7122 DAG.getConstant(Value, dl, MVT::i32),
7123 DAG.getConstant(Shift, dl, MVT::i32));
7125 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7129 return SDValue();
7132 // Try 16-bit splatted SIMD immediate.
7133 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7134 const APInt &Bits,
7135 const SDValue *LHS = nullptr) {
7136 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7137 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7138 EVT VT = Op.getValueType();
7139 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
7140 bool isAdvSIMDModImm = false;
7141 uint64_t Shift;
7143 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7144 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7145 Shift = 0;
7147 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7148 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7149 Shift = 8;
7152 if (isAdvSIMDModImm) {
7153 SDLoc dl(Op);
7154 SDValue Mov;
7156 if (LHS)
7157 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7158 DAG.getConstant(Value, dl, MVT::i32),
7159 DAG.getConstant(Shift, dl, MVT::i32));
7160 else
7161 Mov = DAG.getNode(NewOp, dl, MovTy,
7162 DAG.getConstant(Value, dl, MVT::i32),
7163 DAG.getConstant(Shift, dl, MVT::i32));
7165 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7169 return SDValue();
7172 // Try 32-bit splatted SIMD immediate with shifted ones.
7173 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7174 SelectionDAG &DAG, const APInt &Bits) {
7175 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7176 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7177 EVT VT = Op.getValueType();
7178 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7179 bool isAdvSIMDModImm = false;
7180 uint64_t Shift;
7182 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7183 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7184 Shift = 264;
7186 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7187 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7188 Shift = 272;
7191 if (isAdvSIMDModImm) {
7192 SDLoc dl(Op);
7193 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7194 DAG.getConstant(Value, dl, MVT::i32),
7195 DAG.getConstant(Shift, dl, MVT::i32));
7196 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7200 return SDValue();
7203 // Try 8-bit splatted SIMD immediate.
7204 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7205 const APInt &Bits) {
7206 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7207 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7208 EVT VT = Op.getValueType();
7209 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7211 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7212 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7214 SDLoc dl(Op);
7215 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7216 DAG.getConstant(Value, dl, MVT::i32));
7217 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7221 return SDValue();
7224 // Try FP splatted SIMD immediate.
7225 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7226 const APInt &Bits) {
7227 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7228 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7229 EVT VT = Op.getValueType();
7230 bool isWide = (VT.getSizeInBits() == 128);
7231 MVT MovTy;
7232 bool isAdvSIMDModImm = false;
7234 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7235 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7236 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7238 else if (isWide &&
7239 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7240 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7241 MovTy = MVT::v2f64;
7244 if (isAdvSIMDModImm) {
7245 SDLoc dl(Op);
7246 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7247 DAG.getConstant(Value, dl, MVT::i32));
7248 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7252 return SDValue();
7255 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7256 // consists of only the same constant int value, returned in reference arg
7257 // ConstVal
7258 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7259 uint64_t &ConstVal) {
7260 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7261 if (!Bvec)
7262 return false;
7263 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7264 if (!FirstElt)
7265 return false;
7266 EVT VT = Bvec->getValueType(0);
7267 unsigned NumElts = VT.getVectorNumElements();
7268 for (unsigned i = 1; i < NumElts; ++i)
7269 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7270 return false;
7271 ConstVal = FirstElt->getZExtValue();
7272 return true;
7275 static unsigned getIntrinsicID(const SDNode *N) {
7276 unsigned Opcode = N->getOpcode();
7277 switch (Opcode) {
7278 default:
7279 return Intrinsic::not_intrinsic;
7280 case ISD::INTRINSIC_WO_CHAIN: {
7281 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7282 if (IID < Intrinsic::num_intrinsics)
7283 return IID;
7284 return Intrinsic::not_intrinsic;
7289 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7290 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7291 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7292 // Also, logical shift right -> sri, with the same structure.
7293 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7294 EVT VT = N->getValueType(0);
7296 if (!VT.isVector())
7297 return SDValue();
7299 SDLoc DL(N);
7301 // Is the first op an AND?
7302 const SDValue And = N->getOperand(0);
7303 if (And.getOpcode() != ISD::AND)
7304 return SDValue();
7306 // Is the second op an shl or lshr?
7307 SDValue Shift = N->getOperand(1);
7308 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7309 // or AArch64ISD::VLSHR vector, #shift
7310 unsigned ShiftOpc = Shift.getOpcode();
7311 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7312 return SDValue();
7313 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7315 // Is the shift amount constant?
7316 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7317 if (!C2node)
7318 return SDValue();
7320 // Is the and mask vector all constant?
7321 uint64_t C1;
7322 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7323 return SDValue();
7325 // Is C1 == ~C2, taking into account how much one can shift elements of a
7326 // particular size?
7327 uint64_t C2 = C2node->getZExtValue();
7328 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7329 if (C2 > ElemSizeInBits)
7330 return SDValue();
7331 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7332 if ((C1 & ElemMask) != (~C2 & ElemMask))
7333 return SDValue();
7335 SDValue X = And.getOperand(0);
7336 SDValue Y = Shift.getOperand(0);
7338 unsigned Intrin =
7339 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7340 SDValue ResultSLI =
7341 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7342 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7343 Shift.getOperand(1));
7345 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7346 LLVM_DEBUG(N->dump(&DAG));
7347 LLVM_DEBUG(dbgs() << "into: \n");
7348 LLVM_DEBUG(ResultSLI->dump(&DAG));
7350 ++NumShiftInserts;
7351 return ResultSLI;
7354 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7355 SelectionDAG &DAG) const {
7356 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7357 if (EnableAArch64SlrGeneration) {
7358 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7359 return Res;
7362 EVT VT = Op.getValueType();
7364 SDValue LHS = Op.getOperand(0);
7365 BuildVectorSDNode *BVN =
7366 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7367 if (!BVN) {
7368 // OR commutes, so try swapping the operands.
7369 LHS = Op.getOperand(1);
7370 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7372 if (!BVN)
7373 return Op;
7375 APInt DefBits(VT.getSizeInBits(), 0);
7376 APInt UndefBits(VT.getSizeInBits(), 0);
7377 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7378 SDValue NewOp;
7380 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7381 DefBits, &LHS)) ||
7382 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7383 DefBits, &LHS)))
7384 return NewOp;
7386 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7387 UndefBits, &LHS)) ||
7388 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7389 UndefBits, &LHS)))
7390 return NewOp;
7393 // We can always fall back to a non-immediate OR.
7394 return Op;
7397 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7398 // be truncated to fit element width.
7399 static SDValue NormalizeBuildVector(SDValue Op,
7400 SelectionDAG &DAG) {
7401 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7402 SDLoc dl(Op);
7403 EVT VT = Op.getValueType();
7404 EVT EltTy= VT.getVectorElementType();
7406 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7407 return Op;
7409 SmallVector<SDValue, 16> Ops;
7410 for (SDValue Lane : Op->ops()) {
7411 // For integer vectors, type legalization would have promoted the
7412 // operands already. Otherwise, if Op is a floating-point splat
7413 // (with operands cast to integers), then the only possibilities
7414 // are constants and UNDEFs.
7415 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7416 APInt LowBits(EltTy.getSizeInBits(),
7417 CstLane->getZExtValue());
7418 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7419 } else if (Lane.getNode()->isUndef()) {
7420 Lane = DAG.getUNDEF(MVT::i32);
7421 } else {
7422 assert(Lane.getValueType() == MVT::i32 &&
7423 "Unexpected BUILD_VECTOR operand type");
7425 Ops.push_back(Lane);
7427 return DAG.getBuildVector(VT, dl, Ops);
7430 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7431 EVT VT = Op.getValueType();
7433 APInt DefBits(VT.getSizeInBits(), 0);
7434 APInt UndefBits(VT.getSizeInBits(), 0);
7435 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7436 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7437 SDValue NewOp;
7438 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7439 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7440 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7441 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7442 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7443 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7444 return NewOp;
7446 DefBits = ~DefBits;
7447 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7448 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7449 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7450 return NewOp;
7452 DefBits = UndefBits;
7453 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7454 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7455 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7456 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7457 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7458 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7459 return NewOp;
7461 DefBits = ~UndefBits;
7462 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7463 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7464 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7465 return NewOp;
7468 return SDValue();
7471 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7472 SelectionDAG &DAG) const {
7473 EVT VT = Op.getValueType();
7475 // Try to build a simple constant vector.
7476 Op = NormalizeBuildVector(Op, DAG);
7477 if (VT.isInteger()) {
7478 // Certain vector constants, used to express things like logical NOT and
7479 // arithmetic NEG, are passed through unmodified. This allows special
7480 // patterns for these operations to match, which will lower these constants
7481 // to whatever is proven necessary.
7482 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7483 if (BVN->isConstant())
7484 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7485 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7486 APInt Val(BitSize,
7487 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7488 if (Val.isNullValue() || Val.isAllOnesValue())
7489 return Op;
7493 if (SDValue V = ConstantBuildVector(Op, DAG))
7494 return V;
7496 // Scan through the operands to find some interesting properties we can
7497 // exploit:
7498 // 1) If only one value is used, we can use a DUP, or
7499 // 2) if only the low element is not undef, we can just insert that, or
7500 // 3) if only one constant value is used (w/ some non-constant lanes),
7501 // we can splat the constant value into the whole vector then fill
7502 // in the non-constant lanes.
7503 // 4) FIXME: If different constant values are used, but we can intelligently
7504 // select the values we'll be overwriting for the non-constant
7505 // lanes such that we can directly materialize the vector
7506 // some other way (MOVI, e.g.), we can be sneaky.
7507 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7508 SDLoc dl(Op);
7509 unsigned NumElts = VT.getVectorNumElements();
7510 bool isOnlyLowElement = true;
7511 bool usesOnlyOneValue = true;
7512 bool usesOnlyOneConstantValue = true;
7513 bool isConstant = true;
7514 bool AllLanesExtractElt = true;
7515 unsigned NumConstantLanes = 0;
7516 SDValue Value;
7517 SDValue ConstantValue;
7518 for (unsigned i = 0; i < NumElts; ++i) {
7519 SDValue V = Op.getOperand(i);
7520 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7521 AllLanesExtractElt = false;
7522 if (V.isUndef())
7523 continue;
7524 if (i > 0)
7525 isOnlyLowElement = false;
7526 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7527 isConstant = false;
7529 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7530 ++NumConstantLanes;
7531 if (!ConstantValue.getNode())
7532 ConstantValue = V;
7533 else if (ConstantValue != V)
7534 usesOnlyOneConstantValue = false;
7537 if (!Value.getNode())
7538 Value = V;
7539 else if (V != Value)
7540 usesOnlyOneValue = false;
7543 if (!Value.getNode()) {
7544 LLVM_DEBUG(
7545 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7546 return DAG.getUNDEF(VT);
7549 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7550 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7551 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7552 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7553 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7554 "SCALAR_TO_VECTOR node\n");
7555 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7558 if (AllLanesExtractElt) {
7559 SDNode *Vector = nullptr;
7560 bool Even = false;
7561 bool Odd = false;
7562 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7563 // the Odd pattern <1,3,5,...>.
7564 for (unsigned i = 0; i < NumElts; ++i) {
7565 SDValue V = Op.getOperand(i);
7566 const SDNode *N = V.getNode();
7567 if (!isa<ConstantSDNode>(N->getOperand(1)))
7568 break;
7569 SDValue N0 = N->getOperand(0);
7571 // All elements are extracted from the same vector.
7572 if (!Vector) {
7573 Vector = N0.getNode();
7574 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7575 // BUILD_VECTOR.
7576 if (VT.getVectorElementType() !=
7577 N0.getValueType().getVectorElementType())
7578 break;
7579 } else if (Vector != N0.getNode()) {
7580 Odd = false;
7581 Even = false;
7582 break;
7585 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7586 // indices <1,3,5,...>.
7587 uint64_t Val = N->getConstantOperandVal(1);
7588 if (Val == 2 * i) {
7589 Even = true;
7590 continue;
7592 if (Val - 1 == 2 * i) {
7593 Odd = true;
7594 continue;
7597 // Something does not match: abort.
7598 Odd = false;
7599 Even = false;
7600 break;
7602 if (Even || Odd) {
7603 SDValue LHS =
7604 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7605 DAG.getConstant(0, dl, MVT::i64));
7606 SDValue RHS =
7607 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7608 DAG.getConstant(NumElts, dl, MVT::i64));
7610 if (Even && !Odd)
7611 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7612 RHS);
7613 if (Odd && !Even)
7614 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7615 RHS);
7619 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7620 // i32 and try again.
7621 if (usesOnlyOneValue) {
7622 if (!isConstant) {
7623 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7624 Value.getValueType() != VT) {
7625 LLVM_DEBUG(
7626 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7627 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7630 // This is actually a DUPLANExx operation, which keeps everything vectory.
7632 SDValue Lane = Value.getOperand(1);
7633 Value = Value.getOperand(0);
7634 if (Value.getValueSizeInBits() == 64) {
7635 LLVM_DEBUG(
7636 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7637 "widening it\n");
7638 Value = WidenVector(Value, DAG);
7641 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7642 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7645 if (VT.getVectorElementType().isFloatingPoint()) {
7646 SmallVector<SDValue, 8> Ops;
7647 EVT EltTy = VT.getVectorElementType();
7648 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7649 "Unsupported floating-point vector type");
7650 LLVM_DEBUG(
7651 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7652 "BITCASTS, and try again\n");
7653 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7654 for (unsigned i = 0; i < NumElts; ++i)
7655 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7656 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7657 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7658 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7659 Val.dump(););
7660 Val = LowerBUILD_VECTOR(Val, DAG);
7661 if (Val.getNode())
7662 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7666 // If there was only one constant value used and for more than one lane,
7667 // start by splatting that value, then replace the non-constant lanes. This
7668 // is better than the default, which will perform a separate initialization
7669 // for each lane.
7670 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7671 // Firstly, try to materialize the splat constant.
7672 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7673 Val = ConstantBuildVector(Vec, DAG);
7674 if (!Val) {
7675 // Otherwise, materialize the constant and splat it.
7676 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7677 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7680 // Now insert the non-constant lanes.
7681 for (unsigned i = 0; i < NumElts; ++i) {
7682 SDValue V = Op.getOperand(i);
7683 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7684 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7685 // Note that type legalization likely mucked about with the VT of the
7686 // source operand, so we may have to convert it here before inserting.
7687 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7689 return Val;
7692 // This will generate a load from the constant pool.
7693 if (isConstant) {
7694 LLVM_DEBUG(
7695 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7696 "expansion\n");
7697 return SDValue();
7700 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7701 if (NumElts >= 4) {
7702 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7703 return shuffle;
7706 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7707 // know the default expansion would otherwise fall back on something even
7708 // worse. For a vector with one or two non-undef values, that's
7709 // scalar_to_vector for the elements followed by a shuffle (provided the
7710 // shuffle is valid for the target) and materialization element by element
7711 // on the stack followed by a load for everything else.
7712 if (!isConstant && !usesOnlyOneValue) {
7713 LLVM_DEBUG(
7714 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7715 "of INSERT_VECTOR_ELT\n");
7717 SDValue Vec = DAG.getUNDEF(VT);
7718 SDValue Op0 = Op.getOperand(0);
7719 unsigned i = 0;
7721 // Use SCALAR_TO_VECTOR for lane zero to
7722 // a) Avoid a RMW dependency on the full vector register, and
7723 // b) Allow the register coalescer to fold away the copy if the
7724 // value is already in an S or D register, and we're forced to emit an
7725 // INSERT_SUBREG that we can't fold anywhere.
7727 // We also allow types like i8 and i16 which are illegal scalar but legal
7728 // vector element types. After type-legalization the inserted value is
7729 // extended (i32) and it is safe to cast them to the vector type by ignoring
7730 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7731 if (!Op0.isUndef()) {
7732 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7733 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7734 ++i;
7736 LLVM_DEBUG(if (i < NumElts) dbgs()
7737 << "Creating nodes for the other vector elements:\n";);
7738 for (; i < NumElts; ++i) {
7739 SDValue V = Op.getOperand(i);
7740 if (V.isUndef())
7741 continue;
7742 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7743 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7745 return Vec;
7748 LLVM_DEBUG(
7749 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7750 "better alternative\n");
7751 return SDValue();
7754 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7755 SelectionDAG &DAG) const {
7756 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7758 // Check for non-constant or out of range lane.
7759 EVT VT = Op.getOperand(0).getValueType();
7760 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7761 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7762 return SDValue();
7765 // Insertion/extraction are legal for V128 types.
7766 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7767 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7768 VT == MVT::v8f16)
7769 return Op;
7771 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7772 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7773 return SDValue();
7775 // For V64 types, we perform insertion by expanding the value
7776 // to a V128 type and perform the insertion on that.
7777 SDLoc DL(Op);
7778 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7779 EVT WideTy = WideVec.getValueType();
7781 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7782 Op.getOperand(1), Op.getOperand(2));
7783 // Re-narrow the resultant vector.
7784 return NarrowVector(Node, DAG);
7787 SDValue
7788 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7789 SelectionDAG &DAG) const {
7790 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7792 // Check for non-constant or out of range lane.
7793 EVT VT = Op.getOperand(0).getValueType();
7794 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7795 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7796 return SDValue();
7799 // Insertion/extraction are legal for V128 types.
7800 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7801 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7802 VT == MVT::v8f16)
7803 return Op;
7805 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7806 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7807 return SDValue();
7809 // For V64 types, we perform extraction by expanding the value
7810 // to a V128 type and perform the extraction on that.
7811 SDLoc DL(Op);
7812 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7813 EVT WideTy = WideVec.getValueType();
7815 EVT ExtrTy = WideTy.getVectorElementType();
7816 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7817 ExtrTy = MVT::i32;
7819 // For extractions, we just return the result directly.
7820 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7821 Op.getOperand(1));
7824 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7825 SelectionDAG &DAG) const {
7826 EVT VT = Op.getOperand(0).getValueType();
7827 SDLoc dl(Op);
7828 // Just in case...
7829 if (!VT.isVector())
7830 return SDValue();
7832 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7833 if (!Cst)
7834 return SDValue();
7835 unsigned Val = Cst->getZExtValue();
7837 unsigned Size = Op.getValueSizeInBits();
7839 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7840 if (Val == 0)
7841 return Op;
7843 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7844 // that directly.
7845 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7846 return Op;
7848 return SDValue();
7851 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7852 if (VT.getVectorNumElements() == 4 &&
7853 (VT.is128BitVector() || VT.is64BitVector())) {
7854 unsigned PFIndexes[4];
7855 for (unsigned i = 0; i != 4; ++i) {
7856 if (M[i] < 0)
7857 PFIndexes[i] = 8;
7858 else
7859 PFIndexes[i] = M[i];
7862 // Compute the index in the perfect shuffle table.
7863 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7864 PFIndexes[2] * 9 + PFIndexes[3];
7865 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7866 unsigned Cost = (PFEntry >> 30);
7868 if (Cost <= 4)
7869 return true;
7872 bool DummyBool;
7873 int DummyInt;
7874 unsigned DummyUnsigned;
7876 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7877 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7878 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7879 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7880 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7881 isZIPMask(M, VT, DummyUnsigned) ||
7882 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7883 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7884 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7885 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7886 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7889 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7890 /// operand of a vector shift operation, where all the elements of the
7891 /// build_vector must have the same constant integer value.
7892 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7893 // Ignore bit_converts.
7894 while (Op.getOpcode() == ISD::BITCAST)
7895 Op = Op.getOperand(0);
7896 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7897 APInt SplatBits, SplatUndef;
7898 unsigned SplatBitSize;
7899 bool HasAnyUndefs;
7900 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7901 HasAnyUndefs, ElementBits) ||
7902 SplatBitSize > ElementBits)
7903 return false;
7904 Cnt = SplatBits.getSExtValue();
7905 return true;
7908 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7909 /// operand of a vector shift left operation. That value must be in the range:
7910 /// 0 <= Value < ElementBits for a left shift; or
7911 /// 0 <= Value <= ElementBits for a long left shift.
7912 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7913 assert(VT.isVector() && "vector shift count is not a vector type");
7914 int64_t ElementBits = VT.getScalarSizeInBits();
7915 if (!getVShiftImm(Op, ElementBits, Cnt))
7916 return false;
7917 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7920 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7921 /// operand of a vector shift right operation. The value must be in the range:
7922 /// 1 <= Value <= ElementBits for a right shift; or
7923 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7924 assert(VT.isVector() && "vector shift count is not a vector type");
7925 int64_t ElementBits = VT.getScalarSizeInBits();
7926 if (!getVShiftImm(Op, ElementBits, Cnt))
7927 return false;
7928 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7931 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7932 SelectionDAG &DAG) const {
7933 EVT VT = Op.getValueType();
7934 SDLoc DL(Op);
7935 int64_t Cnt;
7937 if (!Op.getOperand(1).getValueType().isVector())
7938 return Op;
7939 unsigned EltSize = VT.getScalarSizeInBits();
7941 switch (Op.getOpcode()) {
7942 default:
7943 llvm_unreachable("unexpected shift opcode");
7945 case ISD::SHL:
7946 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7947 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7948 DAG.getConstant(Cnt, DL, MVT::i32));
7949 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7950 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7951 MVT::i32),
7952 Op.getOperand(0), Op.getOperand(1));
7953 case ISD::SRA:
7954 case ISD::SRL:
7955 // Right shift immediate
7956 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7957 unsigned Opc =
7958 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7959 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7960 DAG.getConstant(Cnt, DL, MVT::i32));
7963 // Right shift register. Note, there is not a shift right register
7964 // instruction, but the shift left register instruction takes a signed
7965 // value, where negative numbers specify a right shift.
7966 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7967 : Intrinsic::aarch64_neon_ushl;
7968 // negate the shift amount
7969 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7970 SDValue NegShiftLeft =
7971 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7972 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7973 NegShift);
7974 return NegShiftLeft;
7977 return SDValue();
7980 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7981 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7982 const SDLoc &dl, SelectionDAG &DAG) {
7983 EVT SrcVT = LHS.getValueType();
7984 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7985 "function only supposed to emit natural comparisons");
7987 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7988 APInt CnstBits(VT.getSizeInBits(), 0);
7989 APInt UndefBits(VT.getSizeInBits(), 0);
7990 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7991 bool IsZero = IsCnst && (CnstBits == 0);
7993 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7994 switch (CC) {
7995 default:
7996 return SDValue();
7997 case AArch64CC::NE: {
7998 SDValue Fcmeq;
7999 if (IsZero)
8000 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8001 else
8002 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8003 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
8005 case AArch64CC::EQ:
8006 if (IsZero)
8007 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
8008 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
8009 case AArch64CC::GE:
8010 if (IsZero)
8011 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
8012 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
8013 case AArch64CC::GT:
8014 if (IsZero)
8015 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
8016 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
8017 case AArch64CC::LS:
8018 if (IsZero)
8019 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
8020 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
8021 case AArch64CC::LT:
8022 if (!NoNans)
8023 return SDValue();
8024 // If we ignore NaNs then we can use to the MI implementation.
8025 LLVM_FALLTHROUGH;
8026 case AArch64CC::MI:
8027 if (IsZero)
8028 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
8029 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
8033 switch (CC) {
8034 default:
8035 return SDValue();
8036 case AArch64CC::NE: {
8037 SDValue Cmeq;
8038 if (IsZero)
8039 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8040 else
8041 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8042 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
8044 case AArch64CC::EQ:
8045 if (IsZero)
8046 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
8047 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
8048 case AArch64CC::GE:
8049 if (IsZero)
8050 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
8051 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
8052 case AArch64CC::GT:
8053 if (IsZero)
8054 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
8055 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
8056 case AArch64CC::LE:
8057 if (IsZero)
8058 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
8059 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
8060 case AArch64CC::LS:
8061 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
8062 case AArch64CC::LO:
8063 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
8064 case AArch64CC::LT:
8065 if (IsZero)
8066 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
8067 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
8068 case AArch64CC::HI:
8069 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
8070 case AArch64CC::HS:
8071 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
8075 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
8076 SelectionDAG &DAG) const {
8077 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8078 SDValue LHS = Op.getOperand(0);
8079 SDValue RHS = Op.getOperand(1);
8080 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
8081 SDLoc dl(Op);
8083 if (LHS.getValueType().getVectorElementType().isInteger()) {
8084 assert(LHS.getValueType() == RHS.getValueType());
8085 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
8086 SDValue Cmp =
8087 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
8088 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8091 const bool FullFP16 =
8092 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
8094 // Make v4f16 (only) fcmp operations utilise vector instructions
8095 // v8f16 support will be a litle more complicated
8096 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
8097 if (LHS.getValueType().getVectorNumElements() == 4) {
8098 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
8099 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
8100 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
8101 DAG.ReplaceAllUsesWith(Op, NewSetcc);
8102 CmpVT = MVT::v4i32;
8103 } else
8104 return SDValue();
8107 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
8108 LHS.getValueType().getVectorElementType() != MVT::f128);
8110 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
8111 // clean. Some of them require two branches to implement.
8112 AArch64CC::CondCode CC1, CC2;
8113 bool ShouldInvert;
8114 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
8116 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
8117 SDValue Cmp =
8118 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
8119 if (!Cmp.getNode())
8120 return SDValue();
8122 if (CC2 != AArch64CC::AL) {
8123 SDValue Cmp2 =
8124 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
8125 if (!Cmp2.getNode())
8126 return SDValue();
8128 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
8131 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
8133 if (ShouldInvert)
8134 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
8136 return Cmp;
8139 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
8140 SelectionDAG &DAG) {
8141 SDValue VecOp = ScalarOp.getOperand(0);
8142 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8143 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8144 DAG.getConstant(0, DL, MVT::i64));
8147 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8148 SelectionDAG &DAG) const {
8149 SDLoc dl(Op);
8150 switch (Op.getOpcode()) {
8151 case ISD::VECREDUCE_ADD:
8152 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8153 case ISD::VECREDUCE_SMAX:
8154 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8155 case ISD::VECREDUCE_SMIN:
8156 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8157 case ISD::VECREDUCE_UMAX:
8158 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8159 case ISD::VECREDUCE_UMIN:
8160 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8161 case ISD::VECREDUCE_FMAX: {
8162 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8163 return DAG.getNode(
8164 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8165 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8166 Op.getOperand(0));
8168 case ISD::VECREDUCE_FMIN: {
8169 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8170 return DAG.getNode(
8171 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8172 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8173 Op.getOperand(0));
8175 default:
8176 llvm_unreachable("Unhandled reduction");
8180 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8181 SelectionDAG &DAG) const {
8182 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8183 if (!Subtarget.hasLSE())
8184 return SDValue();
8186 // LSE has an atomic load-add instruction, but not a load-sub.
8187 SDLoc dl(Op);
8188 MVT VT = Op.getSimpleValueType();
8189 SDValue RHS = Op.getOperand(2);
8190 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8191 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8192 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8193 Op.getOperand(0), Op.getOperand(1), RHS,
8194 AN->getMemOperand());
8197 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8198 SelectionDAG &DAG) const {
8199 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8200 if (!Subtarget.hasLSE())
8201 return SDValue();
8203 // LSE has an atomic load-clear instruction, but not a load-and.
8204 SDLoc dl(Op);
8205 MVT VT = Op.getSimpleValueType();
8206 SDValue RHS = Op.getOperand(2);
8207 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8208 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8209 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8210 Op.getOperand(0), Op.getOperand(1), RHS,
8211 AN->getMemOperand());
8214 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8215 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8216 SDLoc dl(Op);
8217 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8218 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8220 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8221 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8222 if (Subtarget->hasCustomCallingConv())
8223 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8225 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8226 DAG.getConstant(4, dl, MVT::i64));
8227 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8228 Chain =
8229 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8230 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8231 DAG.getRegisterMask(Mask), Chain.getValue(1));
8232 // To match the actual intent better, we should read the output from X15 here
8233 // again (instead of potentially spilling it to the stack), but rereading Size
8234 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8235 // here.
8237 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8238 DAG.getConstant(4, dl, MVT::i64));
8239 return Chain;
8242 SDValue
8243 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8244 SelectionDAG &DAG) const {
8245 assert(Subtarget->isTargetWindows() &&
8246 "Only Windows alloca probing supported");
8247 SDLoc dl(Op);
8248 // Get the inputs.
8249 SDNode *Node = Op.getNode();
8250 SDValue Chain = Op.getOperand(0);
8251 SDValue Size = Op.getOperand(1);
8252 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8253 EVT VT = Node->getValueType(0);
8255 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8256 "no-stack-arg-probe")) {
8257 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8258 Chain = SP.getValue(1);
8259 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8260 if (Align)
8261 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8262 DAG.getConstant(-(uint64_t)Align, dl, VT));
8263 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8264 SDValue Ops[2] = {SP, Chain};
8265 return DAG.getMergeValues(Ops, dl);
8268 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8270 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8272 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8273 Chain = SP.getValue(1);
8274 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8275 if (Align)
8276 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8277 DAG.getConstant(-(uint64_t)Align, dl, VT));
8278 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8280 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8281 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8283 SDValue Ops[2] = {SP, Chain};
8284 return DAG.getMergeValues(Ops, dl);
8287 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8288 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8289 /// specified in the intrinsic calls.
8290 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8291 const CallInst &I,
8292 MachineFunction &MF,
8293 unsigned Intrinsic) const {
8294 auto &DL = I.getModule()->getDataLayout();
8295 switch (Intrinsic) {
8296 case Intrinsic::aarch64_neon_ld2:
8297 case Intrinsic::aarch64_neon_ld3:
8298 case Intrinsic::aarch64_neon_ld4:
8299 case Intrinsic::aarch64_neon_ld1x2:
8300 case Intrinsic::aarch64_neon_ld1x3:
8301 case Intrinsic::aarch64_neon_ld1x4:
8302 case Intrinsic::aarch64_neon_ld2lane:
8303 case Intrinsic::aarch64_neon_ld3lane:
8304 case Intrinsic::aarch64_neon_ld4lane:
8305 case Intrinsic::aarch64_neon_ld2r:
8306 case Intrinsic::aarch64_neon_ld3r:
8307 case Intrinsic::aarch64_neon_ld4r: {
8308 Info.opc = ISD::INTRINSIC_W_CHAIN;
8309 // Conservatively set memVT to the entire set of vectors loaded.
8310 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8311 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8312 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8313 Info.offset = 0;
8314 Info.align.reset();
8315 // volatile loads with NEON intrinsics not supported
8316 Info.flags = MachineMemOperand::MOLoad;
8317 return true;
8319 case Intrinsic::aarch64_neon_st2:
8320 case Intrinsic::aarch64_neon_st3:
8321 case Intrinsic::aarch64_neon_st4:
8322 case Intrinsic::aarch64_neon_st1x2:
8323 case Intrinsic::aarch64_neon_st1x3:
8324 case Intrinsic::aarch64_neon_st1x4:
8325 case Intrinsic::aarch64_neon_st2lane:
8326 case Intrinsic::aarch64_neon_st3lane:
8327 case Intrinsic::aarch64_neon_st4lane: {
8328 Info.opc = ISD::INTRINSIC_VOID;
8329 // Conservatively set memVT to the entire set of vectors stored.
8330 unsigned NumElts = 0;
8331 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8332 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8333 if (!ArgTy->isVectorTy())
8334 break;
8335 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8337 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8338 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8339 Info.offset = 0;
8340 Info.align.reset();
8341 // volatile stores with NEON intrinsics not supported
8342 Info.flags = MachineMemOperand::MOStore;
8343 return true;
8345 case Intrinsic::aarch64_ldaxr:
8346 case Intrinsic::aarch64_ldxr: {
8347 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8348 Info.opc = ISD::INTRINSIC_W_CHAIN;
8349 Info.memVT = MVT::getVT(PtrTy->getElementType());
8350 Info.ptrVal = I.getArgOperand(0);
8351 Info.offset = 0;
8352 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8353 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8354 return true;
8356 case Intrinsic::aarch64_stlxr:
8357 case Intrinsic::aarch64_stxr: {
8358 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8359 Info.opc = ISD::INTRINSIC_W_CHAIN;
8360 Info.memVT = MVT::getVT(PtrTy->getElementType());
8361 Info.ptrVal = I.getArgOperand(1);
8362 Info.offset = 0;
8363 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8364 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8365 return true;
8367 case Intrinsic::aarch64_ldaxp:
8368 case Intrinsic::aarch64_ldxp:
8369 Info.opc = ISD::INTRINSIC_W_CHAIN;
8370 Info.memVT = MVT::i128;
8371 Info.ptrVal = I.getArgOperand(0);
8372 Info.offset = 0;
8373 Info.align = Align(16);
8374 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8375 return true;
8376 case Intrinsic::aarch64_stlxp:
8377 case Intrinsic::aarch64_stxp:
8378 Info.opc = ISD::INTRINSIC_W_CHAIN;
8379 Info.memVT = MVT::i128;
8380 Info.ptrVal = I.getArgOperand(2);
8381 Info.offset = 0;
8382 Info.align = Align(16);
8383 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8384 return true;
8385 default:
8386 break;
8389 return false;
8392 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8393 ISD::LoadExtType ExtTy,
8394 EVT NewVT) const {
8395 // TODO: This may be worth removing. Check regression tests for diffs.
8396 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8397 return false;
8399 // If we're reducing the load width in order to avoid having to use an extra
8400 // instruction to do extension then it's probably a good idea.
8401 if (ExtTy != ISD::NON_EXTLOAD)
8402 return true;
8403 // Don't reduce load width if it would prevent us from combining a shift into
8404 // the offset.
8405 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8406 assert(Mem);
8407 const SDValue &Base = Mem->getBasePtr();
8408 if (Base.getOpcode() == ISD::ADD &&
8409 Base.getOperand(1).getOpcode() == ISD::SHL &&
8410 Base.getOperand(1).hasOneUse() &&
8411 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8412 // The shift can be combined if it matches the size of the value being
8413 // loaded (and so reducing the width would make it not match).
8414 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8415 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8416 if (ShiftAmount == Log2_32(LoadBytes))
8417 return false;
8419 // We have no reason to disallow reducing the load width, so allow it.
8420 return true;
8423 // Truncations from 64-bit GPR to 32-bit GPR is free.
8424 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8425 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8426 return false;
8427 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8428 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8429 return NumBits1 > NumBits2;
8431 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8432 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8433 return false;
8434 unsigned NumBits1 = VT1.getSizeInBits();
8435 unsigned NumBits2 = VT2.getSizeInBits();
8436 return NumBits1 > NumBits2;
8439 /// Check if it is profitable to hoist instruction in then/else to if.
8440 /// Not profitable if I and it's user can form a FMA instruction
8441 /// because we prefer FMSUB/FMADD.
8442 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8443 if (I->getOpcode() != Instruction::FMul)
8444 return true;
8446 if (!I->hasOneUse())
8447 return true;
8449 Instruction *User = I->user_back();
8451 if (User &&
8452 !(User->getOpcode() == Instruction::FSub ||
8453 User->getOpcode() == Instruction::FAdd))
8454 return true;
8456 const TargetOptions &Options = getTargetMachine().Options;
8457 const DataLayout &DL = I->getModule()->getDataLayout();
8458 EVT VT = getValueType(DL, User->getOperand(0)->getType());
8460 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8461 isOperationLegalOrCustom(ISD::FMA, VT) &&
8462 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8463 Options.UnsafeFPMath));
8466 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8467 // 64-bit GPR.
8468 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8469 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8470 return false;
8471 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8472 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8473 return NumBits1 == 32 && NumBits2 == 64;
8475 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8476 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8477 return false;
8478 unsigned NumBits1 = VT1.getSizeInBits();
8479 unsigned NumBits2 = VT2.getSizeInBits();
8480 return NumBits1 == 32 && NumBits2 == 64;
8483 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8484 EVT VT1 = Val.getValueType();
8485 if (isZExtFree(VT1, VT2)) {
8486 return true;
8489 if (Val.getOpcode() != ISD::LOAD)
8490 return false;
8492 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8493 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8494 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8495 VT1.getSizeInBits() <= 32);
8498 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8499 if (isa<FPExtInst>(Ext))
8500 return false;
8502 // Vector types are not free.
8503 if (Ext->getType()->isVectorTy())
8504 return false;
8506 for (const Use &U : Ext->uses()) {
8507 // The extension is free if we can fold it with a left shift in an
8508 // addressing mode or an arithmetic operation: add, sub, and cmp.
8510 // Is there a shift?
8511 const Instruction *Instr = cast<Instruction>(U.getUser());
8513 // Is this a constant shift?
8514 switch (Instr->getOpcode()) {
8515 case Instruction::Shl:
8516 if (!isa<ConstantInt>(Instr->getOperand(1)))
8517 return false;
8518 break;
8519 case Instruction::GetElementPtr: {
8520 gep_type_iterator GTI = gep_type_begin(Instr);
8521 auto &DL = Ext->getModule()->getDataLayout();
8522 std::advance(GTI, U.getOperandNo()-1);
8523 Type *IdxTy = GTI.getIndexedType();
8524 // This extension will end up with a shift because of the scaling factor.
8525 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8526 // Get the shift amount based on the scaling factor:
8527 // log2(sizeof(IdxTy)) - log2(8).
8528 uint64_t ShiftAmt =
8529 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
8530 // Is the constant foldable in the shift of the addressing mode?
8531 // I.e., shift amount is between 1 and 4 inclusive.
8532 if (ShiftAmt == 0 || ShiftAmt > 4)
8533 return false;
8534 break;
8536 case Instruction::Trunc:
8537 // Check if this is a noop.
8538 // trunc(sext ty1 to ty2) to ty1.
8539 if (Instr->getType() == Ext->getOperand(0)->getType())
8540 continue;
8541 LLVM_FALLTHROUGH;
8542 default:
8543 return false;
8546 // At this point we can use the bfm family, so this extension is free
8547 // for that use.
8549 return true;
8552 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8553 /// or upper half of the vector elements.
8554 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8555 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8556 auto *FullVT = cast<VectorType>(FullV->getType());
8557 auto *HalfVT = cast<VectorType>(HalfV->getType());
8558 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8561 auto extractHalf = [](Value *FullV, Value *HalfV) {
8562 auto *FullVT = cast<VectorType>(FullV->getType());
8563 auto *HalfVT = cast<VectorType>(HalfV->getType());
8564 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8567 Constant *M1, *M2;
8568 Value *S1Op1, *S2Op1;
8569 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8570 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8571 return false;
8573 // Check that the operands are half as wide as the result and we extract
8574 // half of the elements of the input vectors.
8575 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8576 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8577 return false;
8579 // Check the mask extracts either the lower or upper half of vector
8580 // elements.
8581 int M1Start = -1;
8582 int M2Start = -1;
8583 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8584 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8585 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8586 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8587 return false;
8589 return true;
8592 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8593 /// of the vector elements.
8594 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8595 auto areExtDoubled = [](Instruction *Ext) {
8596 return Ext->getType()->getScalarSizeInBits() ==
8597 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8600 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8601 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8602 !areExtDoubled(cast<Instruction>(Ext1)) ||
8603 !areExtDoubled(cast<Instruction>(Ext2)))
8604 return false;
8606 return true;
8609 /// Check if sinking \p I's operands to I's basic block is profitable, because
8610 /// the operands can be folded into a target instruction, e.g.
8611 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8612 bool AArch64TargetLowering::shouldSinkOperands(
8613 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8614 if (!I->getType()->isVectorTy())
8615 return false;
8617 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8618 switch (II->getIntrinsicID()) {
8619 case Intrinsic::aarch64_neon_umull:
8620 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8621 return false;
8622 Ops.push_back(&II->getOperandUse(0));
8623 Ops.push_back(&II->getOperandUse(1));
8624 return true;
8625 default:
8626 return false;
8630 switch (I->getOpcode()) {
8631 case Instruction::Sub:
8632 case Instruction::Add: {
8633 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8634 return false;
8636 // If the exts' operands extract either the lower or upper elements, we
8637 // can sink them too.
8638 auto Ext1 = cast<Instruction>(I->getOperand(0));
8639 auto Ext2 = cast<Instruction>(I->getOperand(1));
8640 if (areExtractShuffleVectors(Ext1, Ext2)) {
8641 Ops.push_back(&Ext1->getOperandUse(0));
8642 Ops.push_back(&Ext2->getOperandUse(0));
8645 Ops.push_back(&I->getOperandUse(0));
8646 Ops.push_back(&I->getOperandUse(1));
8648 return true;
8650 default:
8651 return false;
8653 return false;
8656 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8657 unsigned &RequiredAligment) const {
8658 if (!LoadedType.isSimple() ||
8659 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8660 return false;
8661 // Cyclone supports unaligned accesses.
8662 RequiredAligment = 0;
8663 unsigned NumBits = LoadedType.getSizeInBits();
8664 return NumBits == 32 || NumBits == 64;
8667 /// A helper function for determining the number of interleaved accesses we
8668 /// will generate when lowering accesses of the given type.
8669 unsigned
8670 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8671 const DataLayout &DL) const {
8672 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8675 MachineMemOperand::Flags
8676 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8677 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8678 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8679 return MOStridedAccess;
8680 return MachineMemOperand::MONone;
8683 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8684 VectorType *VecTy, const DataLayout &DL) const {
8686 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8687 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8689 // Ensure the number of vector elements is greater than 1.
8690 if (VecTy->getNumElements() < 2)
8691 return false;
8693 // Ensure the element type is legal.
8694 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8695 return false;
8697 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8698 // 128 will be split into multiple interleaved accesses.
8699 return VecSize == 64 || VecSize % 128 == 0;
8702 /// Lower an interleaved load into a ldN intrinsic.
8704 /// E.g. Lower an interleaved load (Factor = 2):
8705 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8706 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8707 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8709 /// Into:
8710 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8711 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8712 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8713 bool AArch64TargetLowering::lowerInterleavedLoad(
8714 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8715 ArrayRef<unsigned> Indices, unsigned Factor) const {
8716 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8717 "Invalid interleave factor");
8718 assert(!Shuffles.empty() && "Empty shufflevector input");
8719 assert(Shuffles.size() == Indices.size() &&
8720 "Unmatched number of shufflevectors and indices");
8722 const DataLayout &DL = LI->getModule()->getDataLayout();
8724 VectorType *VecTy = Shuffles[0]->getType();
8726 // Skip if we do not have NEON and skip illegal vector types. We can
8727 // "legalize" wide vector types into multiple interleaved accesses as long as
8728 // the vector types are divisible by 128.
8729 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8730 return false;
8732 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8734 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8735 // load integer vectors first and then convert to pointer vectors.
8736 Type *EltTy = VecTy->getVectorElementType();
8737 if (EltTy->isPointerTy())
8738 VecTy =
8739 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8741 IRBuilder<> Builder(LI);
8743 // The base address of the load.
8744 Value *BaseAddr = LI->getPointerOperand();
8746 if (NumLoads > 1) {
8747 // If we're going to generate more than one load, reset the sub-vector type
8748 // to something legal.
8749 VecTy = VectorType::get(VecTy->getVectorElementType(),
8750 VecTy->getVectorNumElements() / NumLoads);
8752 // We will compute the pointer operand of each load from the original base
8753 // address using GEPs. Cast the base address to a pointer to the scalar
8754 // element type.
8755 BaseAddr = Builder.CreateBitCast(
8756 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8757 LI->getPointerAddressSpace()));
8760 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8761 Type *Tys[2] = {VecTy, PtrTy};
8762 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8763 Intrinsic::aarch64_neon_ld3,
8764 Intrinsic::aarch64_neon_ld4};
8765 Function *LdNFunc =
8766 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8768 // Holds sub-vectors extracted from the load intrinsic return values. The
8769 // sub-vectors are associated with the shufflevector instructions they will
8770 // replace.
8771 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8773 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8775 // If we're generating more than one load, compute the base address of
8776 // subsequent loads as an offset from the previous.
8777 if (LoadCount > 0)
8778 BaseAddr =
8779 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8780 VecTy->getVectorNumElements() * Factor);
8782 CallInst *LdN = Builder.CreateCall(
8783 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8785 // Extract and store the sub-vectors returned by the load intrinsic.
8786 for (unsigned i = 0; i < Shuffles.size(); i++) {
8787 ShuffleVectorInst *SVI = Shuffles[i];
8788 unsigned Index = Indices[i];
8790 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8792 // Convert the integer vector to pointer vector if the element is pointer.
8793 if (EltTy->isPointerTy())
8794 SubVec = Builder.CreateIntToPtr(
8795 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8796 VecTy->getVectorNumElements()));
8797 SubVecs[SVI].push_back(SubVec);
8801 // Replace uses of the shufflevector instructions with the sub-vectors
8802 // returned by the load intrinsic. If a shufflevector instruction is
8803 // associated with more than one sub-vector, those sub-vectors will be
8804 // concatenated into a single wide vector.
8805 for (ShuffleVectorInst *SVI : Shuffles) {
8806 auto &SubVec = SubVecs[SVI];
8807 auto *WideVec =
8808 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8809 SVI->replaceAllUsesWith(WideVec);
8812 return true;
8815 /// Lower an interleaved store into a stN intrinsic.
8817 /// E.g. Lower an interleaved store (Factor = 3):
8818 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8819 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8820 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8822 /// Into:
8823 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8824 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8825 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8826 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8828 /// Note that the new shufflevectors will be removed and we'll only generate one
8829 /// st3 instruction in CodeGen.
8831 /// Example for a more general valid mask (Factor 3). Lower:
8832 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8833 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8834 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8836 /// Into:
8837 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8838 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8839 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8840 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8841 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8842 ShuffleVectorInst *SVI,
8843 unsigned Factor) const {
8844 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8845 "Invalid interleave factor");
8847 VectorType *VecTy = SVI->getType();
8848 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8849 "Invalid interleaved store");
8851 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8852 Type *EltTy = VecTy->getVectorElementType();
8853 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8855 const DataLayout &DL = SI->getModule()->getDataLayout();
8857 // Skip if we do not have NEON and skip illegal vector types. We can
8858 // "legalize" wide vector types into multiple interleaved accesses as long as
8859 // the vector types are divisible by 128.
8860 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8861 return false;
8863 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8865 Value *Op0 = SVI->getOperand(0);
8866 Value *Op1 = SVI->getOperand(1);
8867 IRBuilder<> Builder(SI);
8869 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8870 // vectors to integer vectors.
8871 if (EltTy->isPointerTy()) {
8872 Type *IntTy = DL.getIntPtrType(EltTy);
8873 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8875 // Convert to the corresponding integer vector.
8876 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8877 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8878 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8880 SubVecTy = VectorType::get(IntTy, LaneLen);
8883 // The base address of the store.
8884 Value *BaseAddr = SI->getPointerOperand();
8886 if (NumStores > 1) {
8887 // If we're going to generate more than one store, reset the lane length
8888 // and sub-vector type to something legal.
8889 LaneLen /= NumStores;
8890 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8892 // We will compute the pointer operand of each store from the original base
8893 // address using GEPs. Cast the base address to a pointer to the scalar
8894 // element type.
8895 BaseAddr = Builder.CreateBitCast(
8896 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8897 SI->getPointerAddressSpace()));
8900 auto Mask = SVI->getShuffleMask();
8902 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8903 Type *Tys[2] = {SubVecTy, PtrTy};
8904 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8905 Intrinsic::aarch64_neon_st3,
8906 Intrinsic::aarch64_neon_st4};
8907 Function *StNFunc =
8908 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8910 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8912 SmallVector<Value *, 5> Ops;
8914 // Split the shufflevector operands into sub vectors for the new stN call.
8915 for (unsigned i = 0; i < Factor; i++) {
8916 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8917 if (Mask[IdxI] >= 0) {
8918 Ops.push_back(Builder.CreateShuffleVector(
8919 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8920 } else {
8921 unsigned StartMask = 0;
8922 for (unsigned j = 1; j < LaneLen; j++) {
8923 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8924 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8925 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8926 break;
8929 // Note: Filling undef gaps with random elements is ok, since
8930 // those elements were being written anyway (with undefs).
8931 // In the case of all undefs we're defaulting to using elems from 0
8932 // Note: StartMask cannot be negative, it's checked in
8933 // isReInterleaveMask
8934 Ops.push_back(Builder.CreateShuffleVector(
8935 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8939 // If we generating more than one store, we compute the base address of
8940 // subsequent stores as an offset from the previous.
8941 if (StoreCount > 0)
8942 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8943 BaseAddr, LaneLen * Factor);
8945 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8946 Builder.CreateCall(StNFunc, Ops);
8948 return true;
8951 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8952 unsigned AlignCheck) {
8953 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8954 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8957 EVT AArch64TargetLowering::getOptimalMemOpType(
8958 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8959 bool ZeroMemset, bool MemcpyStrSrc,
8960 const AttributeList &FuncAttributes) const {
8961 bool CanImplicitFloat =
8962 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8963 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8964 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8965 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8966 // taken one instruction to materialize the v2i64 zero and one store (with
8967 // restrictive addressing mode). Just do i64 stores.
8968 bool IsSmallMemset = IsMemset && Size < 32;
8969 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8970 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8971 return true;
8972 bool Fast;
8973 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8974 &Fast) &&
8975 Fast;
8978 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8979 AlignmentIsAcceptable(MVT::v2i64, 16))
8980 return MVT::v2i64;
8981 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8982 return MVT::f128;
8983 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8984 return MVT::i64;
8985 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8986 return MVT::i32;
8987 return MVT::Other;
8990 LLT AArch64TargetLowering::getOptimalMemOpLLT(
8991 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8992 bool ZeroMemset, bool MemcpyStrSrc,
8993 const AttributeList &FuncAttributes) const {
8994 bool CanImplicitFloat =
8995 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8996 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8997 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8998 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8999 // taken one instruction to materialize the v2i64 zero and one store (with
9000 // restrictive addressing mode). Just do i64 stores.
9001 bool IsSmallMemset = IsMemset && Size < 32;
9002 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
9003 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
9004 return true;
9005 bool Fast;
9006 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
9007 &Fast) &&
9008 Fast;
9011 if (CanUseNEON && IsMemset && !IsSmallMemset &&
9012 AlignmentIsAcceptable(MVT::v2i64, 16))
9013 return LLT::vector(2, 64);
9014 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
9015 return LLT::scalar(128);
9016 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
9017 return LLT::scalar(64);
9018 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
9019 return LLT::scalar(32);
9020 return LLT();
9023 // 12-bit optionally shifted immediates are legal for adds.
9024 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
9025 if (Immed == std::numeric_limits<int64_t>::min()) {
9026 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
9027 << ": avoid UB for INT64_MIN\n");
9028 return false;
9030 // Same encoding for add/sub, just flip the sign.
9031 Immed = std::abs(Immed);
9032 bool IsLegal = ((Immed >> 12) == 0 ||
9033 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
9034 LLVM_DEBUG(dbgs() << "Is " << Immed
9035 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
9036 return IsLegal;
9039 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
9040 // immediates is the same as for an add or a sub.
9041 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
9042 return isLegalAddImmediate(Immed);
9045 /// isLegalAddressingMode - Return true if the addressing mode represented
9046 /// by AM is legal for this target, for a load/store of the specified type.
9047 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
9048 const AddrMode &AM, Type *Ty,
9049 unsigned AS, Instruction *I) const {
9050 // AArch64 has five basic addressing modes:
9051 // reg
9052 // reg + 9-bit signed offset
9053 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
9054 // reg1 + reg2
9055 // reg + SIZE_IN_BYTES * reg
9057 // No global is ever allowed as a base.
9058 if (AM.BaseGV)
9059 return false;
9061 // No reg+reg+imm addressing.
9062 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
9063 return false;
9065 // check reg + imm case:
9066 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
9067 uint64_t NumBytes = 0;
9068 if (Ty->isSized()) {
9069 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
9070 NumBytes = NumBits / 8;
9071 if (!isPowerOf2_64(NumBits))
9072 NumBytes = 0;
9075 if (!AM.Scale) {
9076 int64_t Offset = AM.BaseOffs;
9078 // 9-bit signed offset
9079 if (isInt<9>(Offset))
9080 return true;
9082 // 12-bit unsigned offset
9083 unsigned shift = Log2_64(NumBytes);
9084 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
9085 // Must be a multiple of NumBytes (NumBytes is a power of 2)
9086 (Offset >> shift) << shift == Offset)
9087 return true;
9088 return false;
9091 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
9093 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
9096 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
9097 // Consider splitting large offset of struct or array.
9098 return true;
9101 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
9102 const AddrMode &AM, Type *Ty,
9103 unsigned AS) const {
9104 // Scaling factors are not free at all.
9105 // Operands | Rt Latency
9106 // -------------------------------------------
9107 // Rt, [Xn, Xm] | 4
9108 // -------------------------------------------
9109 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
9110 // Rt, [Xn, Wm, <extend> #imm] |
9111 if (isLegalAddressingMode(DL, AM, Ty, AS))
9112 // Scale represents reg2 * scale, thus account for 1 if
9113 // it is not equal to 0 or 1.
9114 return AM.Scale != 0 && AM.Scale != 1;
9115 return -1;
9118 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9119 VT = VT.getScalarType();
9121 if (!VT.isSimple())
9122 return false;
9124 switch (VT.getSimpleVT().SimpleTy) {
9125 case MVT::f32:
9126 case MVT::f64:
9127 return true;
9128 default:
9129 break;
9132 return false;
9135 const MCPhysReg *
9136 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
9137 // LR is a callee-save register, but we must treat it as clobbered by any call
9138 // site. Hence we include LR in the scratch registers, which are in turn added
9139 // as implicit-defs for stackmaps and patchpoints.
9140 static const MCPhysReg ScratchRegs[] = {
9141 AArch64::X16, AArch64::X17, AArch64::LR, 0
9143 return ScratchRegs;
9146 bool
9147 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9148 CombineLevel Level) const {
9149 N = N->getOperand(0).getNode();
9150 EVT VT = N->getValueType(0);
9151 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9152 // it with shift to let it be lowered to UBFX.
9153 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9154 isa<ConstantSDNode>(N->getOperand(1))) {
9155 uint64_t TruncMask = N->getConstantOperandVal(1);
9156 if (isMask_64(TruncMask) &&
9157 N->getOperand(0).getOpcode() == ISD::SRL &&
9158 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9159 return false;
9161 return true;
9164 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9165 Type *Ty) const {
9166 assert(Ty->isIntegerTy());
9168 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9169 if (BitSize == 0)
9170 return false;
9172 int64_t Val = Imm.getSExtValue();
9173 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9174 return true;
9176 if ((int64_t)Val < 0)
9177 Val = ~Val;
9178 if (BitSize == 32)
9179 Val &= (1LL << 32) - 1;
9181 unsigned LZ = countLeadingZeros((uint64_t)Val);
9182 unsigned Shift = (63 - LZ) / 16;
9183 // MOVZ is free so return true for one or fewer MOVK.
9184 return Shift < 3;
9187 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9188 unsigned Index) const {
9189 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9190 return false;
9192 return (Index == 0 || Index == ResVT.getVectorNumElements());
9195 /// Turn vector tests of the signbit in the form of:
9196 /// xor (sra X, elt_size(X)-1), -1
9197 /// into:
9198 /// cmge X, X, #0
9199 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9200 const AArch64Subtarget *Subtarget) {
9201 EVT VT = N->getValueType(0);
9202 if (!Subtarget->hasNEON() || !VT.isVector())
9203 return SDValue();
9205 // There must be a shift right algebraic before the xor, and the xor must be a
9206 // 'not' operation.
9207 SDValue Shift = N->getOperand(0);
9208 SDValue Ones = N->getOperand(1);
9209 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9210 !ISD::isBuildVectorAllOnes(Ones.getNode()))
9211 return SDValue();
9213 // The shift should be smearing the sign bit across each vector element.
9214 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9215 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9216 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9217 return SDValue();
9219 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9222 // Generate SUBS and CSEL for integer abs.
9223 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9224 EVT VT = N->getValueType(0);
9226 SDValue N0 = N->getOperand(0);
9227 SDValue N1 = N->getOperand(1);
9228 SDLoc DL(N);
9230 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9231 // and change it to SUB and CSEL.
9232 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9233 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9234 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9235 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9236 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9237 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9238 N0.getOperand(0));
9239 // Generate SUBS & CSEL.
9240 SDValue Cmp =
9241 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9242 N0.getOperand(0), DAG.getConstant(0, DL, VT));
9243 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9244 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9245 SDValue(Cmp.getNode(), 1));
9247 return SDValue();
9250 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9251 TargetLowering::DAGCombinerInfo &DCI,
9252 const AArch64Subtarget *Subtarget) {
9253 if (DCI.isBeforeLegalizeOps())
9254 return SDValue();
9256 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9257 return Cmp;
9259 return performIntegerAbsCombine(N, DAG);
9262 SDValue
9263 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9264 SelectionDAG &DAG,
9265 SmallVectorImpl<SDNode *> &Created) const {
9266 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9267 if (isIntDivCheap(N->getValueType(0), Attr))
9268 return SDValue(N,0); // Lower SDIV as SDIV
9270 // fold (sdiv X, pow2)
9271 EVT VT = N->getValueType(0);
9272 if ((VT != MVT::i32 && VT != MVT::i64) ||
9273 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9274 return SDValue();
9276 SDLoc DL(N);
9277 SDValue N0 = N->getOperand(0);
9278 unsigned Lg2 = Divisor.countTrailingZeros();
9279 SDValue Zero = DAG.getConstant(0, DL, VT);
9280 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9282 // Add (N0 < 0) ? Pow2 - 1 : 0;
9283 SDValue CCVal;
9284 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9285 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9286 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9288 Created.push_back(Cmp.getNode());
9289 Created.push_back(Add.getNode());
9290 Created.push_back(CSel.getNode());
9292 // Divide by pow2.
9293 SDValue SRA =
9294 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9296 // If we're dividing by a positive value, we're done. Otherwise, we must
9297 // negate the result.
9298 if (Divisor.isNonNegative())
9299 return SRA;
9301 Created.push_back(SRA.getNode());
9302 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9305 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9306 TargetLowering::DAGCombinerInfo &DCI,
9307 const AArch64Subtarget *Subtarget) {
9308 if (DCI.isBeforeLegalizeOps())
9309 return SDValue();
9311 // The below optimizations require a constant RHS.
9312 if (!isa<ConstantSDNode>(N->getOperand(1)))
9313 return SDValue();
9315 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9316 const APInt &ConstValue = C->getAPIntValue();
9318 // Multiplication of a power of two plus/minus one can be done more
9319 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9320 // future CPUs have a cheaper MADD instruction, this may need to be
9321 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9322 // 64-bit is 5 cycles, so this is always a win.
9323 // More aggressively, some multiplications N0 * C can be lowered to
9324 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9325 // e.g. 6=3*2=(2+1)*2.
9326 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9327 // which equals to (1+2)*16-(1+2).
9328 SDValue N0 = N->getOperand(0);
9329 // TrailingZeroes is used to test if the mul can be lowered to
9330 // shift+add+shift.
9331 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9332 if (TrailingZeroes) {
9333 // Conservatively do not lower to shift+add+shift if the mul might be
9334 // folded into smul or umul.
9335 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9336 isZeroExtended(N0.getNode(), DAG)))
9337 return SDValue();
9338 // Conservatively do not lower to shift+add+shift if the mul might be
9339 // folded into madd or msub.
9340 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9341 N->use_begin()->getOpcode() == ISD::SUB))
9342 return SDValue();
9344 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9345 // and shift+add+shift.
9346 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9348 unsigned ShiftAmt, AddSubOpc;
9349 // Is the shifted value the LHS operand of the add/sub?
9350 bool ShiftValUseIsN0 = true;
9351 // Do we need to negate the result?
9352 bool NegateResult = false;
9354 if (ConstValue.isNonNegative()) {
9355 // (mul x, 2^N + 1) => (add (shl x, N), x)
9356 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9357 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9358 APInt SCVMinus1 = ShiftedConstValue - 1;
9359 APInt CVPlus1 = ConstValue + 1;
9360 if (SCVMinus1.isPowerOf2()) {
9361 ShiftAmt = SCVMinus1.logBase2();
9362 AddSubOpc = ISD::ADD;
9363 } else if (CVPlus1.isPowerOf2()) {
9364 ShiftAmt = CVPlus1.logBase2();
9365 AddSubOpc = ISD::SUB;
9366 } else
9367 return SDValue();
9368 } else {
9369 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9370 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9371 APInt CVNegPlus1 = -ConstValue + 1;
9372 APInt CVNegMinus1 = -ConstValue - 1;
9373 if (CVNegPlus1.isPowerOf2()) {
9374 ShiftAmt = CVNegPlus1.logBase2();
9375 AddSubOpc = ISD::SUB;
9376 ShiftValUseIsN0 = false;
9377 } else if (CVNegMinus1.isPowerOf2()) {
9378 ShiftAmt = CVNegMinus1.logBase2();
9379 AddSubOpc = ISD::ADD;
9380 NegateResult = true;
9381 } else
9382 return SDValue();
9385 SDLoc DL(N);
9386 EVT VT = N->getValueType(0);
9387 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9388 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9390 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9391 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9392 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9393 assert(!(NegateResult && TrailingZeroes) &&
9394 "NegateResult and TrailingZeroes cannot both be true for now.");
9395 // Negate the result.
9396 if (NegateResult)
9397 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9398 // Shift the result.
9399 if (TrailingZeroes)
9400 return DAG.getNode(ISD::SHL, DL, VT, Res,
9401 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9402 return Res;
9405 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9406 SelectionDAG &DAG) {
9407 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9408 // optimize away operation when it's from a constant.
9410 // The general transformation is:
9411 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9412 // AND(VECTOR_CMP(x,y), constant2)
9413 // constant2 = UNARYOP(constant)
9415 // Early exit if this isn't a vector operation, the operand of the
9416 // unary operation isn't a bitwise AND, or if the sizes of the operations
9417 // aren't the same.
9418 EVT VT = N->getValueType(0);
9419 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9420 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9421 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9422 return SDValue();
9424 // Now check that the other operand of the AND is a constant. We could
9425 // make the transformation for non-constant splats as well, but it's unclear
9426 // that would be a benefit as it would not eliminate any operations, just
9427 // perform one more step in scalar code before moving to the vector unit.
9428 if (BuildVectorSDNode *BV =
9429 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9430 // Bail out if the vector isn't a constant.
9431 if (!BV->isConstant())
9432 return SDValue();
9434 // Everything checks out. Build up the new and improved node.
9435 SDLoc DL(N);
9436 EVT IntVT = BV->getValueType(0);
9437 // Create a new constant of the appropriate type for the transformed
9438 // DAG.
9439 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9440 // The AND node needs bitcasts to/from an integer vector type around it.
9441 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9442 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9443 N->getOperand(0)->getOperand(0), MaskConst);
9444 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9445 return Res;
9448 return SDValue();
9451 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9452 const AArch64Subtarget *Subtarget) {
9453 // First try to optimize away the conversion when it's conditionally from
9454 // a constant. Vectors only.
9455 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9456 return Res;
9458 EVT VT = N->getValueType(0);
9459 if (VT != MVT::f32 && VT != MVT::f64)
9460 return SDValue();
9462 // Only optimize when the source and destination types have the same width.
9463 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9464 return SDValue();
9466 // If the result of an integer load is only used by an integer-to-float
9467 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9468 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9469 SDValue N0 = N->getOperand(0);
9470 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9471 // Do not change the width of a volatile load.
9472 !cast<LoadSDNode>(N0)->isVolatile()) {
9473 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9474 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9475 LN0->getPointerInfo(), LN0->getAlignment(),
9476 LN0->getMemOperand()->getFlags());
9478 // Make sure successors of the original load stay after it by updating them
9479 // to use the new Chain.
9480 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9482 unsigned Opcode =
9483 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9484 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9487 return SDValue();
9490 /// Fold a floating-point multiply by power of two into floating-point to
9491 /// fixed-point conversion.
9492 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9493 TargetLowering::DAGCombinerInfo &DCI,
9494 const AArch64Subtarget *Subtarget) {
9495 if (!Subtarget->hasNEON())
9496 return SDValue();
9498 if (!N->getValueType(0).isSimple())
9499 return SDValue();
9501 SDValue Op = N->getOperand(0);
9502 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9503 Op.getOpcode() != ISD::FMUL)
9504 return SDValue();
9506 SDValue ConstVec = Op->getOperand(1);
9507 if (!isa<BuildVectorSDNode>(ConstVec))
9508 return SDValue();
9510 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9511 uint32_t FloatBits = FloatTy.getSizeInBits();
9512 if (FloatBits != 32 && FloatBits != 64)
9513 return SDValue();
9515 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9516 uint32_t IntBits = IntTy.getSizeInBits();
9517 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9518 return SDValue();
9520 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9521 if (IntBits > FloatBits)
9522 return SDValue();
9524 BitVector UndefElements;
9525 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9526 int32_t Bits = IntBits == 64 ? 64 : 32;
9527 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9528 if (C == -1 || C == 0 || C > Bits)
9529 return SDValue();
9531 MVT ResTy;
9532 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9533 switch (NumLanes) {
9534 default:
9535 return SDValue();
9536 case 2:
9537 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9538 break;
9539 case 4:
9540 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9541 break;
9544 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9545 return SDValue();
9547 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9548 "Illegal vector type after legalization");
9550 SDLoc DL(N);
9551 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9552 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9553 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9554 SDValue FixConv =
9555 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9556 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9557 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9558 // We can handle smaller integers by generating an extra trunc.
9559 if (IntBits < FloatBits)
9560 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9562 return FixConv;
9565 /// Fold a floating-point divide by power of two into fixed-point to
9566 /// floating-point conversion.
9567 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9568 TargetLowering::DAGCombinerInfo &DCI,
9569 const AArch64Subtarget *Subtarget) {
9570 if (!Subtarget->hasNEON())
9571 return SDValue();
9573 SDValue Op = N->getOperand(0);
9574 unsigned Opc = Op->getOpcode();
9575 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9576 !Op.getOperand(0).getValueType().isSimple() ||
9577 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9578 return SDValue();
9580 SDValue ConstVec = N->getOperand(1);
9581 if (!isa<BuildVectorSDNode>(ConstVec))
9582 return SDValue();
9584 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9585 int32_t IntBits = IntTy.getSizeInBits();
9586 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9587 return SDValue();
9589 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9590 int32_t FloatBits = FloatTy.getSizeInBits();
9591 if (FloatBits != 32 && FloatBits != 64)
9592 return SDValue();
9594 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9595 if (IntBits > FloatBits)
9596 return SDValue();
9598 BitVector UndefElements;
9599 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9600 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9601 if (C == -1 || C == 0 || C > FloatBits)
9602 return SDValue();
9604 MVT ResTy;
9605 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9606 switch (NumLanes) {
9607 default:
9608 return SDValue();
9609 case 2:
9610 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9611 break;
9612 case 4:
9613 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9614 break;
9617 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9618 return SDValue();
9620 SDLoc DL(N);
9621 SDValue ConvInput = Op.getOperand(0);
9622 bool IsSigned = Opc == ISD::SINT_TO_FP;
9623 if (IntBits < FloatBits)
9624 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9625 ResTy, ConvInput);
9627 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9628 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9629 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9630 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9631 DAG.getConstant(C, DL, MVT::i32));
9634 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9635 /// searches for and classifies those shifts.
9636 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9637 bool &FromHi) {
9638 if (N.getOpcode() == ISD::SHL)
9639 FromHi = false;
9640 else if (N.getOpcode() == ISD::SRL)
9641 FromHi = true;
9642 else
9643 return false;
9645 if (!isa<ConstantSDNode>(N.getOperand(1)))
9646 return false;
9648 ShiftAmount = N->getConstantOperandVal(1);
9649 Src = N->getOperand(0);
9650 return true;
9653 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9654 /// registers viewed as a high/low pair. This function looks for the pattern:
9655 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9656 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9657 /// aren't independent.
9658 static SDValue tryCombineToEXTR(SDNode *N,
9659 TargetLowering::DAGCombinerInfo &DCI) {
9660 SelectionDAG &DAG = DCI.DAG;
9661 SDLoc DL(N);
9662 EVT VT = N->getValueType(0);
9664 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9666 if (VT != MVT::i32 && VT != MVT::i64)
9667 return SDValue();
9669 SDValue LHS;
9670 uint32_t ShiftLHS = 0;
9671 bool LHSFromHi = false;
9672 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9673 return SDValue();
9675 SDValue RHS;
9676 uint32_t ShiftRHS = 0;
9677 bool RHSFromHi = false;
9678 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9679 return SDValue();
9681 // If they're both trying to come from the high part of the register, they're
9682 // not really an EXTR.
9683 if (LHSFromHi == RHSFromHi)
9684 return SDValue();
9686 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9687 return SDValue();
9689 if (LHSFromHi) {
9690 std::swap(LHS, RHS);
9691 std::swap(ShiftLHS, ShiftRHS);
9694 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9695 DAG.getConstant(ShiftRHS, DL, MVT::i64));
9698 static SDValue tryCombineToBSL(SDNode *N,
9699 TargetLowering::DAGCombinerInfo &DCI) {
9700 EVT VT = N->getValueType(0);
9701 SelectionDAG &DAG = DCI.DAG;
9702 SDLoc DL(N);
9704 if (!VT.isVector())
9705 return SDValue();
9707 SDValue N0 = N->getOperand(0);
9708 if (N0.getOpcode() != ISD::AND)
9709 return SDValue();
9711 SDValue N1 = N->getOperand(1);
9712 if (N1.getOpcode() != ISD::AND)
9713 return SDValue();
9715 // We only have to look for constant vectors here since the general, variable
9716 // case can be handled in TableGen.
9717 unsigned Bits = VT.getScalarSizeInBits();
9718 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9719 for (int i = 1; i >= 0; --i)
9720 for (int j = 1; j >= 0; --j) {
9721 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9722 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9723 if (!BVN0 || !BVN1)
9724 continue;
9726 bool FoundMatch = true;
9727 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9728 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9729 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9730 if (!CN0 || !CN1 ||
9731 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9732 FoundMatch = false;
9733 break;
9737 if (FoundMatch)
9738 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9739 N0->getOperand(1 - i), N1->getOperand(1 - j));
9742 return SDValue();
9745 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9746 const AArch64Subtarget *Subtarget) {
9747 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9748 SelectionDAG &DAG = DCI.DAG;
9749 EVT VT = N->getValueType(0);
9751 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9752 return SDValue();
9754 if (SDValue Res = tryCombineToEXTR(N, DCI))
9755 return Res;
9757 if (SDValue Res = tryCombineToBSL(N, DCI))
9758 return Res;
9760 return SDValue();
9763 static SDValue performANDCombine(SDNode *N,
9764 TargetLowering::DAGCombinerInfo &DCI) {
9765 SelectionDAG &DAG = DCI.DAG;
9766 SDValue LHS = N->getOperand(0);
9767 EVT VT = N->getValueType(0);
9768 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9769 return SDValue();
9771 BuildVectorSDNode *BVN =
9772 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9773 if (!BVN)
9774 return SDValue();
9776 // AND does not accept an immediate, so check if we can use a BIC immediate
9777 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9778 // pattern in isel, because some immediates may be lowered to the preferred
9779 // (and x, (movi imm)) form, even though an mvni representation also exists.
9780 APInt DefBits(VT.getSizeInBits(), 0);
9781 APInt UndefBits(VT.getSizeInBits(), 0);
9782 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9783 SDValue NewOp;
9785 DefBits = ~DefBits;
9786 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9787 DefBits, &LHS)) ||
9788 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9789 DefBits, &LHS)))
9790 return NewOp;
9792 UndefBits = ~UndefBits;
9793 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9794 UndefBits, &LHS)) ||
9795 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9796 UndefBits, &LHS)))
9797 return NewOp;
9800 return SDValue();
9803 static SDValue performSRLCombine(SDNode *N,
9804 TargetLowering::DAGCombinerInfo &DCI) {
9805 SelectionDAG &DAG = DCI.DAG;
9806 EVT VT = N->getValueType(0);
9807 if (VT != MVT::i32 && VT != MVT::i64)
9808 return SDValue();
9810 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9811 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9812 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9813 SDValue N0 = N->getOperand(0);
9814 if (N0.getOpcode() == ISD::BSWAP) {
9815 SDLoc DL(N);
9816 SDValue N1 = N->getOperand(1);
9817 SDValue N00 = N0.getOperand(0);
9818 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9819 uint64_t ShiftAmt = C->getZExtValue();
9820 if (VT == MVT::i32 && ShiftAmt == 16 &&
9821 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9822 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9823 if (VT == MVT::i64 && ShiftAmt == 32 &&
9824 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9825 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9828 return SDValue();
9831 static SDValue performBitcastCombine(SDNode *N,
9832 TargetLowering::DAGCombinerInfo &DCI,
9833 SelectionDAG &DAG) {
9834 // Wait 'til after everything is legalized to try this. That way we have
9835 // legal vector types and such.
9836 if (DCI.isBeforeLegalizeOps())
9837 return SDValue();
9839 // Remove extraneous bitcasts around an extract_subvector.
9840 // For example,
9841 // (v4i16 (bitconvert
9842 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9843 // becomes
9844 // (extract_subvector ((v8i16 ...), (i64 4)))
9846 // Only interested in 64-bit vectors as the ultimate result.
9847 EVT VT = N->getValueType(0);
9848 if (!VT.isVector())
9849 return SDValue();
9850 if (VT.getSimpleVT().getSizeInBits() != 64)
9851 return SDValue();
9852 // Is the operand an extract_subvector starting at the beginning or halfway
9853 // point of the vector? A low half may also come through as an
9854 // EXTRACT_SUBREG, so look for that, too.
9855 SDValue Op0 = N->getOperand(0);
9856 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9857 !(Op0->isMachineOpcode() &&
9858 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9859 return SDValue();
9860 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9861 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9862 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9863 return SDValue();
9864 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9865 if (idx != AArch64::dsub)
9866 return SDValue();
9867 // The dsub reference is equivalent to a lane zero subvector reference.
9868 idx = 0;
9870 // Look through the bitcast of the input to the extract.
9871 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9872 return SDValue();
9873 SDValue Source = Op0->getOperand(0)->getOperand(0);
9874 // If the source type has twice the number of elements as our destination
9875 // type, we know this is an extract of the high or low half of the vector.
9876 EVT SVT = Source->getValueType(0);
9877 if (!SVT.isVector() ||
9878 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9879 return SDValue();
9881 LLVM_DEBUG(
9882 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9884 // Create the simplified form to just extract the low or high half of the
9885 // vector directly rather than bothering with the bitcasts.
9886 SDLoc dl(N);
9887 unsigned NumElements = VT.getVectorNumElements();
9888 if (idx) {
9889 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9890 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9891 } else {
9892 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9893 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9894 Source, SubReg),
9899 static SDValue performConcatVectorsCombine(SDNode *N,
9900 TargetLowering::DAGCombinerInfo &DCI,
9901 SelectionDAG &DAG) {
9902 SDLoc dl(N);
9903 EVT VT = N->getValueType(0);
9904 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9906 // Optimize concat_vectors of truncated vectors, where the intermediate
9907 // type is illegal, to avoid said illegality, e.g.,
9908 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9909 // (v2i16 (truncate (v2i64)))))
9910 // ->
9911 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9912 // (v4i32 (bitcast (v2i64))),
9913 // <0, 2, 4, 6>)))
9914 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9915 // on both input and result type, so we might generate worse code.
9916 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9917 if (N->getNumOperands() == 2 &&
9918 N0->getOpcode() == ISD::TRUNCATE &&
9919 N1->getOpcode() == ISD::TRUNCATE) {
9920 SDValue N00 = N0->getOperand(0);
9921 SDValue N10 = N1->getOperand(0);
9922 EVT N00VT = N00.getValueType();
9924 if (N00VT == N10.getValueType() &&
9925 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9926 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9927 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9928 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9929 for (size_t i = 0; i < Mask.size(); ++i)
9930 Mask[i] = i * 2;
9931 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9932 DAG.getVectorShuffle(
9933 MidVT, dl,
9934 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9935 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9939 // Wait 'til after everything is legalized to try this. That way we have
9940 // legal vector types and such.
9941 if (DCI.isBeforeLegalizeOps())
9942 return SDValue();
9944 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9945 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9946 // canonicalise to that.
9947 if (N0 == N1 && VT.getVectorNumElements() == 2) {
9948 assert(VT.getScalarSizeInBits() == 64);
9949 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9950 DAG.getConstant(0, dl, MVT::i64));
9953 // Canonicalise concat_vectors so that the right-hand vector has as few
9954 // bit-casts as possible before its real operation. The primary matching
9955 // destination for these operations will be the narrowing "2" instructions,
9956 // which depend on the operation being performed on this right-hand vector.
9957 // For example,
9958 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9959 // becomes
9960 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9962 if (N1->getOpcode() != ISD::BITCAST)
9963 return SDValue();
9964 SDValue RHS = N1->getOperand(0);
9965 MVT RHSTy = RHS.getValueType().getSimpleVT();
9966 // If the RHS is not a vector, this is not the pattern we're looking for.
9967 if (!RHSTy.isVector())
9968 return SDValue();
9970 LLVM_DEBUG(
9971 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9973 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9974 RHSTy.getVectorNumElements() * 2);
9975 return DAG.getNode(ISD::BITCAST, dl, VT,
9976 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9977 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9978 RHS));
9981 static SDValue tryCombineFixedPointConvert(SDNode *N,
9982 TargetLowering::DAGCombinerInfo &DCI,
9983 SelectionDAG &DAG) {
9984 // Wait until after everything is legalized to try this. That way we have
9985 // legal vector types and such.
9986 if (DCI.isBeforeLegalizeOps())
9987 return SDValue();
9988 // Transform a scalar conversion of a value from a lane extract into a
9989 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9990 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9991 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9993 // The second form interacts better with instruction selection and the
9994 // register allocator to avoid cross-class register copies that aren't
9995 // coalescable due to a lane reference.
9997 // Check the operand and see if it originates from a lane extract.
9998 SDValue Op1 = N->getOperand(1);
9999 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10000 // Yep, no additional predication needed. Perform the transform.
10001 SDValue IID = N->getOperand(0);
10002 SDValue Shift = N->getOperand(2);
10003 SDValue Vec = Op1.getOperand(0);
10004 SDValue Lane = Op1.getOperand(1);
10005 EVT ResTy = N->getValueType(0);
10006 EVT VecResTy;
10007 SDLoc DL(N);
10009 // The vector width should be 128 bits by the time we get here, even
10010 // if it started as 64 bits (the extract_vector handling will have
10011 // done so).
10012 assert(Vec.getValueSizeInBits() == 128 &&
10013 "unexpected vector size on extract_vector_elt!");
10014 if (Vec.getValueType() == MVT::v4i32)
10015 VecResTy = MVT::v4f32;
10016 else if (Vec.getValueType() == MVT::v2i64)
10017 VecResTy = MVT::v2f64;
10018 else
10019 llvm_unreachable("unexpected vector type!");
10021 SDValue Convert =
10022 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
10023 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
10025 return SDValue();
10028 // AArch64 high-vector "long" operations are formed by performing the non-high
10029 // version on an extract_subvector of each operand which gets the high half:
10031 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
10033 // However, there are cases which don't have an extract_high explicitly, but
10034 // have another operation that can be made compatible with one for free. For
10035 // example:
10037 // (dupv64 scalar) --> (extract_high (dup128 scalar))
10039 // This routine does the actual conversion of such DUPs, once outer routines
10040 // have determined that everything else is in order.
10041 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
10042 // similarly here.
10043 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
10044 switch (N.getOpcode()) {
10045 case AArch64ISD::DUP:
10046 case AArch64ISD::DUPLANE8:
10047 case AArch64ISD::DUPLANE16:
10048 case AArch64ISD::DUPLANE32:
10049 case AArch64ISD::DUPLANE64:
10050 case AArch64ISD::MOVI:
10051 case AArch64ISD::MOVIshift:
10052 case AArch64ISD::MOVIedit:
10053 case AArch64ISD::MOVImsl:
10054 case AArch64ISD::MVNIshift:
10055 case AArch64ISD::MVNImsl:
10056 break;
10057 default:
10058 // FMOV could be supported, but isn't very useful, as it would only occur
10059 // if you passed a bitcast' floating point immediate to an eligible long
10060 // integer op (addl, smull, ...).
10061 return SDValue();
10064 MVT NarrowTy = N.getSimpleValueType();
10065 if (!NarrowTy.is64BitVector())
10066 return SDValue();
10068 MVT ElementTy = NarrowTy.getVectorElementType();
10069 unsigned NumElems = NarrowTy.getVectorNumElements();
10070 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
10072 SDLoc dl(N);
10073 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
10074 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
10075 DAG.getConstant(NumElems, dl, MVT::i64));
10078 static bool isEssentiallyExtractHighSubvector(SDValue N) {
10079 if (N.getOpcode() == ISD::BITCAST)
10080 N = N.getOperand(0);
10081 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10082 return false;
10083 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
10084 N.getOperand(0).getValueType().getVectorNumElements() / 2;
10087 /// Helper structure to keep track of ISD::SET_CC operands.
10088 struct GenericSetCCInfo {
10089 const SDValue *Opnd0;
10090 const SDValue *Opnd1;
10091 ISD::CondCode CC;
10094 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
10095 struct AArch64SetCCInfo {
10096 const SDValue *Cmp;
10097 AArch64CC::CondCode CC;
10100 /// Helper structure to keep track of SetCC information.
10101 union SetCCInfo {
10102 GenericSetCCInfo Generic;
10103 AArch64SetCCInfo AArch64;
10106 /// Helper structure to be able to read SetCC information. If set to
10107 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
10108 /// GenericSetCCInfo.
10109 struct SetCCInfoAndKind {
10110 SetCCInfo Info;
10111 bool IsAArch64;
10114 /// Check whether or not \p Op is a SET_CC operation, either a generic or
10115 /// an
10116 /// AArch64 lowered one.
10117 /// \p SetCCInfo is filled accordingly.
10118 /// \post SetCCInfo is meanginfull only when this function returns true.
10119 /// \return True when Op is a kind of SET_CC operation.
10120 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
10121 // If this is a setcc, this is straight forward.
10122 if (Op.getOpcode() == ISD::SETCC) {
10123 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
10124 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
10125 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10126 SetCCInfo.IsAArch64 = false;
10127 return true;
10129 // Otherwise, check if this is a matching csel instruction.
10130 // In other words:
10131 // - csel 1, 0, cc
10132 // - csel 0, 1, !cc
10133 if (Op.getOpcode() != AArch64ISD::CSEL)
10134 return false;
10135 // Set the information about the operands.
10136 // TODO: we want the operands of the Cmp not the csel
10137 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
10138 SetCCInfo.IsAArch64 = true;
10139 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
10140 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10142 // Check that the operands matches the constraints:
10143 // (1) Both operands must be constants.
10144 // (2) One must be 1 and the other must be 0.
10145 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10146 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10148 // Check (1).
10149 if (!TValue || !FValue)
10150 return false;
10152 // Check (2).
10153 if (!TValue->isOne()) {
10154 // Update the comparison when we are interested in !cc.
10155 std::swap(TValue, FValue);
10156 SetCCInfo.Info.AArch64.CC =
10157 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10159 return TValue->isOne() && FValue->isNullValue();
10162 // Returns true if Op is setcc or zext of setcc.
10163 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10164 if (isSetCC(Op, Info))
10165 return true;
10166 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10167 isSetCC(Op->getOperand(0), Info));
10170 // The folding we want to perform is:
10171 // (add x, [zext] (setcc cc ...) )
10172 // -->
10173 // (csel x, (add x, 1), !cc ...)
10175 // The latter will get matched to a CSINC instruction.
10176 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10177 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10178 SDValue LHS = Op->getOperand(0);
10179 SDValue RHS = Op->getOperand(1);
10180 SetCCInfoAndKind InfoAndKind;
10182 // If neither operand is a SET_CC, give up.
10183 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10184 std::swap(LHS, RHS);
10185 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10186 return SDValue();
10189 // FIXME: This could be generatized to work for FP comparisons.
10190 EVT CmpVT = InfoAndKind.IsAArch64
10191 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10192 : InfoAndKind.Info.Generic.Opnd0->getValueType();
10193 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10194 return SDValue();
10196 SDValue CCVal;
10197 SDValue Cmp;
10198 SDLoc dl(Op);
10199 if (InfoAndKind.IsAArch64) {
10200 CCVal = DAG.getConstant(
10201 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10202 MVT::i32);
10203 Cmp = *InfoAndKind.Info.AArch64.Cmp;
10204 } else
10205 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10206 *InfoAndKind.Info.Generic.Opnd1,
10207 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10208 CCVal, DAG, dl);
10210 EVT VT = Op->getValueType(0);
10211 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10212 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10215 // The basic add/sub long vector instructions have variants with "2" on the end
10216 // which act on the high-half of their inputs. They are normally matched by
10217 // patterns like:
10219 // (add (zeroext (extract_high LHS)),
10220 // (zeroext (extract_high RHS)))
10221 // -> uaddl2 vD, vN, vM
10223 // However, if one of the extracts is something like a duplicate, this
10224 // instruction can still be used profitably. This function puts the DAG into a
10225 // more appropriate form for those patterns to trigger.
10226 static SDValue performAddSubLongCombine(SDNode *N,
10227 TargetLowering::DAGCombinerInfo &DCI,
10228 SelectionDAG &DAG) {
10229 if (DCI.isBeforeLegalizeOps())
10230 return SDValue();
10232 MVT VT = N->getSimpleValueType(0);
10233 if (!VT.is128BitVector()) {
10234 if (N->getOpcode() == ISD::ADD)
10235 return performSetccAddFolding(N, DAG);
10236 return SDValue();
10239 // Make sure both branches are extended in the same way.
10240 SDValue LHS = N->getOperand(0);
10241 SDValue RHS = N->getOperand(1);
10242 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10243 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10244 LHS.getOpcode() != RHS.getOpcode())
10245 return SDValue();
10247 unsigned ExtType = LHS.getOpcode();
10249 // It's not worth doing if at least one of the inputs isn't already an
10250 // extract, but we don't know which it'll be so we have to try both.
10251 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10252 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10253 if (!RHS.getNode())
10254 return SDValue();
10256 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10257 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10258 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10259 if (!LHS.getNode())
10260 return SDValue();
10262 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10265 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10268 // Massage DAGs which we can use the high-half "long" operations on into
10269 // something isel will recognize better. E.g.
10271 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10272 // (aarch64_neon_umull (extract_high (v2i64 vec)))
10273 // (extract_high (v2i64 (dup128 scalar)))))
10275 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10276 TargetLowering::DAGCombinerInfo &DCI,
10277 SelectionDAG &DAG) {
10278 if (DCI.isBeforeLegalizeOps())
10279 return SDValue();
10281 SDValue LHS = N->getOperand(1);
10282 SDValue RHS = N->getOperand(2);
10283 assert(LHS.getValueType().is64BitVector() &&
10284 RHS.getValueType().is64BitVector() &&
10285 "unexpected shape for long operation");
10287 // Either node could be a DUP, but it's not worth doing both of them (you'd
10288 // just as well use the non-high version) so look for a corresponding extract
10289 // operation on the other "wing".
10290 if (isEssentiallyExtractHighSubvector(LHS)) {
10291 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10292 if (!RHS.getNode())
10293 return SDValue();
10294 } else if (isEssentiallyExtractHighSubvector(RHS)) {
10295 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10296 if (!LHS.getNode())
10297 return SDValue();
10300 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10301 N->getOperand(0), LHS, RHS);
10304 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10305 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10306 unsigned ElemBits = ElemTy.getSizeInBits();
10308 int64_t ShiftAmount;
10309 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10310 APInt SplatValue, SplatUndef;
10311 unsigned SplatBitSize;
10312 bool HasAnyUndefs;
10313 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10314 HasAnyUndefs, ElemBits) ||
10315 SplatBitSize != ElemBits)
10316 return SDValue();
10318 ShiftAmount = SplatValue.getSExtValue();
10319 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10320 ShiftAmount = CVN->getSExtValue();
10321 } else
10322 return SDValue();
10324 unsigned Opcode;
10325 bool IsRightShift;
10326 switch (IID) {
10327 default:
10328 llvm_unreachable("Unknown shift intrinsic");
10329 case Intrinsic::aarch64_neon_sqshl:
10330 Opcode = AArch64ISD::SQSHL_I;
10331 IsRightShift = false;
10332 break;
10333 case Intrinsic::aarch64_neon_uqshl:
10334 Opcode = AArch64ISD::UQSHL_I;
10335 IsRightShift = false;
10336 break;
10337 case Intrinsic::aarch64_neon_srshl:
10338 Opcode = AArch64ISD::SRSHR_I;
10339 IsRightShift = true;
10340 break;
10341 case Intrinsic::aarch64_neon_urshl:
10342 Opcode = AArch64ISD::URSHR_I;
10343 IsRightShift = true;
10344 break;
10345 case Intrinsic::aarch64_neon_sqshlu:
10346 Opcode = AArch64ISD::SQSHLU_I;
10347 IsRightShift = false;
10348 break;
10349 case Intrinsic::aarch64_neon_sshl:
10350 case Intrinsic::aarch64_neon_ushl:
10351 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
10352 // left shift for positive shift amounts. Below, we only replace the current
10353 // node with VSHL, if this condition is met.
10354 Opcode = AArch64ISD::VSHL;
10355 IsRightShift = false;
10356 break;
10359 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10360 SDLoc dl(N);
10361 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10362 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10363 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10364 SDLoc dl(N);
10365 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10366 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10369 return SDValue();
10372 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10373 // the intrinsics must be legal and take an i32, this means there's almost
10374 // certainly going to be a zext in the DAG which we can eliminate.
10375 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10376 SDValue AndN = N->getOperand(2);
10377 if (AndN.getOpcode() != ISD::AND)
10378 return SDValue();
10380 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10381 if (!CMask || CMask->getZExtValue() != Mask)
10382 return SDValue();
10384 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10385 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10388 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10389 SelectionDAG &DAG) {
10390 SDLoc dl(N);
10391 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10392 DAG.getNode(Opc, dl,
10393 N->getOperand(1).getSimpleValueType(),
10394 N->getOperand(1)),
10395 DAG.getConstant(0, dl, MVT::i64));
10398 static SDValue performIntrinsicCombine(SDNode *N,
10399 TargetLowering::DAGCombinerInfo &DCI,
10400 const AArch64Subtarget *Subtarget) {
10401 SelectionDAG &DAG = DCI.DAG;
10402 unsigned IID = getIntrinsicID(N);
10403 switch (IID) {
10404 default:
10405 break;
10406 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10407 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10408 return tryCombineFixedPointConvert(N, DCI, DAG);
10409 case Intrinsic::aarch64_neon_saddv:
10410 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10411 case Intrinsic::aarch64_neon_uaddv:
10412 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10413 case Intrinsic::aarch64_neon_sminv:
10414 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10415 case Intrinsic::aarch64_neon_uminv:
10416 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10417 case Intrinsic::aarch64_neon_smaxv:
10418 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10419 case Intrinsic::aarch64_neon_umaxv:
10420 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10421 case Intrinsic::aarch64_neon_fmax:
10422 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10423 N->getOperand(1), N->getOperand(2));
10424 case Intrinsic::aarch64_neon_fmin:
10425 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10426 N->getOperand(1), N->getOperand(2));
10427 case Intrinsic::aarch64_neon_fmaxnm:
10428 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10429 N->getOperand(1), N->getOperand(2));
10430 case Intrinsic::aarch64_neon_fminnm:
10431 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10432 N->getOperand(1), N->getOperand(2));
10433 case Intrinsic::aarch64_neon_smull:
10434 case Intrinsic::aarch64_neon_umull:
10435 case Intrinsic::aarch64_neon_pmull:
10436 case Intrinsic::aarch64_neon_sqdmull:
10437 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10438 case Intrinsic::aarch64_neon_sqshl:
10439 case Intrinsic::aarch64_neon_uqshl:
10440 case Intrinsic::aarch64_neon_sqshlu:
10441 case Intrinsic::aarch64_neon_srshl:
10442 case Intrinsic::aarch64_neon_urshl:
10443 case Intrinsic::aarch64_neon_sshl:
10444 case Intrinsic::aarch64_neon_ushl:
10445 return tryCombineShiftImm(IID, N, DAG);
10446 case Intrinsic::aarch64_crc32b:
10447 case Intrinsic::aarch64_crc32cb:
10448 return tryCombineCRC32(0xff, N, DAG);
10449 case Intrinsic::aarch64_crc32h:
10450 case Intrinsic::aarch64_crc32ch:
10451 return tryCombineCRC32(0xffff, N, DAG);
10453 return SDValue();
10456 static SDValue performExtendCombine(SDNode *N,
10457 TargetLowering::DAGCombinerInfo &DCI,
10458 SelectionDAG &DAG) {
10459 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10460 // we can convert that DUP into another extract_high (of a bigger DUP), which
10461 // helps the backend to decide that an sabdl2 would be useful, saving a real
10462 // extract_high operation.
10463 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10464 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10465 SDNode *ABDNode = N->getOperand(0).getNode();
10466 unsigned IID = getIntrinsicID(ABDNode);
10467 if (IID == Intrinsic::aarch64_neon_sabd ||
10468 IID == Intrinsic::aarch64_neon_uabd) {
10469 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10470 if (!NewABD.getNode())
10471 return SDValue();
10473 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10474 NewABD);
10478 // This is effectively a custom type legalization for AArch64.
10480 // Type legalization will split an extend of a small, legal, type to a larger
10481 // illegal type by first splitting the destination type, often creating
10482 // illegal source types, which then get legalized in isel-confusing ways,
10483 // leading to really terrible codegen. E.g.,
10484 // %result = v8i32 sext v8i8 %value
10485 // becomes
10486 // %losrc = extract_subreg %value, ...
10487 // %hisrc = extract_subreg %value, ...
10488 // %lo = v4i32 sext v4i8 %losrc
10489 // %hi = v4i32 sext v4i8 %hisrc
10490 // Things go rapidly downhill from there.
10492 // For AArch64, the [sz]ext vector instructions can only go up one element
10493 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10494 // take two instructions.
10496 // This implies that the most efficient way to do the extend from v8i8
10497 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10498 // the normal splitting to happen for the v8i16->v8i32.
10500 // This is pre-legalization to catch some cases where the default
10501 // type legalization will create ill-tempered code.
10502 if (!DCI.isBeforeLegalizeOps())
10503 return SDValue();
10505 // We're only interested in cleaning things up for non-legal vector types
10506 // here. If both the source and destination are legal, things will just
10507 // work naturally without any fiddling.
10508 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10509 EVT ResVT = N->getValueType(0);
10510 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10511 return SDValue();
10512 // If the vector type isn't a simple VT, it's beyond the scope of what
10513 // we're worried about here. Let legalization do its thing and hope for
10514 // the best.
10515 SDValue Src = N->getOperand(0);
10516 EVT SrcVT = Src->getValueType(0);
10517 if (!ResVT.isSimple() || !SrcVT.isSimple())
10518 return SDValue();
10520 // If the source VT is a 64-bit vector, we can play games and get the
10521 // better results we want.
10522 if (SrcVT.getSizeInBits() != 64)
10523 return SDValue();
10525 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10526 unsigned ElementCount = SrcVT.getVectorNumElements();
10527 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10528 SDLoc DL(N);
10529 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10531 // Now split the rest of the operation into two halves, each with a 64
10532 // bit source.
10533 EVT LoVT, HiVT;
10534 SDValue Lo, Hi;
10535 unsigned NumElements = ResVT.getVectorNumElements();
10536 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10537 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10538 ResVT.getVectorElementType(), NumElements / 2);
10540 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10541 LoVT.getVectorNumElements());
10542 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10543 DAG.getConstant(0, DL, MVT::i64));
10544 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10545 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10546 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10547 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10549 // Now combine the parts back together so we still have a single result
10550 // like the combiner expects.
10551 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10554 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10555 SDValue SplatVal, unsigned NumVecElts) {
10556 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10557 unsigned OrigAlignment = St.getAlignment();
10558 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10560 // Create scalar stores. This is at least as good as the code sequence for a
10561 // split unaligned store which is a dup.s, ext.b, and two stores.
10562 // Most of the time the three stores should be replaced by store pair
10563 // instructions (stp).
10564 SDLoc DL(&St);
10565 SDValue BasePtr = St.getBasePtr();
10566 uint64_t BaseOffset = 0;
10568 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10569 SDValue NewST1 =
10570 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10571 OrigAlignment, St.getMemOperand()->getFlags());
10573 // As this in ISel, we will not merge this add which may degrade results.
10574 if (BasePtr->getOpcode() == ISD::ADD &&
10575 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10576 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10577 BasePtr = BasePtr->getOperand(0);
10580 unsigned Offset = EltOffset;
10581 while (--NumVecElts) {
10582 unsigned Alignment = MinAlign(OrigAlignment, Offset);
10583 SDValue OffsetPtr =
10584 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10585 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10586 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10587 PtrInfo.getWithOffset(Offset), Alignment,
10588 St.getMemOperand()->getFlags());
10589 Offset += EltOffset;
10591 return NewST1;
10594 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10595 /// load store optimizer pass will merge them to store pair stores. This should
10596 /// be better than a movi to create the vector zero followed by a vector store
10597 /// if the zero constant is not re-used, since one instructions and one register
10598 /// live range will be removed.
10600 /// For example, the final generated code should be:
10602 /// stp xzr, xzr, [x0]
10604 /// instead of:
10606 /// movi v0.2d, #0
10607 /// str q0, [x0]
10609 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10610 SDValue StVal = St.getValue();
10611 EVT VT = StVal.getValueType();
10613 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10614 // 2, 3 or 4 i32 elements.
10615 int NumVecElts = VT.getVectorNumElements();
10616 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10617 VT.getVectorElementType().getSizeInBits() == 64) ||
10618 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10619 VT.getVectorElementType().getSizeInBits() == 32)))
10620 return SDValue();
10622 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10623 return SDValue();
10625 // If the zero constant has more than one use then the vector store could be
10626 // better since the constant mov will be amortized and stp q instructions
10627 // should be able to be formed.
10628 if (!StVal.hasOneUse())
10629 return SDValue();
10631 // If the store is truncating then it's going down to i16 or smaller, which
10632 // means it can be implemented in a single store anyway.
10633 if (St.isTruncatingStore())
10634 return SDValue();
10636 // If the immediate offset of the address operand is too large for the stp
10637 // instruction, then bail out.
10638 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10639 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10640 if (Offset < -512 || Offset > 504)
10641 return SDValue();
10644 for (int I = 0; I < NumVecElts; ++I) {
10645 SDValue EltVal = StVal.getOperand(I);
10646 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10647 return SDValue();
10650 // Use a CopyFromReg WZR/XZR here to prevent
10651 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10652 SDLoc DL(&St);
10653 unsigned ZeroReg;
10654 EVT ZeroVT;
10655 if (VT.getVectorElementType().getSizeInBits() == 32) {
10656 ZeroReg = AArch64::WZR;
10657 ZeroVT = MVT::i32;
10658 } else {
10659 ZeroReg = AArch64::XZR;
10660 ZeroVT = MVT::i64;
10662 SDValue SplatVal =
10663 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10664 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10667 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10668 /// value. The load store optimizer pass will merge them to store pair stores.
10669 /// This has better performance than a splat of the scalar followed by a split
10670 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10671 /// followed by an ext.b and two stores.
10672 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10673 SDValue StVal = St.getValue();
10674 EVT VT = StVal.getValueType();
10676 // Don't replace floating point stores, they possibly won't be transformed to
10677 // stp because of the store pair suppress pass.
10678 if (VT.isFloatingPoint())
10679 return SDValue();
10681 // We can express a splat as store pair(s) for 2 or 4 elements.
10682 unsigned NumVecElts = VT.getVectorNumElements();
10683 if (NumVecElts != 4 && NumVecElts != 2)
10684 return SDValue();
10686 // If the store is truncating then it's going down to i16 or smaller, which
10687 // means it can be implemented in a single store anyway.
10688 if (St.isTruncatingStore())
10689 return SDValue();
10691 // Check that this is a splat.
10692 // Make sure that each of the relevant vector element locations are inserted
10693 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10694 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10695 SDValue SplatVal;
10696 for (unsigned I = 0; I < NumVecElts; ++I) {
10697 // Check for insert vector elements.
10698 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10699 return SDValue();
10701 // Check that same value is inserted at each vector element.
10702 if (I == 0)
10703 SplatVal = StVal.getOperand(1);
10704 else if (StVal.getOperand(1) != SplatVal)
10705 return SDValue();
10707 // Check insert element index.
10708 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10709 if (!CIndex)
10710 return SDValue();
10711 uint64_t IndexVal = CIndex->getZExtValue();
10712 if (IndexVal >= NumVecElts)
10713 return SDValue();
10714 IndexNotInserted.reset(IndexVal);
10716 StVal = StVal.getOperand(0);
10718 // Check that all vector element locations were inserted to.
10719 if (IndexNotInserted.any())
10720 return SDValue();
10722 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10725 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10726 SelectionDAG &DAG,
10727 const AArch64Subtarget *Subtarget) {
10729 StoreSDNode *S = cast<StoreSDNode>(N);
10730 if (S->isVolatile() || S->isIndexed())
10731 return SDValue();
10733 SDValue StVal = S->getValue();
10734 EVT VT = StVal.getValueType();
10735 if (!VT.isVector())
10736 return SDValue();
10738 // If we get a splat of zeros, convert this vector store to a store of
10739 // scalars. They will be merged into store pairs of xzr thereby removing one
10740 // instruction and one register.
10741 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10742 return ReplacedZeroSplat;
10744 // FIXME: The logic for deciding if an unaligned store should be split should
10745 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10746 // a call to that function here.
10748 if (!Subtarget->isMisaligned128StoreSlow())
10749 return SDValue();
10751 // Don't split at -Oz.
10752 if (DAG.getMachineFunction().getFunction().hasMinSize())
10753 return SDValue();
10755 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10756 // those up regresses performance on micro-benchmarks and olden/bh.
10757 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10758 return SDValue();
10760 // Split unaligned 16B stores. They are terrible for performance.
10761 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10762 // extensions can use this to mark that it does not want splitting to happen
10763 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10764 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10765 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10766 S->getAlignment() <= 2)
10767 return SDValue();
10769 // If we get a splat of a scalar convert this vector store to a store of
10770 // scalars. They will be merged into store pairs thereby removing two
10771 // instructions.
10772 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10773 return ReplacedSplat;
10775 SDLoc DL(S);
10777 // Split VT into two.
10778 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10779 unsigned NumElts = HalfVT.getVectorNumElements();
10780 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10781 DAG.getConstant(0, DL, MVT::i64));
10782 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10783 DAG.getConstant(NumElts, DL, MVT::i64));
10784 SDValue BasePtr = S->getBasePtr();
10785 SDValue NewST1 =
10786 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10787 S->getAlignment(), S->getMemOperand()->getFlags());
10788 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10789 DAG.getConstant(8, DL, MVT::i64));
10790 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10791 S->getPointerInfo(), S->getAlignment(),
10792 S->getMemOperand()->getFlags());
10795 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10796 /// post-increment LD1R.
10797 static SDValue performPostLD1Combine(SDNode *N,
10798 TargetLowering::DAGCombinerInfo &DCI,
10799 bool IsLaneOp) {
10800 if (DCI.isBeforeLegalizeOps())
10801 return SDValue();
10803 SelectionDAG &DAG = DCI.DAG;
10804 EVT VT = N->getValueType(0);
10806 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10807 SDNode *LD = N->getOperand(LoadIdx).getNode();
10808 // If it is not LOAD, can not do such combine.
10809 if (LD->getOpcode() != ISD::LOAD)
10810 return SDValue();
10812 // The vector lane must be a constant in the LD1LANE opcode.
10813 SDValue Lane;
10814 if (IsLaneOp) {
10815 Lane = N->getOperand(2);
10816 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10817 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10818 return SDValue();
10821 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10822 EVT MemVT = LoadSDN->getMemoryVT();
10823 // Check if memory operand is the same type as the vector element.
10824 if (MemVT != VT.getVectorElementType())
10825 return SDValue();
10827 // Check if there are other uses. If so, do not combine as it will introduce
10828 // an extra load.
10829 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10830 ++UI) {
10831 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10832 continue;
10833 if (*UI != N)
10834 return SDValue();
10837 SDValue Addr = LD->getOperand(1);
10838 SDValue Vector = N->getOperand(0);
10839 // Search for a use of the address operand that is an increment.
10840 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10841 Addr.getNode()->use_end(); UI != UE; ++UI) {
10842 SDNode *User = *UI;
10843 if (User->getOpcode() != ISD::ADD
10844 || UI.getUse().getResNo() != Addr.getResNo())
10845 continue;
10847 // If the increment is a constant, it must match the memory ref size.
10848 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10849 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10850 uint32_t IncVal = CInc->getZExtValue();
10851 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10852 if (IncVal != NumBytes)
10853 continue;
10854 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10857 // To avoid cycle construction make sure that neither the load nor the add
10858 // are predecessors to each other or the Vector.
10859 SmallPtrSet<const SDNode *, 32> Visited;
10860 SmallVector<const SDNode *, 16> Worklist;
10861 Visited.insert(Addr.getNode());
10862 Worklist.push_back(User);
10863 Worklist.push_back(LD);
10864 Worklist.push_back(Vector.getNode());
10865 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10866 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10867 continue;
10869 SmallVector<SDValue, 8> Ops;
10870 Ops.push_back(LD->getOperand(0)); // Chain
10871 if (IsLaneOp) {
10872 Ops.push_back(Vector); // The vector to be inserted
10873 Ops.push_back(Lane); // The lane to be inserted in the vector
10875 Ops.push_back(Addr);
10876 Ops.push_back(Inc);
10878 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10879 SDVTList SDTys = DAG.getVTList(Tys);
10880 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10881 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10882 MemVT,
10883 LoadSDN->getMemOperand());
10885 // Update the uses.
10886 SDValue NewResults[] = {
10887 SDValue(LD, 0), // The result of load
10888 SDValue(UpdN.getNode(), 2) // Chain
10890 DCI.CombineTo(LD, NewResults);
10891 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10892 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10894 break;
10896 return SDValue();
10899 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10900 /// address translation.
10901 static bool performTBISimplification(SDValue Addr,
10902 TargetLowering::DAGCombinerInfo &DCI,
10903 SelectionDAG &DAG) {
10904 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10905 KnownBits Known;
10906 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10907 !DCI.isBeforeLegalizeOps());
10908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10909 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10910 DCI.CommitTargetLoweringOpt(TLO);
10911 return true;
10913 return false;
10916 static SDValue performSTORECombine(SDNode *N,
10917 TargetLowering::DAGCombinerInfo &DCI,
10918 SelectionDAG &DAG,
10919 const AArch64Subtarget *Subtarget) {
10920 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10921 return Split;
10923 if (Subtarget->supportsAddressTopByteIgnored() &&
10924 performTBISimplification(N->getOperand(2), DCI, DAG))
10925 return SDValue(N, 0);
10927 return SDValue();
10931 /// Target-specific DAG combine function for NEON load/store intrinsics
10932 /// to merge base address updates.
10933 static SDValue performNEONPostLDSTCombine(SDNode *N,
10934 TargetLowering::DAGCombinerInfo &DCI,
10935 SelectionDAG &DAG) {
10936 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10937 return SDValue();
10939 unsigned AddrOpIdx = N->getNumOperands() - 1;
10940 SDValue Addr = N->getOperand(AddrOpIdx);
10942 // Search for a use of the address operand that is an increment.
10943 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10944 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10945 SDNode *User = *UI;
10946 if (User->getOpcode() != ISD::ADD ||
10947 UI.getUse().getResNo() != Addr.getResNo())
10948 continue;
10950 // Check that the add is independent of the load/store. Otherwise, folding
10951 // it would create a cycle.
10952 SmallPtrSet<const SDNode *, 32> Visited;
10953 SmallVector<const SDNode *, 16> Worklist;
10954 Visited.insert(Addr.getNode());
10955 Worklist.push_back(N);
10956 Worklist.push_back(User);
10957 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10958 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10959 continue;
10961 // Find the new opcode for the updating load/store.
10962 bool IsStore = false;
10963 bool IsLaneOp = false;
10964 bool IsDupOp = false;
10965 unsigned NewOpc = 0;
10966 unsigned NumVecs = 0;
10967 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10968 switch (IntNo) {
10969 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10970 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10971 NumVecs = 2; break;
10972 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10973 NumVecs = 3; break;
10974 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10975 NumVecs = 4; break;
10976 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10977 NumVecs = 2; IsStore = true; break;
10978 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10979 NumVecs = 3; IsStore = true; break;
10980 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10981 NumVecs = 4; IsStore = true; break;
10982 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10983 NumVecs = 2; break;
10984 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10985 NumVecs = 3; break;
10986 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10987 NumVecs = 4; break;
10988 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10989 NumVecs = 2; IsStore = true; break;
10990 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10991 NumVecs = 3; IsStore = true; break;
10992 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10993 NumVecs = 4; IsStore = true; break;
10994 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10995 NumVecs = 2; IsDupOp = true; break;
10996 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10997 NumVecs = 3; IsDupOp = true; break;
10998 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10999 NumVecs = 4; IsDupOp = true; break;
11000 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
11001 NumVecs = 2; IsLaneOp = true; break;
11002 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
11003 NumVecs = 3; IsLaneOp = true; break;
11004 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
11005 NumVecs = 4; IsLaneOp = true; break;
11006 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
11007 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
11008 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
11009 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
11010 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
11011 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
11014 EVT VecTy;
11015 if (IsStore)
11016 VecTy = N->getOperand(2).getValueType();
11017 else
11018 VecTy = N->getValueType(0);
11020 // If the increment is a constant, it must match the memory ref size.
11021 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11022 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
11023 uint32_t IncVal = CInc->getZExtValue();
11024 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11025 if (IsLaneOp || IsDupOp)
11026 NumBytes /= VecTy.getVectorNumElements();
11027 if (IncVal != NumBytes)
11028 continue;
11029 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
11031 SmallVector<SDValue, 8> Ops;
11032 Ops.push_back(N->getOperand(0)); // Incoming chain
11033 // Load lane and store have vector list as input.
11034 if (IsLaneOp || IsStore)
11035 for (unsigned i = 2; i < AddrOpIdx; ++i)
11036 Ops.push_back(N->getOperand(i));
11037 Ops.push_back(Addr); // Base register
11038 Ops.push_back(Inc);
11040 // Return Types.
11041 EVT Tys[6];
11042 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
11043 unsigned n;
11044 for (n = 0; n < NumResultVecs; ++n)
11045 Tys[n] = VecTy;
11046 Tys[n++] = MVT::i64; // Type of write back register
11047 Tys[n] = MVT::Other; // Type of the chain
11048 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
11050 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
11051 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
11052 MemInt->getMemoryVT(),
11053 MemInt->getMemOperand());
11055 // Update the uses.
11056 std::vector<SDValue> NewResults;
11057 for (unsigned i = 0; i < NumResultVecs; ++i) {
11058 NewResults.push_back(SDValue(UpdN.getNode(), i));
11060 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
11061 DCI.CombineTo(N, NewResults);
11062 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11064 break;
11066 return SDValue();
11069 // Checks to see if the value is the prescribed width and returns information
11070 // about its extension mode.
11071 static
11072 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
11073 ExtType = ISD::NON_EXTLOAD;
11074 switch(V.getNode()->getOpcode()) {
11075 default:
11076 return false;
11077 case ISD::LOAD: {
11078 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
11079 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
11080 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
11081 ExtType = LoadNode->getExtensionType();
11082 return true;
11084 return false;
11086 case ISD::AssertSext: {
11087 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11088 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11089 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11090 ExtType = ISD::SEXTLOAD;
11091 return true;
11093 return false;
11095 case ISD::AssertZext: {
11096 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
11097 if ((TypeNode->getVT() == MVT::i8 && width == 8)
11098 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
11099 ExtType = ISD::ZEXTLOAD;
11100 return true;
11102 return false;
11104 case ISD::Constant:
11105 case ISD::TargetConstant: {
11106 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
11107 1LL << (width - 1);
11111 return true;
11114 // This function does a whole lot of voodoo to determine if the tests are
11115 // equivalent without and with a mask. Essentially what happens is that given a
11116 // DAG resembling:
11118 // +-------------+ +-------------+ +-------------+ +-------------+
11119 // | Input | | AddConstant | | CompConstant| | CC |
11120 // +-------------+ +-------------+ +-------------+ +-------------+
11121 // | | | |
11122 // V V | +----------+
11123 // +-------------+ +----+ | |
11124 // | ADD | |0xff| | |
11125 // +-------------+ +----+ | |
11126 // | | | |
11127 // V V | |
11128 // +-------------+ | |
11129 // | AND | | |
11130 // +-------------+ | |
11131 // | | |
11132 // +-----+ | |
11133 // | | |
11134 // V V V
11135 // +-------------+
11136 // | CMP |
11137 // +-------------+
11139 // The AND node may be safely removed for some combinations of inputs. In
11140 // particular we need to take into account the extension type of the Input,
11141 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
11142 // width of the input (this can work for any width inputs, the above graph is
11143 // specific to 8 bits.
11145 // The specific equations were worked out by generating output tables for each
11146 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
11147 // problem was simplified by working with 4 bit inputs, which means we only
11148 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
11149 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
11150 // patterns present in both extensions (0,7). For every distinct set of
11151 // AddConstant and CompConstants bit patterns we can consider the masked and
11152 // unmasked versions to be equivalent if the result of this function is true for
11153 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11155 // sub w8, w0, w1
11156 // and w10, w8, #0x0f
11157 // cmp w8, w2
11158 // cset w9, AArch64CC
11159 // cmp w10, w2
11160 // cset w11, AArch64CC
11161 // cmp w9, w11
11162 // cset w0, eq
11163 // ret
11165 // Since the above function shows when the outputs are equivalent it defines
11166 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11167 // would be expensive to run during compiles. The equations below were written
11168 // in a test harness that confirmed they gave equivalent outputs to the above
11169 // for all inputs function, so they can be used determine if the removal is
11170 // legal instead.
11172 // isEquivalentMaskless() is the code for testing if the AND can be removed
11173 // factored out of the DAG recognition as the DAG can take several forms.
11175 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11176 ISD::LoadExtType ExtType, int AddConstant,
11177 int CompConstant) {
11178 // By being careful about our equations and only writing the in term
11179 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11180 // make them generally applicable to all bit widths.
11181 int MaxUInt = (1 << width);
11183 // For the purposes of these comparisons sign extending the type is
11184 // equivalent to zero extending the add and displacing it by half the integer
11185 // width. Provided we are careful and make sure our equations are valid over
11186 // the whole range we can just adjust the input and avoid writing equations
11187 // for sign extended inputs.
11188 if (ExtType == ISD::SEXTLOAD)
11189 AddConstant -= (1 << (width-1));
11191 switch(CC) {
11192 case AArch64CC::LE:
11193 case AArch64CC::GT:
11194 if ((AddConstant == 0) ||
11195 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11196 (AddConstant >= 0 && CompConstant < 0) ||
11197 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11198 return true;
11199 break;
11200 case AArch64CC::LT:
11201 case AArch64CC::GE:
11202 if ((AddConstant == 0) ||
11203 (AddConstant >= 0 && CompConstant <= 0) ||
11204 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11205 return true;
11206 break;
11207 case AArch64CC::HI:
11208 case AArch64CC::LS:
11209 if ((AddConstant >= 0 && CompConstant < 0) ||
11210 (AddConstant <= 0 && CompConstant >= -1 &&
11211 CompConstant < AddConstant + MaxUInt))
11212 return true;
11213 break;
11214 case AArch64CC::PL:
11215 case AArch64CC::MI:
11216 if ((AddConstant == 0) ||
11217 (AddConstant > 0 && CompConstant <= 0) ||
11218 (AddConstant < 0 && CompConstant <= AddConstant))
11219 return true;
11220 break;
11221 case AArch64CC::LO:
11222 case AArch64CC::HS:
11223 if ((AddConstant >= 0 && CompConstant <= 0) ||
11224 (AddConstant <= 0 && CompConstant >= 0 &&
11225 CompConstant <= AddConstant + MaxUInt))
11226 return true;
11227 break;
11228 case AArch64CC::EQ:
11229 case AArch64CC::NE:
11230 if ((AddConstant > 0 && CompConstant < 0) ||
11231 (AddConstant < 0 && CompConstant >= 0 &&
11232 CompConstant < AddConstant + MaxUInt) ||
11233 (AddConstant >= 0 && CompConstant >= 0 &&
11234 CompConstant >= AddConstant) ||
11235 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11236 return true;
11237 break;
11238 case AArch64CC::VS:
11239 case AArch64CC::VC:
11240 case AArch64CC::AL:
11241 case AArch64CC::NV:
11242 return true;
11243 case AArch64CC::Invalid:
11244 break;
11247 return false;
11250 static
11251 SDValue performCONDCombine(SDNode *N,
11252 TargetLowering::DAGCombinerInfo &DCI,
11253 SelectionDAG &DAG, unsigned CCIndex,
11254 unsigned CmpIndex) {
11255 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11256 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11257 unsigned CondOpcode = SubsNode->getOpcode();
11259 if (CondOpcode != AArch64ISD::SUBS)
11260 return SDValue();
11262 // There is a SUBS feeding this condition. Is it fed by a mask we can
11263 // use?
11265 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11266 unsigned MaskBits = 0;
11268 if (AndNode->getOpcode() != ISD::AND)
11269 return SDValue();
11271 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11272 uint32_t CNV = CN->getZExtValue();
11273 if (CNV == 255)
11274 MaskBits = 8;
11275 else if (CNV == 65535)
11276 MaskBits = 16;
11279 if (!MaskBits)
11280 return SDValue();
11282 SDValue AddValue = AndNode->getOperand(0);
11284 if (AddValue.getOpcode() != ISD::ADD)
11285 return SDValue();
11287 // The basic dag structure is correct, grab the inputs and validate them.
11289 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11290 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11291 SDValue SubsInputValue = SubsNode->getOperand(1);
11293 // The mask is present and the provenance of all the values is a smaller type,
11294 // lets see if the mask is superfluous.
11296 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11297 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11298 return SDValue();
11300 ISD::LoadExtType ExtType;
11302 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11303 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11304 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11305 return SDValue();
11307 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11308 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11309 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11310 return SDValue();
11312 // The AND is not necessary, remove it.
11314 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11315 SubsNode->getValueType(1));
11316 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11318 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11319 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11321 return SDValue(N, 0);
11324 // Optimize compare with zero and branch.
11325 static SDValue performBRCONDCombine(SDNode *N,
11326 TargetLowering::DAGCombinerInfo &DCI,
11327 SelectionDAG &DAG) {
11328 MachineFunction &MF = DAG.getMachineFunction();
11329 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11330 // will not be produced, as they are conditional branch instructions that do
11331 // not set flags.
11332 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11333 return SDValue();
11335 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11336 N = NV.getNode();
11337 SDValue Chain = N->getOperand(0);
11338 SDValue Dest = N->getOperand(1);
11339 SDValue CCVal = N->getOperand(2);
11340 SDValue Cmp = N->getOperand(3);
11342 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11343 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11344 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11345 return SDValue();
11347 unsigned CmpOpc = Cmp.getOpcode();
11348 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11349 return SDValue();
11351 // Only attempt folding if there is only one use of the flag and no use of the
11352 // value.
11353 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11354 return SDValue();
11356 SDValue LHS = Cmp.getOperand(0);
11357 SDValue RHS = Cmp.getOperand(1);
11359 assert(LHS.getValueType() == RHS.getValueType() &&
11360 "Expected the value type to be the same for both operands!");
11361 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11362 return SDValue();
11364 if (isNullConstant(LHS))
11365 std::swap(LHS, RHS);
11367 if (!isNullConstant(RHS))
11368 return SDValue();
11370 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11371 LHS.getOpcode() == ISD::SRL)
11372 return SDValue();
11374 // Fold the compare into the branch instruction.
11375 SDValue BR;
11376 if (CC == AArch64CC::EQ)
11377 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11378 else
11379 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11381 // Do not add new nodes to DAG combiner worklist.
11382 DCI.CombineTo(N, BR, false);
11384 return SDValue();
11387 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11388 // as well as whether the test should be inverted. This code is required to
11389 // catch these cases (as opposed to standard dag combines) because
11390 // AArch64ISD::TBZ is matched during legalization.
11391 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11392 SelectionDAG &DAG) {
11394 if (!Op->hasOneUse())
11395 return Op;
11397 // We don't handle undef/constant-fold cases below, as they should have
11398 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11399 // etc.)
11401 // (tbz (trunc x), b) -> (tbz x, b)
11402 // This case is just here to enable more of the below cases to be caught.
11403 if (Op->getOpcode() == ISD::TRUNCATE &&
11404 Bit < Op->getValueType(0).getSizeInBits()) {
11405 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11408 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11409 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11410 Bit < Op->getOperand(0).getValueSizeInBits()) {
11411 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11414 if (Op->getNumOperands() != 2)
11415 return Op;
11417 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11418 if (!C)
11419 return Op;
11421 switch (Op->getOpcode()) {
11422 default:
11423 return Op;
11425 // (tbz (and x, m), b) -> (tbz x, b)
11426 case ISD::AND:
11427 if ((C->getZExtValue() >> Bit) & 1)
11428 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11429 return Op;
11431 // (tbz (shl x, c), b) -> (tbz x, b-c)
11432 case ISD::SHL:
11433 if (C->getZExtValue() <= Bit &&
11434 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11435 Bit = Bit - C->getZExtValue();
11436 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11438 return Op;
11440 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11441 case ISD::SRA:
11442 Bit = Bit + C->getZExtValue();
11443 if (Bit >= Op->getValueType(0).getSizeInBits())
11444 Bit = Op->getValueType(0).getSizeInBits() - 1;
11445 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11447 // (tbz (srl x, c), b) -> (tbz x, b+c)
11448 case ISD::SRL:
11449 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11450 Bit = Bit + C->getZExtValue();
11451 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11453 return Op;
11455 // (tbz (xor x, -1), b) -> (tbnz x, b)
11456 case ISD::XOR:
11457 if ((C->getZExtValue() >> Bit) & 1)
11458 Invert = !Invert;
11459 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11463 // Optimize test single bit zero/non-zero and branch.
11464 static SDValue performTBZCombine(SDNode *N,
11465 TargetLowering::DAGCombinerInfo &DCI,
11466 SelectionDAG &DAG) {
11467 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11468 bool Invert = false;
11469 SDValue TestSrc = N->getOperand(1);
11470 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11472 if (TestSrc == NewTestSrc)
11473 return SDValue();
11475 unsigned NewOpc = N->getOpcode();
11476 if (Invert) {
11477 if (NewOpc == AArch64ISD::TBZ)
11478 NewOpc = AArch64ISD::TBNZ;
11479 else {
11480 assert(NewOpc == AArch64ISD::TBNZ);
11481 NewOpc = AArch64ISD::TBZ;
11485 SDLoc DL(N);
11486 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11487 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11490 // vselect (v1i1 setcc) ->
11491 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
11492 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11493 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11494 // such VSELECT.
11495 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11496 SDValue N0 = N->getOperand(0);
11497 EVT CCVT = N0.getValueType();
11499 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11500 CCVT.getVectorElementType() != MVT::i1)
11501 return SDValue();
11503 EVT ResVT = N->getValueType(0);
11504 EVT CmpVT = N0.getOperand(0).getValueType();
11505 // Only combine when the result type is of the same size as the compared
11506 // operands.
11507 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11508 return SDValue();
11510 SDValue IfTrue = N->getOperand(1);
11511 SDValue IfFalse = N->getOperand(2);
11512 SDValue SetCC =
11513 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11514 N0.getOperand(0), N0.getOperand(1),
11515 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11516 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11517 IfTrue, IfFalse);
11520 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11521 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11522 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11523 /// with a vector one followed by a DUP shuffle on the result.
11524 static SDValue performSelectCombine(SDNode *N,
11525 TargetLowering::DAGCombinerInfo &DCI) {
11526 SelectionDAG &DAG = DCI.DAG;
11527 SDValue N0 = N->getOperand(0);
11528 EVT ResVT = N->getValueType(0);
11530 if (N0.getOpcode() != ISD::SETCC)
11531 return SDValue();
11533 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11534 // scalar SetCCResultType. We also don't expect vectors, because we assume
11535 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11536 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11537 "Scalar-SETCC feeding SELECT has unexpected result type!");
11539 // If NumMaskElts == 0, the comparison is larger than select result. The
11540 // largest real NEON comparison is 64-bits per lane, which means the result is
11541 // at most 32-bits and an illegal vector. Just bail out for now.
11542 EVT SrcVT = N0.getOperand(0).getValueType();
11544 // Don't try to do this optimization when the setcc itself has i1 operands.
11545 // There are no legal vectors of i1, so this would be pointless.
11546 if (SrcVT == MVT::i1)
11547 return SDValue();
11549 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11550 if (!ResVT.isVector() || NumMaskElts == 0)
11551 return SDValue();
11553 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11554 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11556 // Also bail out if the vector CCVT isn't the same size as ResVT.
11557 // This can happen if the SETCC operand size doesn't divide the ResVT size
11558 // (e.g., f64 vs v3f32).
11559 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11560 return SDValue();
11562 // Make sure we didn't create illegal types, if we're not supposed to.
11563 assert(DCI.isBeforeLegalize() ||
11564 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11566 // First perform a vector comparison, where lane 0 is the one we're interested
11567 // in.
11568 SDLoc DL(N0);
11569 SDValue LHS =
11570 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11571 SDValue RHS =
11572 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11573 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11575 // Now duplicate the comparison mask we want across all other lanes.
11576 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11577 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11578 Mask = DAG.getNode(ISD::BITCAST, DL,
11579 ResVT.changeVectorElementTypeToInteger(), Mask);
11581 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11584 /// Get rid of unnecessary NVCASTs (that don't change the type).
11585 static SDValue performNVCASTCombine(SDNode *N) {
11586 if (N->getValueType(0) == N->getOperand(0).getValueType())
11587 return N->getOperand(0);
11589 return SDValue();
11592 // If all users of the globaladdr are of the form (globaladdr + constant), find
11593 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11594 // globaladdr as (globaladdr + constant) - constant.
11595 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11596 const AArch64Subtarget *Subtarget,
11597 const TargetMachine &TM) {
11598 auto *GN = cast<GlobalAddressSDNode>(N);
11599 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11600 AArch64II::MO_NO_FLAG)
11601 return SDValue();
11603 uint64_t MinOffset = -1ull;
11604 for (SDNode *N : GN->uses()) {
11605 if (N->getOpcode() != ISD::ADD)
11606 return SDValue();
11607 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11608 if (!C)
11609 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11610 if (!C)
11611 return SDValue();
11612 MinOffset = std::min(MinOffset, C->getZExtValue());
11614 uint64_t Offset = MinOffset + GN->getOffset();
11616 // Require that the new offset is larger than the existing one. Otherwise, we
11617 // can end up oscillating between two possible DAGs, for example,
11618 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11619 if (Offset <= uint64_t(GN->getOffset()))
11620 return SDValue();
11622 // Check whether folding this offset is legal. It must not go out of bounds of
11623 // the referenced object to avoid violating the code model, and must be
11624 // smaller than 2^21 because this is the largest offset expressible in all
11625 // object formats.
11627 // This check also prevents us from folding negative offsets, which will end
11628 // up being treated in the same way as large positive ones. They could also
11629 // cause code model violations, and aren't really common enough to matter.
11630 if (Offset >= (1 << 21))
11631 return SDValue();
11633 const GlobalValue *GV = GN->getGlobal();
11634 Type *T = GV->getValueType();
11635 if (!T->isSized() ||
11636 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11637 return SDValue();
11639 SDLoc DL(GN);
11640 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11641 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11642 DAG.getConstant(MinOffset, DL, MVT::i64));
11645 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11646 DAGCombinerInfo &DCI) const {
11647 SelectionDAG &DAG = DCI.DAG;
11648 switch (N->getOpcode()) {
11649 default:
11650 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11651 break;
11652 case ISD::ADD:
11653 case ISD::SUB:
11654 return performAddSubLongCombine(N, DCI, DAG);
11655 case ISD::XOR:
11656 return performXorCombine(N, DAG, DCI, Subtarget);
11657 case ISD::MUL:
11658 return performMulCombine(N, DAG, DCI, Subtarget);
11659 case ISD::SINT_TO_FP:
11660 case ISD::UINT_TO_FP:
11661 return performIntToFpCombine(N, DAG, Subtarget);
11662 case ISD::FP_TO_SINT:
11663 case ISD::FP_TO_UINT:
11664 return performFpToIntCombine(N, DAG, DCI, Subtarget);
11665 case ISD::FDIV:
11666 return performFDivCombine(N, DAG, DCI, Subtarget);
11667 case ISD::OR:
11668 return performORCombine(N, DCI, Subtarget);
11669 case ISD::AND:
11670 return performANDCombine(N, DCI);
11671 case ISD::SRL:
11672 return performSRLCombine(N, DCI);
11673 case ISD::INTRINSIC_WO_CHAIN:
11674 return performIntrinsicCombine(N, DCI, Subtarget);
11675 case ISD::ANY_EXTEND:
11676 case ISD::ZERO_EXTEND:
11677 case ISD::SIGN_EXTEND:
11678 return performExtendCombine(N, DCI, DAG);
11679 case ISD::BITCAST:
11680 return performBitcastCombine(N, DCI, DAG);
11681 case ISD::CONCAT_VECTORS:
11682 return performConcatVectorsCombine(N, DCI, DAG);
11683 case ISD::SELECT:
11684 return performSelectCombine(N, DCI);
11685 case ISD::VSELECT:
11686 return performVSelectCombine(N, DCI.DAG);
11687 case ISD::LOAD:
11688 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11689 return SDValue(N, 0);
11690 break;
11691 case ISD::STORE:
11692 return performSTORECombine(N, DCI, DAG, Subtarget);
11693 case AArch64ISD::BRCOND:
11694 return performBRCONDCombine(N, DCI, DAG);
11695 case AArch64ISD::TBNZ:
11696 case AArch64ISD::TBZ:
11697 return performTBZCombine(N, DCI, DAG);
11698 case AArch64ISD::CSEL:
11699 return performCONDCombine(N, DCI, DAG, 2, 3);
11700 case AArch64ISD::DUP:
11701 return performPostLD1Combine(N, DCI, false);
11702 case AArch64ISD::NVCAST:
11703 return performNVCASTCombine(N);
11704 case ISD::INSERT_VECTOR_ELT:
11705 return performPostLD1Combine(N, DCI, true);
11706 case ISD::INTRINSIC_VOID:
11707 case ISD::INTRINSIC_W_CHAIN:
11708 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11709 case Intrinsic::aarch64_neon_ld2:
11710 case Intrinsic::aarch64_neon_ld3:
11711 case Intrinsic::aarch64_neon_ld4:
11712 case Intrinsic::aarch64_neon_ld1x2:
11713 case Intrinsic::aarch64_neon_ld1x3:
11714 case Intrinsic::aarch64_neon_ld1x4:
11715 case Intrinsic::aarch64_neon_ld2lane:
11716 case Intrinsic::aarch64_neon_ld3lane:
11717 case Intrinsic::aarch64_neon_ld4lane:
11718 case Intrinsic::aarch64_neon_ld2r:
11719 case Intrinsic::aarch64_neon_ld3r:
11720 case Intrinsic::aarch64_neon_ld4r:
11721 case Intrinsic::aarch64_neon_st2:
11722 case Intrinsic::aarch64_neon_st3:
11723 case Intrinsic::aarch64_neon_st4:
11724 case Intrinsic::aarch64_neon_st1x2:
11725 case Intrinsic::aarch64_neon_st1x3:
11726 case Intrinsic::aarch64_neon_st1x4:
11727 case Intrinsic::aarch64_neon_st2lane:
11728 case Intrinsic::aarch64_neon_st3lane:
11729 case Intrinsic::aarch64_neon_st4lane:
11730 return performNEONPostLDSTCombine(N, DCI, DAG);
11731 default:
11732 break;
11734 break;
11735 case ISD::GlobalAddress:
11736 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11738 return SDValue();
11741 // Check if the return value is used as only a return value, as otherwise
11742 // we can't perform a tail-call. In particular, we need to check for
11743 // target ISD nodes that are returns and any other "odd" constructs
11744 // that the generic analysis code won't necessarily catch.
11745 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11746 SDValue &Chain) const {
11747 if (N->getNumValues() != 1)
11748 return false;
11749 if (!N->hasNUsesOfValue(1, 0))
11750 return false;
11752 SDValue TCChain = Chain;
11753 SDNode *Copy = *N->use_begin();
11754 if (Copy->getOpcode() == ISD::CopyToReg) {
11755 // If the copy has a glue operand, we conservatively assume it isn't safe to
11756 // perform a tail call.
11757 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11758 MVT::Glue)
11759 return false;
11760 TCChain = Copy->getOperand(0);
11761 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11762 return false;
11764 bool HasRet = false;
11765 for (SDNode *Node : Copy->uses()) {
11766 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11767 return false;
11768 HasRet = true;
11771 if (!HasRet)
11772 return false;
11774 Chain = TCChain;
11775 return true;
11778 // Return whether the an instruction can potentially be optimized to a tail
11779 // call. This will cause the optimizers to attempt to move, or duplicate,
11780 // return instructions to help enable tail call optimizations for this
11781 // instruction.
11782 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11783 return CI->isTailCall();
11786 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11787 SDValue &Offset,
11788 ISD::MemIndexedMode &AM,
11789 bool &IsInc,
11790 SelectionDAG &DAG) const {
11791 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11792 return false;
11794 Base = Op->getOperand(0);
11795 // All of the indexed addressing mode instructions take a signed
11796 // 9 bit immediate offset.
11797 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11798 int64_t RHSC = RHS->getSExtValue();
11799 if (Op->getOpcode() == ISD::SUB)
11800 RHSC = -(uint64_t)RHSC;
11801 if (!isInt<9>(RHSC))
11802 return false;
11803 IsInc = (Op->getOpcode() == ISD::ADD);
11804 Offset = Op->getOperand(1);
11805 return true;
11807 return false;
11810 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11811 SDValue &Offset,
11812 ISD::MemIndexedMode &AM,
11813 SelectionDAG &DAG) const {
11814 EVT VT;
11815 SDValue Ptr;
11816 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11817 VT = LD->getMemoryVT();
11818 Ptr = LD->getBasePtr();
11819 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11820 VT = ST->getMemoryVT();
11821 Ptr = ST->getBasePtr();
11822 } else
11823 return false;
11825 bool IsInc;
11826 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11827 return false;
11828 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11829 return true;
11832 bool AArch64TargetLowering::getPostIndexedAddressParts(
11833 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11834 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11835 EVT VT;
11836 SDValue Ptr;
11837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11838 VT = LD->getMemoryVT();
11839 Ptr = LD->getBasePtr();
11840 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11841 VT = ST->getMemoryVT();
11842 Ptr = ST->getBasePtr();
11843 } else
11844 return false;
11846 bool IsInc;
11847 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11848 return false;
11849 // Post-indexing updates the base, so it's not a valid transform
11850 // if that's not the same as the load's pointer.
11851 if (Ptr != Base)
11852 return false;
11853 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11854 return true;
11857 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11858 SelectionDAG &DAG) {
11859 SDLoc DL(N);
11860 SDValue Op = N->getOperand(0);
11862 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11863 return;
11865 Op = SDValue(
11866 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11867 DAG.getUNDEF(MVT::i32), Op,
11868 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11870 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11871 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11874 static void ReplaceReductionResults(SDNode *N,
11875 SmallVectorImpl<SDValue> &Results,
11876 SelectionDAG &DAG, unsigned InterOp,
11877 unsigned AcrossOp) {
11878 EVT LoVT, HiVT;
11879 SDValue Lo, Hi;
11880 SDLoc dl(N);
11881 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11882 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11883 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11884 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11885 Results.push_back(SplitVal);
11888 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11889 SDLoc DL(N);
11890 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11891 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11892 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11893 DAG.getConstant(64, DL, MVT::i64)));
11894 return std::make_pair(Lo, Hi);
11897 // Create an even/odd pair of X registers holding integer value V.
11898 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11899 SDLoc dl(V.getNode());
11900 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11901 SDValue VHi = DAG.getAnyExtOrTrunc(
11902 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11903 dl, MVT::i64);
11904 if (DAG.getDataLayout().isBigEndian())
11905 std::swap (VLo, VHi);
11906 SDValue RegClass =
11907 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11908 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11909 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11910 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11911 return SDValue(
11912 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11915 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11916 SmallVectorImpl<SDValue> &Results,
11917 SelectionDAG &DAG,
11918 const AArch64Subtarget *Subtarget) {
11919 assert(N->getValueType(0) == MVT::i128 &&
11920 "AtomicCmpSwap on types less than 128 should be legal");
11922 if (Subtarget->hasLSE()) {
11923 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11924 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11925 SDValue Ops[] = {
11926 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11927 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11928 N->getOperand(1), // Ptr
11929 N->getOperand(0), // Chain in
11932 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11934 unsigned Opcode;
11935 switch (MemOp->getOrdering()) {
11936 case AtomicOrdering::Monotonic:
11937 Opcode = AArch64::CASPX;
11938 break;
11939 case AtomicOrdering::Acquire:
11940 Opcode = AArch64::CASPAX;
11941 break;
11942 case AtomicOrdering::Release:
11943 Opcode = AArch64::CASPLX;
11944 break;
11945 case AtomicOrdering::AcquireRelease:
11946 case AtomicOrdering::SequentiallyConsistent:
11947 Opcode = AArch64::CASPALX;
11948 break;
11949 default:
11950 llvm_unreachable("Unexpected ordering!");
11953 MachineSDNode *CmpSwap = DAG.getMachineNode(
11954 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11955 DAG.setNodeMemRefs(CmpSwap, {MemOp});
11957 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11958 if (DAG.getDataLayout().isBigEndian())
11959 std::swap(SubReg1, SubReg2);
11960 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11961 SDValue(CmpSwap, 0)));
11962 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11963 SDValue(CmpSwap, 0)));
11964 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11965 return;
11968 auto Desired = splitInt128(N->getOperand(2), DAG);
11969 auto New = splitInt128(N->getOperand(3), DAG);
11970 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11971 New.first, New.second, N->getOperand(0)};
11972 SDNode *CmpSwap = DAG.getMachineNode(
11973 AArch64::CMP_SWAP_128, SDLoc(N),
11974 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11976 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11977 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11979 Results.push_back(SDValue(CmpSwap, 0));
11980 Results.push_back(SDValue(CmpSwap, 1));
11981 Results.push_back(SDValue(CmpSwap, 3));
11984 void AArch64TargetLowering::ReplaceNodeResults(
11985 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11986 switch (N->getOpcode()) {
11987 default:
11988 llvm_unreachable("Don't know how to custom expand this");
11989 case ISD::BITCAST:
11990 ReplaceBITCASTResults(N, Results, DAG);
11991 return;
11992 case ISD::VECREDUCE_ADD:
11993 case ISD::VECREDUCE_SMAX:
11994 case ISD::VECREDUCE_SMIN:
11995 case ISD::VECREDUCE_UMAX:
11996 case ISD::VECREDUCE_UMIN:
11997 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11998 return;
12000 case AArch64ISD::SADDV:
12001 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
12002 return;
12003 case AArch64ISD::UADDV:
12004 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
12005 return;
12006 case AArch64ISD::SMINV:
12007 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
12008 return;
12009 case AArch64ISD::UMINV:
12010 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
12011 return;
12012 case AArch64ISD::SMAXV:
12013 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
12014 return;
12015 case AArch64ISD::UMAXV:
12016 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
12017 return;
12018 case ISD::FP_TO_UINT:
12019 case ISD::FP_TO_SINT:
12020 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
12021 // Let normal code take care of it by not adding anything to Results.
12022 return;
12023 case ISD::ATOMIC_CMP_SWAP:
12024 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
12025 return;
12029 bool AArch64TargetLowering::useLoadStackGuardNode() const {
12030 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
12031 return TargetLowering::useLoadStackGuardNode();
12032 return true;
12035 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
12036 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12037 // reciprocal if there are three or more FDIVs.
12038 return 3;
12041 TargetLoweringBase::LegalizeTypeAction
12042 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
12043 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
12044 // v4i16, v2i32 instead of to promote.
12045 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
12046 VT == MVT::v1f32)
12047 return TypeWidenVector;
12049 return TargetLoweringBase::getPreferredVectorAction(VT);
12052 // Loads and stores less than 128-bits are already atomic; ones above that
12053 // are doomed anyway, so defer to the default libcall and blame the OS when
12054 // things go wrong.
12055 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12056 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12057 return Size == 128;
12060 // Loads and stores less than 128-bits are already atomic; ones above that
12061 // are doomed anyway, so defer to the default libcall and blame the OS when
12062 // things go wrong.
12063 TargetLowering::AtomicExpansionKind
12064 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12065 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12066 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
12069 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
12070 TargetLowering::AtomicExpansionKind
12071 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12072 if (AI->isFloatingPointOperation())
12073 return AtomicExpansionKind::CmpXChg;
12075 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12076 if (Size > 128) return AtomicExpansionKind::None;
12077 // Nand not supported in LSE.
12078 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
12079 // Leave 128 bits to LLSC.
12080 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
12083 TargetLowering::AtomicExpansionKind
12084 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
12085 AtomicCmpXchgInst *AI) const {
12086 // If subtarget has LSE, leave cmpxchg intact for codegen.
12087 if (Subtarget->hasLSE())
12088 return AtomicExpansionKind::None;
12089 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12090 // implement cmpxchg without spilling. If the address being exchanged is also
12091 // on the stack and close enough to the spill slot, this can lead to a
12092 // situation where the monitor always gets cleared and the atomic operation
12093 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12094 if (getTargetMachine().getOptLevel() == 0)
12095 return AtomicExpansionKind::None;
12096 return AtomicExpansionKind::LLSC;
12099 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12100 AtomicOrdering Ord) const {
12101 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12102 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12103 bool IsAcquire = isAcquireOrStronger(Ord);
12105 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
12106 // intrinsic must return {i64, i64} and we have to recombine them into a
12107 // single i128 here.
12108 if (ValTy->getPrimitiveSizeInBits() == 128) {
12109 Intrinsic::ID Int =
12110 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
12111 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
12113 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12114 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
12116 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12117 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12118 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12119 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12120 return Builder.CreateOr(
12121 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
12124 Type *Tys[] = { Addr->getType() };
12125 Intrinsic::ID Int =
12126 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
12127 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
12129 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
12131 const DataLayout &DL = M->getDataLayout();
12132 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
12133 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
12135 return Builder.CreateBitCast(Trunc, EltTy);
12138 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12139 IRBuilder<> &Builder) const {
12140 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12141 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
12144 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
12145 Value *Val, Value *Addr,
12146 AtomicOrdering Ord) const {
12147 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12148 bool IsRelease = isReleaseOrStronger(Ord);
12150 // Since the intrinsics must have legal type, the i128 intrinsics take two
12151 // parameters: "i64, i64". We must marshal Val into the appropriate form
12152 // before the call.
12153 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
12154 Intrinsic::ID Int =
12155 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
12156 Function *Stxr = Intrinsic::getDeclaration(M, Int);
12157 Type *Int64Ty = Type::getInt64Ty(M->getContext());
12159 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
12160 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
12161 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12162 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
12165 Intrinsic::ID Int =
12166 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12167 Type *Tys[] = { Addr->getType() };
12168 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12170 const DataLayout &DL = M->getDataLayout();
12171 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12172 Val = Builder.CreateBitCast(Val, IntValTy);
12174 return Builder.CreateCall(Stxr,
12175 {Builder.CreateZExtOrBitCast(
12176 Val, Stxr->getFunctionType()->getParamType(0)),
12177 Addr});
12180 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12181 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12182 return Ty->isArrayTy();
12185 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12186 EVT) const {
12187 return false;
12190 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
12191 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12192 Function *ThreadPointerFunc =
12193 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
12194 return IRB.CreatePointerCast(
12195 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12196 Offset),
12197 IRB.getInt8PtrTy()->getPointerTo(0));
12200 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12201 // Android provides a fixed TLS slot for the stack cookie. See the definition
12202 // of TLS_SLOT_STACK_GUARD in
12203 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12204 if (Subtarget->isTargetAndroid())
12205 return UseTlsOffset(IRB, 0x28);
12207 // Fuchsia is similar.
12208 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12209 if (Subtarget->isTargetFuchsia())
12210 return UseTlsOffset(IRB, -0x10);
12212 return TargetLowering::getIRStackGuard(IRB);
12215 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12216 // MSVC CRT provides functionalities for stack protection.
12217 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12218 // MSVC CRT has a global variable holding security cookie.
12219 M.getOrInsertGlobal("__security_cookie",
12220 Type::getInt8PtrTy(M.getContext()));
12222 // MSVC CRT has a function to validate security cookie.
12223 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12224 "__security_check_cookie", Type::getVoidTy(M.getContext()),
12225 Type::getInt8PtrTy(M.getContext()));
12226 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12227 F->setCallingConv(CallingConv::Win64);
12228 F->addAttribute(1, Attribute::AttrKind::InReg);
12230 return;
12232 TargetLowering::insertSSPDeclarations(M);
12235 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12236 // MSVC CRT has a global variable holding security cookie.
12237 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12238 return M.getGlobalVariable("__security_cookie");
12239 return TargetLowering::getSDagStackGuard(M);
12242 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
12243 // MSVC CRT has a function to validate security cookie.
12244 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12245 return M.getFunction("__security_check_cookie");
12246 return TargetLowering::getSSPStackGuardCheck(M);
12249 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
12250 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12251 // definition of TLS_SLOT_SAFESTACK in
12252 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12253 if (Subtarget->isTargetAndroid())
12254 return UseTlsOffset(IRB, 0x48);
12256 // Fuchsia is similar.
12257 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12258 if (Subtarget->isTargetFuchsia())
12259 return UseTlsOffset(IRB, -0x8);
12261 return TargetLowering::getSafeStackPointerLocation(IRB);
12264 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12265 const Instruction &AndI) const {
12266 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12267 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12268 // may be beneficial to sink in other cases, but we would have to check that
12269 // the cmp would not get folded into the br to form a cbz for these to be
12270 // beneficial.
12271 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12272 if (!Mask)
12273 return false;
12274 return Mask->getValue().isPowerOf2();
12277 bool AArch64TargetLowering::
12278 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12279 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12280 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12281 SelectionDAG &DAG) const {
12282 // Does baseline recommend not to perform the fold by default?
12283 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12284 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12285 return false;
12286 // Else, if this is a vector shift, prefer 'shl'.
12287 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12290 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
12291 SDNode *N) const {
12292 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
12293 !Subtarget->isTargetWindows())
12294 return false;
12295 return true;
12298 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12299 // Update IsSplitCSR in AArch64unctionInfo.
12300 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12301 AFI->setIsSplitCSR(true);
12304 void AArch64TargetLowering::insertCopiesSplitCSR(
12305 MachineBasicBlock *Entry,
12306 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12307 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12308 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12309 if (!IStart)
12310 return;
12312 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12313 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12314 MachineBasicBlock::iterator MBBI = Entry->begin();
12315 for (const MCPhysReg *I = IStart; *I; ++I) {
12316 const TargetRegisterClass *RC = nullptr;
12317 if (AArch64::GPR64RegClass.contains(*I))
12318 RC = &AArch64::GPR64RegClass;
12319 else if (AArch64::FPR64RegClass.contains(*I))
12320 RC = &AArch64::FPR64RegClass;
12321 else
12322 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12324 Register NewVR = MRI->createVirtualRegister(RC);
12325 // Create copy from CSR to a virtual register.
12326 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12327 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12328 // nounwind. If we want to generalize this later, we may need to emit
12329 // CFI pseudo-instructions.
12330 assert(Entry->getParent()->getFunction().hasFnAttribute(
12331 Attribute::NoUnwind) &&
12332 "Function should be nounwind in insertCopiesSplitCSR!");
12333 Entry->addLiveIn(*I);
12334 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12335 .addReg(*I);
12337 // Insert the copy-back instructions right before the terminator.
12338 for (auto *Exit : Exits)
12339 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12340 TII->get(TargetOpcode::COPY), *I)
12341 .addReg(NewVR);
12345 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12346 // Integer division on AArch64 is expensive. However, when aggressively
12347 // optimizing for code size, we prefer to use a div instruction, as it is
12348 // usually smaller than the alternative sequence.
12349 // The exception to this is vector division. Since AArch64 doesn't have vector
12350 // integer division, leaving the division as-is is a loss even in terms of
12351 // size, because it will have to be scalarized, while the alternative code
12352 // sequence can be performed in vector form.
12353 bool OptSize =
12354 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12355 return OptSize && !VT.isVector();
12358 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12359 // We want inc-of-add for scalars and sub-of-not for vectors.
12360 return VT.isScalarInteger();
12363 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12364 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12367 unsigned
12368 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
12369 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12370 return getPointerTy(DL).getSizeInBits();
12372 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12375 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12376 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12377 TargetLoweringBase::finalizeLowering(MF);
12380 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12381 bool AArch64TargetLowering::needsFixedCatchObjects() const {
12382 return false;