[ARM] Remove declaration of unimplemented function. NFC.
[llvm-complete.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
blobef535beaa6c5e8968e737d636d3d4254bf0e4dd5
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/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/Use.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Target/TargetMachine.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <algorithm>
80 #include <bitset>
81 #include <cassert>
82 #include <cctype>
83 #include <cstdint>
84 #include <cstdlib>
85 #include <iterator>
86 #include <limits>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
91 using namespace llvm;
92 using namespace llvm::PatternMatch;
94 #define DEBUG_TYPE "aarch64-lower"
96 STATISTIC(NumTailCalls, "Number of tail calls");
97 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
98 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
100 static cl::opt<bool>
101 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
102 cl::desc("Allow AArch64 SLI/SRI formation"),
103 cl::init(false));
105 // FIXME: The necessary dtprel relocations don't seem to be supported
106 // well in the GNU bfd and gold linkers at the moment. Therefore, by
107 // default, for now, fall back to GeneralDynamic code generation.
108 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 cl::init(false));
113 static cl::opt<bool>
114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
115 cl::desc("Enable AArch64 logical imm instruction "
116 "optimization"),
117 cl::init(true));
119 /// Value type used for condition codes.
120 static const MVT MVT_CC = MVT::i32;
122 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
123 const AArch64Subtarget &STI)
124 : TargetLowering(TM), Subtarget(&STI) {
125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
132 // Set up the register classes.
133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
136 if (Subtarget->hasFPARMv8()) {
137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
143 if (Subtarget->hasNEON()) {
144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32);
148 addDRTypeForNEON(MVT::v8i8);
149 addDRTypeForNEON(MVT::v4i16);
150 addDRTypeForNEON(MVT::v2i32);
151 addDRTypeForNEON(MVT::v1i64);
152 addDRTypeForNEON(MVT::v1f64);
153 addDRTypeForNEON(MVT::v4f16);
155 addQRTypeForNEON(MVT::v4f32);
156 addQRTypeForNEON(MVT::v2f64);
157 addQRTypeForNEON(MVT::v16i8);
158 addQRTypeForNEON(MVT::v8i16);
159 addQRTypeForNEON(MVT::v4i32);
160 addQRTypeForNEON(MVT::v2i64);
161 addQRTypeForNEON(MVT::v8f16);
164 if (Subtarget->hasSVE()) {
165 // Add legal sve predicate types
166 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
167 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
168 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
169 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
171 // Add legal sve data types
172 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
173 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
174 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
175 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
177 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
178 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
179 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
180 addRegisterClass(MVT::nxv1f32, &AArch64::ZPRRegClass);
181 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
182 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
183 addRegisterClass(MVT::nxv1f64, &AArch64::ZPRRegClass);
184 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
187 // Compute derived properties from the register classes
188 computeRegisterProperties(Subtarget->getRegisterInfo());
190 // Provide all sorts of operation actions
191 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
192 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
193 setOperationAction(ISD::SETCC, MVT::i32, Custom);
194 setOperationAction(ISD::SETCC, MVT::i64, Custom);
195 setOperationAction(ISD::SETCC, MVT::f16, Custom);
196 setOperationAction(ISD::SETCC, MVT::f32, Custom);
197 setOperationAction(ISD::SETCC, MVT::f64, Custom);
198 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
199 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
200 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
201 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
202 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
203 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
204 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
205 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
206 setOperationAction(ISD::SELECT, MVT::i32, Custom);
207 setOperationAction(ISD::SELECT, MVT::i64, Custom);
208 setOperationAction(ISD::SELECT, MVT::f16, Custom);
209 setOperationAction(ISD::SELECT, MVT::f32, Custom);
210 setOperationAction(ISD::SELECT, MVT::f64, Custom);
211 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
212 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
213 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
214 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
215 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
216 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
217 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
219 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
220 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
221 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
223 setOperationAction(ISD::FREM, MVT::f32, Expand);
224 setOperationAction(ISD::FREM, MVT::f64, Expand);
225 setOperationAction(ISD::FREM, MVT::f80, Expand);
227 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
229 // Custom lowering hooks are needed for XOR
230 // to fold it into CSINC/CSINV.
231 setOperationAction(ISD::XOR, MVT::i32, Custom);
232 setOperationAction(ISD::XOR, MVT::i64, Custom);
234 // Virtually no operation on f128 is legal, but LLVM can't expand them when
235 // there's a valid register class, so we need custom operations in most cases.
236 setOperationAction(ISD::FABS, MVT::f128, Expand);
237 setOperationAction(ISD::FADD, MVT::f128, Custom);
238 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
239 setOperationAction(ISD::FCOS, MVT::f128, Expand);
240 setOperationAction(ISD::FDIV, MVT::f128, Custom);
241 setOperationAction(ISD::FMA, MVT::f128, Expand);
242 setOperationAction(ISD::FMUL, MVT::f128, Custom);
243 setOperationAction(ISD::FNEG, MVT::f128, Expand);
244 setOperationAction(ISD::FPOW, MVT::f128, Expand);
245 setOperationAction(ISD::FREM, MVT::f128, Expand);
246 setOperationAction(ISD::FRINT, MVT::f128, Expand);
247 setOperationAction(ISD::FSIN, MVT::f128, Expand);
248 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
249 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
250 setOperationAction(ISD::FSUB, MVT::f128, Custom);
251 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
252 setOperationAction(ISD::SETCC, MVT::f128, Custom);
253 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
254 setOperationAction(ISD::SELECT, MVT::f128, Custom);
255 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
256 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
258 // Lowering for many of the conversions is actually specified by the non-f128
259 // type. The LowerXXX function will be trivial when f128 isn't involved.
260 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
262 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
263 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
264 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
265 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
266 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
267 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
268 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
269 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
270 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
272 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
273 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
275 // Variable arguments.
276 setOperationAction(ISD::VASTART, MVT::Other, Custom);
277 setOperationAction(ISD::VAARG, MVT::Other, Custom);
278 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
279 setOperationAction(ISD::VAEND, MVT::Other, Expand);
281 // Variable-sized objects.
282 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
283 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
285 if (Subtarget->isTargetWindows())
286 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
287 else
288 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
290 // Constant pool entries
291 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
293 // BlockAddress
294 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
296 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
297 setOperationAction(ISD::ADDC, MVT::i32, Custom);
298 setOperationAction(ISD::ADDE, MVT::i32, Custom);
299 setOperationAction(ISD::SUBC, MVT::i32, Custom);
300 setOperationAction(ISD::SUBE, MVT::i32, Custom);
301 setOperationAction(ISD::ADDC, MVT::i64, Custom);
302 setOperationAction(ISD::ADDE, MVT::i64, Custom);
303 setOperationAction(ISD::SUBC, MVT::i64, Custom);
304 setOperationAction(ISD::SUBE, MVT::i64, Custom);
306 // AArch64 lacks both left-rotate and popcount instructions.
307 setOperationAction(ISD::ROTL, MVT::i32, Expand);
308 setOperationAction(ISD::ROTL, MVT::i64, Expand);
309 for (MVT VT : MVT::vector_valuetypes()) {
310 setOperationAction(ISD::ROTL, VT, Expand);
311 setOperationAction(ISD::ROTR, VT, Expand);
314 // AArch64 doesn't have {U|S}MUL_LOHI.
315 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
316 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
318 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
319 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
321 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
322 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
323 for (MVT VT : MVT::vector_valuetypes()) {
324 setOperationAction(ISD::SDIVREM, VT, Expand);
325 setOperationAction(ISD::UDIVREM, VT, Expand);
327 setOperationAction(ISD::SREM, MVT::i32, Expand);
328 setOperationAction(ISD::SREM, MVT::i64, Expand);
329 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
330 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
331 setOperationAction(ISD::UREM, MVT::i32, Expand);
332 setOperationAction(ISD::UREM, MVT::i64, Expand);
334 // Custom lower Add/Sub/Mul with overflow.
335 setOperationAction(ISD::SADDO, MVT::i32, Custom);
336 setOperationAction(ISD::SADDO, MVT::i64, Custom);
337 setOperationAction(ISD::UADDO, MVT::i32, Custom);
338 setOperationAction(ISD::UADDO, MVT::i64, Custom);
339 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
340 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
341 setOperationAction(ISD::USUBO, MVT::i32, Custom);
342 setOperationAction(ISD::USUBO, MVT::i64, Custom);
343 setOperationAction(ISD::SMULO, MVT::i32, Custom);
344 setOperationAction(ISD::SMULO, MVT::i64, Custom);
345 setOperationAction(ISD::UMULO, MVT::i32, Custom);
346 setOperationAction(ISD::UMULO, MVT::i64, Custom);
348 setOperationAction(ISD::FSIN, MVT::f32, Expand);
349 setOperationAction(ISD::FSIN, MVT::f64, Expand);
350 setOperationAction(ISD::FCOS, MVT::f32, Expand);
351 setOperationAction(ISD::FCOS, MVT::f64, Expand);
352 setOperationAction(ISD::FPOW, MVT::f32, Expand);
353 setOperationAction(ISD::FPOW, MVT::f64, Expand);
354 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
356 if (Subtarget->hasFullFP16())
357 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
358 else
359 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
361 setOperationAction(ISD::FREM, MVT::f16, Promote);
362 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
363 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
364 setOperationAction(ISD::FPOW, MVT::f16, Promote);
365 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
366 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
367 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
368 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370 setOperationAction(ISD::FCOS, MVT::f16, Promote);
371 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
372 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSIN, MVT::f16, Promote);
374 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
375 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
376 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
377 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
378 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
379 setOperationAction(ISD::FEXP, MVT::f16, Promote);
380 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
381 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
382 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
383 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385 setOperationAction(ISD::FLOG, MVT::f16, Promote);
386 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
387 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
388 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
389 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
390 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
391 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
392 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
393 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
395 if (!Subtarget->hasFullFP16()) {
396 setOperationAction(ISD::SELECT, MVT::f16, Promote);
397 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
398 setOperationAction(ISD::SETCC, MVT::f16, Promote);
399 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
400 setOperationAction(ISD::FADD, MVT::f16, Promote);
401 setOperationAction(ISD::FSUB, MVT::f16, Promote);
402 setOperationAction(ISD::FMUL, MVT::f16, Promote);
403 setOperationAction(ISD::FDIV, MVT::f16, Promote);
404 setOperationAction(ISD::FMA, MVT::f16, Promote);
405 setOperationAction(ISD::FNEG, MVT::f16, Promote);
406 setOperationAction(ISD::FABS, MVT::f16, Promote);
407 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
408 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
409 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
410 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
411 setOperationAction(ISD::FRINT, MVT::f16, Promote);
412 setOperationAction(ISD::FROUND, MVT::f16, Promote);
413 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
414 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
415 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
416 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
417 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
419 // promote v4f16 to v4f32 when that is known to be safe.
420 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
421 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
422 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
423 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
424 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
425 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
426 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
427 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
428 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
429 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
430 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
431 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
433 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
434 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
435 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
436 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
437 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
438 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
439 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
440 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
441 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
442 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
443 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
444 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
445 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
446 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
447 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
449 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
450 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
451 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
452 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
453 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
454 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
455 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
456 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
457 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
458 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
459 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
460 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
461 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
462 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
463 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
464 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
465 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
466 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
467 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
468 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
471 // AArch64 has implementations of a lot of rounding-like FP operations.
472 for (MVT Ty : {MVT::f32, MVT::f64}) {
473 setOperationAction(ISD::FFLOOR, Ty, Legal);
474 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
475 setOperationAction(ISD::FCEIL, Ty, Legal);
476 setOperationAction(ISD::FRINT, Ty, Legal);
477 setOperationAction(ISD::FTRUNC, Ty, Legal);
478 setOperationAction(ISD::FROUND, Ty, Legal);
479 setOperationAction(ISD::FMINNUM, Ty, Legal);
480 setOperationAction(ISD::FMAXNUM, Ty, Legal);
481 setOperationAction(ISD::FMINIMUM, Ty, Legal);
482 setOperationAction(ISD::FMAXIMUM, Ty, Legal);
483 setOperationAction(ISD::LROUND, Ty, Legal);
484 setOperationAction(ISD::LLROUND, Ty, Legal);
485 setOperationAction(ISD::LRINT, Ty, Legal);
486 setOperationAction(ISD::LLRINT, Ty, Legal);
489 if (Subtarget->hasFullFP16()) {
490 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
491 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
492 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
493 setOperationAction(ISD::FRINT, MVT::f16, Legal);
494 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
495 setOperationAction(ISD::FROUND, MVT::f16, Legal);
496 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
497 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
498 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
499 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
502 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
504 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
506 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
509 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
510 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
512 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
513 // This requires the Performance Monitors extension.
514 if (Subtarget->hasPerfMon())
515 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
517 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
518 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
519 // Issue __sincos_stret if available.
520 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
521 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
522 } else {
523 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
524 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
527 // Make floating-point constants legal for the large code model, so they don't
528 // become loads from the constant pool.
529 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
530 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
531 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
534 // AArch64 does not have floating-point extending loads, i1 sign-extending
535 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
536 for (MVT VT : MVT::fp_valuetypes()) {
537 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
538 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
539 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
540 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
542 for (MVT VT : MVT::integer_valuetypes())
543 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
545 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
546 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
547 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
548 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
549 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
550 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
551 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
553 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
554 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
556 // Indexed loads and stores are supported.
557 for (unsigned im = (unsigned)ISD::PRE_INC;
558 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
559 setIndexedLoadAction(im, MVT::i8, Legal);
560 setIndexedLoadAction(im, MVT::i16, Legal);
561 setIndexedLoadAction(im, MVT::i32, Legal);
562 setIndexedLoadAction(im, MVT::i64, Legal);
563 setIndexedLoadAction(im, MVT::f64, Legal);
564 setIndexedLoadAction(im, MVT::f32, Legal);
565 setIndexedLoadAction(im, MVT::f16, Legal);
566 setIndexedStoreAction(im, MVT::i8, Legal);
567 setIndexedStoreAction(im, MVT::i16, Legal);
568 setIndexedStoreAction(im, MVT::i32, Legal);
569 setIndexedStoreAction(im, MVT::i64, Legal);
570 setIndexedStoreAction(im, MVT::f64, Legal);
571 setIndexedStoreAction(im, MVT::f32, Legal);
572 setIndexedStoreAction(im, MVT::f16, Legal);
575 // Trap.
576 setOperationAction(ISD::TRAP, MVT::Other, Legal);
577 if (Subtarget->isTargetWindows())
578 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
580 // We combine OR nodes for bitfield operations.
581 setTargetDAGCombine(ISD::OR);
582 // Try to create BICs for vector ANDs.
583 setTargetDAGCombine(ISD::AND);
585 // Vector add and sub nodes may conceal a high-half opportunity.
586 // Also, try to fold ADD into CSINC/CSINV..
587 setTargetDAGCombine(ISD::ADD);
588 setTargetDAGCombine(ISD::SUB);
589 setTargetDAGCombine(ISD::SRL);
590 setTargetDAGCombine(ISD::XOR);
591 setTargetDAGCombine(ISD::SINT_TO_FP);
592 setTargetDAGCombine(ISD::UINT_TO_FP);
594 setTargetDAGCombine(ISD::FP_TO_SINT);
595 setTargetDAGCombine(ISD::FP_TO_UINT);
596 setTargetDAGCombine(ISD::FDIV);
598 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
600 setTargetDAGCombine(ISD::ANY_EXTEND);
601 setTargetDAGCombine(ISD::ZERO_EXTEND);
602 setTargetDAGCombine(ISD::SIGN_EXTEND);
603 setTargetDAGCombine(ISD::BITCAST);
604 setTargetDAGCombine(ISD::CONCAT_VECTORS);
605 setTargetDAGCombine(ISD::STORE);
606 if (Subtarget->supportsAddressTopByteIgnored())
607 setTargetDAGCombine(ISD::LOAD);
609 setTargetDAGCombine(ISD::MUL);
611 setTargetDAGCombine(ISD::SELECT);
612 setTargetDAGCombine(ISD::VSELECT);
614 setTargetDAGCombine(ISD::INTRINSIC_VOID);
615 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
616 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
618 setTargetDAGCombine(ISD::GlobalAddress);
620 // In case of strict alignment, avoid an excessive number of byte wide stores.
621 MaxStoresPerMemsetOptSize = 8;
622 MaxStoresPerMemset = Subtarget->requiresStrictAlign()
623 ? MaxStoresPerMemsetOptSize : 32;
625 MaxGluedStoresPerMemcpy = 4;
626 MaxStoresPerMemcpyOptSize = 4;
627 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
628 ? MaxStoresPerMemcpyOptSize : 16;
630 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
632 MaxLoadsPerMemcmpOptSize = 4;
633 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
634 ? MaxLoadsPerMemcmpOptSize : 8;
636 setStackPointerRegisterToSaveRestore(AArch64::SP);
638 setSchedulingPreference(Sched::Hybrid);
640 EnableExtLdPromotion = true;
642 // Set required alignment.
643 setMinFunctionAlignment(llvm::Align(4));
644 // Set preferred alignments.
645 setPrefLoopAlignment(llvm::Align(1ULL << STI.getPrefLoopLogAlignment()));
646 setPrefFunctionAlignment(
647 llvm::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::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::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 ISD::INTRINSIC_W_CHAIN: {
1057 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1058 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1059 switch (IntID) {
1060 default: return;
1061 case Intrinsic::aarch64_ldaxr:
1062 case Intrinsic::aarch64_ldxr: {
1063 unsigned BitWidth = Known.getBitWidth();
1064 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1065 unsigned MemBits = VT.getScalarSizeInBits();
1066 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1067 return;
1070 break;
1072 case ISD::INTRINSIC_WO_CHAIN:
1073 case ISD::INTRINSIC_VOID: {
1074 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1075 switch (IntNo) {
1076 default:
1077 break;
1078 case Intrinsic::aarch64_neon_umaxv:
1079 case Intrinsic::aarch64_neon_uminv: {
1080 // Figure out the datatype of the vector operand. The UMINV instruction
1081 // will zero extend the result, so we can mark as known zero all the
1082 // bits larger than the element datatype. 32-bit or larget doesn't need
1083 // this as those are legal types and will be handled by isel directly.
1084 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1085 unsigned BitWidth = Known.getBitWidth();
1086 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1087 assert(BitWidth >= 8 && "Unexpected width!");
1088 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1089 Known.Zero |= Mask;
1090 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1091 assert(BitWidth >= 16 && "Unexpected width!");
1092 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1093 Known.Zero |= Mask;
1095 break;
1096 } break;
1102 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1103 EVT) const {
1104 return MVT::i64;
1107 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1108 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1109 bool *Fast) const {
1110 if (Subtarget->requiresStrictAlign())
1111 return false;
1113 if (Fast) {
1114 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1115 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1116 // See comments in performSTORECombine() for more details about
1117 // these conditions.
1119 // Code that uses clang vector extensions can mark that it
1120 // wants unaligned accesses to be treated as fast by
1121 // underspecifying alignment to be 1 or 2.
1122 Align <= 2 ||
1124 // Disregard v2i64. Memcpy lowering produces those and splitting
1125 // them regresses performance on micro-benchmarks and olden/bh.
1126 VT == MVT::v2i64;
1128 return true;
1131 // Same as above but handling LLTs instead.
1132 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1133 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1134 bool *Fast) const {
1135 if (Subtarget->requiresStrictAlign())
1136 return false;
1138 if (Fast) {
1139 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1140 *Fast = !Subtarget->isMisaligned128StoreSlow() ||
1141 Ty.getSizeInBytes() != 16 ||
1142 // See comments in performSTORECombine() for more details about
1143 // these conditions.
1145 // Code that uses clang vector extensions can mark that it
1146 // wants unaligned accesses to be treated as fast by
1147 // underspecifying alignment to be 1 or 2.
1148 Align <= 2 ||
1150 // Disregard v2i64. Memcpy lowering produces those and splitting
1151 // them regresses performance on micro-benchmarks and olden/bh.
1152 Ty == LLT::vector(2, 64);
1154 return true;
1157 FastISel *
1158 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1159 const TargetLibraryInfo *libInfo) const {
1160 return AArch64::createFastISel(funcInfo, libInfo);
1163 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1164 switch ((AArch64ISD::NodeType)Opcode) {
1165 case AArch64ISD::FIRST_NUMBER: break;
1166 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1167 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1168 case AArch64ISD::ADR: return "AArch64ISD::ADR";
1169 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1170 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1171 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1172 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1173 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1174 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1175 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1176 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1177 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1178 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1179 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1180 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1181 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1182 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1183 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1184 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1185 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1186 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1187 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1188 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1189 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1190 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1191 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1192 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1193 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1194 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1195 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1196 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1197 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1198 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1199 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1200 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1201 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1202 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1203 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1204 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1205 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1206 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1207 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1208 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1209 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1210 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1211 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1212 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1213 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1214 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1215 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1216 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1217 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1218 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1219 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1220 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1221 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1222 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1223 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1224 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1225 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1226 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1227 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1228 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1229 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1230 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1231 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1232 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1233 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1234 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1235 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1236 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1237 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1238 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1239 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1240 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1241 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1242 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1243 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1244 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1245 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1246 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1247 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1248 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1249 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1250 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1251 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1252 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1253 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1254 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1255 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1256 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1257 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1258 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1259 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1260 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1261 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1262 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1263 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1264 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1265 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1266 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1267 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1268 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1269 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1270 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1271 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1272 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1273 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1274 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1275 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1276 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1277 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1278 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1279 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1280 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1281 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1282 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1283 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1284 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1285 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1286 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1287 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1288 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1289 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1290 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1291 case AArch64ISD::STG: return "AArch64ISD::STG";
1292 case AArch64ISD::STZG: return "AArch64ISD::STZG";
1293 case AArch64ISD::ST2G: return "AArch64ISD::ST2G";
1294 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G";
1296 return nullptr;
1299 MachineBasicBlock *
1300 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1301 MachineBasicBlock *MBB) const {
1302 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1303 // phi node:
1305 // OrigBB:
1306 // [... previous instrs leading to comparison ...]
1307 // b.ne TrueBB
1308 // b EndBB
1309 // TrueBB:
1310 // ; Fallthrough
1311 // EndBB:
1312 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1314 MachineFunction *MF = MBB->getParent();
1315 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1316 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1317 DebugLoc DL = MI.getDebugLoc();
1318 MachineFunction::iterator It = ++MBB->getIterator();
1320 Register DestReg = MI.getOperand(0).getReg();
1321 Register IfTrueReg = MI.getOperand(1).getReg();
1322 Register IfFalseReg = MI.getOperand(2).getReg();
1323 unsigned CondCode = MI.getOperand(3).getImm();
1324 bool NZCVKilled = MI.getOperand(4).isKill();
1326 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1327 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1328 MF->insert(It, TrueBB);
1329 MF->insert(It, EndBB);
1331 // Transfer rest of current basic-block to EndBB
1332 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1333 MBB->end());
1334 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1336 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1337 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1338 MBB->addSuccessor(TrueBB);
1339 MBB->addSuccessor(EndBB);
1341 // TrueBB falls through to the end.
1342 TrueBB->addSuccessor(EndBB);
1344 if (!NZCVKilled) {
1345 TrueBB->addLiveIn(AArch64::NZCV);
1346 EndBB->addLiveIn(AArch64::NZCV);
1349 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1350 .addReg(IfTrueReg)
1351 .addMBB(TrueBB)
1352 .addReg(IfFalseReg)
1353 .addMBB(MBB);
1355 MI.eraseFromParent();
1356 return EndBB;
1359 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
1360 MachineInstr &MI, MachineBasicBlock *BB) const {
1361 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1362 BB->getParent()->getFunction().getPersonalityFn())) &&
1363 "SEH does not use catchret!");
1364 return BB;
1367 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad(
1368 MachineInstr &MI, MachineBasicBlock *BB) const {
1369 MI.eraseFromParent();
1370 return BB;
1373 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1374 MachineInstr &MI, MachineBasicBlock *BB) const {
1375 switch (MI.getOpcode()) {
1376 default:
1377 #ifndef NDEBUG
1378 MI.dump();
1379 #endif
1380 llvm_unreachable("Unexpected instruction for custom inserter!");
1382 case AArch64::F128CSEL:
1383 return EmitF128CSEL(MI, BB);
1385 case TargetOpcode::STACKMAP:
1386 case TargetOpcode::PATCHPOINT:
1387 return emitPatchPoint(MI, BB);
1389 case AArch64::CATCHRET:
1390 return EmitLoweredCatchRet(MI, BB);
1391 case AArch64::CATCHPAD:
1392 return EmitLoweredCatchPad(MI, BB);
1396 //===----------------------------------------------------------------------===//
1397 // AArch64 Lowering private implementation.
1398 //===----------------------------------------------------------------------===//
1400 //===----------------------------------------------------------------------===//
1401 // Lowering Code
1402 //===----------------------------------------------------------------------===//
1404 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1405 /// CC
1406 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1407 switch (CC) {
1408 default:
1409 llvm_unreachable("Unknown condition code!");
1410 case ISD::SETNE:
1411 return AArch64CC::NE;
1412 case ISD::SETEQ:
1413 return AArch64CC::EQ;
1414 case ISD::SETGT:
1415 return AArch64CC::GT;
1416 case ISD::SETGE:
1417 return AArch64CC::GE;
1418 case ISD::SETLT:
1419 return AArch64CC::LT;
1420 case ISD::SETLE:
1421 return AArch64CC::LE;
1422 case ISD::SETUGT:
1423 return AArch64CC::HI;
1424 case ISD::SETUGE:
1425 return AArch64CC::HS;
1426 case ISD::SETULT:
1427 return AArch64CC::LO;
1428 case ISD::SETULE:
1429 return AArch64CC::LS;
1433 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1434 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1435 AArch64CC::CondCode &CondCode,
1436 AArch64CC::CondCode &CondCode2) {
1437 CondCode2 = AArch64CC::AL;
1438 switch (CC) {
1439 default:
1440 llvm_unreachable("Unknown FP condition!");
1441 case ISD::SETEQ:
1442 case ISD::SETOEQ:
1443 CondCode = AArch64CC::EQ;
1444 break;
1445 case ISD::SETGT:
1446 case ISD::SETOGT:
1447 CondCode = AArch64CC::GT;
1448 break;
1449 case ISD::SETGE:
1450 case ISD::SETOGE:
1451 CondCode = AArch64CC::GE;
1452 break;
1453 case ISD::SETOLT:
1454 CondCode = AArch64CC::MI;
1455 break;
1456 case ISD::SETOLE:
1457 CondCode = AArch64CC::LS;
1458 break;
1459 case ISD::SETONE:
1460 CondCode = AArch64CC::MI;
1461 CondCode2 = AArch64CC::GT;
1462 break;
1463 case ISD::SETO:
1464 CondCode = AArch64CC::VC;
1465 break;
1466 case ISD::SETUO:
1467 CondCode = AArch64CC::VS;
1468 break;
1469 case ISD::SETUEQ:
1470 CondCode = AArch64CC::EQ;
1471 CondCode2 = AArch64CC::VS;
1472 break;
1473 case ISD::SETUGT:
1474 CondCode = AArch64CC::HI;
1475 break;
1476 case ISD::SETUGE:
1477 CondCode = AArch64CC::PL;
1478 break;
1479 case ISD::SETLT:
1480 case ISD::SETULT:
1481 CondCode = AArch64CC::LT;
1482 break;
1483 case ISD::SETLE:
1484 case ISD::SETULE:
1485 CondCode = AArch64CC::LE;
1486 break;
1487 case ISD::SETNE:
1488 case ISD::SETUNE:
1489 CondCode = AArch64CC::NE;
1490 break;
1494 /// Convert a DAG fp condition code to an AArch64 CC.
1495 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1496 /// should be AND'ed instead of OR'ed.
1497 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1498 AArch64CC::CondCode &CondCode,
1499 AArch64CC::CondCode &CondCode2) {
1500 CondCode2 = AArch64CC::AL;
1501 switch (CC) {
1502 default:
1503 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1504 assert(CondCode2 == AArch64CC::AL);
1505 break;
1506 case ISD::SETONE:
1507 // (a one b)
1508 // == ((a olt b) || (a ogt b))
1509 // == ((a ord b) && (a une b))
1510 CondCode = AArch64CC::VC;
1511 CondCode2 = AArch64CC::NE;
1512 break;
1513 case ISD::SETUEQ:
1514 // (a ueq b)
1515 // == ((a uno b) || (a oeq b))
1516 // == ((a ule b) && (a uge b))
1517 CondCode = AArch64CC::PL;
1518 CondCode2 = AArch64CC::LE;
1519 break;
1523 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1524 /// CC usable with the vector instructions. Fewer operations are available
1525 /// without a real NZCV register, so we have to use less efficient combinations
1526 /// to get the same effect.
1527 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1528 AArch64CC::CondCode &CondCode,
1529 AArch64CC::CondCode &CondCode2,
1530 bool &Invert) {
1531 Invert = false;
1532 switch (CC) {
1533 default:
1534 // Mostly the scalar mappings work fine.
1535 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1536 break;
1537 case ISD::SETUO:
1538 Invert = true;
1539 LLVM_FALLTHROUGH;
1540 case ISD::SETO:
1541 CondCode = AArch64CC::MI;
1542 CondCode2 = AArch64CC::GE;
1543 break;
1544 case ISD::SETUEQ:
1545 case ISD::SETULT:
1546 case ISD::SETULE:
1547 case ISD::SETUGT:
1548 case ISD::SETUGE:
1549 // All of the compare-mask comparisons are ordered, but we can switch
1550 // between the two by a double inversion. E.g. ULE == !OGT.
1551 Invert = true;
1552 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1553 break;
1557 static bool isLegalArithImmed(uint64_t C) {
1558 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1559 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1560 LLVM_DEBUG(dbgs() << "Is imm " << C
1561 << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1562 return IsLegal;
1565 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1566 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1567 // can be set differently by this operation. It comes down to whether
1568 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1569 // everything is fine. If not then the optimization is wrong. Thus general
1570 // comparisons are only valid if op2 != 0.
1572 // So, finally, the only LLVM-native comparisons that don't mention C and V
1573 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1574 // the absence of information about op2.
1575 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1576 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1577 (CC == ISD::SETEQ || CC == ISD::SETNE);
1580 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1581 const SDLoc &dl, SelectionDAG &DAG) {
1582 EVT VT = LHS.getValueType();
1583 const bool FullFP16 =
1584 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1586 if (VT.isFloatingPoint()) {
1587 assert(VT != MVT::f128);
1588 if (VT == MVT::f16 && !FullFP16) {
1589 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1590 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1591 VT = MVT::f32;
1593 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1596 // The CMP instruction is just an alias for SUBS, and representing it as
1597 // SUBS means that it's possible to get CSE with subtract operations.
1598 // A later phase can perform the optimization of setting the destination
1599 // register to WZR/XZR if it ends up being unused.
1600 unsigned Opcode = AArch64ISD::SUBS;
1602 if (isCMN(RHS, CC)) {
1603 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1604 Opcode = AArch64ISD::ADDS;
1605 RHS = RHS.getOperand(1);
1606 } else if (isCMN(LHS, CC)) {
1607 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1608 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1609 Opcode = AArch64ISD::ADDS;
1610 LHS = LHS.getOperand(1);
1611 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1612 !isUnsignedIntSetCC(CC)) {
1613 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1614 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1615 // of the signed comparisons.
1616 Opcode = AArch64ISD::ANDS;
1617 RHS = LHS.getOperand(1);
1618 LHS = LHS.getOperand(0);
1621 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1622 .getValue(1);
1625 /// \defgroup AArch64CCMP CMP;CCMP matching
1627 /// These functions deal with the formation of CMP;CCMP;... sequences.
1628 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1629 /// a comparison. They set the NZCV flags to a predefined value if their
1630 /// predicate is false. This allows to express arbitrary conjunctions, for
1631 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1632 /// expressed as:
1633 /// cmp A
1634 /// ccmp B, inv(CB), CA
1635 /// check for CB flags
1637 /// This naturally lets us implement chains of AND operations with SETCC
1638 /// operands. And we can even implement some other situations by transforming
1639 /// them:
1640 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1641 /// negating the flags used in a CCMP/FCCMP operations.
1642 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1643 /// by negating the flags we test for afterwards. i.e.
1644 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1645 /// - Note that we can only ever negate all previously processed results.
1646 /// What we can not implement by flipping the flags to test is a negation
1647 /// of two sub-trees (because the negation affects all sub-trees emitted so
1648 /// far, so the 2nd sub-tree we emit would also affect the first).
1649 /// With those tools we can implement some OR operations:
1650 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1651 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1652 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1653 /// elimination rules from earlier to implement the whole thing as a
1654 /// CCMP/FCCMP chain.
1656 /// As complete example:
1657 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1658 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1659 /// can be reassociated to:
1660 /// or (and (setCC (cmp C)) setCD (cmp D))
1661 // (or (setCA (cmp A)) (setCB (cmp B)))
1662 /// can be transformed to:
1663 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1664 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1665 /// which can be implemented as:
1666 /// cmp C
1667 /// ccmp D, inv(CD), CC
1668 /// ccmp A, CA, inv(CD)
1669 /// ccmp B, CB, inv(CA)
1670 /// check for CB flags
1672 /// A counterexample is "or (and A B) (and C D)" which translates to
1673 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1674 /// can only implement 1 of the inner (not) operations, but not both!
1675 /// @{
1677 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1678 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1679 ISD::CondCode CC, SDValue CCOp,
1680 AArch64CC::CondCode Predicate,
1681 AArch64CC::CondCode OutCC,
1682 const SDLoc &DL, SelectionDAG &DAG) {
1683 unsigned Opcode = 0;
1684 const bool FullFP16 =
1685 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1687 if (LHS.getValueType().isFloatingPoint()) {
1688 assert(LHS.getValueType() != MVT::f128);
1689 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1690 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1691 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1693 Opcode = AArch64ISD::FCCMP;
1694 } else if (RHS.getOpcode() == ISD::SUB) {
1695 SDValue SubOp0 = RHS.getOperand(0);
1696 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1697 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1698 Opcode = AArch64ISD::CCMN;
1699 RHS = RHS.getOperand(1);
1702 if (Opcode == 0)
1703 Opcode = AArch64ISD::CCMP;
1705 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1706 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1707 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1708 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1709 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1712 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1713 /// expressed as a conjunction. See \ref AArch64CCMP.
1714 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1715 /// changing the conditions on the SETCC tests.
1716 /// (this means we can call emitConjunctionRec() with
1717 /// Negate==true on this sub-tree)
1718 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1719 /// cannot do the negation naturally. We are required to
1720 /// emit the subtree first in this case.
1721 /// \param WillNegate Is true if are called when the result of this
1722 /// subexpression must be negated. This happens when the
1723 /// outer expression is an OR. We can use this fact to know
1724 /// that we have a double negation (or (or ...) ...) that
1725 /// can be implemented for free.
1726 static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
1727 bool &MustBeFirst, bool WillNegate,
1728 unsigned Depth = 0) {
1729 if (!Val.hasOneUse())
1730 return false;
1731 unsigned Opcode = Val->getOpcode();
1732 if (Opcode == ISD::SETCC) {
1733 if (Val->getOperand(0).getValueType() == MVT::f128)
1734 return false;
1735 CanNegate = true;
1736 MustBeFirst = false;
1737 return true;
1739 // Protect against exponential runtime and stack overflow.
1740 if (Depth > 6)
1741 return false;
1742 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1743 bool IsOR = Opcode == ISD::OR;
1744 SDValue O0 = Val->getOperand(0);
1745 SDValue O1 = Val->getOperand(1);
1746 bool CanNegateL;
1747 bool MustBeFirstL;
1748 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
1749 return false;
1750 bool CanNegateR;
1751 bool MustBeFirstR;
1752 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
1753 return false;
1755 if (MustBeFirstL && MustBeFirstR)
1756 return false;
1758 if (IsOR) {
1759 // For an OR expression we need to be able to naturally negate at least
1760 // one side or we cannot do the transformation at all.
1761 if (!CanNegateL && !CanNegateR)
1762 return false;
1763 // If we the result of the OR will be negated and we can naturally negate
1764 // the leafs, then this sub-tree as a whole negates naturally.
1765 CanNegate = WillNegate && CanNegateL && CanNegateR;
1766 // If we cannot naturally negate the whole sub-tree, then this must be
1767 // emitted first.
1768 MustBeFirst = !CanNegate;
1769 } else {
1770 assert(Opcode == ISD::AND && "Must be OR or AND");
1771 // We cannot naturally negate an AND operation.
1772 CanNegate = false;
1773 MustBeFirst = MustBeFirstL || MustBeFirstR;
1775 return true;
1777 return false;
1780 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1781 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1782 /// Tries to transform the given i1 producing node @p Val to a series compare
1783 /// and conditional compare operations. @returns an NZCV flags producing node
1784 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1785 /// transformation was not possible.
1786 /// \p Negate is true if we want this sub-tree being negated just by changing
1787 /// SETCC conditions.
1788 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
1789 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1790 AArch64CC::CondCode Predicate) {
1791 // We're at a tree leaf, produce a conditional comparison operation.
1792 unsigned Opcode = Val->getOpcode();
1793 if (Opcode == ISD::SETCC) {
1794 SDValue LHS = Val->getOperand(0);
1795 SDValue RHS = Val->getOperand(1);
1796 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1797 bool isInteger = LHS.getValueType().isInteger();
1798 if (Negate)
1799 CC = getSetCCInverse(CC, isInteger);
1800 SDLoc DL(Val);
1801 // Determine OutCC and handle FP special case.
1802 if (isInteger) {
1803 OutCC = changeIntCCToAArch64CC(CC);
1804 } else {
1805 assert(LHS.getValueType().isFloatingPoint());
1806 AArch64CC::CondCode ExtraCC;
1807 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1808 // Some floating point conditions can't be tested with a single condition
1809 // code. Construct an additional comparison in this case.
1810 if (ExtraCC != AArch64CC::AL) {
1811 SDValue ExtraCmp;
1812 if (!CCOp.getNode())
1813 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1814 else
1815 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1816 ExtraCC, DL, DAG);
1817 CCOp = ExtraCmp;
1818 Predicate = ExtraCC;
1822 // Produce a normal comparison if we are first in the chain
1823 if (!CCOp)
1824 return emitComparison(LHS, RHS, CC, DL, DAG);
1825 // Otherwise produce a ccmp.
1826 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1827 DAG);
1829 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
1831 bool IsOR = Opcode == ISD::OR;
1833 SDValue LHS = Val->getOperand(0);
1834 bool CanNegateL;
1835 bool MustBeFirstL;
1836 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
1837 assert(ValidL && "Valid conjunction/disjunction tree");
1838 (void)ValidL;
1840 SDValue RHS = Val->getOperand(1);
1841 bool CanNegateR;
1842 bool MustBeFirstR;
1843 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
1844 assert(ValidR && "Valid conjunction/disjunction tree");
1845 (void)ValidR;
1847 // Swap sub-tree that must come first to the right side.
1848 if (MustBeFirstL) {
1849 assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
1850 std::swap(LHS, RHS);
1851 std::swap(CanNegateL, CanNegateR);
1852 std::swap(MustBeFirstL, MustBeFirstR);
1855 bool NegateR;
1856 bool NegateAfterR;
1857 bool NegateL;
1858 bool NegateAfterAll;
1859 if (Opcode == ISD::OR) {
1860 // Swap the sub-tree that we can negate naturally to the left.
1861 if (!CanNegateL) {
1862 assert(CanNegateR && "at least one side must be negatable");
1863 assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
1864 assert(!Negate);
1865 std::swap(LHS, RHS);
1866 NegateR = false;
1867 NegateAfterR = true;
1868 } else {
1869 // Negate the left sub-tree if possible, otherwise negate the result.
1870 NegateR = CanNegateR;
1871 NegateAfterR = !CanNegateR;
1873 NegateL = true;
1874 NegateAfterAll = !Negate;
1875 } else {
1876 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
1877 assert(!Negate && "Valid conjunction/disjunction tree");
1879 NegateL = false;
1880 NegateR = false;
1881 NegateAfterR = false;
1882 NegateAfterAll = false;
1885 // Emit sub-trees.
1886 AArch64CC::CondCode RHSCC;
1887 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
1888 if (NegateAfterR)
1889 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1890 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
1891 if (NegateAfterAll)
1892 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1893 return CmpL;
1896 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1897 /// In some cases this is even possible with OR operations in the expression.
1898 /// See \ref AArch64CCMP.
1899 /// \see emitConjunctionRec().
1900 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
1901 AArch64CC::CondCode &OutCC) {
1902 bool DummyCanNegate;
1903 bool DummyMustBeFirst;
1904 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
1905 return SDValue();
1907 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
1910 /// @}
1912 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1913 /// extension operations.
1914 static unsigned getCmpOperandFoldingProfit(SDValue Op) {
1915 auto isSupportedExtend = [&](SDValue V) {
1916 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1917 return true;
1919 if (V.getOpcode() == ISD::AND)
1920 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1921 uint64_t Mask = MaskCst->getZExtValue();
1922 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1925 return false;
1928 if (!Op.hasOneUse())
1929 return 0;
1931 if (isSupportedExtend(Op))
1932 return 1;
1934 unsigned Opc = Op.getOpcode();
1935 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1936 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1937 uint64_t Shift = ShiftCst->getZExtValue();
1938 if (isSupportedExtend(Op.getOperand(0)))
1939 return (Shift <= 4) ? 2 : 1;
1940 EVT VT = Op.getValueType();
1941 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1942 return 1;
1945 return 0;
1948 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1949 SDValue &AArch64cc, SelectionDAG &DAG,
1950 const SDLoc &dl) {
1951 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1952 EVT VT = RHS.getValueType();
1953 uint64_t C = RHSC->getZExtValue();
1954 if (!isLegalArithImmed(C)) {
1955 // Constant does not fit, try adjusting it by one?
1956 switch (CC) {
1957 default:
1958 break;
1959 case ISD::SETLT:
1960 case ISD::SETGE:
1961 if ((VT == MVT::i32 && C != 0x80000000 &&
1962 isLegalArithImmed((uint32_t)(C - 1))) ||
1963 (VT == MVT::i64 && C != 0x80000000ULL &&
1964 isLegalArithImmed(C - 1ULL))) {
1965 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1966 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1967 RHS = DAG.getConstant(C, dl, VT);
1969 break;
1970 case ISD::SETULT:
1971 case ISD::SETUGE:
1972 if ((VT == MVT::i32 && C != 0 &&
1973 isLegalArithImmed((uint32_t)(C - 1))) ||
1974 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1975 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1976 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1977 RHS = DAG.getConstant(C, dl, VT);
1979 break;
1980 case ISD::SETLE:
1981 case ISD::SETGT:
1982 if ((VT == MVT::i32 && C != INT32_MAX &&
1983 isLegalArithImmed((uint32_t)(C + 1))) ||
1984 (VT == MVT::i64 && C != INT64_MAX &&
1985 isLegalArithImmed(C + 1ULL))) {
1986 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1987 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1988 RHS = DAG.getConstant(C, dl, VT);
1990 break;
1991 case ISD::SETULE:
1992 case ISD::SETUGT:
1993 if ((VT == MVT::i32 && C != UINT32_MAX &&
1994 isLegalArithImmed((uint32_t)(C + 1))) ||
1995 (VT == MVT::i64 && C != UINT64_MAX &&
1996 isLegalArithImmed(C + 1ULL))) {
1997 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1998 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1999 RHS = DAG.getConstant(C, dl, VT);
2001 break;
2006 // Comparisons are canonicalized so that the RHS operand is simpler than the
2007 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2008 // can fold some shift+extend operations on the RHS operand, so swap the
2009 // operands if that can be done.
2011 // For example:
2012 // lsl w13, w11, #1
2013 // cmp w13, w12
2014 // can be turned into:
2015 // cmp w12, w11, lsl #1
2016 if (!isa<ConstantSDNode>(RHS) ||
2017 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
2018 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
2020 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
2021 std::swap(LHS, RHS);
2022 CC = ISD::getSetCCSwappedOperands(CC);
2026 SDValue Cmp;
2027 AArch64CC::CondCode AArch64CC;
2028 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
2029 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
2031 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2032 // For the i8 operand, the largest immediate is 255, so this can be easily
2033 // encoded in the compare instruction. For the i16 operand, however, the
2034 // largest immediate cannot be encoded in the compare.
2035 // Therefore, use a sign extending load and cmn to avoid materializing the
2036 // -1 constant. For example,
2037 // movz w1, #65535
2038 // ldrh w0, [x0, #0]
2039 // cmp w0, w1
2040 // >
2041 // ldrsh w0, [x0, #0]
2042 // cmn w0, #1
2043 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2044 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2045 // ensure both the LHS and RHS are truly zero extended and to make sure the
2046 // transformation is profitable.
2047 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
2048 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
2049 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
2050 LHS.getNode()->hasNUsesOfValue(1, 0)) {
2051 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
2052 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
2053 SDValue SExt =
2054 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
2055 DAG.getValueType(MVT::i16));
2056 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
2057 RHS.getValueType()),
2058 CC, dl, DAG);
2059 AArch64CC = changeIntCCToAArch64CC(CC);
2063 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
2064 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
2065 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
2066 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
2071 if (!Cmp) {
2072 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2073 AArch64CC = changeIntCCToAArch64CC(CC);
2075 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
2076 return Cmp;
2079 static std::pair<SDValue, SDValue>
2080 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
2081 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
2082 "Unsupported value type");
2083 SDValue Value, Overflow;
2084 SDLoc DL(Op);
2085 SDValue LHS = Op.getOperand(0);
2086 SDValue RHS = Op.getOperand(1);
2087 unsigned Opc = 0;
2088 switch (Op.getOpcode()) {
2089 default:
2090 llvm_unreachable("Unknown overflow instruction!");
2091 case ISD::SADDO:
2092 Opc = AArch64ISD::ADDS;
2093 CC = AArch64CC::VS;
2094 break;
2095 case ISD::UADDO:
2096 Opc = AArch64ISD::ADDS;
2097 CC = AArch64CC::HS;
2098 break;
2099 case ISD::SSUBO:
2100 Opc = AArch64ISD::SUBS;
2101 CC = AArch64CC::VS;
2102 break;
2103 case ISD::USUBO:
2104 Opc = AArch64ISD::SUBS;
2105 CC = AArch64CC::LO;
2106 break;
2107 // Multiply needs a little bit extra work.
2108 case ISD::SMULO:
2109 case ISD::UMULO: {
2110 CC = AArch64CC::NE;
2111 bool IsSigned = Op.getOpcode() == ISD::SMULO;
2112 if (Op.getValueType() == MVT::i32) {
2113 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2114 // For a 32 bit multiply with overflow check we want the instruction
2115 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2116 // need to generate the following pattern:
2117 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2118 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
2119 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
2120 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2121 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
2122 DAG.getConstant(0, DL, MVT::i64));
2123 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2124 // operation. We need to clear out the upper 32 bits, because we used a
2125 // widening multiply that wrote all 64 bits. In the end this should be a
2126 // noop.
2127 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
2128 if (IsSigned) {
2129 // The signed overflow check requires more than just a simple check for
2130 // any bit set in the upper 32 bits of the result. These bits could be
2131 // just the sign bits of a negative number. To perform the overflow
2132 // check we have to arithmetic shift right the 32nd bit of the result by
2133 // 31 bits. Then we compare the result to the upper 32 bits.
2134 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
2135 DAG.getConstant(32, DL, MVT::i64));
2136 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
2137 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
2138 DAG.getConstant(31, DL, MVT::i64));
2139 // It is important that LowerBits is last, otherwise the arithmetic
2140 // shift will not be folded into the compare (SUBS).
2141 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2142 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2143 .getValue(1);
2144 } else {
2145 // The overflow check for unsigned multiply is easy. We only need to
2146 // check if any of the upper 32 bits are set. This can be done with a
2147 // CMP (shifted register). For that we need to generate the following
2148 // pattern:
2149 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2150 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2151 DAG.getConstant(32, DL, MVT::i64));
2152 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2153 Overflow =
2154 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2155 DAG.getConstant(0, DL, MVT::i64),
2156 UpperBits).getValue(1);
2158 break;
2160 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2161 // For the 64 bit multiply
2162 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2163 if (IsSigned) {
2164 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2165 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2166 DAG.getConstant(63, DL, MVT::i64));
2167 // It is important that LowerBits is last, otherwise the arithmetic
2168 // shift will not be folded into the compare (SUBS).
2169 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2170 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2171 .getValue(1);
2172 } else {
2173 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2174 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2175 Overflow =
2176 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2177 DAG.getConstant(0, DL, MVT::i64),
2178 UpperBits).getValue(1);
2180 break;
2182 } // switch (...)
2184 if (Opc) {
2185 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2187 // Emit the AArch64 operation with overflow check.
2188 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2189 Overflow = Value.getValue(1);
2191 return std::make_pair(Value, Overflow);
2194 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2195 RTLIB::Libcall Call) const {
2196 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2197 MakeLibCallOptions CallOptions;
2198 return makeLibCall(DAG, Call, MVT::f128, Ops, CallOptions, SDLoc(Op)).first;
2201 // Returns true if the given Op is the overflow flag result of an overflow
2202 // intrinsic operation.
2203 static bool isOverflowIntrOpRes(SDValue Op) {
2204 unsigned Opc = Op.getOpcode();
2205 return (Op.getResNo() == 1 &&
2206 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2207 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2210 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
2211 SDValue Sel = Op.getOperand(0);
2212 SDValue Other = Op.getOperand(1);
2213 SDLoc dl(Sel);
2215 // If the operand is an overflow checking operation, invert the condition
2216 // code and kill the Not operation. I.e., transform:
2217 // (xor (overflow_op_bool, 1))
2218 // -->
2219 // (csel 1, 0, invert(cc), overflow_op_bool)
2220 // ... which later gets transformed to just a cset instruction with an
2221 // inverted condition code, rather than a cset + eor sequence.
2222 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2223 // Only lower legal XALUO ops.
2224 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2225 return SDValue();
2227 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2228 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2229 AArch64CC::CondCode CC;
2230 SDValue Value, Overflow;
2231 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2232 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2233 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2234 CCVal, Overflow);
2236 // If neither operand is a SELECT_CC, give up.
2237 if (Sel.getOpcode() != ISD::SELECT_CC)
2238 std::swap(Sel, Other);
2239 if (Sel.getOpcode() != ISD::SELECT_CC)
2240 return Op;
2242 // The folding we want to perform is:
2243 // (xor x, (select_cc a, b, cc, 0, -1) )
2244 // -->
2245 // (csel x, (xor x, -1), cc ...)
2247 // The latter will get matched to a CSINV instruction.
2249 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2250 SDValue LHS = Sel.getOperand(0);
2251 SDValue RHS = Sel.getOperand(1);
2252 SDValue TVal = Sel.getOperand(2);
2253 SDValue FVal = Sel.getOperand(3);
2255 // FIXME: This could be generalized to non-integer comparisons.
2256 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2257 return Op;
2259 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2260 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2262 // The values aren't constants, this isn't the pattern we're looking for.
2263 if (!CFVal || !CTVal)
2264 return Op;
2266 // We can commute the SELECT_CC by inverting the condition. This
2267 // might be needed to make this fit into a CSINV pattern.
2268 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2269 std::swap(TVal, FVal);
2270 std::swap(CTVal, CFVal);
2271 CC = ISD::getSetCCInverse(CC, true);
2274 // If the constants line up, perform the transform!
2275 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2276 SDValue CCVal;
2277 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2279 FVal = Other;
2280 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2281 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2283 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2284 CCVal, Cmp);
2287 return Op;
2290 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2291 EVT VT = Op.getValueType();
2293 // Let legalize expand this if it isn't a legal type yet.
2294 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2295 return SDValue();
2297 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2299 unsigned Opc;
2300 bool ExtraOp = false;
2301 switch (Op.getOpcode()) {
2302 default:
2303 llvm_unreachable("Invalid code");
2304 case ISD::ADDC:
2305 Opc = AArch64ISD::ADDS;
2306 break;
2307 case ISD::SUBC:
2308 Opc = AArch64ISD::SUBS;
2309 break;
2310 case ISD::ADDE:
2311 Opc = AArch64ISD::ADCS;
2312 ExtraOp = true;
2313 break;
2314 case ISD::SUBE:
2315 Opc = AArch64ISD::SBCS;
2316 ExtraOp = true;
2317 break;
2320 if (!ExtraOp)
2321 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2322 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2323 Op.getOperand(2));
2326 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2327 // Let legalize expand this if it isn't a legal type yet.
2328 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2329 return SDValue();
2331 SDLoc dl(Op);
2332 AArch64CC::CondCode CC;
2333 // The actual operation that sets the overflow or carry flag.
2334 SDValue Value, Overflow;
2335 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2337 // We use 0 and 1 as false and true values.
2338 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2339 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2341 // We use an inverted condition, because the conditional select is inverted
2342 // too. This will allow it to be selected to a single instruction:
2343 // CSINC Wd, WZR, WZR, invert(cond).
2344 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2345 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2346 CCVal, Overflow);
2348 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2349 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2352 // Prefetch operands are:
2353 // 1: Address to prefetch
2354 // 2: bool isWrite
2355 // 3: int locality (0 = no locality ... 3 = extreme locality)
2356 // 4: bool isDataCache
2357 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2358 SDLoc DL(Op);
2359 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2360 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2361 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2363 bool IsStream = !Locality;
2364 // When the locality number is set
2365 if (Locality) {
2366 // The front-end should have filtered out the out-of-range values
2367 assert(Locality <= 3 && "Prefetch locality out-of-range");
2368 // The locality degree is the opposite of the cache speed.
2369 // Put the number the other way around.
2370 // The encoding starts at 0 for level 1
2371 Locality = 3 - Locality;
2374 // built the mask value encoding the expected behavior.
2375 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2376 (!IsData << 3) | // IsDataCache bit
2377 (Locality << 1) | // Cache level bits
2378 (unsigned)IsStream; // Stream bit
2379 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2380 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2383 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2384 SelectionDAG &DAG) const {
2385 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2387 RTLIB::Libcall LC;
2388 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2390 return LowerF128Call(Op, DAG, LC);
2393 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2394 SelectionDAG &DAG) const {
2395 if (Op.getOperand(0).getValueType() != MVT::f128) {
2396 // It's legal except when f128 is involved
2397 return Op;
2400 RTLIB::Libcall LC;
2401 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2403 // FP_ROUND node has a second operand indicating whether it is known to be
2404 // precise. That doesn't take part in the LibCall so we can't directly use
2405 // LowerF128Call.
2406 SDValue SrcVal = Op.getOperand(0);
2407 MakeLibCallOptions CallOptions;
2408 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, CallOptions,
2409 SDLoc(Op)).first;
2412 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
2413 SelectionDAG &DAG) const {
2414 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2415 // Any additional optimization in this function should be recorded
2416 // in the cost tables.
2417 EVT InVT = Op.getOperand(0).getValueType();
2418 EVT VT = Op.getValueType();
2419 unsigned NumElts = InVT.getVectorNumElements();
2421 // f16 conversions are promoted to f32 when full fp16 is not supported.
2422 if (InVT.getVectorElementType() == MVT::f16 &&
2423 !Subtarget->hasFullFP16()) {
2424 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2425 SDLoc dl(Op);
2426 return DAG.getNode(
2427 Op.getOpcode(), dl, Op.getValueType(),
2428 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2431 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2432 SDLoc dl(Op);
2433 SDValue Cv =
2434 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2435 Op.getOperand(0));
2436 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2439 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2440 SDLoc dl(Op);
2441 MVT ExtVT =
2442 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2443 VT.getVectorNumElements());
2444 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2445 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2448 // Type changing conversions are illegal.
2449 return Op;
2452 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2453 SelectionDAG &DAG) const {
2454 if (Op.getOperand(0).getValueType().isVector())
2455 return LowerVectorFP_TO_INT(Op, DAG);
2457 // f16 conversions are promoted to f32 when full fp16 is not supported.
2458 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2459 !Subtarget->hasFullFP16()) {
2460 SDLoc dl(Op);
2461 return DAG.getNode(
2462 Op.getOpcode(), dl, Op.getValueType(),
2463 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2466 if (Op.getOperand(0).getValueType() != MVT::f128) {
2467 // It's legal except when f128 is involved
2468 return Op;
2471 RTLIB::Libcall LC;
2472 if (Op.getOpcode() == ISD::FP_TO_SINT)
2473 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2474 else
2475 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2477 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2478 MakeLibCallOptions CallOptions;
2479 return makeLibCall(DAG, LC, Op.getValueType(), Ops, CallOptions, SDLoc(Op)).first;
2482 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2483 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2484 // Any additional optimization in this function should be recorded
2485 // in the cost tables.
2486 EVT VT = Op.getValueType();
2487 SDLoc dl(Op);
2488 SDValue In = Op.getOperand(0);
2489 EVT InVT = In.getValueType();
2491 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2492 MVT CastVT =
2493 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2494 InVT.getVectorNumElements());
2495 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2496 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2499 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2500 unsigned CastOpc =
2501 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2502 EVT CastVT = VT.changeVectorElementTypeToInteger();
2503 In = DAG.getNode(CastOpc, dl, CastVT, In);
2504 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2507 return Op;
2510 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2511 SelectionDAG &DAG) const {
2512 if (Op.getValueType().isVector())
2513 return LowerVectorINT_TO_FP(Op, DAG);
2515 // f16 conversions are promoted to f32 when full fp16 is not supported.
2516 if (Op.getValueType() == MVT::f16 &&
2517 !Subtarget->hasFullFP16()) {
2518 SDLoc dl(Op);
2519 return DAG.getNode(
2520 ISD::FP_ROUND, dl, MVT::f16,
2521 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2522 DAG.getIntPtrConstant(0, dl));
2525 // i128 conversions are libcalls.
2526 if (Op.getOperand(0).getValueType() == MVT::i128)
2527 return SDValue();
2529 // Other conversions are legal, unless it's to the completely software-based
2530 // fp128.
2531 if (Op.getValueType() != MVT::f128)
2532 return Op;
2534 RTLIB::Libcall LC;
2535 if (Op.getOpcode() == ISD::SINT_TO_FP)
2536 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2537 else
2538 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2540 return LowerF128Call(Op, DAG, LC);
2543 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 // For iOS, we want to call an alternative entry point: __sincos_stret,
2546 // which returns the values in two S / D registers.
2547 SDLoc dl(Op);
2548 SDValue Arg = Op.getOperand(0);
2549 EVT ArgVT = Arg.getValueType();
2550 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2552 ArgListTy Args;
2553 ArgListEntry Entry;
2555 Entry.Node = Arg;
2556 Entry.Ty = ArgTy;
2557 Entry.IsSExt = false;
2558 Entry.IsZExt = false;
2559 Args.push_back(Entry);
2561 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2562 : RTLIB::SINCOS_STRET_F32;
2563 const char *LibcallName = getLibcallName(LC);
2564 SDValue Callee =
2565 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2567 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2568 TargetLowering::CallLoweringInfo CLI(DAG);
2569 CLI.setDebugLoc(dl)
2570 .setChain(DAG.getEntryNode())
2571 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2573 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2574 return CallResult.first;
2577 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2578 if (Op.getValueType() != MVT::f16)
2579 return SDValue();
2581 assert(Op.getOperand(0).getValueType() == MVT::i16);
2582 SDLoc DL(Op);
2584 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2585 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2586 return SDValue(
2587 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2588 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2592 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2593 if (OrigVT.getSizeInBits() >= 64)
2594 return OrigVT;
2596 assert(OrigVT.isSimple() && "Expecting a simple value type");
2598 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2599 switch (OrigSimpleTy) {
2600 default: llvm_unreachable("Unexpected Vector Type");
2601 case MVT::v2i8:
2602 case MVT::v2i16:
2603 return MVT::v2i32;
2604 case MVT::v4i8:
2605 return MVT::v4i16;
2609 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2610 const EVT &OrigTy,
2611 const EVT &ExtTy,
2612 unsigned ExtOpcode) {
2613 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2614 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2615 // 64-bits we need to insert a new extension so that it will be 64-bits.
2616 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2617 if (OrigTy.getSizeInBits() >= 64)
2618 return N;
2620 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2621 EVT NewVT = getExtensionTo64Bits(OrigTy);
2623 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2626 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2627 bool isSigned) {
2628 EVT VT = N->getValueType(0);
2630 if (N->getOpcode() != ISD::BUILD_VECTOR)
2631 return false;
2633 for (const SDValue &Elt : N->op_values()) {
2634 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2635 unsigned EltSize = VT.getScalarSizeInBits();
2636 unsigned HalfSize = EltSize / 2;
2637 if (isSigned) {
2638 if (!isIntN(HalfSize, C->getSExtValue()))
2639 return false;
2640 } else {
2641 if (!isUIntN(HalfSize, C->getZExtValue()))
2642 return false;
2644 continue;
2646 return false;
2649 return true;
2652 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2653 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2654 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2655 N->getOperand(0)->getValueType(0),
2656 N->getValueType(0),
2657 N->getOpcode());
2659 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2660 EVT VT = N->getValueType(0);
2661 SDLoc dl(N);
2662 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2663 unsigned NumElts = VT.getVectorNumElements();
2664 MVT TruncVT = MVT::getIntegerVT(EltSize);
2665 SmallVector<SDValue, 8> Ops;
2666 for (unsigned i = 0; i != NumElts; ++i) {
2667 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2668 const APInt &CInt = C->getAPIntValue();
2669 // Element types smaller than 32 bits are not legal, so use i32 elements.
2670 // The values are implicitly truncated so sext vs. zext doesn't matter.
2671 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2673 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2676 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2677 return N->getOpcode() == ISD::SIGN_EXTEND ||
2678 isExtendedBUILD_VECTOR(N, DAG, true);
2681 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2682 return N->getOpcode() == ISD::ZERO_EXTEND ||
2683 isExtendedBUILD_VECTOR(N, DAG, false);
2686 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2687 unsigned Opcode = N->getOpcode();
2688 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2689 SDNode *N0 = N->getOperand(0).getNode();
2690 SDNode *N1 = N->getOperand(1).getNode();
2691 return N0->hasOneUse() && N1->hasOneUse() &&
2692 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2694 return false;
2697 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2698 unsigned Opcode = N->getOpcode();
2699 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2700 SDNode *N0 = N->getOperand(0).getNode();
2701 SDNode *N1 = N->getOperand(1).getNode();
2702 return N0->hasOneUse() && N1->hasOneUse() &&
2703 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2705 return false;
2708 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2709 SelectionDAG &DAG) const {
2710 // The rounding mode is in bits 23:22 of the FPSCR.
2711 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2712 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2713 // so that the shift + and get folded into a bitfield extract.
2714 SDLoc dl(Op);
2716 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2717 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2718 MVT::i64));
2719 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2720 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2721 DAG.getConstant(1U << 22, dl, MVT::i32));
2722 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2723 DAG.getConstant(22, dl, MVT::i32));
2724 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2725 DAG.getConstant(3, dl, MVT::i32));
2728 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2729 // Multiplications are only custom-lowered for 128-bit vectors so that
2730 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2731 EVT VT = Op.getValueType();
2732 assert(VT.is128BitVector() && VT.isInteger() &&
2733 "unexpected type for custom-lowering ISD::MUL");
2734 SDNode *N0 = Op.getOperand(0).getNode();
2735 SDNode *N1 = Op.getOperand(1).getNode();
2736 unsigned NewOpc = 0;
2737 bool isMLA = false;
2738 bool isN0SExt = isSignExtended(N0, DAG);
2739 bool isN1SExt = isSignExtended(N1, DAG);
2740 if (isN0SExt && isN1SExt)
2741 NewOpc = AArch64ISD::SMULL;
2742 else {
2743 bool isN0ZExt = isZeroExtended(N0, DAG);
2744 bool isN1ZExt = isZeroExtended(N1, DAG);
2745 if (isN0ZExt && isN1ZExt)
2746 NewOpc = AArch64ISD::UMULL;
2747 else if (isN1SExt || isN1ZExt) {
2748 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2749 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2750 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2751 NewOpc = AArch64ISD::SMULL;
2752 isMLA = true;
2753 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2754 NewOpc = AArch64ISD::UMULL;
2755 isMLA = true;
2756 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2757 std::swap(N0, N1);
2758 NewOpc = AArch64ISD::UMULL;
2759 isMLA = true;
2763 if (!NewOpc) {
2764 if (VT == MVT::v2i64)
2765 // Fall through to expand this. It is not legal.
2766 return SDValue();
2767 else
2768 // Other vector multiplications are legal.
2769 return Op;
2773 // Legalize to a S/UMULL instruction
2774 SDLoc DL(Op);
2775 SDValue Op0;
2776 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2777 if (!isMLA) {
2778 Op0 = skipExtensionForVectorMULL(N0, DAG);
2779 assert(Op0.getValueType().is64BitVector() &&
2780 Op1.getValueType().is64BitVector() &&
2781 "unexpected types for extended operands to VMULL");
2782 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2784 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2785 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2786 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2787 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2788 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2789 EVT Op1VT = Op1.getValueType();
2790 return DAG.getNode(N0->getOpcode(), DL, VT,
2791 DAG.getNode(NewOpc, DL, VT,
2792 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2793 DAG.getNode(NewOpc, DL, VT,
2794 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2797 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2798 SelectionDAG &DAG) const {
2799 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2800 SDLoc dl(Op);
2801 switch (IntNo) {
2802 default: return SDValue(); // Don't custom lower most intrinsics.
2803 case Intrinsic::thread_pointer: {
2804 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2805 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2807 case Intrinsic::aarch64_neon_abs: {
2808 EVT Ty = Op.getValueType();
2809 if (Ty == MVT::i64) {
2810 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
2811 Op.getOperand(1));
2812 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
2813 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
2814 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
2815 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
2816 } else {
2817 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2820 case Intrinsic::aarch64_neon_smax:
2821 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2822 Op.getOperand(1), Op.getOperand(2));
2823 case Intrinsic::aarch64_neon_umax:
2824 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2825 Op.getOperand(1), Op.getOperand(2));
2826 case Intrinsic::aarch64_neon_smin:
2827 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2828 Op.getOperand(1), Op.getOperand(2));
2829 case Intrinsic::aarch64_neon_umin:
2830 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2831 Op.getOperand(1), Op.getOperand(2));
2833 case Intrinsic::localaddress: {
2834 const auto &MF = DAG.getMachineFunction();
2835 const auto *RegInfo = Subtarget->getRegisterInfo();
2836 unsigned Reg = RegInfo->getLocalAddressRegister(MF);
2837 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
2838 Op.getSimpleValueType());
2841 case Intrinsic::eh_recoverfp: {
2842 // FIXME: This needs to be implemented to correctly handle highly aligned
2843 // stack objects. For now we simply return the incoming FP. Refer D53541
2844 // for more details.
2845 SDValue FnOp = Op.getOperand(1);
2846 SDValue IncomingFPOp = Op.getOperand(2);
2847 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
2848 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
2849 if (!Fn)
2850 report_fatal_error(
2851 "llvm.eh.recoverfp must take a function as the first argument");
2852 return IncomingFPOp;
2857 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2858 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
2859 EVT VT, EVT MemVT,
2860 SelectionDAG &DAG) {
2861 assert(VT.isVector() && "VT should be a vector type");
2862 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2864 SDValue Value = ST->getValue();
2866 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2867 // the word lane which represent the v4i8 subvector. It optimizes the store
2868 // to:
2870 // xtn v0.8b, v0.8h
2871 // str s0, [x0]
2873 SDValue Undef = DAG.getUNDEF(MVT::i16);
2874 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2875 {Undef, Undef, Undef, Undef});
2877 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2878 Value, UndefVec);
2879 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2881 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2882 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2883 Trunc, DAG.getConstant(0, DL, MVT::i64));
2885 return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2886 ST->getBasePtr(), ST->getMemOperand());
2889 // Custom lowering for any store, vector or scalar and/or default or with
2890 // a truncate operations. Currently only custom lower truncate operation
2891 // from vector v4i16 to v4i8.
2892 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2893 SelectionDAG &DAG) const {
2894 SDLoc Dl(Op);
2895 StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2896 assert (StoreNode && "Can only custom lower store nodes");
2898 SDValue Value = StoreNode->getValue();
2900 EVT VT = Value.getValueType();
2901 EVT MemVT = StoreNode->getMemoryVT();
2903 assert (VT.isVector() && "Can only custom lower vector store types");
2905 unsigned AS = StoreNode->getAddressSpace();
2906 unsigned Align = StoreNode->getAlignment();
2907 if (Align < MemVT.getStoreSize() &&
2908 !allowsMisalignedMemoryAccesses(
2909 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) {
2910 return scalarizeVectorStore(StoreNode, DAG);
2913 if (StoreNode->isTruncatingStore()) {
2914 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2917 return SDValue();
2920 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2921 SelectionDAG &DAG) const {
2922 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2923 LLVM_DEBUG(Op.dump());
2925 switch (Op.getOpcode()) {
2926 default:
2927 llvm_unreachable("unimplemented operand");
2928 return SDValue();
2929 case ISD::BITCAST:
2930 return LowerBITCAST(Op, DAG);
2931 case ISD::GlobalAddress:
2932 return LowerGlobalAddress(Op, DAG);
2933 case ISD::GlobalTLSAddress:
2934 return LowerGlobalTLSAddress(Op, DAG);
2935 case ISD::SETCC:
2936 return LowerSETCC(Op, DAG);
2937 case ISD::BR_CC:
2938 return LowerBR_CC(Op, DAG);
2939 case ISD::SELECT:
2940 return LowerSELECT(Op, DAG);
2941 case ISD::SELECT_CC:
2942 return LowerSELECT_CC(Op, DAG);
2943 case ISD::JumpTable:
2944 return LowerJumpTable(Op, DAG);
2945 case ISD::BR_JT:
2946 return LowerBR_JT(Op, DAG);
2947 case ISD::ConstantPool:
2948 return LowerConstantPool(Op, DAG);
2949 case ISD::BlockAddress:
2950 return LowerBlockAddress(Op, DAG);
2951 case ISD::VASTART:
2952 return LowerVASTART(Op, DAG);
2953 case ISD::VACOPY:
2954 return LowerVACOPY(Op, DAG);
2955 case ISD::VAARG:
2956 return LowerVAARG(Op, DAG);
2957 case ISD::ADDC:
2958 case ISD::ADDE:
2959 case ISD::SUBC:
2960 case ISD::SUBE:
2961 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2962 case ISD::SADDO:
2963 case ISD::UADDO:
2964 case ISD::SSUBO:
2965 case ISD::USUBO:
2966 case ISD::SMULO:
2967 case ISD::UMULO:
2968 return LowerXALUO(Op, DAG);
2969 case ISD::FADD:
2970 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2971 case ISD::FSUB:
2972 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2973 case ISD::FMUL:
2974 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2975 case ISD::FDIV:
2976 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2977 case ISD::FP_ROUND:
2978 return LowerFP_ROUND(Op, DAG);
2979 case ISD::FP_EXTEND:
2980 return LowerFP_EXTEND(Op, DAG);
2981 case ISD::FRAMEADDR:
2982 return LowerFRAMEADDR(Op, DAG);
2983 case ISD::SPONENTRY:
2984 return LowerSPONENTRY(Op, DAG);
2985 case ISD::RETURNADDR:
2986 return LowerRETURNADDR(Op, DAG);
2987 case ISD::ADDROFRETURNADDR:
2988 return LowerADDROFRETURNADDR(Op, DAG);
2989 case ISD::INSERT_VECTOR_ELT:
2990 return LowerINSERT_VECTOR_ELT(Op, DAG);
2991 case ISD::EXTRACT_VECTOR_ELT:
2992 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2993 case ISD::BUILD_VECTOR:
2994 return LowerBUILD_VECTOR(Op, DAG);
2995 case ISD::VECTOR_SHUFFLE:
2996 return LowerVECTOR_SHUFFLE(Op, DAG);
2997 case ISD::EXTRACT_SUBVECTOR:
2998 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2999 case ISD::SRA:
3000 case ISD::SRL:
3001 case ISD::SHL:
3002 return LowerVectorSRA_SRL_SHL(Op, DAG);
3003 case ISD::SHL_PARTS:
3004 return LowerShiftLeftParts(Op, DAG);
3005 case ISD::SRL_PARTS:
3006 case ISD::SRA_PARTS:
3007 return LowerShiftRightParts(Op, DAG);
3008 case ISD::CTPOP:
3009 return LowerCTPOP(Op, DAG);
3010 case ISD::FCOPYSIGN:
3011 return LowerFCOPYSIGN(Op, DAG);
3012 case ISD::OR:
3013 return LowerVectorOR(Op, DAG);
3014 case ISD::XOR:
3015 return LowerXOR(Op, DAG);
3016 case ISD::PREFETCH:
3017 return LowerPREFETCH(Op, DAG);
3018 case ISD::SINT_TO_FP:
3019 case ISD::UINT_TO_FP:
3020 return LowerINT_TO_FP(Op, DAG);
3021 case ISD::FP_TO_SINT:
3022 case ISD::FP_TO_UINT:
3023 return LowerFP_TO_INT(Op, DAG);
3024 case ISD::FSINCOS:
3025 return LowerFSINCOS(Op, DAG);
3026 case ISD::FLT_ROUNDS_:
3027 return LowerFLT_ROUNDS_(Op, DAG);
3028 case ISD::MUL:
3029 return LowerMUL(Op, DAG);
3030 case ISD::INTRINSIC_WO_CHAIN:
3031 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3032 case ISD::STORE:
3033 return LowerSTORE(Op, DAG);
3034 case ISD::VECREDUCE_ADD:
3035 case ISD::VECREDUCE_SMAX:
3036 case ISD::VECREDUCE_SMIN:
3037 case ISD::VECREDUCE_UMAX:
3038 case ISD::VECREDUCE_UMIN:
3039 case ISD::VECREDUCE_FMAX:
3040 case ISD::VECREDUCE_FMIN:
3041 return LowerVECREDUCE(Op, DAG);
3042 case ISD::ATOMIC_LOAD_SUB:
3043 return LowerATOMIC_LOAD_SUB(Op, DAG);
3044 case ISD::ATOMIC_LOAD_AND:
3045 return LowerATOMIC_LOAD_AND(Op, DAG);
3046 case ISD::DYNAMIC_STACKALLOC:
3047 return LowerDYNAMIC_STACKALLOC(Op, DAG);
3051 //===----------------------------------------------------------------------===//
3052 // Calling Convention Implementation
3053 //===----------------------------------------------------------------------===//
3055 /// Selects the correct CCAssignFn for a given CallingConvention value.
3056 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
3057 bool IsVarArg) const {
3058 switch (CC) {
3059 default:
3060 report_fatal_error("Unsupported calling convention.");
3061 case CallingConv::WebKit_JS:
3062 return CC_AArch64_WebKit_JS;
3063 case CallingConv::GHC:
3064 return CC_AArch64_GHC;
3065 case CallingConv::C:
3066 case CallingConv::Fast:
3067 case CallingConv::PreserveMost:
3068 case CallingConv::CXX_FAST_TLS:
3069 case CallingConv::Swift:
3070 if (Subtarget->isTargetWindows() && IsVarArg)
3071 return CC_AArch64_Win64_VarArg;
3072 if (!Subtarget->isTargetDarwin())
3073 return CC_AArch64_AAPCS;
3074 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
3075 case CallingConv::Win64:
3076 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
3077 case CallingConv::AArch64_VectorCall:
3078 return CC_AArch64_AAPCS;
3082 CCAssignFn *
3083 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
3084 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3085 : RetCC_AArch64_AAPCS;
3088 SDValue AArch64TargetLowering::LowerFormalArguments(
3089 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3090 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3091 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3092 MachineFunction &MF = DAG.getMachineFunction();
3093 MachineFrameInfo &MFI = MF.getFrameInfo();
3094 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3096 // Assign locations to all of the incoming arguments.
3097 SmallVector<CCValAssign, 16> ArgLocs;
3098 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3099 *DAG.getContext());
3101 // At this point, Ins[].VT may already be promoted to i32. To correctly
3102 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3103 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3104 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3105 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3106 // LocVT.
3107 unsigned NumArgs = Ins.size();
3108 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3109 unsigned CurArgIdx = 0;
3110 for (unsigned i = 0; i != NumArgs; ++i) {
3111 MVT ValVT = Ins[i].VT;
3112 if (Ins[i].isOrigArg()) {
3113 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3114 CurArgIdx = Ins[i].getOrigArgIndex();
3116 // Get type of the original argument.
3117 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3118 /*AllowUnknown*/ true);
3119 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3120 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3121 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3122 ValVT = MVT::i8;
3123 else if (ActualMVT == MVT::i16)
3124 ValVT = MVT::i16;
3126 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3127 bool Res =
3128 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3129 assert(!Res && "Call operand has unhandled type");
3130 (void)Res;
3132 assert(ArgLocs.size() == Ins.size());
3133 SmallVector<SDValue, 16> ArgValues;
3134 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3135 CCValAssign &VA = ArgLocs[i];
3137 if (Ins[i].Flags.isByVal()) {
3138 // Byval is used for HFAs in the PCS, but the system should work in a
3139 // non-compliant manner for larger structs.
3140 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3141 int Size = Ins[i].Flags.getByValSize();
3142 unsigned NumRegs = (Size + 7) / 8;
3144 // FIXME: This works on big-endian for composite byvals, which are the common
3145 // case. It should also work for fundamental types too.
3146 unsigned FrameIdx =
3147 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3148 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3149 InVals.push_back(FrameIdxN);
3151 continue;
3154 if (VA.isRegLoc()) {
3155 // Arguments stored in registers.
3156 EVT RegVT = VA.getLocVT();
3158 SDValue ArgValue;
3159 const TargetRegisterClass *RC;
3161 if (RegVT == MVT::i32)
3162 RC = &AArch64::GPR32RegClass;
3163 else if (RegVT == MVT::i64)
3164 RC = &AArch64::GPR64RegClass;
3165 else if (RegVT == MVT::f16)
3166 RC = &AArch64::FPR16RegClass;
3167 else if (RegVT == MVT::f32)
3168 RC = &AArch64::FPR32RegClass;
3169 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3170 RC = &AArch64::FPR64RegClass;
3171 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3172 RC = &AArch64::FPR128RegClass;
3173 else if (RegVT.isScalableVector() &&
3174 RegVT.getVectorElementType() == MVT::i1)
3175 RC = &AArch64::PPRRegClass;
3176 else if (RegVT.isScalableVector())
3177 RC = &AArch64::ZPRRegClass;
3178 else
3179 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3181 // Transform the arguments in physical registers into virtual ones.
3182 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3183 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3185 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3186 // to 64 bits. Insert an assert[sz]ext to capture this, then
3187 // truncate to the right size.
3188 switch (VA.getLocInfo()) {
3189 default:
3190 llvm_unreachable("Unknown loc info!");
3191 case CCValAssign::Full:
3192 break;
3193 case CCValAssign::Indirect:
3194 assert(VA.getValVT().isScalableVector() &&
3195 "Only scalable vectors can be passed indirectly");
3196 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3197 case CCValAssign::BCvt:
3198 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3199 break;
3200 case CCValAssign::AExt:
3201 case CCValAssign::SExt:
3202 case CCValAssign::ZExt:
3203 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3204 // nodes after our lowering.
3205 assert(RegVT == Ins[i].VT && "incorrect register location selected");
3206 break;
3209 InVals.push_back(ArgValue);
3211 } else { // VA.isRegLoc()
3212 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3213 unsigned ArgOffset = VA.getLocMemOffset();
3214 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3216 uint32_t BEAlign = 0;
3217 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3218 !Ins[i].Flags.isInConsecutiveRegs())
3219 BEAlign = 8 - ArgSize;
3221 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3223 // Create load nodes to retrieve arguments from the stack.
3224 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3225 SDValue ArgValue;
3227 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3228 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3229 MVT MemVT = VA.getValVT();
3231 switch (VA.getLocInfo()) {
3232 default:
3233 break;
3234 case CCValAssign::BCvt:
3235 MemVT = VA.getLocVT();
3236 break;
3237 case CCValAssign::Indirect:
3238 assert(VA.getValVT().isScalableVector() &&
3239 "Only scalable vectors can be passed indirectly");
3240 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3241 case CCValAssign::SExt:
3242 ExtType = ISD::SEXTLOAD;
3243 break;
3244 case CCValAssign::ZExt:
3245 ExtType = ISD::ZEXTLOAD;
3246 break;
3247 case CCValAssign::AExt:
3248 ExtType = ISD::EXTLOAD;
3249 break;
3252 ArgValue = DAG.getExtLoad(
3253 ExtType, DL, VA.getLocVT(), Chain, FIN,
3254 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3255 MemVT);
3257 InVals.push_back(ArgValue);
3261 // varargs
3262 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3263 if (isVarArg) {
3264 if (!Subtarget->isTargetDarwin() || IsWin64) {
3265 // The AAPCS variadic function ABI is identical to the non-variadic
3266 // one. As a result there may be more arguments in registers and we should
3267 // save them for future reference.
3268 // Win64 variadic functions also pass arguments in registers, but all float
3269 // arguments are passed in integer registers.
3270 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3273 // This will point to the next argument passed via stack.
3274 unsigned StackOffset = CCInfo.getNextStackOffset();
3275 // We currently pass all varargs at 8-byte alignment.
3276 StackOffset = ((StackOffset + 7) & ~7);
3277 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3279 if (MFI.hasMustTailInVarArgFunc()) {
3280 SmallVector<MVT, 2> RegParmTypes;
3281 RegParmTypes.push_back(MVT::i64);
3282 RegParmTypes.push_back(MVT::f128);
3283 // Compute the set of forwarded registers. The rest are scratch.
3284 SmallVectorImpl<ForwardedRegister> &Forwards =
3285 FuncInfo->getForwardedMustTailRegParms();
3286 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
3287 CC_AArch64_AAPCS);
3289 // Conservatively forward X8, since it might be used for aggregate return.
3290 if (!CCInfo.isAllocated(AArch64::X8)) {
3291 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
3292 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
3297 // On Windows, InReg pointers must be returned, so record the pointer in a
3298 // virtual register at the start of the function so it can be returned in the
3299 // epilogue.
3300 if (IsWin64) {
3301 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3302 if (Ins[I].Flags.isInReg()) {
3303 assert(!FuncInfo->getSRetReturnReg());
3305 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3306 Register Reg =
3307 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3308 FuncInfo->setSRetReturnReg(Reg);
3310 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
3311 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3312 break;
3317 unsigned StackArgSize = CCInfo.getNextStackOffset();
3318 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3319 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3320 // This is a non-standard ABI so by fiat I say we're allowed to make full
3321 // use of the stack area to be popped, which must be aligned to 16 bytes in
3322 // any case:
3323 StackArgSize = alignTo(StackArgSize, 16);
3325 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3326 // a multiple of 16.
3327 FuncInfo->setArgumentStackToRestore(StackArgSize);
3329 // This realignment carries over to the available bytes below. Our own
3330 // callers will guarantee the space is free by giving an aligned value to
3331 // CALLSEQ_START.
3333 // Even if we're not expected to free up the space, it's useful to know how
3334 // much is there while considering tail calls (because we can reuse it).
3335 FuncInfo->setBytesInStackArgArea(StackArgSize);
3337 if (Subtarget->hasCustomCallingConv())
3338 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3340 return Chain;
3343 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3344 SelectionDAG &DAG,
3345 const SDLoc &DL,
3346 SDValue &Chain) const {
3347 MachineFunction &MF = DAG.getMachineFunction();
3348 MachineFrameInfo &MFI = MF.getFrameInfo();
3349 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3350 auto PtrVT = getPointerTy(DAG.getDataLayout());
3351 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3353 SmallVector<SDValue, 8> MemOps;
3355 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3356 AArch64::X3, AArch64::X4, AArch64::X5,
3357 AArch64::X6, AArch64::X7 };
3358 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3359 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3361 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3362 int GPRIdx = 0;
3363 if (GPRSaveSize != 0) {
3364 if (IsWin64) {
3365 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3366 if (GPRSaveSize & 15)
3367 // The extra size here, if triggered, will always be 8.
3368 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3369 } else
3370 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3372 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3374 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3375 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3376 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3377 SDValue Store = DAG.getStore(
3378 Val.getValue(1), DL, Val, FIN,
3379 IsWin64
3380 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
3381 GPRIdx,
3382 (i - FirstVariadicGPR) * 8)
3383 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
3384 MemOps.push_back(Store);
3385 FIN =
3386 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3389 FuncInfo->setVarArgsGPRIndex(GPRIdx);
3390 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3392 if (Subtarget->hasFPARMv8() && !IsWin64) {
3393 static const MCPhysReg FPRArgRegs[] = {
3394 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3395 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3396 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3397 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3399 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3400 int FPRIdx = 0;
3401 if (FPRSaveSize != 0) {
3402 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3404 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3406 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3407 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3408 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3410 SDValue Store = DAG.getStore(
3411 Val.getValue(1), DL, Val, FIN,
3412 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3413 MemOps.push_back(Store);
3414 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3415 DAG.getConstant(16, DL, PtrVT));
3418 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3419 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3422 if (!MemOps.empty()) {
3423 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3427 /// LowerCallResult - Lower the result values of a call into the
3428 /// appropriate copies out of appropriate physical registers.
3429 SDValue AArch64TargetLowering::LowerCallResult(
3430 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3431 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3432 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3433 SDValue ThisVal) const {
3434 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3435 ? RetCC_AArch64_WebKit_JS
3436 : RetCC_AArch64_AAPCS;
3437 // Assign locations to each value returned by this call.
3438 SmallVector<CCValAssign, 16> RVLocs;
3439 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3440 *DAG.getContext());
3441 CCInfo.AnalyzeCallResult(Ins, RetCC);
3443 // Copy all of the result registers out of their specified physreg.
3444 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3445 CCValAssign VA = RVLocs[i];
3447 // Pass 'this' value directly from the argument to return value, to avoid
3448 // reg unit interference
3449 if (i == 0 && isThisReturn) {
3450 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3451 "unexpected return calling convention register assignment");
3452 InVals.push_back(ThisVal);
3453 continue;
3456 SDValue Val =
3457 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3458 Chain = Val.getValue(1);
3459 InFlag = Val.getValue(2);
3461 switch (VA.getLocInfo()) {
3462 default:
3463 llvm_unreachable("Unknown loc info!");
3464 case CCValAssign::Full:
3465 break;
3466 case CCValAssign::BCvt:
3467 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3468 break;
3471 InVals.push_back(Val);
3474 return Chain;
3477 /// Return true if the calling convention is one that we can guarantee TCO for.
3478 static bool canGuaranteeTCO(CallingConv::ID CC) {
3479 return CC == CallingConv::Fast;
3482 /// Return true if we might ever do TCO for calls with this calling convention.
3483 static bool mayTailCallThisCC(CallingConv::ID CC) {
3484 switch (CC) {
3485 case CallingConv::C:
3486 case CallingConv::PreserveMost:
3487 case CallingConv::Swift:
3488 return true;
3489 default:
3490 return canGuaranteeTCO(CC);
3494 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3495 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3496 const SmallVectorImpl<ISD::OutputArg> &Outs,
3497 const SmallVectorImpl<SDValue> &OutVals,
3498 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3499 if (!mayTailCallThisCC(CalleeCC))
3500 return false;
3502 MachineFunction &MF = DAG.getMachineFunction();
3503 const Function &CallerF = MF.getFunction();
3504 CallingConv::ID CallerCC = CallerF.getCallingConv();
3505 bool CCMatch = CallerCC == CalleeCC;
3507 // Byval parameters hand the function a pointer directly into the stack area
3508 // we want to reuse during a tail call. Working around this *is* possible (see
3509 // X86) but less efficient and uglier in LowerCall.
3510 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3511 e = CallerF.arg_end();
3512 i != e; ++i) {
3513 if (i->hasByValAttr())
3514 return false;
3516 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3517 // In this case, it is necessary to save/restore X0 in the callee. Tail
3518 // call opt interferes with this. So we disable tail call opt when the
3519 // caller has an argument with "inreg" attribute.
3521 // FIXME: Check whether the callee also has an "inreg" argument.
3522 if (i->hasInRegAttr())
3523 return false;
3526 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3527 return canGuaranteeTCO(CalleeCC) && CCMatch;
3529 // Externally-defined functions with weak linkage should not be
3530 // tail-called on AArch64 when the OS does not support dynamic
3531 // pre-emption of symbols, as the AAELF spec requires normal calls
3532 // to undefined weak functions to be replaced with a NOP or jump to the
3533 // next instruction. The behaviour of branch instructions in this
3534 // situation (as used for tail calls) is implementation-defined, so we
3535 // cannot rely on the linker replacing the tail call with a return.
3536 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3537 const GlobalValue *GV = G->getGlobal();
3538 const Triple &TT = getTargetMachine().getTargetTriple();
3539 if (GV->hasExternalWeakLinkage() &&
3540 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3541 return false;
3544 // Now we search for cases where we can use a tail call without changing the
3545 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3546 // concept.
3548 // I want anyone implementing a new calling convention to think long and hard
3549 // about this assert.
3550 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3551 "Unexpected variadic calling convention");
3553 LLVMContext &C = *DAG.getContext();
3554 if (isVarArg && !Outs.empty()) {
3555 // At least two cases here: if caller is fastcc then we can't have any
3556 // memory arguments (we'd be expected to clean up the stack afterwards). If
3557 // caller is C then we could potentially use its argument area.
3559 // FIXME: for now we take the most conservative of these in both cases:
3560 // disallow all variadic memory operands.
3561 SmallVector<CCValAssign, 16> ArgLocs;
3562 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3564 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3565 for (const CCValAssign &ArgLoc : ArgLocs)
3566 if (!ArgLoc.isRegLoc())
3567 return false;
3570 // Check that the call results are passed in the same way.
3571 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3572 CCAssignFnForCall(CalleeCC, isVarArg),
3573 CCAssignFnForCall(CallerCC, isVarArg)))
3574 return false;
3575 // The callee has to preserve all registers the caller needs to preserve.
3576 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3577 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3578 if (!CCMatch) {
3579 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3580 if (Subtarget->hasCustomCallingConv()) {
3581 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3582 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3584 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3585 return false;
3588 // Nothing more to check if the callee is taking no arguments
3589 if (Outs.empty())
3590 return true;
3592 SmallVector<CCValAssign, 16> ArgLocs;
3593 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3595 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3597 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3599 // If the stack arguments for this call do not fit into our own save area then
3600 // the call cannot be made tail.
3601 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3602 return false;
3604 const MachineRegisterInfo &MRI = MF.getRegInfo();
3605 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3606 return false;
3608 return true;
3611 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3612 SelectionDAG &DAG,
3613 MachineFrameInfo &MFI,
3614 int ClobberedFI) const {
3615 SmallVector<SDValue, 8> ArgChains;
3616 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3617 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3619 // Include the original chain at the beginning of the list. When this is
3620 // used by target LowerCall hooks, this helps legalize find the
3621 // CALLSEQ_BEGIN node.
3622 ArgChains.push_back(Chain);
3624 // Add a chain value for each stack argument corresponding
3625 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3626 UE = DAG.getEntryNode().getNode()->use_end();
3627 U != UE; ++U)
3628 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3629 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3630 if (FI->getIndex() < 0) {
3631 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3632 int64_t InLastByte = InFirstByte;
3633 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3635 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3636 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3637 ArgChains.push_back(SDValue(L, 1));
3640 // Build a tokenfactor for all the chains.
3641 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3644 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3645 bool TailCallOpt) const {
3646 return CallCC == CallingConv::Fast && TailCallOpt;
3649 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3650 /// and add input and output parameter nodes.
3651 SDValue
3652 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3653 SmallVectorImpl<SDValue> &InVals) const {
3654 SelectionDAG &DAG = CLI.DAG;
3655 SDLoc &DL = CLI.DL;
3656 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3657 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3658 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3659 SDValue Chain = CLI.Chain;
3660 SDValue Callee = CLI.Callee;
3661 bool &IsTailCall = CLI.IsTailCall;
3662 CallingConv::ID CallConv = CLI.CallConv;
3663 bool IsVarArg = CLI.IsVarArg;
3665 MachineFunction &MF = DAG.getMachineFunction();
3666 bool IsThisReturn = false;
3668 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3669 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3670 bool IsSibCall = false;
3672 if (IsTailCall) {
3673 // Check if it's really possible to do a tail call.
3674 IsTailCall = isEligibleForTailCallOptimization(
3675 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3676 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3677 report_fatal_error("failed to perform tail call elimination on a call "
3678 "site marked musttail");
3680 // A sibling call is one where we're under the usual C ABI and not planning
3681 // to change that but can still do a tail call:
3682 if (!TailCallOpt && IsTailCall)
3683 IsSibCall = true;
3685 if (IsTailCall)
3686 ++NumTailCalls;
3689 // Analyze operands of the call, assigning locations to each operand.
3690 SmallVector<CCValAssign, 16> ArgLocs;
3691 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3692 *DAG.getContext());
3694 if (IsVarArg) {
3695 // Handle fixed and variable vector arguments differently.
3696 // Variable vector arguments always go into memory.
3697 unsigned NumArgs = Outs.size();
3699 for (unsigned i = 0; i != NumArgs; ++i) {
3700 MVT ArgVT = Outs[i].VT;
3701 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3702 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3703 /*IsVarArg=*/ !Outs[i].IsFixed);
3704 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3705 assert(!Res && "Call operand has unhandled type");
3706 (void)Res;
3708 } else {
3709 // At this point, Outs[].VT may already be promoted to i32. To correctly
3710 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3711 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3712 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3713 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3714 // LocVT.
3715 unsigned NumArgs = Outs.size();
3716 for (unsigned i = 0; i != NumArgs; ++i) {
3717 MVT ValVT = Outs[i].VT;
3718 // Get type of the original argument.
3719 EVT ActualVT = getValueType(DAG.getDataLayout(),
3720 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3721 /*AllowUnknown*/ true);
3722 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3723 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3724 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3725 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3726 ValVT = MVT::i8;
3727 else if (ActualMVT == MVT::i16)
3728 ValVT = MVT::i16;
3730 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3731 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3732 assert(!Res && "Call operand has unhandled type");
3733 (void)Res;
3737 // Get a count of how many bytes are to be pushed on the stack.
3738 unsigned NumBytes = CCInfo.getNextStackOffset();
3740 if (IsSibCall) {
3741 // Since we're not changing the ABI to make this a tail call, the memory
3742 // operands are already available in the caller's incoming argument space.
3743 NumBytes = 0;
3746 // FPDiff is the byte offset of the call's argument area from the callee's.
3747 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3748 // by this amount for a tail call. In a sibling call it must be 0 because the
3749 // caller will deallocate the entire stack and the callee still expects its
3750 // arguments to begin at SP+0. Completely unused for non-tail calls.
3751 int FPDiff = 0;
3753 if (IsTailCall && !IsSibCall) {
3754 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3756 // Since callee will pop argument stack as a tail call, we must keep the
3757 // popped size 16-byte aligned.
3758 NumBytes = alignTo(NumBytes, 16);
3760 // FPDiff will be negative if this tail call requires more space than we
3761 // would automatically have in our incoming argument space. Positive if we
3762 // can actually shrink the stack.
3763 FPDiff = NumReusableBytes - NumBytes;
3765 // The stack pointer must be 16-byte aligned at all times it's used for a
3766 // memory operation, which in practice means at *all* times and in
3767 // particular across call boundaries. Therefore our own arguments started at
3768 // a 16-byte aligned SP and the delta applied for the tail call should
3769 // satisfy the same constraint.
3770 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3773 // Adjust the stack pointer for the new arguments...
3774 // These operations are automatically eliminated by the prolog/epilog pass
3775 if (!IsSibCall)
3776 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3778 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3779 getPointerTy(DAG.getDataLayout()));
3781 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3782 SmallVector<SDValue, 8> MemOpChains;
3783 auto PtrVT = getPointerTy(DAG.getDataLayout());
3785 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) {
3786 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
3787 for (const auto &F : Forwards) {
3788 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
3789 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3793 // Walk the register/memloc assignments, inserting copies/loads.
3794 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3795 ++i, ++realArgIdx) {
3796 CCValAssign &VA = ArgLocs[i];
3797 SDValue Arg = OutVals[realArgIdx];
3798 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3800 // Promote the value if needed.
3801 switch (VA.getLocInfo()) {
3802 default:
3803 llvm_unreachable("Unknown loc info!");
3804 case CCValAssign::Full:
3805 break;
3806 case CCValAssign::SExt:
3807 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3808 break;
3809 case CCValAssign::ZExt:
3810 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3811 break;
3812 case CCValAssign::AExt:
3813 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3814 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3815 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3816 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3818 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3819 break;
3820 case CCValAssign::BCvt:
3821 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3822 break;
3823 case CCValAssign::FPExt:
3824 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3825 break;
3826 case CCValAssign::Indirect:
3827 assert(VA.getValVT().isScalableVector() &&
3828 "Only scalable vectors can be passed indirectly");
3829 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3832 if (VA.isRegLoc()) {
3833 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3834 Outs[0].VT == MVT::i64) {
3835 assert(VA.getLocVT() == MVT::i64 &&
3836 "unexpected calling convention register assignment");
3837 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3838 "unexpected use of 'returned'");
3839 IsThisReturn = true;
3841 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3842 } else {
3843 assert(VA.isMemLoc());
3845 SDValue DstAddr;
3846 MachinePointerInfo DstInfo;
3848 // FIXME: This works on big-endian for composite byvals, which are the
3849 // common case. It should also work for fundamental types too.
3850 uint32_t BEAlign = 0;
3851 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3852 : VA.getValVT().getSizeInBits();
3853 OpSize = (OpSize + 7) / 8;
3854 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3855 !Flags.isInConsecutiveRegs()) {
3856 if (OpSize < 8)
3857 BEAlign = 8 - OpSize;
3859 unsigned LocMemOffset = VA.getLocMemOffset();
3860 int32_t Offset = LocMemOffset + BEAlign;
3861 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3862 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3864 if (IsTailCall) {
3865 Offset = Offset + FPDiff;
3866 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3868 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3869 DstInfo =
3870 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3872 // Make sure any stack arguments overlapping with where we're storing
3873 // are loaded before this eventual operation. Otherwise they'll be
3874 // clobbered.
3875 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3876 } else {
3877 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3879 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3880 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3881 LocMemOffset);
3884 if (Outs[i].Flags.isByVal()) {
3885 SDValue SizeNode =
3886 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3887 SDValue Cpy = DAG.getMemcpy(
3888 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3889 /*isVol = */ false, /*AlwaysInline = */ false,
3890 /*isTailCall = */ false,
3891 DstInfo, MachinePointerInfo());
3893 MemOpChains.push_back(Cpy);
3894 } else {
3895 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3896 // promoted to a legal register type i32, we should truncate Arg back to
3897 // i1/i8/i16.
3898 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3899 VA.getValVT() == MVT::i16)
3900 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3902 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3903 MemOpChains.push_back(Store);
3908 if (!MemOpChains.empty())
3909 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3911 // Build a sequence of copy-to-reg nodes chained together with token chain
3912 // and flag operands which copy the outgoing args into the appropriate regs.
3913 SDValue InFlag;
3914 for (auto &RegToPass : RegsToPass) {
3915 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3916 RegToPass.second, InFlag);
3917 InFlag = Chain.getValue(1);
3920 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3921 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3922 // node so that legalize doesn't hack it.
3923 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3924 auto GV = G->getGlobal();
3925 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3926 AArch64II::MO_GOT) {
3927 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3928 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3929 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3930 assert(Subtarget->isTargetWindows() &&
3931 "Windows is the only supported COFF target");
3932 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3933 } else {
3934 const GlobalValue *GV = G->getGlobal();
3935 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3937 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3938 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3939 Subtarget->isTargetMachO()) {
3940 const char *Sym = S->getSymbol();
3941 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3942 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3943 } else {
3944 const char *Sym = S->getSymbol();
3945 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3949 // We don't usually want to end the call-sequence here because we would tidy
3950 // the frame up *after* the call, however in the ABI-changing tail-call case
3951 // we've carefully laid out the parameters so that when sp is reset they'll be
3952 // in the correct location.
3953 if (IsTailCall && !IsSibCall) {
3954 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3955 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3956 InFlag = Chain.getValue(1);
3959 std::vector<SDValue> Ops;
3960 Ops.push_back(Chain);
3961 Ops.push_back(Callee);
3963 if (IsTailCall) {
3964 // Each tail call may have to adjust the stack by a different amount, so
3965 // this information must travel along with the operation for eventual
3966 // consumption by emitEpilogue.
3967 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3970 // Add argument registers to the end of the list so that they are known live
3971 // into the call.
3972 for (auto &RegToPass : RegsToPass)
3973 Ops.push_back(DAG.getRegister(RegToPass.first,
3974 RegToPass.second.getValueType()));
3976 // Check callee args/returns for SVE registers and set calling convention
3977 // accordingly.
3978 if (CallConv == CallingConv::C) {
3979 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
3980 return Out.VT.isScalableVector();
3982 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
3983 return In.VT.isScalableVector();
3986 if (CalleeInSVE || CalleeOutSVE)
3987 CallConv = CallingConv::AArch64_SVE_VectorCall;
3990 // Add a register mask operand representing the call-preserved registers.
3991 const uint32_t *Mask;
3992 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3993 if (IsThisReturn) {
3994 // For 'this' returns, use the X0-preserving mask if applicable
3995 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3996 if (!Mask) {
3997 IsThisReturn = false;
3998 Mask = TRI->getCallPreservedMask(MF, CallConv);
4000 } else
4001 Mask = TRI->getCallPreservedMask(MF, CallConv);
4003 if (Subtarget->hasCustomCallingConv())
4004 TRI->UpdateCustomCallPreservedMask(MF, &Mask);
4006 if (TRI->isAnyArgRegReserved(MF))
4007 TRI->emitReservedArgRegCallError(MF);
4009 assert(Mask && "Missing call preserved mask for calling convention");
4010 Ops.push_back(DAG.getRegisterMask(Mask));
4012 if (InFlag.getNode())
4013 Ops.push_back(InFlag);
4015 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4017 // If we're doing a tall call, use a TC_RETURN here rather than an
4018 // actual call instruction.
4019 if (IsTailCall) {
4020 MF.getFrameInfo().setHasTailCall();
4021 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
4024 // Returns a chain and a flag for retval copy to use.
4025 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
4026 InFlag = Chain.getValue(1);
4028 uint64_t CalleePopBytes =
4029 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
4031 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
4032 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
4033 InFlag, DL);
4034 if (!Ins.empty())
4035 InFlag = Chain.getValue(1);
4037 // Handle result values, copying them out of physregs into vregs that we
4038 // return.
4039 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
4040 InVals, IsThisReturn,
4041 IsThisReturn ? OutVals[0] : SDValue());
4044 bool AArch64TargetLowering::CanLowerReturn(
4045 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
4046 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
4047 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4048 ? RetCC_AArch64_WebKit_JS
4049 : RetCC_AArch64_AAPCS;
4050 SmallVector<CCValAssign, 16> RVLocs;
4051 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
4052 return CCInfo.CheckReturn(Outs, RetCC);
4055 SDValue
4056 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
4057 bool isVarArg,
4058 const SmallVectorImpl<ISD::OutputArg> &Outs,
4059 const SmallVectorImpl<SDValue> &OutVals,
4060 const SDLoc &DL, SelectionDAG &DAG) const {
4061 auto &MF = DAG.getMachineFunction();
4062 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4064 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
4065 ? RetCC_AArch64_WebKit_JS
4066 : RetCC_AArch64_AAPCS;
4067 SmallVector<CCValAssign, 16> RVLocs;
4068 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4069 *DAG.getContext());
4070 CCInfo.AnalyzeReturn(Outs, RetCC);
4072 // Copy the result values into the output registers.
4073 SDValue Flag;
4074 SmallVector<SDValue, 4> RetOps(1, Chain);
4075 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
4076 ++i, ++realRVLocIdx) {
4077 CCValAssign &VA = RVLocs[i];
4078 assert(VA.isRegLoc() && "Can only return in registers!");
4079 SDValue Arg = OutVals[realRVLocIdx];
4081 switch (VA.getLocInfo()) {
4082 default:
4083 llvm_unreachable("Unknown loc info!");
4084 case CCValAssign::Full:
4085 if (Outs[i].ArgVT == MVT::i1) {
4086 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4087 // value. This is strictly redundant on Darwin (which uses "zeroext
4088 // i1"), but will be optimised out before ISel.
4089 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
4090 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
4092 break;
4093 case CCValAssign::BCvt:
4094 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
4095 break;
4098 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
4099 Flag = Chain.getValue(1);
4100 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4103 // Windows AArch64 ABIs require that for returning structs by value we copy
4104 // the sret argument into X0 for the return.
4105 // We saved the argument into a virtual register in the entry block,
4106 // so now we copy the value out and into X0.
4107 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
4108 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
4109 getPointerTy(MF.getDataLayout()));
4111 unsigned RetValReg = AArch64::X0;
4112 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
4113 Flag = Chain.getValue(1);
4115 RetOps.push_back(
4116 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
4119 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4120 const MCPhysReg *I =
4121 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
4122 if (I) {
4123 for (; *I; ++I) {
4124 if (AArch64::GPR64RegClass.contains(*I))
4125 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
4126 else if (AArch64::FPR64RegClass.contains(*I))
4127 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
4128 else
4129 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4133 RetOps[0] = Chain; // Update chain.
4135 // Add the flag if we have it.
4136 if (Flag.getNode())
4137 RetOps.push_back(Flag);
4139 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
4142 //===----------------------------------------------------------------------===//
4143 // Other Lowering Code
4144 //===----------------------------------------------------------------------===//
4146 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
4147 SelectionDAG &DAG,
4148 unsigned Flag) const {
4149 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
4150 N->getOffset(), Flag);
4153 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
4154 SelectionDAG &DAG,
4155 unsigned Flag) const {
4156 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
4159 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
4160 SelectionDAG &DAG,
4161 unsigned Flag) const {
4162 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
4163 N->getOffset(), Flag);
4166 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
4167 SelectionDAG &DAG,
4168 unsigned Flag) const {
4169 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
4172 // (loadGOT sym)
4173 template <class NodeTy>
4174 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
4175 unsigned Flags) const {
4176 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4177 SDLoc DL(N);
4178 EVT Ty = getPointerTy(DAG.getDataLayout());
4179 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
4180 // FIXME: Once remat is capable of dealing with instructions with register
4181 // operands, expand this into two nodes instead of using a wrapper node.
4182 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
4185 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4186 template <class NodeTy>
4187 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
4188 unsigned Flags) const {
4189 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4190 SDLoc DL(N);
4191 EVT Ty = getPointerTy(DAG.getDataLayout());
4192 const unsigned char MO_NC = AArch64II::MO_NC;
4193 return DAG.getNode(
4194 AArch64ISD::WrapperLarge, DL, Ty,
4195 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
4196 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
4197 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
4198 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
4201 // (addlow (adrp %hi(sym)) %lo(sym))
4202 template <class NodeTy>
4203 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
4204 unsigned Flags) const {
4205 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4206 SDLoc DL(N);
4207 EVT Ty = getPointerTy(DAG.getDataLayout());
4208 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
4209 SDValue Lo = getTargetNode(N, Ty, DAG,
4210 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
4211 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
4212 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
4215 // (adr sym)
4216 template <class NodeTy>
4217 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
4218 unsigned Flags) const {
4219 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4220 SDLoc DL(N);
4221 EVT Ty = getPointerTy(DAG.getDataLayout());
4222 SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4223 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4226 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4227 SelectionDAG &DAG) const {
4228 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4229 const GlobalValue *GV = GN->getGlobal();
4230 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4232 if (OpFlags != AArch64II::MO_NO_FLAG)
4233 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4234 "unexpected offset in global node");
4236 // This also catches the large code model case for Darwin, and tiny code
4237 // model with got relocations.
4238 if ((OpFlags & AArch64II::MO_GOT) != 0) {
4239 return getGOT(GN, DAG, OpFlags);
4242 SDValue Result;
4243 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4244 Result = getAddrLarge(GN, DAG, OpFlags);
4245 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4246 Result = getAddrTiny(GN, DAG, OpFlags);
4247 } else {
4248 Result = getAddr(GN, DAG, OpFlags);
4250 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4251 SDLoc DL(GN);
4252 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
4253 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4254 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
4255 return Result;
4258 /// Convert a TLS address reference into the correct sequence of loads
4259 /// and calls to compute the variable's address (for Darwin, currently) and
4260 /// return an SDValue containing the final node.
4262 /// Darwin only has one TLS scheme which must be capable of dealing with the
4263 /// fully general situation, in the worst case. This means:
4264 /// + "extern __thread" declaration.
4265 /// + Defined in a possibly unknown dynamic library.
4267 /// The general system is that each __thread variable has a [3 x i64] descriptor
4268 /// which contains information used by the runtime to calculate the address. The
4269 /// only part of this the compiler needs to know about is the first xword, which
4270 /// contains a function pointer that must be called with the address of the
4271 /// entire descriptor in "x0".
4273 /// Since this descriptor may be in a different unit, in general even the
4274 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4275 /// is:
4276 /// adrp x0, _var@TLVPPAGE
4277 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4278 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4279 /// ; the function pointer
4280 /// blr x1 ; Uses descriptor address in x0
4281 /// ; Address of _var is now in x0.
4283 /// If the address of _var's descriptor *is* known to the linker, then it can
4284 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4285 /// a slight efficiency gain.
4286 SDValue
4287 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4288 SelectionDAG &DAG) const {
4289 assert(Subtarget->isTargetDarwin() &&
4290 "This function expects a Darwin target");
4292 SDLoc DL(Op);
4293 MVT PtrVT = getPointerTy(DAG.getDataLayout());
4294 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4296 SDValue TLVPAddr =
4297 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4298 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4300 // The first entry in the descriptor is a function pointer that we must call
4301 // to obtain the address of the variable.
4302 SDValue Chain = DAG.getEntryNode();
4303 SDValue FuncTLVGet = DAG.getLoad(
4304 MVT::i64, DL, Chain, DescAddr,
4305 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
4306 /* Alignment = */ 8,
4307 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
4308 Chain = FuncTLVGet.getValue(1);
4310 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4311 MFI.setAdjustsStack(true);
4313 // TLS calls preserve all registers except those that absolutely must be
4314 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4315 // silly).
4316 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4317 const uint32_t *Mask = TRI->getTLSCallPreservedMask();
4318 if (Subtarget->hasCustomCallingConv())
4319 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
4321 // Finally, we can make the call. This is just a degenerate version of a
4322 // normal AArch64 call node: x0 takes the address of the descriptor, and
4323 // returns the address of the variable in this thread.
4324 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
4325 Chain =
4326 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
4327 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
4328 DAG.getRegisterMask(Mask), Chain.getValue(1));
4329 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
4332 /// When accessing thread-local variables under either the general-dynamic or
4333 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4334 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4335 /// is a function pointer to carry out the resolution.
4337 /// The sequence is:
4338 /// adrp x0, :tlsdesc:var
4339 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4340 /// add x0, x0, #:tlsdesc_lo12:var
4341 /// .tlsdesccall var
4342 /// blr x1
4343 /// (TPIDR_EL0 offset now in x0)
4345 /// The above sequence must be produced unscheduled, to enable the linker to
4346 /// optimize/relax this sequence.
4347 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4348 /// above sequence, and expanded really late in the compilation flow, to ensure
4349 /// the sequence is produced as per above.
4350 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
4351 const SDLoc &DL,
4352 SelectionDAG &DAG) const {
4353 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4355 SDValue Chain = DAG.getEntryNode();
4356 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4358 Chain =
4359 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
4360 SDValue Glue = Chain.getValue(1);
4362 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
4365 SDValue
4366 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
4367 SelectionDAG &DAG) const {
4368 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
4369 if (getTargetMachine().getCodeModel() == CodeModel::Large)
4370 report_fatal_error("ELF TLS only supported in small memory model");
4371 // Different choices can be made for the maximum size of the TLS area for a
4372 // module. For the small address model, the default TLS size is 16MiB and the
4373 // maximum TLS size is 4GiB.
4374 // FIXME: add -mtls-size command line option and make it control the 16MiB
4375 // vs. 4GiB code sequence generation.
4376 // FIXME: add tiny codemodel support. We currently generate the same code as
4377 // small, which may be larger than needed.
4378 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4380 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
4382 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
4383 if (Model == TLSModel::LocalDynamic)
4384 Model = TLSModel::GeneralDynamic;
4387 SDValue TPOff;
4388 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4389 SDLoc DL(Op);
4390 const GlobalValue *GV = GA->getGlobal();
4392 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
4394 if (Model == TLSModel::LocalExec) {
4395 SDValue HiVar = DAG.getTargetGlobalAddress(
4396 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4397 SDValue LoVar = DAG.getTargetGlobalAddress(
4398 GV, DL, PtrVT, 0,
4399 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4401 SDValue TPWithOff_lo =
4402 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
4403 HiVar,
4404 DAG.getTargetConstant(0, DL, MVT::i32)),
4406 SDValue TPWithOff =
4407 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
4408 LoVar,
4409 DAG.getTargetConstant(0, DL, MVT::i32)),
4411 return TPWithOff;
4412 } else if (Model == TLSModel::InitialExec) {
4413 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4414 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
4415 } else if (Model == TLSModel::LocalDynamic) {
4416 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4417 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4418 // the beginning of the module's TLS region, followed by a DTPREL offset
4419 // calculation.
4421 // These accesses will need deduplicating if there's more than one.
4422 AArch64FunctionInfo *MFI =
4423 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4424 MFI->incNumLocalDynamicTLSAccesses();
4426 // The call needs a relocation too for linker relaxation. It doesn't make
4427 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4428 // the address.
4429 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
4430 AArch64II::MO_TLS);
4432 // Now we can calculate the offset from TPIDR_EL0 to this module's
4433 // thread-local area.
4434 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4436 // Now use :dtprel_whatever: operations to calculate this variable's offset
4437 // in its thread-storage area.
4438 SDValue HiVar = DAG.getTargetGlobalAddress(
4439 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4440 SDValue LoVar = DAG.getTargetGlobalAddress(
4441 GV, DL, MVT::i64, 0,
4442 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4444 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
4445 DAG.getTargetConstant(0, DL, MVT::i32)),
4447 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
4448 DAG.getTargetConstant(0, DL, MVT::i32)),
4450 } else if (Model == TLSModel::GeneralDynamic) {
4451 // The call needs a relocation too for linker relaxation. It doesn't make
4452 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4453 // the address.
4454 SDValue SymAddr =
4455 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4457 // Finally we can make a call to calculate the offset from tpidr_el0.
4458 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
4459 } else
4460 llvm_unreachable("Unsupported ELF TLS access model");
4462 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
4465 SDValue
4466 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
4467 SelectionDAG &DAG) const {
4468 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
4470 SDValue Chain = DAG.getEntryNode();
4471 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4472 SDLoc DL(Op);
4474 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
4476 // Load the ThreadLocalStoragePointer from the TEB
4477 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4478 SDValue TLSArray =
4479 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
4480 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
4481 Chain = TLSArray.getValue(1);
4483 // Load the TLS index from the C runtime;
4484 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4485 // This also does the same as LOADgot, but using a generic i32 load,
4486 // while LOADgot only loads i64.
4487 SDValue TLSIndexHi =
4488 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
4489 SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
4490 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4491 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
4492 SDValue TLSIndex =
4493 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
4494 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
4495 Chain = TLSIndex.getValue(1);
4497 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4498 // offset into the TLSArray.
4499 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
4500 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
4501 DAG.getConstant(3, DL, PtrVT));
4502 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
4503 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
4504 MachinePointerInfo());
4505 Chain = TLS.getValue(1);
4507 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4508 const GlobalValue *GV = GA->getGlobal();
4509 SDValue TGAHi = DAG.getTargetGlobalAddress(
4510 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
4511 SDValue TGALo = DAG.getTargetGlobalAddress(
4512 GV, DL, PtrVT, 0,
4513 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4515 // Add the offset from the start of the .tls section (section base).
4516 SDValue Addr =
4517 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
4518 DAG.getTargetConstant(0, DL, MVT::i32)),
4520 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
4521 return Addr;
4524 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
4525 SelectionDAG &DAG) const {
4526 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4527 if (DAG.getTarget().useEmulatedTLS())
4528 return LowerToTLSEmulatedModel(GA, DAG);
4530 if (Subtarget->isTargetDarwin())
4531 return LowerDarwinGlobalTLSAddress(Op, DAG);
4532 if (Subtarget->isTargetELF())
4533 return LowerELFGlobalTLSAddress(Op, DAG);
4534 if (Subtarget->isTargetWindows())
4535 return LowerWindowsGlobalTLSAddress(Op, DAG);
4537 llvm_unreachable("Unexpected platform trying to use TLS");
4540 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4541 SDValue Chain = Op.getOperand(0);
4542 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4543 SDValue LHS = Op.getOperand(2);
4544 SDValue RHS = Op.getOperand(3);
4545 SDValue Dest = Op.getOperand(4);
4546 SDLoc dl(Op);
4548 MachineFunction &MF = DAG.getMachineFunction();
4549 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4550 // will not be produced, as they are conditional branch instructions that do
4551 // not set flags.
4552 bool ProduceNonFlagSettingCondBr =
4553 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
4555 // Handle f128 first, since lowering it will result in comparing the return
4556 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4557 // is expecting to deal with.
4558 if (LHS.getValueType() == MVT::f128) {
4559 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4561 // If softenSetCCOperands returned a scalar, we need to compare the result
4562 // against zero to select between true and false values.
4563 if (!RHS.getNode()) {
4564 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4565 CC = ISD::SETNE;
4569 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4570 // instruction.
4571 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4572 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4573 // Only lower legal XALUO ops.
4574 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4575 return SDValue();
4577 // The actual operation with overflow check.
4578 AArch64CC::CondCode OFCC;
4579 SDValue Value, Overflow;
4580 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4582 if (CC == ISD::SETNE)
4583 OFCC = getInvertedCondCode(OFCC);
4584 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4586 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4587 Overflow);
4590 if (LHS.getValueType().isInteger()) {
4591 assert((LHS.getValueType() == RHS.getValueType()) &&
4592 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4594 // If the RHS of the comparison is zero, we can potentially fold this
4595 // to a specialized branch.
4596 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4597 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
4598 if (CC == ISD::SETEQ) {
4599 // See if we can use a TBZ to fold in an AND as well.
4600 // TBZ has a smaller branch displacement than CBZ. If the offset is
4601 // out of bounds, a late MI-layer pass rewrites branches.
4602 // 403.gcc is an example that hits this case.
4603 if (LHS.getOpcode() == ISD::AND &&
4604 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4605 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4606 SDValue Test = LHS.getOperand(0);
4607 uint64_t Mask = LHS.getConstantOperandVal(1);
4608 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4609 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4610 Dest);
4613 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4614 } else if (CC == ISD::SETNE) {
4615 // See if we can use a TBZ to fold in an AND as well.
4616 // TBZ has a smaller branch displacement than CBZ. If the offset is
4617 // out of bounds, a late MI-layer pass rewrites branches.
4618 // 403.gcc is an example that hits this case.
4619 if (LHS.getOpcode() == ISD::AND &&
4620 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4621 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4622 SDValue Test = LHS.getOperand(0);
4623 uint64_t Mask = LHS.getConstantOperandVal(1);
4624 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4625 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4626 Dest);
4629 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4630 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4631 // Don't combine AND since emitComparison converts the AND to an ANDS
4632 // (a.k.a. TST) and the test in the test bit and branch instruction
4633 // becomes redundant. This would also increase register pressure.
4634 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4635 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4636 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4639 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4640 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
4641 // Don't combine AND since emitComparison converts the AND to an ANDS
4642 // (a.k.a. TST) and the test in the test bit and branch instruction
4643 // becomes redundant. This would also increase register pressure.
4644 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4645 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4646 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4649 SDValue CCVal;
4650 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4651 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4652 Cmp);
4655 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4656 LHS.getValueType() == MVT::f64);
4658 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4659 // clean. Some of them require two branches to implement.
4660 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4661 AArch64CC::CondCode CC1, CC2;
4662 changeFPCCToAArch64CC(CC, CC1, CC2);
4663 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4664 SDValue BR1 =
4665 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4666 if (CC2 != AArch64CC::AL) {
4667 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4668 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4669 Cmp);
4672 return BR1;
4675 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4676 SelectionDAG &DAG) const {
4677 EVT VT = Op.getValueType();
4678 SDLoc DL(Op);
4680 SDValue In1 = Op.getOperand(0);
4681 SDValue In2 = Op.getOperand(1);
4682 EVT SrcVT = In2.getValueType();
4684 if (SrcVT.bitsLT(VT))
4685 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4686 else if (SrcVT.bitsGT(VT))
4687 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4689 EVT VecVT;
4690 uint64_t EltMask;
4691 SDValue VecVal1, VecVal2;
4693 auto setVecVal = [&] (int Idx) {
4694 if (!VT.isVector()) {
4695 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4696 DAG.getUNDEF(VecVT), In1);
4697 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4698 DAG.getUNDEF(VecVT), In2);
4699 } else {
4700 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4701 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4705 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4706 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4707 EltMask = 0x80000000ULL;
4708 setVecVal(AArch64::ssub);
4709 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4710 VecVT = MVT::v2i64;
4712 // We want to materialize a mask with the high bit set, but the AdvSIMD
4713 // immediate moves cannot materialize that in a single instruction for
4714 // 64-bit elements. Instead, materialize zero and then negate it.
4715 EltMask = 0;
4717 setVecVal(AArch64::dsub);
4718 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4719 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4720 EltMask = 0x8000ULL;
4721 setVecVal(AArch64::hsub);
4722 } else {
4723 llvm_unreachable("Invalid type for copysign!");
4726 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4728 // If we couldn't materialize the mask above, then the mask vector will be
4729 // the zero vector, and we need to negate it here.
4730 if (VT == MVT::f64 || VT == MVT::v2f64) {
4731 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4732 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4733 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4736 SDValue Sel =
4737 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4739 if (VT == MVT::f16)
4740 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4741 if (VT == MVT::f32)
4742 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4743 else if (VT == MVT::f64)
4744 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4745 else
4746 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4749 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4750 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4751 Attribute::NoImplicitFloat))
4752 return SDValue();
4754 if (!Subtarget->hasNEON())
4755 return SDValue();
4757 // While there is no integer popcount instruction, it can
4758 // be more efficiently lowered to the following sequence that uses
4759 // AdvSIMD registers/instructions as long as the copies to/from
4760 // the AdvSIMD registers are cheap.
4761 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4762 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4763 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4764 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4765 SDValue Val = Op.getOperand(0);
4766 SDLoc DL(Op);
4767 EVT VT = Op.getValueType();
4769 if (VT == MVT::i32 || VT == MVT::i64) {
4770 if (VT == MVT::i32)
4771 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4772 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4774 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4775 SDValue UaddLV = DAG.getNode(
4776 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4777 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4779 if (VT == MVT::i64)
4780 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4781 return UaddLV;
4784 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
4785 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
4786 "Unexpected type for custom ctpop lowering");
4788 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4789 Val = DAG.getBitcast(VT8Bit, Val);
4790 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
4792 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4793 unsigned EltSize = 8;
4794 unsigned NumElts = VT.is64BitVector() ? 8 : 16;
4795 while (EltSize != VT.getScalarSizeInBits()) {
4796 EltSize *= 2;
4797 NumElts /= 2;
4798 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
4799 Val = DAG.getNode(
4800 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
4801 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
4804 return Val;
4807 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4809 if (Op.getValueType().isVector())
4810 return LowerVSETCC(Op, DAG);
4812 SDValue LHS = Op.getOperand(0);
4813 SDValue RHS = Op.getOperand(1);
4814 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4815 SDLoc dl(Op);
4817 // We chose ZeroOrOneBooleanContents, so use zero and one.
4818 EVT VT = Op.getValueType();
4819 SDValue TVal = DAG.getConstant(1, dl, VT);
4820 SDValue FVal = DAG.getConstant(0, dl, VT);
4822 // Handle f128 first, since one possible outcome is a normal integer
4823 // comparison which gets picked up by the next if statement.
4824 if (LHS.getValueType() == MVT::f128) {
4825 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4827 // If softenSetCCOperands returned a scalar, use it.
4828 if (!RHS.getNode()) {
4829 assert(LHS.getValueType() == Op.getValueType() &&
4830 "Unexpected setcc expansion!");
4831 return LHS;
4835 if (LHS.getValueType().isInteger()) {
4836 SDValue CCVal;
4837 SDValue Cmp =
4838 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4840 // Note that we inverted the condition above, so we reverse the order of
4841 // the true and false operands here. This will allow the setcc to be
4842 // matched to a single CSINC instruction.
4843 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4846 // Now we know we're dealing with FP values.
4847 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4848 LHS.getValueType() == MVT::f64);
4850 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4851 // and do the comparison.
4852 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4854 AArch64CC::CondCode CC1, CC2;
4855 changeFPCCToAArch64CC(CC, CC1, CC2);
4856 if (CC2 == AArch64CC::AL) {
4857 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4858 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4860 // Note that we inverted the condition above, so we reverse the order of
4861 // the true and false operands here. This will allow the setcc to be
4862 // matched to a single CSINC instruction.
4863 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4864 } else {
4865 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4866 // totally clean. Some of them require two CSELs to implement. As is in
4867 // this case, we emit the first CSEL and then emit a second using the output
4868 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4870 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4871 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4872 SDValue CS1 =
4873 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4875 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4876 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4880 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4881 SDValue RHS, SDValue TVal,
4882 SDValue FVal, const SDLoc &dl,
4883 SelectionDAG &DAG) const {
4884 // Handle f128 first, because it will result in a comparison of some RTLIB
4885 // call result against zero.
4886 if (LHS.getValueType() == MVT::f128) {
4887 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
4889 // If softenSetCCOperands returned a scalar, we need to compare the result
4890 // against zero to select between true and false values.
4891 if (!RHS.getNode()) {
4892 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4893 CC = ISD::SETNE;
4897 // Also handle f16, for which we need to do a f32 comparison.
4898 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4899 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4900 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4903 // Next, handle integers.
4904 if (LHS.getValueType().isInteger()) {
4905 assert((LHS.getValueType() == RHS.getValueType()) &&
4906 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4908 unsigned Opcode = AArch64ISD::CSEL;
4910 // If both the TVal and the FVal are constants, see if we can swap them in
4911 // order to for a CSINV or CSINC out of them.
4912 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4913 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4915 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4916 std::swap(TVal, FVal);
4917 std::swap(CTVal, CFVal);
4918 CC = ISD::getSetCCInverse(CC, true);
4919 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4920 std::swap(TVal, FVal);
4921 std::swap(CTVal, CFVal);
4922 CC = ISD::getSetCCInverse(CC, true);
4923 } else if (TVal.getOpcode() == ISD::XOR) {
4924 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4925 // with a CSINV rather than a CSEL.
4926 if (isAllOnesConstant(TVal.getOperand(1))) {
4927 std::swap(TVal, FVal);
4928 std::swap(CTVal, CFVal);
4929 CC = ISD::getSetCCInverse(CC, true);
4931 } else if (TVal.getOpcode() == ISD::SUB) {
4932 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4933 // that we can match with a CSNEG rather than a CSEL.
4934 if (isNullConstant(TVal.getOperand(0))) {
4935 std::swap(TVal, FVal);
4936 std::swap(CTVal, CFVal);
4937 CC = ISD::getSetCCInverse(CC, true);
4939 } else if (CTVal && CFVal) {
4940 const int64_t TrueVal = CTVal->getSExtValue();
4941 const int64_t FalseVal = CFVal->getSExtValue();
4942 bool Swap = false;
4944 // If both TVal and FVal are constants, see if FVal is the
4945 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4946 // instead of a CSEL in that case.
4947 if (TrueVal == ~FalseVal) {
4948 Opcode = AArch64ISD::CSINV;
4949 } else if (TrueVal == -FalseVal) {
4950 Opcode = AArch64ISD::CSNEG;
4951 } else if (TVal.getValueType() == MVT::i32) {
4952 // If our operands are only 32-bit wide, make sure we use 32-bit
4953 // arithmetic for the check whether we can use CSINC. This ensures that
4954 // the addition in the check will wrap around properly in case there is
4955 // an overflow (which would not be the case if we do the check with
4956 // 64-bit arithmetic).
4957 const uint32_t TrueVal32 = CTVal->getZExtValue();
4958 const uint32_t FalseVal32 = CFVal->getZExtValue();
4960 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4961 Opcode = AArch64ISD::CSINC;
4963 if (TrueVal32 > FalseVal32) {
4964 Swap = true;
4967 // 64-bit check whether we can use CSINC.
4968 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4969 Opcode = AArch64ISD::CSINC;
4971 if (TrueVal > FalseVal) {
4972 Swap = true;
4976 // Swap TVal and FVal if necessary.
4977 if (Swap) {
4978 std::swap(TVal, FVal);
4979 std::swap(CTVal, CFVal);
4980 CC = ISD::getSetCCInverse(CC, true);
4983 if (Opcode != AArch64ISD::CSEL) {
4984 // Drop FVal since we can get its value by simply inverting/negating
4985 // TVal.
4986 FVal = TVal;
4990 // Avoid materializing a constant when possible by reusing a known value in
4991 // a register. However, don't perform this optimization if the known value
4992 // is one, zero or negative one in the case of a CSEL. We can always
4993 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4994 // FVal, respectively.
4995 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4996 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4997 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4998 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4999 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
5000 // "a != C ? x : a" to avoid materializing C.
5001 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
5002 TVal = LHS;
5003 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
5004 FVal = LHS;
5005 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
5006 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
5007 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5008 // avoid materializing C.
5009 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
5010 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
5011 Opcode = AArch64ISD::CSINV;
5012 TVal = LHS;
5013 FVal = DAG.getConstant(0, dl, FVal.getValueType());
5017 SDValue CCVal;
5018 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
5019 EVT VT = TVal.getValueType();
5020 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
5023 // Now we know we're dealing with FP values.
5024 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
5025 LHS.getValueType() == MVT::f64);
5026 assert(LHS.getValueType() == RHS.getValueType());
5027 EVT VT = TVal.getValueType();
5028 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
5030 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5031 // clean. Some of them require two CSELs to implement.
5032 AArch64CC::CondCode CC1, CC2;
5033 changeFPCCToAArch64CC(CC, CC1, CC2);
5035 if (DAG.getTarget().Options.UnsafeFPMath) {
5036 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5037 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5038 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
5039 if (RHSVal && RHSVal->isZero()) {
5040 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
5041 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
5043 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
5044 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
5045 TVal = LHS;
5046 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
5047 CFVal && CFVal->isZero() &&
5048 FVal.getValueType() == LHS.getValueType())
5049 FVal = LHS;
5053 // Emit first, and possibly only, CSEL.
5054 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
5055 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
5057 // If we need a second CSEL, emit it, using the output of the first as the
5058 // RHS. We're effectively OR'ing the two CC's together.
5059 if (CC2 != AArch64CC::AL) {
5060 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
5061 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
5064 // Otherwise, return the output of the first CSEL.
5065 return CS1;
5068 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
5069 SelectionDAG &DAG) const {
5070 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5071 SDValue LHS = Op.getOperand(0);
5072 SDValue RHS = Op.getOperand(1);
5073 SDValue TVal = Op.getOperand(2);
5074 SDValue FVal = Op.getOperand(3);
5075 SDLoc DL(Op);
5076 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5079 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
5080 SelectionDAG &DAG) const {
5081 SDValue CCVal = Op->getOperand(0);
5082 SDValue TVal = Op->getOperand(1);
5083 SDValue FVal = Op->getOperand(2);
5084 SDLoc DL(Op);
5086 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5087 // instruction.
5088 if (isOverflowIntrOpRes(CCVal)) {
5089 // Only lower legal XALUO ops.
5090 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
5091 return SDValue();
5093 AArch64CC::CondCode OFCC;
5094 SDValue Value, Overflow;
5095 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
5096 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
5098 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
5099 CCVal, Overflow);
5102 // Lower it the same way as we would lower a SELECT_CC node.
5103 ISD::CondCode CC;
5104 SDValue LHS, RHS;
5105 if (CCVal.getOpcode() == ISD::SETCC) {
5106 LHS = CCVal.getOperand(0);
5107 RHS = CCVal.getOperand(1);
5108 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
5109 } else {
5110 LHS = CCVal;
5111 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
5112 CC = ISD::SETNE;
5114 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
5117 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
5118 SelectionDAG &DAG) const {
5119 // Jump table entries as PC relative offsets. No additional tweaking
5120 // is necessary here. Just get the address of the jump table.
5121 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5123 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5124 !Subtarget->isTargetMachO()) {
5125 return getAddrLarge(JT, DAG);
5126 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5127 return getAddrTiny(JT, DAG);
5129 return getAddr(JT, DAG);
5132 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
5133 SelectionDAG &DAG) const {
5134 // Jump table entries as PC relative offsets. No additional tweaking
5135 // is necessary here. Just get the address of the jump table.
5136 SDLoc DL(Op);
5137 SDValue JT = Op.getOperand(1);
5138 SDValue Entry = Op.getOperand(2);
5139 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
5141 SDNode *Dest =
5142 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
5143 Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
5144 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
5145 SDValue(Dest, 0));
5148 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
5149 SelectionDAG &DAG) const {
5150 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5152 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
5153 // Use the GOT for the large code model on iOS.
5154 if (Subtarget->isTargetMachO()) {
5155 return getGOT(CP, DAG);
5157 return getAddrLarge(CP, DAG);
5158 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5159 return getAddrTiny(CP, DAG);
5160 } else {
5161 return getAddr(CP, DAG);
5165 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
5166 SelectionDAG &DAG) const {
5167 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
5168 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
5169 !Subtarget->isTargetMachO()) {
5170 return getAddrLarge(BA, DAG);
5171 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
5172 return getAddrTiny(BA, DAG);
5174 return getAddr(BA, DAG);
5177 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
5178 SelectionDAG &DAG) const {
5179 AArch64FunctionInfo *FuncInfo =
5180 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5182 SDLoc DL(Op);
5183 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
5184 getPointerTy(DAG.getDataLayout()));
5185 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5186 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5187 MachinePointerInfo(SV));
5190 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
5191 SelectionDAG &DAG) const {
5192 AArch64FunctionInfo *FuncInfo =
5193 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
5195 SDLoc DL(Op);
5196 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
5197 ? FuncInfo->getVarArgsGPRIndex()
5198 : FuncInfo->getVarArgsStackIndex(),
5199 getPointerTy(DAG.getDataLayout()));
5200 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5201 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
5202 MachinePointerInfo(SV));
5205 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
5206 SelectionDAG &DAG) const {
5207 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5208 // Standard, section B.3.
5209 MachineFunction &MF = DAG.getMachineFunction();
5210 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
5211 auto PtrVT = getPointerTy(DAG.getDataLayout());
5212 SDLoc DL(Op);
5214 SDValue Chain = Op.getOperand(0);
5215 SDValue VAList = Op.getOperand(1);
5216 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5217 SmallVector<SDValue, 4> MemOps;
5219 // void *__stack at offset 0
5220 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
5221 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
5222 MachinePointerInfo(SV), /* Alignment = */ 8));
5224 // void *__gr_top at offset 8
5225 int GPRSize = FuncInfo->getVarArgsGPRSize();
5226 if (GPRSize > 0) {
5227 SDValue GRTop, GRTopAddr;
5229 GRTopAddr =
5230 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
5232 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
5233 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
5234 DAG.getConstant(GPRSize, DL, PtrVT));
5236 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
5237 MachinePointerInfo(SV, 8),
5238 /* Alignment = */ 8));
5241 // void *__vr_top at offset 16
5242 int FPRSize = FuncInfo->getVarArgsFPRSize();
5243 if (FPRSize > 0) {
5244 SDValue VRTop, VRTopAddr;
5245 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5246 DAG.getConstant(16, DL, PtrVT));
5248 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
5249 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
5250 DAG.getConstant(FPRSize, DL, PtrVT));
5252 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
5253 MachinePointerInfo(SV, 16),
5254 /* Alignment = */ 8));
5257 // int __gr_offs at offset 24
5258 SDValue GROffsAddr =
5259 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
5260 MemOps.push_back(DAG.getStore(
5261 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
5262 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
5264 // int __vr_offs at offset 28
5265 SDValue VROffsAddr =
5266 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
5267 MemOps.push_back(DAG.getStore(
5268 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
5269 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
5271 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
5274 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
5275 SelectionDAG &DAG) const {
5276 MachineFunction &MF = DAG.getMachineFunction();
5278 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
5279 return LowerWin64_VASTART(Op, DAG);
5280 else if (Subtarget->isTargetDarwin())
5281 return LowerDarwin_VASTART(Op, DAG);
5282 else
5283 return LowerAAPCS_VASTART(Op, DAG);
5286 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
5287 SelectionDAG &DAG) const {
5288 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5289 // pointer.
5290 SDLoc DL(Op);
5291 unsigned VaListSize =
5292 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
5293 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5294 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5296 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
5297 Op.getOperand(2),
5298 DAG.getConstant(VaListSize, DL, MVT::i32),
5299 8, false, false, false, MachinePointerInfo(DestSV),
5300 MachinePointerInfo(SrcSV));
5303 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
5304 assert(Subtarget->isTargetDarwin() &&
5305 "automatic va_arg instruction only works on Darwin");
5307 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5308 EVT VT = Op.getValueType();
5309 SDLoc DL(Op);
5310 SDValue Chain = Op.getOperand(0);
5311 SDValue Addr = Op.getOperand(1);
5312 unsigned Align = Op.getConstantOperandVal(3);
5313 auto PtrVT = getPointerTy(DAG.getDataLayout());
5315 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
5316 Chain = VAList.getValue(1);
5318 if (Align > 8) {
5319 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
5320 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5321 DAG.getConstant(Align - 1, DL, PtrVT));
5322 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
5323 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
5326 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5327 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
5329 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5330 // up to 64 bits. At the very least, we have to increase the striding of the
5331 // vaargs list to match this, and for FP values we need to introduce
5332 // FP_ROUND nodes as well.
5333 if (VT.isInteger() && !VT.isVector())
5334 ArgSize = 8;
5335 bool NeedFPTrunc = false;
5336 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
5337 ArgSize = 8;
5338 NeedFPTrunc = true;
5341 // Increment the pointer, VAList, to the next vaarg
5342 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
5343 DAG.getConstant(ArgSize, DL, PtrVT));
5344 // Store the incremented VAList to the legalized pointer
5345 SDValue APStore =
5346 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
5348 // Load the actual argument out of the pointer VAList
5349 if (NeedFPTrunc) {
5350 // Load the value as an f64.
5351 SDValue WideFP =
5352 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
5353 // Round the value down to an f32.
5354 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
5355 DAG.getIntPtrConstant(1, DL));
5356 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
5357 // Merge the rounded value with the chain output of the load.
5358 return DAG.getMergeValues(Ops, DL);
5361 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
5364 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
5365 SelectionDAG &DAG) const {
5366 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5367 MFI.setFrameAddressIsTaken(true);
5369 EVT VT = Op.getValueType();
5370 SDLoc DL(Op);
5371 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5372 SDValue FrameAddr =
5373 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5374 while (Depth--)
5375 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
5376 MachinePointerInfo());
5377 return FrameAddr;
5380 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
5381 SelectionDAG &DAG) const {
5382 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5384 EVT VT = getPointerTy(DAG.getDataLayout());
5385 SDLoc DL(Op);
5386 int FI = MFI.CreateFixedObject(4, 0, false);
5387 return DAG.getFrameIndex(FI, VT);
5390 #define GET_REGISTER_MATCHER
5391 #include "AArch64GenAsmMatcher.inc"
5393 // FIXME? Maybe this could be a TableGen attribute on some registers and
5394 // this table could be generated automatically from RegInfo.
5395 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
5396 SelectionDAG &DAG) const {
5397 unsigned Reg = MatchRegisterName(RegName);
5398 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
5399 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
5400 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
5401 if (!Subtarget->isXRegisterReserved(DwarfRegNum))
5402 Reg = 0;
5404 if (Reg)
5405 return Reg;
5406 report_fatal_error(Twine("Invalid register name \""
5407 + StringRef(RegName) + "\"."));
5410 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
5411 SelectionDAG &DAG) const {
5412 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5414 EVT VT = Op.getValueType();
5415 SDLoc DL(Op);
5417 SDValue FrameAddr =
5418 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
5419 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5421 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
5424 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
5425 SelectionDAG &DAG) const {
5426 MachineFunction &MF = DAG.getMachineFunction();
5427 MachineFrameInfo &MFI = MF.getFrameInfo();
5428 MFI.setReturnAddressIsTaken(true);
5430 EVT VT = Op.getValueType();
5431 SDLoc DL(Op);
5432 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5433 if (Depth) {
5434 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5435 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
5436 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
5437 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
5438 MachinePointerInfo());
5441 // Return LR, which contains the return address. Mark it an implicit live-in.
5442 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
5443 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5446 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5447 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5448 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
5449 SelectionDAG &DAG) const {
5450 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5451 EVT VT = Op.getValueType();
5452 unsigned VTBits = VT.getSizeInBits();
5453 SDLoc dl(Op);
5454 SDValue ShOpLo = Op.getOperand(0);
5455 SDValue ShOpHi = Op.getOperand(1);
5456 SDValue ShAmt = Op.getOperand(2);
5457 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5459 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5461 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5462 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5463 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5465 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5466 // is "undef". We wanted 0, so CSEL it directly.
5467 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5468 ISD::SETEQ, dl, DAG);
5469 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5470 HiBitsForLo =
5471 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5472 HiBitsForLo, CCVal, Cmp);
5474 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5475 DAG.getConstant(VTBits, dl, MVT::i64));
5477 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5478 SDValue LoForNormalShift =
5479 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
5481 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5482 dl, DAG);
5483 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5484 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5485 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5486 LoForNormalShift, CCVal, Cmp);
5488 // AArch64 shifts larger than the register width are wrapped rather than
5489 // clamped, so we can't just emit "hi >> x".
5490 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5491 SDValue HiForBigShift =
5492 Opc == ISD::SRA
5493 ? DAG.getNode(Opc, dl, VT, ShOpHi,
5494 DAG.getConstant(VTBits - 1, dl, MVT::i64))
5495 : DAG.getConstant(0, dl, VT);
5496 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5497 HiForNormalShift, CCVal, Cmp);
5499 SDValue Ops[2] = { Lo, Hi };
5500 return DAG.getMergeValues(Ops, dl);
5503 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5504 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5505 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
5506 SelectionDAG &DAG) const {
5507 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5508 EVT VT = Op.getValueType();
5509 unsigned VTBits = VT.getSizeInBits();
5510 SDLoc dl(Op);
5511 SDValue ShOpLo = Op.getOperand(0);
5512 SDValue ShOpHi = Op.getOperand(1);
5513 SDValue ShAmt = Op.getOperand(2);
5515 assert(Op.getOpcode() == ISD::SHL_PARTS);
5516 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
5517 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
5518 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5520 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5521 // is "undef". We wanted 0, so CSEL it directly.
5522 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
5523 ISD::SETEQ, dl, DAG);
5524 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
5525 LoBitsForHi =
5526 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
5527 LoBitsForHi, CCVal, Cmp);
5529 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
5530 DAG.getConstant(VTBits, dl, MVT::i64));
5531 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5532 SDValue HiForNormalShift =
5533 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
5535 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5537 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
5538 dl, DAG);
5539 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
5540 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
5541 HiForNormalShift, CCVal, Cmp);
5543 // AArch64 shifts of larger than register sizes are wrapped rather than
5544 // clamped, so we can't just emit "lo << a" if a is too big.
5545 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
5546 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5547 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
5548 LoForNormalShift, CCVal, Cmp);
5550 SDValue Ops[2] = { Lo, Hi };
5551 return DAG.getMergeValues(Ops, dl);
5554 bool AArch64TargetLowering::isOffsetFoldingLegal(
5555 const GlobalAddressSDNode *GA) const {
5556 // Offsets are folded in the DAG combine rather than here so that we can
5557 // intelligently choose an offset based on the uses.
5558 return false;
5561 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5562 bool OptForSize) const {
5563 bool IsLegal = false;
5564 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5565 // 16-bit case when target has full fp16 support.
5566 // FIXME: We should be able to handle f128 as well with a clever lowering.
5567 const APInt ImmInt = Imm.bitcastToAPInt();
5568 if (VT == MVT::f64)
5569 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
5570 else if (VT == MVT::f32)
5571 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
5572 else if (VT == MVT::f16 && Subtarget->hasFullFP16())
5573 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
5574 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5575 // generate that fmov.
5577 // If we can not materialize in immediate field for fmov, check if the
5578 // value can be encoded as the immediate operand of a logical instruction.
5579 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5580 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
5581 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5582 // however the mov+fmov sequence is always better because of the reduced
5583 // cache pressure. The timings are still the same if you consider
5584 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5585 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5586 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
5587 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
5588 Insn);
5589 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
5590 IsLegal = Insn.size() <= Limit;
5593 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
5594 << " imm value: "; Imm.dump(););
5595 return IsLegal;
5598 //===----------------------------------------------------------------------===//
5599 // AArch64 Optimization Hooks
5600 //===----------------------------------------------------------------------===//
5602 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
5603 SDValue Operand, SelectionDAG &DAG,
5604 int &ExtraSteps) {
5605 EVT VT = Operand.getValueType();
5606 if (ST->hasNEON() &&
5607 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
5608 VT == MVT::f32 || VT == MVT::v1f32 ||
5609 VT == MVT::v2f32 || VT == MVT::v4f32)) {
5610 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
5611 // For the reciprocal estimates, convergence is quadratic, so the number
5612 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5613 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5614 // the result for float (23 mantissa bits) is 2 and for double (52
5615 // mantissa bits) is 3.
5616 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
5618 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
5621 return SDValue();
5624 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
5625 SelectionDAG &DAG, int Enabled,
5626 int &ExtraSteps,
5627 bool &UseOneConst,
5628 bool Reciprocal) const {
5629 if (Enabled == ReciprocalEstimate::Enabled ||
5630 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5631 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5632 DAG, ExtraSteps)) {
5633 SDLoc DL(Operand);
5634 EVT VT = Operand.getValueType();
5636 SDNodeFlags Flags;
5637 Flags.setAllowReassociation(true);
5639 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5640 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5641 for (int i = ExtraSteps; i > 0; --i) {
5642 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5643 Flags);
5644 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5645 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5647 if (!Reciprocal) {
5648 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5649 VT);
5650 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5651 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5653 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5654 // Correct the result if the operand is 0.0.
5655 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5656 VT, Eq, Operand, Estimate);
5659 ExtraSteps = 0;
5660 return Estimate;
5663 return SDValue();
5666 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5667 SelectionDAG &DAG, int Enabled,
5668 int &ExtraSteps) const {
5669 if (Enabled == ReciprocalEstimate::Enabled)
5670 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5671 DAG, ExtraSteps)) {
5672 SDLoc DL(Operand);
5673 EVT VT = Operand.getValueType();
5675 SDNodeFlags Flags;
5676 Flags.setAllowReassociation(true);
5678 // Newton reciprocal iteration: E * (2 - X * E)
5679 // AArch64 reciprocal iteration instruction: (2 - M * N)
5680 for (int i = ExtraSteps; i > 0; --i) {
5681 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5682 Estimate, Flags);
5683 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5686 ExtraSteps = 0;
5687 return Estimate;
5690 return SDValue();
5693 //===----------------------------------------------------------------------===//
5694 // AArch64 Inline Assembly Support
5695 //===----------------------------------------------------------------------===//
5697 // Table of Constraints
5698 // TODO: This is the current set of constraints supported by ARM for the
5699 // compiler, not all of them may make sense.
5701 // r - A general register
5702 // w - An FP/SIMD register of some size in the range v0-v31
5703 // x - An FP/SIMD register of some size in the range v0-v15
5704 // I - Constant that can be used with an ADD instruction
5705 // J - Constant that can be used with a SUB instruction
5706 // K - Constant that can be used with a 32-bit logical instruction
5707 // L - Constant that can be used with a 64-bit logical instruction
5708 // M - Constant that can be used as a 32-bit MOV immediate
5709 // N - Constant that can be used as a 64-bit MOV immediate
5710 // Q - A memory reference with base register and no offset
5711 // S - A symbolic address
5712 // Y - Floating point constant zero
5713 // Z - Integer constant zero
5715 // Note that general register operands will be output using their 64-bit x
5716 // register name, whatever the size of the variable, unless the asm operand
5717 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5718 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5719 // %q modifier.
5720 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5721 // At this point, we have to lower this constraint to something else, so we
5722 // lower it to an "r" or "w". However, by doing this we will force the result
5723 // to be in register, while the X constraint is much more permissive.
5725 // Although we are correct (we are free to emit anything, without
5726 // constraints), we might break use cases that would expect us to be more
5727 // efficient and emit something else.
5728 if (!Subtarget->hasFPARMv8())
5729 return "r";
5731 if (ConstraintVT.isFloatingPoint())
5732 return "w";
5734 if (ConstraintVT.isVector() &&
5735 (ConstraintVT.getSizeInBits() == 64 ||
5736 ConstraintVT.getSizeInBits() == 128))
5737 return "w";
5739 return "r";
5742 /// getConstraintType - Given a constraint letter, return the type of
5743 /// constraint it is for this target.
5744 AArch64TargetLowering::ConstraintType
5745 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5746 if (Constraint.size() == 1) {
5747 switch (Constraint[0]) {
5748 default:
5749 break;
5750 case 'x':
5751 case 'w':
5752 case 'y':
5753 return C_RegisterClass;
5754 // An address with a single base register. Due to the way we
5755 // currently handle addresses it is the same as 'r'.
5756 case 'Q':
5757 return C_Memory;
5758 case 'I':
5759 case 'J':
5760 case 'K':
5761 case 'L':
5762 case 'M':
5763 case 'N':
5764 case 'Y':
5765 case 'Z':
5766 return C_Immediate;
5767 case 'z':
5768 case 'S': // A symbolic address
5769 return C_Other;
5772 return TargetLowering::getConstraintType(Constraint);
5775 /// Examine constraint type and operand type and determine a weight value.
5776 /// This object must already have been set up with the operand type
5777 /// and the current alternative constraint selected.
5778 TargetLowering::ConstraintWeight
5779 AArch64TargetLowering::getSingleConstraintMatchWeight(
5780 AsmOperandInfo &info, const char *constraint) const {
5781 ConstraintWeight weight = CW_Invalid;
5782 Value *CallOperandVal = info.CallOperandVal;
5783 // If we don't have a value, we can't do a match,
5784 // but allow it at the lowest weight.
5785 if (!CallOperandVal)
5786 return CW_Default;
5787 Type *type = CallOperandVal->getType();
5788 // Look at the constraint type.
5789 switch (*constraint) {
5790 default:
5791 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5792 break;
5793 case 'x':
5794 case 'w':
5795 case 'y':
5796 if (type->isFloatingPointTy() || type->isVectorTy())
5797 weight = CW_Register;
5798 break;
5799 case 'z':
5800 weight = CW_Constant;
5801 break;
5803 return weight;
5806 std::pair<unsigned, const TargetRegisterClass *>
5807 AArch64TargetLowering::getRegForInlineAsmConstraint(
5808 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5809 if (Constraint.size() == 1) {
5810 switch (Constraint[0]) {
5811 case 'r':
5812 if (VT.getSizeInBits() == 64)
5813 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5814 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5815 case 'w':
5816 if (!Subtarget->hasFPARMv8())
5817 break;
5818 if (VT.isScalableVector())
5819 return std::make_pair(0U, &AArch64::ZPRRegClass);
5820 if (VT.getSizeInBits() == 16)
5821 return std::make_pair(0U, &AArch64::FPR16RegClass);
5822 if (VT.getSizeInBits() == 32)
5823 return std::make_pair(0U, &AArch64::FPR32RegClass);
5824 if (VT.getSizeInBits() == 64)
5825 return std::make_pair(0U, &AArch64::FPR64RegClass);
5826 if (VT.getSizeInBits() == 128)
5827 return std::make_pair(0U, &AArch64::FPR128RegClass);
5828 break;
5829 // The instructions that this constraint is designed for can
5830 // only take 128-bit registers so just use that regclass.
5831 case 'x':
5832 if (!Subtarget->hasFPARMv8())
5833 break;
5834 if (VT.isScalableVector())
5835 return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
5836 if (VT.getSizeInBits() == 128)
5837 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5838 break;
5839 case 'y':
5840 if (!Subtarget->hasFPARMv8())
5841 break;
5842 if (VT.isScalableVector())
5843 return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
5844 break;
5847 if (StringRef("{cc}").equals_lower(Constraint))
5848 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5850 // Use the default implementation in TargetLowering to convert the register
5851 // constraint into a member of a register class.
5852 std::pair<unsigned, const TargetRegisterClass *> Res;
5853 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5855 // Not found as a standard register?
5856 if (!Res.second) {
5857 unsigned Size = Constraint.size();
5858 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5859 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5860 int RegNo;
5861 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5862 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5863 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5864 // By default we'll emit v0-v31 for this unless there's a modifier where
5865 // we'll emit the correct register as well.
5866 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5867 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5868 Res.second = &AArch64::FPR64RegClass;
5869 } else {
5870 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5871 Res.second = &AArch64::FPR128RegClass;
5877 if (Res.second && !Subtarget->hasFPARMv8() &&
5878 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
5879 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
5880 return std::make_pair(0U, nullptr);
5882 return Res;
5885 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5886 /// vector. If it is invalid, don't add anything to Ops.
5887 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5888 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5889 SelectionDAG &DAG) const {
5890 SDValue Result;
5892 // Currently only support length 1 constraints.
5893 if (Constraint.length() != 1)
5894 return;
5896 char ConstraintLetter = Constraint[0];
5897 switch (ConstraintLetter) {
5898 default:
5899 break;
5901 // This set of constraints deal with valid constants for various instructions.
5902 // Validate and return a target constant for them if we can.
5903 case 'z': {
5904 // 'z' maps to xzr or wzr so it needs an input of 0.
5905 if (!isNullConstant(Op))
5906 return;
5908 if (Op.getValueType() == MVT::i64)
5909 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5910 else
5911 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5912 break;
5914 case 'S': {
5915 // An absolute symbolic address or label reference.
5916 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5917 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5918 GA->getValueType(0));
5919 } else if (const BlockAddressSDNode *BA =
5920 dyn_cast<BlockAddressSDNode>(Op)) {
5921 Result =
5922 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5923 } else if (const ExternalSymbolSDNode *ES =
5924 dyn_cast<ExternalSymbolSDNode>(Op)) {
5925 Result =
5926 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5927 } else
5928 return;
5929 break;
5932 case 'I':
5933 case 'J':
5934 case 'K':
5935 case 'L':
5936 case 'M':
5937 case 'N':
5938 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5939 if (!C)
5940 return;
5942 // Grab the value and do some validation.
5943 uint64_t CVal = C->getZExtValue();
5944 switch (ConstraintLetter) {
5945 // The I constraint applies only to simple ADD or SUB immediate operands:
5946 // i.e. 0 to 4095 with optional shift by 12
5947 // The J constraint applies only to ADD or SUB immediates that would be
5948 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5949 // instruction [or vice versa], in other words -1 to -4095 with optional
5950 // left shift by 12.
5951 case 'I':
5952 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5953 break;
5954 return;
5955 case 'J': {
5956 uint64_t NVal = -C->getSExtValue();
5957 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5958 CVal = C->getSExtValue();
5959 break;
5961 return;
5963 // The K and L constraints apply *only* to logical immediates, including
5964 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5965 // been removed and MOV should be used). So these constraints have to
5966 // distinguish between bit patterns that are valid 32-bit or 64-bit
5967 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5968 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5969 // versa.
5970 case 'K':
5971 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5972 break;
5973 return;
5974 case 'L':
5975 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5976 break;
5977 return;
5978 // The M and N constraints are a superset of K and L respectively, for use
5979 // with the MOV (immediate) alias. As well as the logical immediates they
5980 // also match 32 or 64-bit immediates that can be loaded either using a
5981 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5982 // (M) or 64-bit 0x1234000000000000 (N) etc.
5983 // As a note some of this code is liberally stolen from the asm parser.
5984 case 'M': {
5985 if (!isUInt<32>(CVal))
5986 return;
5987 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5988 break;
5989 if ((CVal & 0xFFFF) == CVal)
5990 break;
5991 if ((CVal & 0xFFFF0000ULL) == CVal)
5992 break;
5993 uint64_t NCVal = ~(uint32_t)CVal;
5994 if ((NCVal & 0xFFFFULL) == NCVal)
5995 break;
5996 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5997 break;
5998 return;
6000 case 'N': {
6001 if (AArch64_AM::isLogicalImmediate(CVal, 64))
6002 break;
6003 if ((CVal & 0xFFFFULL) == CVal)
6004 break;
6005 if ((CVal & 0xFFFF0000ULL) == CVal)
6006 break;
6007 if ((CVal & 0xFFFF00000000ULL) == CVal)
6008 break;
6009 if ((CVal & 0xFFFF000000000000ULL) == CVal)
6010 break;
6011 uint64_t NCVal = ~CVal;
6012 if ((NCVal & 0xFFFFULL) == NCVal)
6013 break;
6014 if ((NCVal & 0xFFFF0000ULL) == NCVal)
6015 break;
6016 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
6017 break;
6018 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
6019 break;
6020 return;
6022 default:
6023 return;
6026 // All assembler immediates are 64-bit integers.
6027 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
6028 break;
6031 if (Result.getNode()) {
6032 Ops.push_back(Result);
6033 return;
6036 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6039 //===----------------------------------------------------------------------===//
6040 // AArch64 Advanced SIMD Support
6041 //===----------------------------------------------------------------------===//
6043 /// WidenVector - Given a value in the V64 register class, produce the
6044 /// equivalent value in the V128 register class.
6045 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
6046 EVT VT = V64Reg.getValueType();
6047 unsigned NarrowSize = VT.getVectorNumElements();
6048 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6049 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
6050 SDLoc DL(V64Reg);
6052 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
6053 V64Reg, DAG.getConstant(0, DL, MVT::i32));
6056 /// getExtFactor - Determine the adjustment factor for the position when
6057 /// generating an "extract from vector registers" instruction.
6058 static unsigned getExtFactor(SDValue &V) {
6059 EVT EltType = V.getValueType().getVectorElementType();
6060 return EltType.getSizeInBits() / 8;
6063 /// NarrowVector - Given a value in the V128 register class, produce the
6064 /// equivalent value in the V64 register class.
6065 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
6066 EVT VT = V128Reg.getValueType();
6067 unsigned WideSize = VT.getVectorNumElements();
6068 MVT EltTy = VT.getVectorElementType().getSimpleVT();
6069 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
6070 SDLoc DL(V128Reg);
6072 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
6075 // Gather data to see if the operation can be modelled as a
6076 // shuffle in combination with VEXTs.
6077 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
6078 SelectionDAG &DAG) const {
6079 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6080 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6081 SDLoc dl(Op);
6082 EVT VT = Op.getValueType();
6083 unsigned NumElts = VT.getVectorNumElements();
6085 struct ShuffleSourceInfo {
6086 SDValue Vec;
6087 unsigned MinElt;
6088 unsigned MaxElt;
6090 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6091 // be compatible with the shuffle we intend to construct. As a result
6092 // ShuffleVec will be some sliding window into the original Vec.
6093 SDValue ShuffleVec;
6095 // Code should guarantee that element i in Vec starts at element "WindowBase
6096 // + i * WindowScale in ShuffleVec".
6097 int WindowBase;
6098 int WindowScale;
6100 ShuffleSourceInfo(SDValue Vec)
6101 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
6102 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
6104 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6107 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6108 // node.
6109 SmallVector<ShuffleSourceInfo, 2> Sources;
6110 for (unsigned i = 0; i < NumElts; ++i) {
6111 SDValue V = Op.getOperand(i);
6112 if (V.isUndef())
6113 continue;
6114 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6115 !isa<ConstantSDNode>(V.getOperand(1))) {
6116 LLVM_DEBUG(
6117 dbgs() << "Reshuffle failed: "
6118 "a shuffle can only come from building a vector from "
6119 "various elements of other vectors, provided their "
6120 "indices are constant\n");
6121 return SDValue();
6124 // Add this element source to the list if it's not already there.
6125 SDValue SourceVec = V.getOperand(0);
6126 auto Source = find(Sources, SourceVec);
6127 if (Source == Sources.end())
6128 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6130 // Update the minimum and maximum lane number seen.
6131 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6132 Source->MinElt = std::min(Source->MinElt, EltNo);
6133 Source->MaxElt = std::max(Source->MaxElt, EltNo);
6136 if (Sources.size() > 2) {
6137 LLVM_DEBUG(
6138 dbgs() << "Reshuffle failed: currently only do something sane when at "
6139 "most two source vectors are involved\n");
6140 return SDValue();
6143 // Find out the smallest element size among result and two sources, and use
6144 // it as element size to build the shuffle_vector.
6145 EVT SmallestEltTy = VT.getVectorElementType();
6146 for (auto &Source : Sources) {
6147 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6148 if (SrcEltTy.bitsLT(SmallestEltTy)) {
6149 SmallestEltTy = SrcEltTy;
6152 unsigned ResMultiplier =
6153 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6154 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6155 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6157 // If the source vector is too wide or too narrow, we may nevertheless be able
6158 // to construct a compatible shuffle either by concatenating it with UNDEF or
6159 // extracting a suitable range of elements.
6160 for (auto &Src : Sources) {
6161 EVT SrcVT = Src.ShuffleVec.getValueType();
6163 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6164 continue;
6166 // This stage of the search produces a source with the same element type as
6167 // the original, but with a total width matching the BUILD_VECTOR output.
6168 EVT EltVT = SrcVT.getVectorElementType();
6169 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6170 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6172 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6173 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
6174 // We can pad out the smaller vector for free, so if it's part of a
6175 // shuffle...
6176 Src.ShuffleVec =
6177 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6178 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6179 continue;
6182 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
6184 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6185 LLVM_DEBUG(
6186 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6187 return SDValue();
6190 if (Src.MinElt >= NumSrcElts) {
6191 // The extraction can just take the second half
6192 Src.ShuffleVec =
6193 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6194 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6195 Src.WindowBase = -NumSrcElts;
6196 } else if (Src.MaxElt < NumSrcElts) {
6197 // The extraction can just take the first half
6198 Src.ShuffleVec =
6199 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6200 DAG.getConstant(0, dl, MVT::i64));
6201 } else {
6202 // An actual VEXT is needed
6203 SDValue VEXTSrc1 =
6204 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6205 DAG.getConstant(0, dl, MVT::i64));
6206 SDValue VEXTSrc2 =
6207 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6208 DAG.getConstant(NumSrcElts, dl, MVT::i64));
6209 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
6211 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
6212 VEXTSrc2,
6213 DAG.getConstant(Imm, dl, MVT::i32));
6214 Src.WindowBase = -Src.MinElt;
6218 // Another possible incompatibility occurs from the vector element types. We
6219 // can fix this by bitcasting the source vectors to the same type we intend
6220 // for the shuffle.
6221 for (auto &Src : Sources) {
6222 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6223 if (SrcEltTy == SmallestEltTy)
6224 continue;
6225 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6226 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6227 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6228 Src.WindowBase *= Src.WindowScale;
6231 // Final sanity check before we try to actually produce a shuffle.
6232 LLVM_DEBUG(for (auto Src
6233 : Sources)
6234 assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6236 // The stars all align, our next step is to produce the mask for the shuffle.
6237 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6238 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6239 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6240 SDValue Entry = Op.getOperand(i);
6241 if (Entry.isUndef())
6242 continue;
6244 auto Src = find(Sources, Entry.getOperand(0));
6245 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6247 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6248 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6249 // segment.
6250 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6251 int BitsDefined =
6252 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
6253 int LanesDefined = BitsDefined / BitsPerShuffleLane;
6255 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6256 // starting at the appropriate offset.
6257 int *LaneMask = &Mask[i * ResMultiplier];
6259 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6260 ExtractBase += NumElts * (Src - Sources.begin());
6261 for (int j = 0; j < LanesDefined; ++j)
6262 LaneMask[j] = ExtractBase + j;
6265 // Final check before we try to produce nonsense...
6266 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
6267 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6268 return SDValue();
6271 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6272 for (unsigned i = 0; i < Sources.size(); ++i)
6273 ShuffleOps[i] = Sources[i].ShuffleVec;
6275 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6276 ShuffleOps[1], Mask);
6277 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6279 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
6280 dbgs() << "Reshuffle, creating node: "; V.dump(););
6282 return V;
6285 // check if an EXT instruction can handle the shuffle mask when the
6286 // vector sources of the shuffle are the same.
6287 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6288 unsigned NumElts = VT.getVectorNumElements();
6290 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6291 if (M[0] < 0)
6292 return false;
6294 Imm = M[0];
6296 // If this is a VEXT shuffle, the immediate value is the index of the first
6297 // element. The other shuffle indices must be the successive elements after
6298 // the first one.
6299 unsigned ExpectedElt = Imm;
6300 for (unsigned i = 1; i < NumElts; ++i) {
6301 // Increment the expected index. If it wraps around, just follow it
6302 // back to index zero and keep going.
6303 ++ExpectedElt;
6304 if (ExpectedElt == NumElts)
6305 ExpectedElt = 0;
6307 if (M[i] < 0)
6308 continue; // ignore UNDEF indices
6309 if (ExpectedElt != static_cast<unsigned>(M[i]))
6310 return false;
6313 return true;
6316 // check if an EXT instruction can handle the shuffle mask when the
6317 // vector sources of the shuffle are different.
6318 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
6319 unsigned &Imm) {
6320 // Look for the first non-undef element.
6321 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
6323 // Benefit form APInt to handle overflow when calculating expected element.
6324 unsigned NumElts = VT.getVectorNumElements();
6325 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
6326 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
6327 // The following shuffle indices must be the successive elements after the
6328 // first real element.
6329 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
6330 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
6331 if (FirstWrongElt != M.end())
6332 return false;
6334 // The index of an EXT is the first element if it is not UNDEF.
6335 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6336 // value of the first element. E.g.
6337 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6338 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6339 // ExpectedElt is the last mask index plus 1.
6340 Imm = ExpectedElt.getZExtValue();
6342 // There are two difference cases requiring to reverse input vectors.
6343 // For example, for vector <4 x i32> we have the following cases,
6344 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6345 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6346 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6347 // to reverse two input vectors.
6348 if (Imm < NumElts)
6349 ReverseEXT = true;
6350 else
6351 Imm -= NumElts;
6353 return true;
6356 /// isREVMask - Check if a vector shuffle corresponds to a REV
6357 /// instruction with the specified blocksize. (The order of the elements
6358 /// within each block of the vector is reversed.)
6359 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6360 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
6361 "Only possible block sizes for REV are: 16, 32, 64");
6363 unsigned EltSz = VT.getScalarSizeInBits();
6364 if (EltSz == 64)
6365 return false;
6367 unsigned NumElts = VT.getVectorNumElements();
6368 unsigned BlockElts = M[0] + 1;
6369 // If the first shuffle index is UNDEF, be optimistic.
6370 if (M[0] < 0)
6371 BlockElts = BlockSize / EltSz;
6373 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6374 return false;
6376 for (unsigned i = 0; i < NumElts; ++i) {
6377 if (M[i] < 0)
6378 continue; // ignore UNDEF indices
6379 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
6380 return false;
6383 return true;
6386 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6387 unsigned NumElts = VT.getVectorNumElements();
6388 if (NumElts % 2 != 0)
6389 return false;
6390 WhichResult = (M[0] == 0 ? 0 : 1);
6391 unsigned Idx = WhichResult * NumElts / 2;
6392 for (unsigned i = 0; i != NumElts; i += 2) {
6393 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6394 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
6395 return false;
6396 Idx += 1;
6399 return true;
6402 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6403 unsigned NumElts = VT.getVectorNumElements();
6404 WhichResult = (M[0] == 0 ? 0 : 1);
6405 for (unsigned i = 0; i != NumElts; ++i) {
6406 if (M[i] < 0)
6407 continue; // ignore UNDEF indices
6408 if ((unsigned)M[i] != 2 * i + WhichResult)
6409 return false;
6412 return true;
6415 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6416 unsigned NumElts = VT.getVectorNumElements();
6417 if (NumElts % 2 != 0)
6418 return false;
6419 WhichResult = (M[0] == 0 ? 0 : 1);
6420 for (unsigned i = 0; i < NumElts; i += 2) {
6421 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6422 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
6423 return false;
6425 return true;
6428 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6429 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6430 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6431 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6432 unsigned NumElts = VT.getVectorNumElements();
6433 if (NumElts % 2 != 0)
6434 return false;
6435 WhichResult = (M[0] == 0 ? 0 : 1);
6436 unsigned Idx = WhichResult * NumElts / 2;
6437 for (unsigned i = 0; i != NumElts; i += 2) {
6438 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
6439 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
6440 return false;
6441 Idx += 1;
6444 return true;
6447 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6448 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6449 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6450 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6451 unsigned Half = VT.getVectorNumElements() / 2;
6452 WhichResult = (M[0] == 0 ? 0 : 1);
6453 for (unsigned j = 0; j != 2; ++j) {
6454 unsigned Idx = WhichResult;
6455 for (unsigned i = 0; i != Half; ++i) {
6456 int MIdx = M[i + j * Half];
6457 if (MIdx >= 0 && (unsigned)MIdx != Idx)
6458 return false;
6459 Idx += 2;
6463 return true;
6466 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6467 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6468 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6469 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6470 unsigned NumElts = VT.getVectorNumElements();
6471 if (NumElts % 2 != 0)
6472 return false;
6473 WhichResult = (M[0] == 0 ? 0 : 1);
6474 for (unsigned i = 0; i < NumElts; i += 2) {
6475 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
6476 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
6477 return false;
6479 return true;
6482 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
6483 bool &DstIsLeft, int &Anomaly) {
6484 if (M.size() != static_cast<size_t>(NumInputElements))
6485 return false;
6487 int NumLHSMatch = 0, NumRHSMatch = 0;
6488 int LastLHSMismatch = -1, LastRHSMismatch = -1;
6490 for (int i = 0; i < NumInputElements; ++i) {
6491 if (M[i] == -1) {
6492 ++NumLHSMatch;
6493 ++NumRHSMatch;
6494 continue;
6497 if (M[i] == i)
6498 ++NumLHSMatch;
6499 else
6500 LastLHSMismatch = i;
6502 if (M[i] == i + NumInputElements)
6503 ++NumRHSMatch;
6504 else
6505 LastRHSMismatch = i;
6508 if (NumLHSMatch == NumInputElements - 1) {
6509 DstIsLeft = true;
6510 Anomaly = LastLHSMismatch;
6511 return true;
6512 } else if (NumRHSMatch == NumInputElements - 1) {
6513 DstIsLeft = false;
6514 Anomaly = LastRHSMismatch;
6515 return true;
6518 return false;
6521 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
6522 if (VT.getSizeInBits() != 128)
6523 return false;
6525 unsigned NumElts = VT.getVectorNumElements();
6527 for (int I = 0, E = NumElts / 2; I != E; I++) {
6528 if (Mask[I] != I)
6529 return false;
6532 int Offset = NumElts / 2;
6533 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
6534 if (Mask[I] != I + SplitLHS * Offset)
6535 return false;
6538 return true;
6541 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
6542 SDLoc DL(Op);
6543 EVT VT = Op.getValueType();
6544 SDValue V0 = Op.getOperand(0);
6545 SDValue V1 = Op.getOperand(1);
6546 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
6548 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
6549 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
6550 return SDValue();
6552 bool SplitV0 = V0.getValueSizeInBits() == 128;
6554 if (!isConcatMask(Mask, VT, SplitV0))
6555 return SDValue();
6557 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6558 if (SplitV0) {
6559 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
6560 DAG.getConstant(0, DL, MVT::i64));
6562 if (V1.getValueSizeInBits() == 128) {
6563 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
6564 DAG.getConstant(0, DL, MVT::i64));
6566 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
6569 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6570 /// the specified operations to build the shuffle.
6571 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6572 SDValue RHS, SelectionDAG &DAG,
6573 const SDLoc &dl) {
6574 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6575 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
6576 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
6578 enum {
6579 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6580 OP_VREV,
6581 OP_VDUP0,
6582 OP_VDUP1,
6583 OP_VDUP2,
6584 OP_VDUP3,
6585 OP_VEXT1,
6586 OP_VEXT2,
6587 OP_VEXT3,
6588 OP_VUZPL, // VUZP, left result
6589 OP_VUZPR, // VUZP, right result
6590 OP_VZIPL, // VZIP, left result
6591 OP_VZIPR, // VZIP, right result
6592 OP_VTRNL, // VTRN, left result
6593 OP_VTRNR // VTRN, right result
6596 if (OpNum == OP_COPY) {
6597 if (LHSID == (1 * 9 + 2) * 9 + 3)
6598 return LHS;
6599 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6600 return RHS;
6603 SDValue OpLHS, OpRHS;
6604 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6605 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6606 EVT VT = OpLHS.getValueType();
6608 switch (OpNum) {
6609 default:
6610 llvm_unreachable("Unknown shuffle opcode!");
6611 case OP_VREV:
6612 // VREV divides the vector in half and swaps within the half.
6613 if (VT.getVectorElementType() == MVT::i32 ||
6614 VT.getVectorElementType() == MVT::f32)
6615 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
6616 // vrev <4 x i16> -> REV32
6617 if (VT.getVectorElementType() == MVT::i16 ||
6618 VT.getVectorElementType() == MVT::f16)
6619 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
6620 // vrev <4 x i8> -> REV16
6621 assert(VT.getVectorElementType() == MVT::i8);
6622 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
6623 case OP_VDUP0:
6624 case OP_VDUP1:
6625 case OP_VDUP2:
6626 case OP_VDUP3: {
6627 EVT EltTy = VT.getVectorElementType();
6628 unsigned Opcode;
6629 if (EltTy == MVT::i8)
6630 Opcode = AArch64ISD::DUPLANE8;
6631 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
6632 Opcode = AArch64ISD::DUPLANE16;
6633 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
6634 Opcode = AArch64ISD::DUPLANE32;
6635 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
6636 Opcode = AArch64ISD::DUPLANE64;
6637 else
6638 llvm_unreachable("Invalid vector element type?");
6640 if (VT.getSizeInBits() == 64)
6641 OpLHS = WidenVector(OpLHS, DAG);
6642 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
6643 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
6645 case OP_VEXT1:
6646 case OP_VEXT2:
6647 case OP_VEXT3: {
6648 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
6649 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
6650 DAG.getConstant(Imm, dl, MVT::i32));
6652 case OP_VUZPL:
6653 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
6654 OpRHS);
6655 case OP_VUZPR:
6656 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
6657 OpRHS);
6658 case OP_VZIPL:
6659 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
6660 OpRHS);
6661 case OP_VZIPR:
6662 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6663 OpRHS);
6664 case OP_VTRNL:
6665 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6666 OpRHS);
6667 case OP_VTRNR:
6668 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6669 OpRHS);
6673 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6674 SelectionDAG &DAG) {
6675 // Check to see if we can use the TBL instruction.
6676 SDValue V1 = Op.getOperand(0);
6677 SDValue V2 = Op.getOperand(1);
6678 SDLoc DL(Op);
6680 EVT EltVT = Op.getValueType().getVectorElementType();
6681 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6683 SmallVector<SDValue, 8> TBLMask;
6684 for (int Val : ShuffleMask) {
6685 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6686 unsigned Offset = Byte + Val * BytesPerElt;
6687 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6691 MVT IndexVT = MVT::v8i8;
6692 unsigned IndexLen = 8;
6693 if (Op.getValueSizeInBits() == 128) {
6694 IndexVT = MVT::v16i8;
6695 IndexLen = 16;
6698 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6699 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6701 SDValue Shuffle;
6702 if (V2.getNode()->isUndef()) {
6703 if (IndexLen == 8)
6704 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6705 Shuffle = DAG.getNode(
6706 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6707 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6708 DAG.getBuildVector(IndexVT, DL,
6709 makeArrayRef(TBLMask.data(), IndexLen)));
6710 } else {
6711 if (IndexLen == 8) {
6712 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6713 Shuffle = DAG.getNode(
6714 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6715 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6716 DAG.getBuildVector(IndexVT, DL,
6717 makeArrayRef(TBLMask.data(), IndexLen)));
6718 } else {
6719 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6720 // cannot currently represent the register constraints on the input
6721 // table registers.
6722 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6723 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6724 // IndexLen));
6725 Shuffle = DAG.getNode(
6726 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6727 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6728 V2Cst, DAG.getBuildVector(IndexVT, DL,
6729 makeArrayRef(TBLMask.data(), IndexLen)));
6732 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6735 static unsigned getDUPLANEOp(EVT EltType) {
6736 if (EltType == MVT::i8)
6737 return AArch64ISD::DUPLANE8;
6738 if (EltType == MVT::i16 || EltType == MVT::f16)
6739 return AArch64ISD::DUPLANE16;
6740 if (EltType == MVT::i32 || EltType == MVT::f32)
6741 return AArch64ISD::DUPLANE32;
6742 if (EltType == MVT::i64 || EltType == MVT::f64)
6743 return AArch64ISD::DUPLANE64;
6745 llvm_unreachable("Invalid vector element type?");
6748 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6749 SelectionDAG &DAG) const {
6750 SDLoc dl(Op);
6751 EVT VT = Op.getValueType();
6753 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6755 // Convert shuffles that are directly supported on NEON to target-specific
6756 // DAG nodes, instead of keeping them as shuffles and matching them again
6757 // during code selection. This is more efficient and avoids the possibility
6758 // of inconsistencies between legalization and selection.
6759 ArrayRef<int> ShuffleMask = SVN->getMask();
6761 SDValue V1 = Op.getOperand(0);
6762 SDValue V2 = Op.getOperand(1);
6764 if (SVN->isSplat()) {
6765 int Lane = SVN->getSplatIndex();
6766 // If this is undef splat, generate it via "just" vdup, if possible.
6767 if (Lane == -1)
6768 Lane = 0;
6770 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6771 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6772 V1.getOperand(0));
6773 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6774 // constant. If so, we can just reference the lane's definition directly.
6775 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6776 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6777 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6779 // Otherwise, duplicate from the lane of the input vector.
6780 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6782 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6783 // to make a vector of the same size as this SHUFFLE. We can ignore the
6784 // extract entirely, and canonicalise the concat using WidenVector.
6785 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6786 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6787 V1 = V1.getOperand(0);
6788 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6789 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6790 Lane -= Idx * VT.getVectorNumElements() / 2;
6791 V1 = WidenVector(V1.getOperand(Idx), DAG);
6792 } else if (VT.getSizeInBits() == 64)
6793 V1 = WidenVector(V1, DAG);
6795 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6798 if (isREVMask(ShuffleMask, VT, 64))
6799 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6800 if (isREVMask(ShuffleMask, VT, 32))
6801 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6802 if (isREVMask(ShuffleMask, VT, 16))
6803 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6805 bool ReverseEXT = false;
6806 unsigned Imm;
6807 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6808 if (ReverseEXT)
6809 std::swap(V1, V2);
6810 Imm *= getExtFactor(V1);
6811 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6812 DAG.getConstant(Imm, dl, MVT::i32));
6813 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6814 Imm *= getExtFactor(V1);
6815 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6816 DAG.getConstant(Imm, dl, MVT::i32));
6819 unsigned WhichResult;
6820 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6821 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6822 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6824 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6825 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6826 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6828 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6829 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6830 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6833 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6834 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6835 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6837 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6838 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6839 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6841 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6842 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6843 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6846 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6847 return Concat;
6849 bool DstIsLeft;
6850 int Anomaly;
6851 int NumInputElements = V1.getValueType().getVectorNumElements();
6852 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6853 SDValue DstVec = DstIsLeft ? V1 : V2;
6854 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6856 SDValue SrcVec = V1;
6857 int SrcLane = ShuffleMask[Anomaly];
6858 if (SrcLane >= NumInputElements) {
6859 SrcVec = V2;
6860 SrcLane -= VT.getVectorNumElements();
6862 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6864 EVT ScalarVT = VT.getVectorElementType();
6866 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6867 ScalarVT = MVT::i32;
6869 return DAG.getNode(
6870 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6871 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6872 DstLaneV);
6875 // If the shuffle is not directly supported and it has 4 elements, use
6876 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6877 unsigned NumElts = VT.getVectorNumElements();
6878 if (NumElts == 4) {
6879 unsigned PFIndexes[4];
6880 for (unsigned i = 0; i != 4; ++i) {
6881 if (ShuffleMask[i] < 0)
6882 PFIndexes[i] = 8;
6883 else
6884 PFIndexes[i] = ShuffleMask[i];
6887 // Compute the index in the perfect shuffle table.
6888 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6889 PFIndexes[2] * 9 + PFIndexes[3];
6890 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6891 unsigned Cost = (PFEntry >> 30);
6893 if (Cost <= 4)
6894 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6897 return GenerateTBL(Op, ShuffleMask, DAG);
6900 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6901 APInt &UndefBits) {
6902 EVT VT = BVN->getValueType(0);
6903 APInt SplatBits, SplatUndef;
6904 unsigned SplatBitSize;
6905 bool HasAnyUndefs;
6906 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6907 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6909 for (unsigned i = 0; i < NumSplats; ++i) {
6910 CnstBits <<= SplatBitSize;
6911 UndefBits <<= SplatBitSize;
6912 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6913 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6916 return true;
6919 return false;
6922 // Try 64-bit splatted SIMD immediate.
6923 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6924 const APInt &Bits) {
6925 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6926 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6927 EVT VT = Op.getValueType();
6928 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
6930 if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
6931 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
6933 SDLoc dl(Op);
6934 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
6935 DAG.getConstant(Value, dl, MVT::i32));
6936 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6940 return SDValue();
6943 // Try 32-bit splatted SIMD immediate.
6944 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6945 const APInt &Bits,
6946 const SDValue *LHS = nullptr) {
6947 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6948 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6949 EVT VT = Op.getValueType();
6950 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6951 bool isAdvSIMDModImm = false;
6952 uint64_t Shift;
6954 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
6955 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
6956 Shift = 0;
6958 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
6959 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
6960 Shift = 8;
6962 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
6963 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
6964 Shift = 16;
6966 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
6967 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
6968 Shift = 24;
6971 if (isAdvSIMDModImm) {
6972 SDLoc dl(Op);
6973 SDValue Mov;
6975 if (LHS)
6976 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
6977 DAG.getConstant(Value, dl, MVT::i32),
6978 DAG.getConstant(Shift, dl, MVT::i32));
6979 else
6980 Mov = DAG.getNode(NewOp, dl, MovTy,
6981 DAG.getConstant(Value, dl, MVT::i32),
6982 DAG.getConstant(Shift, dl, MVT::i32));
6984 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6988 return SDValue();
6991 // Try 16-bit splatted SIMD immediate.
6992 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
6993 const APInt &Bits,
6994 const SDValue *LHS = nullptr) {
6995 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
6996 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
6997 EVT VT = Op.getValueType();
6998 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6999 bool isAdvSIMDModImm = false;
7000 uint64_t Shift;
7002 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
7003 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
7004 Shift = 0;
7006 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
7007 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
7008 Shift = 8;
7011 if (isAdvSIMDModImm) {
7012 SDLoc dl(Op);
7013 SDValue Mov;
7015 if (LHS)
7016 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
7017 DAG.getConstant(Value, dl, MVT::i32),
7018 DAG.getConstant(Shift, dl, MVT::i32));
7019 else
7020 Mov = DAG.getNode(NewOp, dl, MovTy,
7021 DAG.getConstant(Value, dl, MVT::i32),
7022 DAG.getConstant(Shift, dl, MVT::i32));
7024 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7028 return SDValue();
7031 // Try 32-bit splatted SIMD immediate with shifted ones.
7032 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
7033 SelectionDAG &DAG, const APInt &Bits) {
7034 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7035 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7036 EVT VT = Op.getValueType();
7037 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
7038 bool isAdvSIMDModImm = false;
7039 uint64_t Shift;
7041 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
7042 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
7043 Shift = 264;
7045 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
7046 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
7047 Shift = 272;
7050 if (isAdvSIMDModImm) {
7051 SDLoc dl(Op);
7052 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7053 DAG.getConstant(Value, dl, MVT::i32),
7054 DAG.getConstant(Shift, dl, MVT::i32));
7055 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7059 return SDValue();
7062 // Try 8-bit splatted SIMD immediate.
7063 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7064 const APInt &Bits) {
7065 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7066 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7067 EVT VT = Op.getValueType();
7068 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
7070 if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
7071 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
7073 SDLoc dl(Op);
7074 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7075 DAG.getConstant(Value, dl, MVT::i32));
7076 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7080 return SDValue();
7083 // Try FP splatted SIMD immediate.
7084 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
7085 const APInt &Bits) {
7086 if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
7087 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
7088 EVT VT = Op.getValueType();
7089 bool isWide = (VT.getSizeInBits() == 128);
7090 MVT MovTy;
7091 bool isAdvSIMDModImm = false;
7093 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
7094 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
7095 MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
7097 else if (isWide &&
7098 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
7099 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
7100 MovTy = MVT::v2f64;
7103 if (isAdvSIMDModImm) {
7104 SDLoc dl(Op);
7105 SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
7106 DAG.getConstant(Value, dl, MVT::i32));
7107 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
7111 return SDValue();
7114 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7115 // consists of only the same constant int value, returned in reference arg
7116 // ConstVal
7117 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
7118 uint64_t &ConstVal) {
7119 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
7120 if (!Bvec)
7121 return false;
7122 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
7123 if (!FirstElt)
7124 return false;
7125 EVT VT = Bvec->getValueType(0);
7126 unsigned NumElts = VT.getVectorNumElements();
7127 for (unsigned i = 1; i < NumElts; ++i)
7128 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
7129 return false;
7130 ConstVal = FirstElt->getZExtValue();
7131 return true;
7134 static unsigned getIntrinsicID(const SDNode *N) {
7135 unsigned Opcode = N->getOpcode();
7136 switch (Opcode) {
7137 default:
7138 return Intrinsic::not_intrinsic;
7139 case ISD::INTRINSIC_WO_CHAIN: {
7140 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7141 if (IID < Intrinsic::num_intrinsics)
7142 return IID;
7143 return Intrinsic::not_intrinsic;
7148 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7149 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7150 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7151 // Also, logical shift right -> sri, with the same structure.
7152 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
7153 EVT VT = N->getValueType(0);
7155 if (!VT.isVector())
7156 return SDValue();
7158 SDLoc DL(N);
7160 // Is the first op an AND?
7161 const SDValue And = N->getOperand(0);
7162 if (And.getOpcode() != ISD::AND)
7163 return SDValue();
7165 // Is the second op an shl or lshr?
7166 SDValue Shift = N->getOperand(1);
7167 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7168 // or AArch64ISD::VLSHR vector, #shift
7169 unsigned ShiftOpc = Shift.getOpcode();
7170 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
7171 return SDValue();
7172 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
7174 // Is the shift amount constant?
7175 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7176 if (!C2node)
7177 return SDValue();
7179 // Is the and mask vector all constant?
7180 uint64_t C1;
7181 if (!isAllConstantBuildVector(And.getOperand(1), C1))
7182 return SDValue();
7184 // Is C1 == ~C2, taking into account how much one can shift elements of a
7185 // particular size?
7186 uint64_t C2 = C2node->getZExtValue();
7187 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
7188 if (C2 > ElemSizeInBits)
7189 return SDValue();
7190 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
7191 if ((C1 & ElemMask) != (~C2 & ElemMask))
7192 return SDValue();
7194 SDValue X = And.getOperand(0);
7195 SDValue Y = Shift.getOperand(0);
7197 unsigned Intrin =
7198 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
7199 SDValue ResultSLI =
7200 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7201 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
7202 Shift.getOperand(1));
7204 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7205 LLVM_DEBUG(N->dump(&DAG));
7206 LLVM_DEBUG(dbgs() << "into: \n");
7207 LLVM_DEBUG(ResultSLI->dump(&DAG));
7209 ++NumShiftInserts;
7210 return ResultSLI;
7213 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
7214 SelectionDAG &DAG) const {
7215 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7216 if (EnableAArch64SlrGeneration) {
7217 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
7218 return Res;
7221 EVT VT = Op.getValueType();
7223 SDValue LHS = Op.getOperand(0);
7224 BuildVectorSDNode *BVN =
7225 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
7226 if (!BVN) {
7227 // OR commutes, so try swapping the operands.
7228 LHS = Op.getOperand(1);
7229 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
7231 if (!BVN)
7232 return Op;
7234 APInt DefBits(VT.getSizeInBits(), 0);
7235 APInt UndefBits(VT.getSizeInBits(), 0);
7236 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7237 SDValue NewOp;
7239 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7240 DefBits, &LHS)) ||
7241 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7242 DefBits, &LHS)))
7243 return NewOp;
7245 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
7246 UndefBits, &LHS)) ||
7247 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
7248 UndefBits, &LHS)))
7249 return NewOp;
7252 // We can always fall back to a non-immediate OR.
7253 return Op;
7256 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7257 // be truncated to fit element width.
7258 static SDValue NormalizeBuildVector(SDValue Op,
7259 SelectionDAG &DAG) {
7260 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7261 SDLoc dl(Op);
7262 EVT VT = Op.getValueType();
7263 EVT EltTy= VT.getVectorElementType();
7265 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
7266 return Op;
7268 SmallVector<SDValue, 16> Ops;
7269 for (SDValue Lane : Op->ops()) {
7270 // For integer vectors, type legalization would have promoted the
7271 // operands already. Otherwise, if Op is a floating-point splat
7272 // (with operands cast to integers), then the only possibilities
7273 // are constants and UNDEFs.
7274 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
7275 APInt LowBits(EltTy.getSizeInBits(),
7276 CstLane->getZExtValue());
7277 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
7278 } else if (Lane.getNode()->isUndef()) {
7279 Lane = DAG.getUNDEF(MVT::i32);
7280 } else {
7281 assert(Lane.getValueType() == MVT::i32 &&
7282 "Unexpected BUILD_VECTOR operand type");
7284 Ops.push_back(Lane);
7286 return DAG.getBuildVector(VT, dl, Ops);
7289 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
7290 EVT VT = Op.getValueType();
7292 APInt DefBits(VT.getSizeInBits(), 0);
7293 APInt UndefBits(VT.getSizeInBits(), 0);
7294 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7295 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
7296 SDValue NewOp;
7297 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7298 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7299 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7300 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7301 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7302 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7303 return NewOp;
7305 DefBits = ~DefBits;
7306 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7307 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7308 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7309 return NewOp;
7311 DefBits = UndefBits;
7312 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
7313 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7314 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
7315 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
7316 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
7317 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
7318 return NewOp;
7320 DefBits = ~UndefBits;
7321 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
7322 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
7323 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
7324 return NewOp;
7327 return SDValue();
7330 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
7331 SelectionDAG &DAG) const {
7332 EVT VT = Op.getValueType();
7334 // Try to build a simple constant vector.
7335 Op = NormalizeBuildVector(Op, DAG);
7336 if (VT.isInteger()) {
7337 // Certain vector constants, used to express things like logical NOT and
7338 // arithmetic NEG, are passed through unmodified. This allows special
7339 // patterns for these operations to match, which will lower these constants
7340 // to whatever is proven necessary.
7341 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7342 if (BVN->isConstant())
7343 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
7344 unsigned BitSize = VT.getVectorElementType().getSizeInBits();
7345 APInt Val(BitSize,
7346 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
7347 if (Val.isNullValue() || Val.isAllOnesValue())
7348 return Op;
7352 if (SDValue V = ConstantBuildVector(Op, DAG))
7353 return V;
7355 // Scan through the operands to find some interesting properties we can
7356 // exploit:
7357 // 1) If only one value is used, we can use a DUP, or
7358 // 2) if only the low element is not undef, we can just insert that, or
7359 // 3) if only one constant value is used (w/ some non-constant lanes),
7360 // we can splat the constant value into the whole vector then fill
7361 // in the non-constant lanes.
7362 // 4) FIXME: If different constant values are used, but we can intelligently
7363 // select the values we'll be overwriting for the non-constant
7364 // lanes such that we can directly materialize the vector
7365 // some other way (MOVI, e.g.), we can be sneaky.
7366 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7367 SDLoc dl(Op);
7368 unsigned NumElts = VT.getVectorNumElements();
7369 bool isOnlyLowElement = true;
7370 bool usesOnlyOneValue = true;
7371 bool usesOnlyOneConstantValue = true;
7372 bool isConstant = true;
7373 bool AllLanesExtractElt = true;
7374 unsigned NumConstantLanes = 0;
7375 SDValue Value;
7376 SDValue ConstantValue;
7377 for (unsigned i = 0; i < NumElts; ++i) {
7378 SDValue V = Op.getOperand(i);
7379 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7380 AllLanesExtractElt = false;
7381 if (V.isUndef())
7382 continue;
7383 if (i > 0)
7384 isOnlyLowElement = false;
7385 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7386 isConstant = false;
7388 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
7389 ++NumConstantLanes;
7390 if (!ConstantValue.getNode())
7391 ConstantValue = V;
7392 else if (ConstantValue != V)
7393 usesOnlyOneConstantValue = false;
7396 if (!Value.getNode())
7397 Value = V;
7398 else if (V != Value)
7399 usesOnlyOneValue = false;
7402 if (!Value.getNode()) {
7403 LLVM_DEBUG(
7404 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7405 return DAG.getUNDEF(VT);
7408 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7409 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7410 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7411 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
7412 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7413 "SCALAR_TO_VECTOR node\n");
7414 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7417 if (AllLanesExtractElt) {
7418 SDNode *Vector = nullptr;
7419 bool Even = false;
7420 bool Odd = false;
7421 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7422 // the Odd pattern <1,3,5,...>.
7423 for (unsigned i = 0; i < NumElts; ++i) {
7424 SDValue V = Op.getOperand(i);
7425 const SDNode *N = V.getNode();
7426 if (!isa<ConstantSDNode>(N->getOperand(1)))
7427 break;
7428 SDValue N0 = N->getOperand(0);
7430 // All elements are extracted from the same vector.
7431 if (!Vector) {
7432 Vector = N0.getNode();
7433 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7434 // BUILD_VECTOR.
7435 if (VT.getVectorElementType() !=
7436 N0.getValueType().getVectorElementType())
7437 break;
7438 } else if (Vector != N0.getNode()) {
7439 Odd = false;
7440 Even = false;
7441 break;
7444 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7445 // indices <1,3,5,...>.
7446 uint64_t Val = N->getConstantOperandVal(1);
7447 if (Val == 2 * i) {
7448 Even = true;
7449 continue;
7451 if (Val - 1 == 2 * i) {
7452 Odd = true;
7453 continue;
7456 // Something does not match: abort.
7457 Odd = false;
7458 Even = false;
7459 break;
7461 if (Even || Odd) {
7462 SDValue LHS =
7463 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7464 DAG.getConstant(0, dl, MVT::i64));
7465 SDValue RHS =
7466 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
7467 DAG.getConstant(NumElts, dl, MVT::i64));
7469 if (Even && !Odd)
7470 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
7471 RHS);
7472 if (Odd && !Even)
7473 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
7474 RHS);
7478 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7479 // i32 and try again.
7480 if (usesOnlyOneValue) {
7481 if (!isConstant) {
7482 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7483 Value.getValueType() != VT) {
7484 LLVM_DEBUG(
7485 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7486 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
7489 // This is actually a DUPLANExx operation, which keeps everything vectory.
7491 SDValue Lane = Value.getOperand(1);
7492 Value = Value.getOperand(0);
7493 if (Value.getValueSizeInBits() == 64) {
7494 LLVM_DEBUG(
7495 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7496 "widening it\n");
7497 Value = WidenVector(Value, DAG);
7500 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
7501 return DAG.getNode(Opcode, dl, VT, Value, Lane);
7504 if (VT.getVectorElementType().isFloatingPoint()) {
7505 SmallVector<SDValue, 8> Ops;
7506 EVT EltTy = VT.getVectorElementType();
7507 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
7508 "Unsupported floating-point vector type");
7509 LLVM_DEBUG(
7510 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7511 "BITCASTS, and try again\n");
7512 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
7513 for (unsigned i = 0; i < NumElts; ++i)
7514 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
7515 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
7516 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7517 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7518 Val.dump(););
7519 Val = LowerBUILD_VECTOR(Val, DAG);
7520 if (Val.getNode())
7521 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7525 // If there was only one constant value used and for more than one lane,
7526 // start by splatting that value, then replace the non-constant lanes. This
7527 // is better than the default, which will perform a separate initialization
7528 // for each lane.
7529 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
7530 // Firstly, try to materialize the splat constant.
7531 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
7532 Val = ConstantBuildVector(Vec, DAG);
7533 if (!Val) {
7534 // Otherwise, materialize the constant and splat it.
7535 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
7536 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
7539 // Now insert the non-constant lanes.
7540 for (unsigned i = 0; i < NumElts; ++i) {
7541 SDValue V = Op.getOperand(i);
7542 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7543 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
7544 // Note that type legalization likely mucked about with the VT of the
7545 // source operand, so we may have to convert it here before inserting.
7546 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
7548 return Val;
7551 // This will generate a load from the constant pool.
7552 if (isConstant) {
7553 LLVM_DEBUG(
7554 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7555 "expansion\n");
7556 return SDValue();
7559 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7560 if (NumElts >= 4) {
7561 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7562 return shuffle;
7565 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7566 // know the default expansion would otherwise fall back on something even
7567 // worse. For a vector with one or two non-undef values, that's
7568 // scalar_to_vector for the elements followed by a shuffle (provided the
7569 // shuffle is valid for the target) and materialization element by element
7570 // on the stack followed by a load for everything else.
7571 if (!isConstant && !usesOnlyOneValue) {
7572 LLVM_DEBUG(
7573 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7574 "of INSERT_VECTOR_ELT\n");
7576 SDValue Vec = DAG.getUNDEF(VT);
7577 SDValue Op0 = Op.getOperand(0);
7578 unsigned i = 0;
7580 // Use SCALAR_TO_VECTOR for lane zero to
7581 // a) Avoid a RMW dependency on the full vector register, and
7582 // b) Allow the register coalescer to fold away the copy if the
7583 // value is already in an S or D register, and we're forced to emit an
7584 // INSERT_SUBREG that we can't fold anywhere.
7586 // We also allow types like i8 and i16 which are illegal scalar but legal
7587 // vector element types. After type-legalization the inserted value is
7588 // extended (i32) and it is safe to cast them to the vector type by ignoring
7589 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7590 if (!Op0.isUndef()) {
7591 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7592 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
7593 ++i;
7595 LLVM_DEBUG(if (i < NumElts) dbgs()
7596 << "Creating nodes for the other vector elements:\n";);
7597 for (; i < NumElts; ++i) {
7598 SDValue V = Op.getOperand(i);
7599 if (V.isUndef())
7600 continue;
7601 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
7602 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7604 return Vec;
7607 LLVM_DEBUG(
7608 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7609 "better alternative\n");
7610 return SDValue();
7613 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
7614 SelectionDAG &DAG) const {
7615 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
7617 // Check for non-constant or out of range lane.
7618 EVT VT = Op.getOperand(0).getValueType();
7619 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
7620 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7621 return SDValue();
7624 // Insertion/extraction are legal for V128 types.
7625 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7626 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7627 VT == MVT::v8f16)
7628 return Op;
7630 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7631 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7632 return SDValue();
7634 // For V64 types, we perform insertion by expanding the value
7635 // to a V128 type and perform the insertion on that.
7636 SDLoc DL(Op);
7637 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7638 EVT WideTy = WideVec.getValueType();
7640 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7641 Op.getOperand(1), Op.getOperand(2));
7642 // Re-narrow the resultant vector.
7643 return NarrowVector(Node, DAG);
7646 SDValue
7647 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7648 SelectionDAG &DAG) const {
7649 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7651 // Check for non-constant or out of range lane.
7652 EVT VT = Op.getOperand(0).getValueType();
7653 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7654 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7655 return SDValue();
7658 // Insertion/extraction are legal for V128 types.
7659 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7660 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7661 VT == MVT::v8f16)
7662 return Op;
7664 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7665 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7666 return SDValue();
7668 // For V64 types, we perform extraction by expanding the value
7669 // to a V128 type and perform the extraction on that.
7670 SDLoc DL(Op);
7671 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7672 EVT WideTy = WideVec.getValueType();
7674 EVT ExtrTy = WideTy.getVectorElementType();
7675 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7676 ExtrTy = MVT::i32;
7678 // For extractions, we just return the result directly.
7679 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7680 Op.getOperand(1));
7683 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7684 SelectionDAG &DAG) const {
7685 EVT VT = Op.getOperand(0).getValueType();
7686 SDLoc dl(Op);
7687 // Just in case...
7688 if (!VT.isVector())
7689 return SDValue();
7691 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7692 if (!Cst)
7693 return SDValue();
7694 unsigned Val = Cst->getZExtValue();
7696 unsigned Size = Op.getValueSizeInBits();
7698 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7699 if (Val == 0)
7700 return Op;
7702 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7703 // that directly.
7704 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7705 return Op;
7707 return SDValue();
7710 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7711 if (VT.getVectorNumElements() == 4 &&
7712 (VT.is128BitVector() || VT.is64BitVector())) {
7713 unsigned PFIndexes[4];
7714 for (unsigned i = 0; i != 4; ++i) {
7715 if (M[i] < 0)
7716 PFIndexes[i] = 8;
7717 else
7718 PFIndexes[i] = M[i];
7721 // Compute the index in the perfect shuffle table.
7722 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7723 PFIndexes[2] * 9 + PFIndexes[3];
7724 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7725 unsigned Cost = (PFEntry >> 30);
7727 if (Cost <= 4)
7728 return true;
7731 bool DummyBool;
7732 int DummyInt;
7733 unsigned DummyUnsigned;
7735 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7736 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7737 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7738 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7739 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7740 isZIPMask(M, VT, DummyUnsigned) ||
7741 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7742 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7743 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7744 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7745 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7748 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7749 /// operand of a vector shift operation, where all the elements of the
7750 /// build_vector must have the same constant integer value.
7751 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7752 // Ignore bit_converts.
7753 while (Op.getOpcode() == ISD::BITCAST)
7754 Op = Op.getOperand(0);
7755 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7756 APInt SplatBits, SplatUndef;
7757 unsigned SplatBitSize;
7758 bool HasAnyUndefs;
7759 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7760 HasAnyUndefs, ElementBits) ||
7761 SplatBitSize > ElementBits)
7762 return false;
7763 Cnt = SplatBits.getSExtValue();
7764 return true;
7767 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7768 /// operand of a vector shift left operation. That value must be in the range:
7769 /// 0 <= Value < ElementBits for a left shift; or
7770 /// 0 <= Value <= ElementBits for a long left shift.
7771 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7772 assert(VT.isVector() && "vector shift count is not a vector type");
7773 int64_t ElementBits = VT.getScalarSizeInBits();
7774 if (!getVShiftImm(Op, ElementBits, Cnt))
7775 return false;
7776 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7779 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7780 /// operand of a vector shift right operation. The value must be in the range:
7781 /// 1 <= Value <= ElementBits for a right shift; or
7782 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7783 assert(VT.isVector() && "vector shift count is not a vector type");
7784 int64_t ElementBits = VT.getScalarSizeInBits();
7785 if (!getVShiftImm(Op, ElementBits, Cnt))
7786 return false;
7787 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7790 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7791 SelectionDAG &DAG) const {
7792 EVT VT = Op.getValueType();
7793 SDLoc DL(Op);
7794 int64_t Cnt;
7796 if (!Op.getOperand(1).getValueType().isVector())
7797 return Op;
7798 unsigned EltSize = VT.getScalarSizeInBits();
7800 switch (Op.getOpcode()) {
7801 default:
7802 llvm_unreachable("unexpected shift opcode");
7804 case ISD::SHL:
7805 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7806 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7807 DAG.getConstant(Cnt, DL, MVT::i32));
7808 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7809 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7810 MVT::i32),
7811 Op.getOperand(0), Op.getOperand(1));
7812 case ISD::SRA:
7813 case ISD::SRL:
7814 // Right shift immediate
7815 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7816 unsigned Opc =
7817 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7818 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7819 DAG.getConstant(Cnt, DL, MVT::i32));
7822 // Right shift register. Note, there is not a shift right register
7823 // instruction, but the shift left register instruction takes a signed
7824 // value, where negative numbers specify a right shift.
7825 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7826 : Intrinsic::aarch64_neon_ushl;
7827 // negate the shift amount
7828 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7829 SDValue NegShiftLeft =
7830 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7831 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7832 NegShift);
7833 return NegShiftLeft;
7836 return SDValue();
7839 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7840 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7841 const SDLoc &dl, SelectionDAG &DAG) {
7842 EVT SrcVT = LHS.getValueType();
7843 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7844 "function only supposed to emit natural comparisons");
7846 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7847 APInt CnstBits(VT.getSizeInBits(), 0);
7848 APInt UndefBits(VT.getSizeInBits(), 0);
7849 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7850 bool IsZero = IsCnst && (CnstBits == 0);
7852 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7853 switch (CC) {
7854 default:
7855 return SDValue();
7856 case AArch64CC::NE: {
7857 SDValue Fcmeq;
7858 if (IsZero)
7859 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7860 else
7861 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7862 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7864 case AArch64CC::EQ:
7865 if (IsZero)
7866 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7867 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7868 case AArch64CC::GE:
7869 if (IsZero)
7870 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7871 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7872 case AArch64CC::GT:
7873 if (IsZero)
7874 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7875 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7876 case AArch64CC::LS:
7877 if (IsZero)
7878 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7879 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7880 case AArch64CC::LT:
7881 if (!NoNans)
7882 return SDValue();
7883 // If we ignore NaNs then we can use to the MI implementation.
7884 LLVM_FALLTHROUGH;
7885 case AArch64CC::MI:
7886 if (IsZero)
7887 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7888 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7892 switch (CC) {
7893 default:
7894 return SDValue();
7895 case AArch64CC::NE: {
7896 SDValue Cmeq;
7897 if (IsZero)
7898 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7899 else
7900 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7901 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7903 case AArch64CC::EQ:
7904 if (IsZero)
7905 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7906 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7907 case AArch64CC::GE:
7908 if (IsZero)
7909 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7910 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7911 case AArch64CC::GT:
7912 if (IsZero)
7913 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7914 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7915 case AArch64CC::LE:
7916 if (IsZero)
7917 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7918 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7919 case AArch64CC::LS:
7920 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7921 case AArch64CC::LO:
7922 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7923 case AArch64CC::LT:
7924 if (IsZero)
7925 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7926 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7927 case AArch64CC::HI:
7928 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7929 case AArch64CC::HS:
7930 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7934 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7935 SelectionDAG &DAG) const {
7936 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7937 SDValue LHS = Op.getOperand(0);
7938 SDValue RHS = Op.getOperand(1);
7939 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7940 SDLoc dl(Op);
7942 if (LHS.getValueType().getVectorElementType().isInteger()) {
7943 assert(LHS.getValueType() == RHS.getValueType());
7944 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7945 SDValue Cmp =
7946 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7947 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7950 const bool FullFP16 =
7951 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
7953 // Make v4f16 (only) fcmp operations utilise vector instructions
7954 // v8f16 support will be a litle more complicated
7955 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
7956 if (LHS.getValueType().getVectorNumElements() == 4) {
7957 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
7958 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
7959 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
7960 DAG.ReplaceAllUsesWith(Op, NewSetcc);
7961 CmpVT = MVT::v4i32;
7962 } else
7963 return SDValue();
7966 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
7967 LHS.getValueType().getVectorElementType() != MVT::f128);
7969 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7970 // clean. Some of them require two branches to implement.
7971 AArch64CC::CondCode CC1, CC2;
7972 bool ShouldInvert;
7973 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7975 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7976 SDValue Cmp =
7977 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7978 if (!Cmp.getNode())
7979 return SDValue();
7981 if (CC2 != AArch64CC::AL) {
7982 SDValue Cmp2 =
7983 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7984 if (!Cmp2.getNode())
7985 return SDValue();
7987 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7990 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7992 if (ShouldInvert)
7993 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7995 return Cmp;
7998 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7999 SelectionDAG &DAG) {
8000 SDValue VecOp = ScalarOp.getOperand(0);
8001 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
8002 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
8003 DAG.getConstant(0, DL, MVT::i64));
8006 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
8007 SelectionDAG &DAG) const {
8008 SDLoc dl(Op);
8009 switch (Op.getOpcode()) {
8010 case ISD::VECREDUCE_ADD:
8011 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
8012 case ISD::VECREDUCE_SMAX:
8013 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
8014 case ISD::VECREDUCE_SMIN:
8015 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
8016 case ISD::VECREDUCE_UMAX:
8017 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
8018 case ISD::VECREDUCE_UMIN:
8019 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
8020 case ISD::VECREDUCE_FMAX: {
8021 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8022 return DAG.getNode(
8023 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8024 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
8025 Op.getOperand(0));
8027 case ISD::VECREDUCE_FMIN: {
8028 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8029 return DAG.getNode(
8030 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
8031 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
8032 Op.getOperand(0));
8034 default:
8035 llvm_unreachable("Unhandled reduction");
8039 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
8040 SelectionDAG &DAG) const {
8041 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8042 if (!Subtarget.hasLSE())
8043 return SDValue();
8045 // LSE has an atomic load-add instruction, but not a load-sub.
8046 SDLoc dl(Op);
8047 MVT VT = Op.getSimpleValueType();
8048 SDValue RHS = Op.getOperand(2);
8049 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8050 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
8051 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
8052 Op.getOperand(0), Op.getOperand(1), RHS,
8053 AN->getMemOperand());
8056 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
8057 SelectionDAG &DAG) const {
8058 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
8059 if (!Subtarget.hasLSE())
8060 return SDValue();
8062 // LSE has an atomic load-clear instruction, but not a load-and.
8063 SDLoc dl(Op);
8064 MVT VT = Op.getSimpleValueType();
8065 SDValue RHS = Op.getOperand(2);
8066 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
8067 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
8068 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
8069 Op.getOperand(0), Op.getOperand(1), RHS,
8070 AN->getMemOperand());
8073 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8074 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
8075 SDLoc dl(Op);
8076 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8077 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
8079 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
8080 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
8081 if (Subtarget->hasCustomCallingConv())
8082 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
8084 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
8085 DAG.getConstant(4, dl, MVT::i64));
8086 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
8087 Chain =
8088 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
8089 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
8090 DAG.getRegisterMask(Mask), Chain.getValue(1));
8091 // To match the actual intent better, we should read the output from X15 here
8092 // again (instead of potentially spilling it to the stack), but rereading Size
8093 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8094 // here.
8096 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
8097 DAG.getConstant(4, dl, MVT::i64));
8098 return Chain;
8101 SDValue
8102 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8103 SelectionDAG &DAG) const {
8104 assert(Subtarget->isTargetWindows() &&
8105 "Only Windows alloca probing supported");
8106 SDLoc dl(Op);
8107 // Get the inputs.
8108 SDNode *Node = Op.getNode();
8109 SDValue Chain = Op.getOperand(0);
8110 SDValue Size = Op.getOperand(1);
8111 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8112 EVT VT = Node->getValueType(0);
8114 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
8115 "no-stack-arg-probe")) {
8116 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8117 Chain = SP.getValue(1);
8118 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8119 if (Align)
8120 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8121 DAG.getConstant(-(uint64_t)Align, dl, VT));
8122 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8123 SDValue Ops[2] = {SP, Chain};
8124 return DAG.getMergeValues(Ops, dl);
8127 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
8129 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
8131 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
8132 Chain = SP.getValue(1);
8133 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
8134 if (Align)
8135 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
8136 DAG.getConstant(-(uint64_t)Align, dl, VT));
8137 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
8139 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
8140 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
8142 SDValue Ops[2] = {SP, Chain};
8143 return DAG.getMergeValues(Ops, dl);
8146 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8147 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8148 /// specified in the intrinsic calls.
8149 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
8150 const CallInst &I,
8151 MachineFunction &MF,
8152 unsigned Intrinsic) const {
8153 auto &DL = I.getModule()->getDataLayout();
8154 switch (Intrinsic) {
8155 case Intrinsic::aarch64_neon_ld2:
8156 case Intrinsic::aarch64_neon_ld3:
8157 case Intrinsic::aarch64_neon_ld4:
8158 case Intrinsic::aarch64_neon_ld1x2:
8159 case Intrinsic::aarch64_neon_ld1x3:
8160 case Intrinsic::aarch64_neon_ld1x4:
8161 case Intrinsic::aarch64_neon_ld2lane:
8162 case Intrinsic::aarch64_neon_ld3lane:
8163 case Intrinsic::aarch64_neon_ld4lane:
8164 case Intrinsic::aarch64_neon_ld2r:
8165 case Intrinsic::aarch64_neon_ld3r:
8166 case Intrinsic::aarch64_neon_ld4r: {
8167 Info.opc = ISD::INTRINSIC_W_CHAIN;
8168 // Conservatively set memVT to the entire set of vectors loaded.
8169 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
8170 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8171 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8172 Info.offset = 0;
8173 Info.align.reset();
8174 // volatile loads with NEON intrinsics not supported
8175 Info.flags = MachineMemOperand::MOLoad;
8176 return true;
8178 case Intrinsic::aarch64_neon_st2:
8179 case Intrinsic::aarch64_neon_st3:
8180 case Intrinsic::aarch64_neon_st4:
8181 case Intrinsic::aarch64_neon_st1x2:
8182 case Intrinsic::aarch64_neon_st1x3:
8183 case Intrinsic::aarch64_neon_st1x4:
8184 case Intrinsic::aarch64_neon_st2lane:
8185 case Intrinsic::aarch64_neon_st3lane:
8186 case Intrinsic::aarch64_neon_st4lane: {
8187 Info.opc = ISD::INTRINSIC_VOID;
8188 // Conservatively set memVT to the entire set of vectors stored.
8189 unsigned NumElts = 0;
8190 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
8191 Type *ArgTy = I.getArgOperand(ArgI)->getType();
8192 if (!ArgTy->isVectorTy())
8193 break;
8194 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
8196 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
8197 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
8198 Info.offset = 0;
8199 Info.align.reset();
8200 // volatile stores with NEON intrinsics not supported
8201 Info.flags = MachineMemOperand::MOStore;
8202 return true;
8204 case Intrinsic::aarch64_ldaxr:
8205 case Intrinsic::aarch64_ldxr: {
8206 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
8207 Info.opc = ISD::INTRINSIC_W_CHAIN;
8208 Info.memVT = MVT::getVT(PtrTy->getElementType());
8209 Info.ptrVal = I.getArgOperand(0);
8210 Info.offset = 0;
8211 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8212 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8213 return true;
8215 case Intrinsic::aarch64_stlxr:
8216 case Intrinsic::aarch64_stxr: {
8217 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
8218 Info.opc = ISD::INTRINSIC_W_CHAIN;
8219 Info.memVT = MVT::getVT(PtrTy->getElementType());
8220 Info.ptrVal = I.getArgOperand(1);
8221 Info.offset = 0;
8222 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
8223 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8224 return true;
8226 case Intrinsic::aarch64_ldaxp:
8227 case Intrinsic::aarch64_ldxp:
8228 Info.opc = ISD::INTRINSIC_W_CHAIN;
8229 Info.memVT = MVT::i128;
8230 Info.ptrVal = I.getArgOperand(0);
8231 Info.offset = 0;
8232 Info.align = Align(16);
8233 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
8234 return true;
8235 case Intrinsic::aarch64_stlxp:
8236 case Intrinsic::aarch64_stxp:
8237 Info.opc = ISD::INTRINSIC_W_CHAIN;
8238 Info.memVT = MVT::i128;
8239 Info.ptrVal = I.getArgOperand(2);
8240 Info.offset = 0;
8241 Info.align = Align(16);
8242 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
8243 return true;
8244 default:
8245 break;
8248 return false;
8251 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
8252 ISD::LoadExtType ExtTy,
8253 EVT NewVT) const {
8254 // TODO: This may be worth removing. Check regression tests for diffs.
8255 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
8256 return false;
8258 // If we're reducing the load width in order to avoid having to use an extra
8259 // instruction to do extension then it's probably a good idea.
8260 if (ExtTy != ISD::NON_EXTLOAD)
8261 return true;
8262 // Don't reduce load width if it would prevent us from combining a shift into
8263 // the offset.
8264 MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
8265 assert(Mem);
8266 const SDValue &Base = Mem->getBasePtr();
8267 if (Base.getOpcode() == ISD::ADD &&
8268 Base.getOperand(1).getOpcode() == ISD::SHL &&
8269 Base.getOperand(1).hasOneUse() &&
8270 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
8271 // The shift can be combined if it matches the size of the value being
8272 // loaded (and so reducing the width would make it not match).
8273 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
8274 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
8275 if (ShiftAmount == Log2_32(LoadBytes))
8276 return false;
8278 // We have no reason to disallow reducing the load width, so allow it.
8279 return true;
8282 // Truncations from 64-bit GPR to 32-bit GPR is free.
8283 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
8284 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8285 return false;
8286 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8287 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8288 return NumBits1 > NumBits2;
8290 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8291 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8292 return false;
8293 unsigned NumBits1 = VT1.getSizeInBits();
8294 unsigned NumBits2 = VT2.getSizeInBits();
8295 return NumBits1 > NumBits2;
8298 /// Check if it is profitable to hoist instruction in then/else to if.
8299 /// Not profitable if I and it's user can form a FMA instruction
8300 /// because we prefer FMSUB/FMADD.
8301 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
8302 if (I->getOpcode() != Instruction::FMul)
8303 return true;
8305 if (!I->hasOneUse())
8306 return true;
8308 Instruction *User = I->user_back();
8310 if (User &&
8311 !(User->getOpcode() == Instruction::FSub ||
8312 User->getOpcode() == Instruction::FAdd))
8313 return true;
8315 const TargetOptions &Options = getTargetMachine().Options;
8316 const DataLayout &DL = I->getModule()->getDataLayout();
8317 EVT VT = getValueType(DL, User->getOperand(0)->getType());
8319 return !(isFMAFasterThanFMulAndFAdd(VT) &&
8320 isOperationLegalOrCustom(ISD::FMA, VT) &&
8321 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
8322 Options.UnsafeFPMath));
8325 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8326 // 64-bit GPR.
8327 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
8328 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8329 return false;
8330 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8331 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8332 return NumBits1 == 32 && NumBits2 == 64;
8334 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8335 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
8336 return false;
8337 unsigned NumBits1 = VT1.getSizeInBits();
8338 unsigned NumBits2 = VT2.getSizeInBits();
8339 return NumBits1 == 32 && NumBits2 == 64;
8342 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
8343 EVT VT1 = Val.getValueType();
8344 if (isZExtFree(VT1, VT2)) {
8345 return true;
8348 if (Val.getOpcode() != ISD::LOAD)
8349 return false;
8351 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8352 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
8353 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
8354 VT1.getSizeInBits() <= 32);
8357 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
8358 if (isa<FPExtInst>(Ext))
8359 return false;
8361 // Vector types are not free.
8362 if (Ext->getType()->isVectorTy())
8363 return false;
8365 for (const Use &U : Ext->uses()) {
8366 // The extension is free if we can fold it with a left shift in an
8367 // addressing mode or an arithmetic operation: add, sub, and cmp.
8369 // Is there a shift?
8370 const Instruction *Instr = cast<Instruction>(U.getUser());
8372 // Is this a constant shift?
8373 switch (Instr->getOpcode()) {
8374 case Instruction::Shl:
8375 if (!isa<ConstantInt>(Instr->getOperand(1)))
8376 return false;
8377 break;
8378 case Instruction::GetElementPtr: {
8379 gep_type_iterator GTI = gep_type_begin(Instr);
8380 auto &DL = Ext->getModule()->getDataLayout();
8381 std::advance(GTI, U.getOperandNo()-1);
8382 Type *IdxTy = GTI.getIndexedType();
8383 // This extension will end up with a shift because of the scaling factor.
8384 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8385 // Get the shift amount based on the scaling factor:
8386 // log2(sizeof(IdxTy)) - log2(8).
8387 uint64_t ShiftAmt =
8388 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
8389 // Is the constant foldable in the shift of the addressing mode?
8390 // I.e., shift amount is between 1 and 4 inclusive.
8391 if (ShiftAmt == 0 || ShiftAmt > 4)
8392 return false;
8393 break;
8395 case Instruction::Trunc:
8396 // Check if this is a noop.
8397 // trunc(sext ty1 to ty2) to ty1.
8398 if (Instr->getType() == Ext->getOperand(0)->getType())
8399 continue;
8400 LLVM_FALLTHROUGH;
8401 default:
8402 return false;
8405 // At this point we can use the bfm family, so this extension is free
8406 // for that use.
8408 return true;
8411 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8412 /// or upper half of the vector elements.
8413 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
8414 auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
8415 auto *FullVT = cast<VectorType>(FullV->getType());
8416 auto *HalfVT = cast<VectorType>(HalfV->getType());
8417 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth();
8420 auto extractHalf = [](Value *FullV, Value *HalfV) {
8421 auto *FullVT = cast<VectorType>(FullV->getType());
8422 auto *HalfVT = cast<VectorType>(HalfV->getType());
8423 return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
8426 Constant *M1, *M2;
8427 Value *S1Op1, *S2Op1;
8428 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) ||
8429 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2))))
8430 return false;
8432 // Check that the operands are half as wide as the result and we extract
8433 // half of the elements of the input vectors.
8434 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
8435 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
8436 return false;
8438 // Check the mask extracts either the lower or upper half of vector
8439 // elements.
8440 int M1Start = -1;
8441 int M2Start = -1;
8442 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2;
8443 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
8444 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
8445 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
8446 return false;
8448 return true;
8451 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8452 /// of the vector elements.
8453 static bool areExtractExts(Value *Ext1, Value *Ext2) {
8454 auto areExtDoubled = [](Instruction *Ext) {
8455 return Ext->getType()->getScalarSizeInBits() ==
8456 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
8459 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
8460 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
8461 !areExtDoubled(cast<Instruction>(Ext1)) ||
8462 !areExtDoubled(cast<Instruction>(Ext2)))
8463 return false;
8465 return true;
8468 /// Check if sinking \p I's operands to I's basic block is profitable, because
8469 /// the operands can be folded into a target instruction, e.g.
8470 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8471 bool AArch64TargetLowering::shouldSinkOperands(
8472 Instruction *I, SmallVectorImpl<Use *> &Ops) const {
8473 if (!I->getType()->isVectorTy())
8474 return false;
8476 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
8477 switch (II->getIntrinsicID()) {
8478 case Intrinsic::aarch64_neon_umull:
8479 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
8480 return false;
8481 Ops.push_back(&II->getOperandUse(0));
8482 Ops.push_back(&II->getOperandUse(1));
8483 return true;
8484 default:
8485 return false;
8489 switch (I->getOpcode()) {
8490 case Instruction::Sub:
8491 case Instruction::Add: {
8492 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
8493 return false;
8495 // If the exts' operands extract either the lower or upper elements, we
8496 // can sink them too.
8497 auto Ext1 = cast<Instruction>(I->getOperand(0));
8498 auto Ext2 = cast<Instruction>(I->getOperand(1));
8499 if (areExtractShuffleVectors(Ext1, Ext2)) {
8500 Ops.push_back(&Ext1->getOperandUse(0));
8501 Ops.push_back(&Ext2->getOperandUse(0));
8504 Ops.push_back(&I->getOperandUse(0));
8505 Ops.push_back(&I->getOperandUse(1));
8507 return true;
8509 default:
8510 return false;
8512 return false;
8515 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
8516 unsigned &RequiredAligment) const {
8517 if (!LoadedType.isSimple() ||
8518 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
8519 return false;
8520 // Cyclone supports unaligned accesses.
8521 RequiredAligment = 0;
8522 unsigned NumBits = LoadedType.getSizeInBits();
8523 return NumBits == 32 || NumBits == 64;
8526 /// A helper function for determining the number of interleaved accesses we
8527 /// will generate when lowering accesses of the given type.
8528 unsigned
8529 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
8530 const DataLayout &DL) const {
8531 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
8534 MachineMemOperand::Flags
8535 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
8536 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
8537 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
8538 return MOStridedAccess;
8539 return MachineMemOperand::MONone;
8542 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8543 VectorType *VecTy, const DataLayout &DL) const {
8545 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
8546 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
8548 // Ensure the number of vector elements is greater than 1.
8549 if (VecTy->getNumElements() < 2)
8550 return false;
8552 // Ensure the element type is legal.
8553 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
8554 return false;
8556 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8557 // 128 will be split into multiple interleaved accesses.
8558 return VecSize == 64 || VecSize % 128 == 0;
8561 /// Lower an interleaved load into a ldN intrinsic.
8563 /// E.g. Lower an interleaved load (Factor = 2):
8564 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8565 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8566 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8568 /// Into:
8569 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8570 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8571 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8572 bool AArch64TargetLowering::lowerInterleavedLoad(
8573 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
8574 ArrayRef<unsigned> Indices, unsigned Factor) const {
8575 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8576 "Invalid interleave factor");
8577 assert(!Shuffles.empty() && "Empty shufflevector input");
8578 assert(Shuffles.size() == Indices.size() &&
8579 "Unmatched number of shufflevectors and indices");
8581 const DataLayout &DL = LI->getModule()->getDataLayout();
8583 VectorType *VecTy = Shuffles[0]->getType();
8585 // Skip if we do not have NEON and skip illegal vector types. We can
8586 // "legalize" wide vector types into multiple interleaved accesses as long as
8587 // the vector types are divisible by 128.
8588 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
8589 return false;
8591 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
8593 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8594 // load integer vectors first and then convert to pointer vectors.
8595 Type *EltTy = VecTy->getVectorElementType();
8596 if (EltTy->isPointerTy())
8597 VecTy =
8598 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
8600 IRBuilder<> Builder(LI);
8602 // The base address of the load.
8603 Value *BaseAddr = LI->getPointerOperand();
8605 if (NumLoads > 1) {
8606 // If we're going to generate more than one load, reset the sub-vector type
8607 // to something legal.
8608 VecTy = VectorType::get(VecTy->getVectorElementType(),
8609 VecTy->getVectorNumElements() / NumLoads);
8611 // We will compute the pointer operand of each load from the original base
8612 // address using GEPs. Cast the base address to a pointer to the scalar
8613 // element type.
8614 BaseAddr = Builder.CreateBitCast(
8615 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
8616 LI->getPointerAddressSpace()));
8619 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
8620 Type *Tys[2] = {VecTy, PtrTy};
8621 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
8622 Intrinsic::aarch64_neon_ld3,
8623 Intrinsic::aarch64_neon_ld4};
8624 Function *LdNFunc =
8625 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
8627 // Holds sub-vectors extracted from the load intrinsic return values. The
8628 // sub-vectors are associated with the shufflevector instructions they will
8629 // replace.
8630 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
8632 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
8634 // If we're generating more than one load, compute the base address of
8635 // subsequent loads as an offset from the previous.
8636 if (LoadCount > 0)
8637 BaseAddr =
8638 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
8639 VecTy->getVectorNumElements() * Factor);
8641 CallInst *LdN = Builder.CreateCall(
8642 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
8644 // Extract and store the sub-vectors returned by the load intrinsic.
8645 for (unsigned i = 0; i < Shuffles.size(); i++) {
8646 ShuffleVectorInst *SVI = Shuffles[i];
8647 unsigned Index = Indices[i];
8649 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
8651 // Convert the integer vector to pointer vector if the element is pointer.
8652 if (EltTy->isPointerTy())
8653 SubVec = Builder.CreateIntToPtr(
8654 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
8655 VecTy->getVectorNumElements()));
8656 SubVecs[SVI].push_back(SubVec);
8660 // Replace uses of the shufflevector instructions with the sub-vectors
8661 // returned by the load intrinsic. If a shufflevector instruction is
8662 // associated with more than one sub-vector, those sub-vectors will be
8663 // concatenated into a single wide vector.
8664 for (ShuffleVectorInst *SVI : Shuffles) {
8665 auto &SubVec = SubVecs[SVI];
8666 auto *WideVec =
8667 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
8668 SVI->replaceAllUsesWith(WideVec);
8671 return true;
8674 /// Lower an interleaved store into a stN intrinsic.
8676 /// E.g. Lower an interleaved store (Factor = 3):
8677 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8678 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8679 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8681 /// Into:
8682 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8683 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8684 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8685 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8687 /// Note that the new shufflevectors will be removed and we'll only generate one
8688 /// st3 instruction in CodeGen.
8690 /// Example for a more general valid mask (Factor 3). Lower:
8691 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8692 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8693 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8695 /// Into:
8696 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8697 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8698 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8699 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8700 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
8701 ShuffleVectorInst *SVI,
8702 unsigned Factor) const {
8703 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
8704 "Invalid interleave factor");
8706 VectorType *VecTy = SVI->getType();
8707 assert(VecTy->getVectorNumElements() % Factor == 0 &&
8708 "Invalid interleaved store");
8710 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
8711 Type *EltTy = VecTy->getVectorElementType();
8712 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
8714 const DataLayout &DL = SI->getModule()->getDataLayout();
8716 // Skip if we do not have NEON and skip illegal vector types. We can
8717 // "legalize" wide vector types into multiple interleaved accesses as long as
8718 // the vector types are divisible by 128.
8719 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
8720 return false;
8722 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
8724 Value *Op0 = SVI->getOperand(0);
8725 Value *Op1 = SVI->getOperand(1);
8726 IRBuilder<> Builder(SI);
8728 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8729 // vectors to integer vectors.
8730 if (EltTy->isPointerTy()) {
8731 Type *IntTy = DL.getIntPtrType(EltTy);
8732 unsigned NumOpElts = Op0->getType()->getVectorNumElements();
8734 // Convert to the corresponding integer vector.
8735 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
8736 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
8737 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
8739 SubVecTy = VectorType::get(IntTy, LaneLen);
8742 // The base address of the store.
8743 Value *BaseAddr = SI->getPointerOperand();
8745 if (NumStores > 1) {
8746 // If we're going to generate more than one store, reset the lane length
8747 // and sub-vector type to something legal.
8748 LaneLen /= NumStores;
8749 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
8751 // We will compute the pointer operand of each store from the original base
8752 // address using GEPs. Cast the base address to a pointer to the scalar
8753 // element type.
8754 BaseAddr = Builder.CreateBitCast(
8755 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
8756 SI->getPointerAddressSpace()));
8759 auto Mask = SVI->getShuffleMask();
8761 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
8762 Type *Tys[2] = {SubVecTy, PtrTy};
8763 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
8764 Intrinsic::aarch64_neon_st3,
8765 Intrinsic::aarch64_neon_st4};
8766 Function *StNFunc =
8767 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
8769 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
8771 SmallVector<Value *, 5> Ops;
8773 // Split the shufflevector operands into sub vectors for the new stN call.
8774 for (unsigned i = 0; i < Factor; i++) {
8775 unsigned IdxI = StoreCount * LaneLen * Factor + i;
8776 if (Mask[IdxI] >= 0) {
8777 Ops.push_back(Builder.CreateShuffleVector(
8778 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
8779 } else {
8780 unsigned StartMask = 0;
8781 for (unsigned j = 1; j < LaneLen; j++) {
8782 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
8783 if (Mask[IdxJ * Factor + IdxI] >= 0) {
8784 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
8785 break;
8788 // Note: Filling undef gaps with random elements is ok, since
8789 // those elements were being written anyway (with undefs).
8790 // In the case of all undefs we're defaulting to using elems from 0
8791 // Note: StartMask cannot be negative, it's checked in
8792 // isReInterleaveMask
8793 Ops.push_back(Builder.CreateShuffleVector(
8794 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
8798 // If we generating more than one store, we compute the base address of
8799 // subsequent stores as an offset from the previous.
8800 if (StoreCount > 0)
8801 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
8802 BaseAddr, LaneLen * Factor);
8804 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
8805 Builder.CreateCall(StNFunc, Ops);
8807 return true;
8810 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8811 unsigned AlignCheck) {
8812 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8813 (DstAlign == 0 || DstAlign % AlignCheck == 0));
8816 EVT AArch64TargetLowering::getOptimalMemOpType(
8817 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8818 bool ZeroMemset, bool MemcpyStrSrc,
8819 const AttributeList &FuncAttributes) const {
8820 bool CanImplicitFloat =
8821 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8822 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8823 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8824 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8825 // taken one instruction to materialize the v2i64 zero and one store (with
8826 // restrictive addressing mode). Just do i64 stores.
8827 bool IsSmallMemset = IsMemset && Size < 32;
8828 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8829 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8830 return true;
8831 bool Fast;
8832 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8833 &Fast) &&
8834 Fast;
8837 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8838 AlignmentIsAcceptable(MVT::v2i64, 16))
8839 return MVT::v2i64;
8840 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8841 return MVT::f128;
8842 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8843 return MVT::i64;
8844 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8845 return MVT::i32;
8846 return MVT::Other;
8849 LLT AArch64TargetLowering::getOptimalMemOpLLT(
8850 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
8851 bool ZeroMemset, bool MemcpyStrSrc,
8852 const AttributeList &FuncAttributes) const {
8853 bool CanImplicitFloat =
8854 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
8855 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
8856 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
8857 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8858 // taken one instruction to materialize the v2i64 zero and one store (with
8859 // restrictive addressing mode). Just do i64 stores.
8860 bool IsSmallMemset = IsMemset && Size < 32;
8861 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) {
8862 if (memOpAlign(SrcAlign, DstAlign, AlignCheck))
8863 return true;
8864 bool Fast;
8865 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
8866 &Fast) &&
8867 Fast;
8870 if (CanUseNEON && IsMemset && !IsSmallMemset &&
8871 AlignmentIsAcceptable(MVT::v2i64, 16))
8872 return LLT::vector(2, 64);
8873 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16))
8874 return LLT::scalar(128);
8875 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8))
8876 return LLT::scalar(64);
8877 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4))
8878 return LLT::scalar(32);
8879 return LLT();
8882 // 12-bit optionally shifted immediates are legal for adds.
8883 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
8884 if (Immed == std::numeric_limits<int64_t>::min()) {
8885 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8886 << ": avoid UB for INT64_MIN\n");
8887 return false;
8889 // Same encoding for add/sub, just flip the sign.
8890 Immed = std::abs(Immed);
8891 bool IsLegal = ((Immed >> 12) == 0 ||
8892 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
8893 LLVM_DEBUG(dbgs() << "Is " << Immed
8894 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
8895 return IsLegal;
8898 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8899 // immediates is the same as for an add or a sub.
8900 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
8901 return isLegalAddImmediate(Immed);
8904 /// isLegalAddressingMode - Return true if the addressing mode represented
8905 /// by AM is legal for this target, for a load/store of the specified type.
8906 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
8907 const AddrMode &AM, Type *Ty,
8908 unsigned AS, Instruction *I) const {
8909 // AArch64 has five basic addressing modes:
8910 // reg
8911 // reg + 9-bit signed offset
8912 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8913 // reg1 + reg2
8914 // reg + SIZE_IN_BYTES * reg
8916 // No global is ever allowed as a base.
8917 if (AM.BaseGV)
8918 return false;
8920 // No reg+reg+imm addressing.
8921 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
8922 return false;
8924 // check reg + imm case:
8925 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8926 uint64_t NumBytes = 0;
8927 if (Ty->isSized()) {
8928 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
8929 NumBytes = NumBits / 8;
8930 if (!isPowerOf2_64(NumBits))
8931 NumBytes = 0;
8934 if (!AM.Scale) {
8935 int64_t Offset = AM.BaseOffs;
8937 // 9-bit signed offset
8938 if (isInt<9>(Offset))
8939 return true;
8941 // 12-bit unsigned offset
8942 unsigned shift = Log2_64(NumBytes);
8943 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8944 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8945 (Offset >> shift) << shift == Offset)
8946 return true;
8947 return false;
8950 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8952 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8955 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8956 // Consider splitting large offset of struct or array.
8957 return true;
8960 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8961 const AddrMode &AM, Type *Ty,
8962 unsigned AS) const {
8963 // Scaling factors are not free at all.
8964 // Operands | Rt Latency
8965 // -------------------------------------------
8966 // Rt, [Xn, Xm] | 4
8967 // -------------------------------------------
8968 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8969 // Rt, [Xn, Wm, <extend> #imm] |
8970 if (isLegalAddressingMode(DL, AM, Ty, AS))
8971 // Scale represents reg2 * scale, thus account for 1 if
8972 // it is not equal to 0 or 1.
8973 return AM.Scale != 0 && AM.Scale != 1;
8974 return -1;
8977 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8978 VT = VT.getScalarType();
8980 if (!VT.isSimple())
8981 return false;
8983 switch (VT.getSimpleVT().SimpleTy) {
8984 case MVT::f32:
8985 case MVT::f64:
8986 return true;
8987 default:
8988 break;
8991 return false;
8994 const MCPhysReg *
8995 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8996 // LR is a callee-save register, but we must treat it as clobbered by any call
8997 // site. Hence we include LR in the scratch registers, which are in turn added
8998 // as implicit-defs for stackmaps and patchpoints.
8999 static const MCPhysReg ScratchRegs[] = {
9000 AArch64::X16, AArch64::X17, AArch64::LR, 0
9002 return ScratchRegs;
9005 bool
9006 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
9007 CombineLevel Level) const {
9008 N = N->getOperand(0).getNode();
9009 EVT VT = N->getValueType(0);
9010 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9011 // it with shift to let it be lowered to UBFX.
9012 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
9013 isa<ConstantSDNode>(N->getOperand(1))) {
9014 uint64_t TruncMask = N->getConstantOperandVal(1);
9015 if (isMask_64(TruncMask) &&
9016 N->getOperand(0).getOpcode() == ISD::SRL &&
9017 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
9018 return false;
9020 return true;
9023 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9024 Type *Ty) const {
9025 assert(Ty->isIntegerTy());
9027 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9028 if (BitSize == 0)
9029 return false;
9031 int64_t Val = Imm.getSExtValue();
9032 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
9033 return true;
9035 if ((int64_t)Val < 0)
9036 Val = ~Val;
9037 if (BitSize == 32)
9038 Val &= (1LL << 32) - 1;
9040 unsigned LZ = countLeadingZeros((uint64_t)Val);
9041 unsigned Shift = (63 - LZ) / 16;
9042 // MOVZ is free so return true for one or fewer MOVK.
9043 return Shift < 3;
9046 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
9047 unsigned Index) const {
9048 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
9049 return false;
9051 return (Index == 0 || Index == ResVT.getVectorNumElements());
9054 /// Turn vector tests of the signbit in the form of:
9055 /// xor (sra X, elt_size(X)-1), -1
9056 /// into:
9057 /// cmge X, X, #0
9058 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
9059 const AArch64Subtarget *Subtarget) {
9060 EVT VT = N->getValueType(0);
9061 if (!Subtarget->hasNEON() || !VT.isVector())
9062 return SDValue();
9064 // There must be a shift right algebraic before the xor, and the xor must be a
9065 // 'not' operation.
9066 SDValue Shift = N->getOperand(0);
9067 SDValue Ones = N->getOperand(1);
9068 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
9069 !ISD::isBuildVectorAllOnes(Ones.getNode()))
9070 return SDValue();
9072 // The shift should be smearing the sign bit across each vector element.
9073 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
9074 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
9075 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
9076 return SDValue();
9078 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
9081 // Generate SUBS and CSEL for integer abs.
9082 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
9083 EVT VT = N->getValueType(0);
9085 SDValue N0 = N->getOperand(0);
9086 SDValue N1 = N->getOperand(1);
9087 SDLoc DL(N);
9089 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9090 // and change it to SUB and CSEL.
9091 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
9092 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
9093 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
9094 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
9095 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
9096 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
9097 N0.getOperand(0));
9098 // Generate SUBS & CSEL.
9099 SDValue Cmp =
9100 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
9101 N0.getOperand(0), DAG.getConstant(0, DL, VT));
9102 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
9103 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
9104 SDValue(Cmp.getNode(), 1));
9106 return SDValue();
9109 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
9110 TargetLowering::DAGCombinerInfo &DCI,
9111 const AArch64Subtarget *Subtarget) {
9112 if (DCI.isBeforeLegalizeOps())
9113 return SDValue();
9115 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
9116 return Cmp;
9118 return performIntegerAbsCombine(N, DAG);
9121 SDValue
9122 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9123 SelectionDAG &DAG,
9124 SmallVectorImpl<SDNode *> &Created) const {
9125 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
9126 if (isIntDivCheap(N->getValueType(0), Attr))
9127 return SDValue(N,0); // Lower SDIV as SDIV
9129 // fold (sdiv X, pow2)
9130 EVT VT = N->getValueType(0);
9131 if ((VT != MVT::i32 && VT != MVT::i64) ||
9132 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9133 return SDValue();
9135 SDLoc DL(N);
9136 SDValue N0 = N->getOperand(0);
9137 unsigned Lg2 = Divisor.countTrailingZeros();
9138 SDValue Zero = DAG.getConstant(0, DL, VT);
9139 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
9141 // Add (N0 < 0) ? Pow2 - 1 : 0;
9142 SDValue CCVal;
9143 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
9144 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
9145 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
9147 Created.push_back(Cmp.getNode());
9148 Created.push_back(Add.getNode());
9149 Created.push_back(CSel.getNode());
9151 // Divide by pow2.
9152 SDValue SRA =
9153 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
9155 // If we're dividing by a positive value, we're done. Otherwise, we must
9156 // negate the result.
9157 if (Divisor.isNonNegative())
9158 return SRA;
9160 Created.push_back(SRA.getNode());
9161 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
9164 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
9165 TargetLowering::DAGCombinerInfo &DCI,
9166 const AArch64Subtarget *Subtarget) {
9167 if (DCI.isBeforeLegalizeOps())
9168 return SDValue();
9170 // The below optimizations require a constant RHS.
9171 if (!isa<ConstantSDNode>(N->getOperand(1)))
9172 return SDValue();
9174 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
9175 const APInt &ConstValue = C->getAPIntValue();
9177 // Multiplication of a power of two plus/minus one can be done more
9178 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9179 // future CPUs have a cheaper MADD instruction, this may need to be
9180 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9181 // 64-bit is 5 cycles, so this is always a win.
9182 // More aggressively, some multiplications N0 * C can be lowered to
9183 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9184 // e.g. 6=3*2=(2+1)*2.
9185 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9186 // which equals to (1+2)*16-(1+2).
9187 SDValue N0 = N->getOperand(0);
9188 // TrailingZeroes is used to test if the mul can be lowered to
9189 // shift+add+shift.
9190 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
9191 if (TrailingZeroes) {
9192 // Conservatively do not lower to shift+add+shift if the mul might be
9193 // folded into smul or umul.
9194 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
9195 isZeroExtended(N0.getNode(), DAG)))
9196 return SDValue();
9197 // Conservatively do not lower to shift+add+shift if the mul might be
9198 // folded into madd or msub.
9199 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
9200 N->use_begin()->getOpcode() == ISD::SUB))
9201 return SDValue();
9203 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9204 // and shift+add+shift.
9205 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
9207 unsigned ShiftAmt, AddSubOpc;
9208 // Is the shifted value the LHS operand of the add/sub?
9209 bool ShiftValUseIsN0 = true;
9210 // Do we need to negate the result?
9211 bool NegateResult = false;
9213 if (ConstValue.isNonNegative()) {
9214 // (mul x, 2^N + 1) => (add (shl x, N), x)
9215 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9216 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9217 APInt SCVMinus1 = ShiftedConstValue - 1;
9218 APInt CVPlus1 = ConstValue + 1;
9219 if (SCVMinus1.isPowerOf2()) {
9220 ShiftAmt = SCVMinus1.logBase2();
9221 AddSubOpc = ISD::ADD;
9222 } else if (CVPlus1.isPowerOf2()) {
9223 ShiftAmt = CVPlus1.logBase2();
9224 AddSubOpc = ISD::SUB;
9225 } else
9226 return SDValue();
9227 } else {
9228 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9229 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9230 APInt CVNegPlus1 = -ConstValue + 1;
9231 APInt CVNegMinus1 = -ConstValue - 1;
9232 if (CVNegPlus1.isPowerOf2()) {
9233 ShiftAmt = CVNegPlus1.logBase2();
9234 AddSubOpc = ISD::SUB;
9235 ShiftValUseIsN0 = false;
9236 } else if (CVNegMinus1.isPowerOf2()) {
9237 ShiftAmt = CVNegMinus1.logBase2();
9238 AddSubOpc = ISD::ADD;
9239 NegateResult = true;
9240 } else
9241 return SDValue();
9244 SDLoc DL(N);
9245 EVT VT = N->getValueType(0);
9246 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
9247 DAG.getConstant(ShiftAmt, DL, MVT::i64));
9249 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
9250 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
9251 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
9252 assert(!(NegateResult && TrailingZeroes) &&
9253 "NegateResult and TrailingZeroes cannot both be true for now.");
9254 // Negate the result.
9255 if (NegateResult)
9256 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
9257 // Shift the result.
9258 if (TrailingZeroes)
9259 return DAG.getNode(ISD::SHL, DL, VT, Res,
9260 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
9261 return Res;
9264 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
9265 SelectionDAG &DAG) {
9266 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9267 // optimize away operation when it's from a constant.
9269 // The general transformation is:
9270 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9271 // AND(VECTOR_CMP(x,y), constant2)
9272 // constant2 = UNARYOP(constant)
9274 // Early exit if this isn't a vector operation, the operand of the
9275 // unary operation isn't a bitwise AND, or if the sizes of the operations
9276 // aren't the same.
9277 EVT VT = N->getValueType(0);
9278 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
9279 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
9280 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
9281 return SDValue();
9283 // Now check that the other operand of the AND is a constant. We could
9284 // make the transformation for non-constant splats as well, but it's unclear
9285 // that would be a benefit as it would not eliminate any operations, just
9286 // perform one more step in scalar code before moving to the vector unit.
9287 if (BuildVectorSDNode *BV =
9288 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
9289 // Bail out if the vector isn't a constant.
9290 if (!BV->isConstant())
9291 return SDValue();
9293 // Everything checks out. Build up the new and improved node.
9294 SDLoc DL(N);
9295 EVT IntVT = BV->getValueType(0);
9296 // Create a new constant of the appropriate type for the transformed
9297 // DAG.
9298 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
9299 // The AND node needs bitcasts to/from an integer vector type around it.
9300 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
9301 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
9302 N->getOperand(0)->getOperand(0), MaskConst);
9303 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
9304 return Res;
9307 return SDValue();
9310 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
9311 const AArch64Subtarget *Subtarget) {
9312 // First try to optimize away the conversion when it's conditionally from
9313 // a constant. Vectors only.
9314 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
9315 return Res;
9317 EVT VT = N->getValueType(0);
9318 if (VT != MVT::f32 && VT != MVT::f64)
9319 return SDValue();
9321 // Only optimize when the source and destination types have the same width.
9322 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
9323 return SDValue();
9325 // If the result of an integer load is only used by an integer-to-float
9326 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9327 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9328 SDValue N0 = N->getOperand(0);
9329 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9330 // Do not change the width of a volatile load.
9331 !cast<LoadSDNode>(N0)->isVolatile()) {
9332 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
9333 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
9334 LN0->getPointerInfo(), LN0->getAlignment(),
9335 LN0->getMemOperand()->getFlags());
9337 // Make sure successors of the original load stay after it by updating them
9338 // to use the new Chain.
9339 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
9341 unsigned Opcode =
9342 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
9343 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
9346 return SDValue();
9349 /// Fold a floating-point multiply by power of two into floating-point to
9350 /// fixed-point conversion.
9351 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
9352 TargetLowering::DAGCombinerInfo &DCI,
9353 const AArch64Subtarget *Subtarget) {
9354 if (!Subtarget->hasNEON())
9355 return SDValue();
9357 if (!N->getValueType(0).isSimple())
9358 return SDValue();
9360 SDValue Op = N->getOperand(0);
9361 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9362 Op.getOpcode() != ISD::FMUL)
9363 return SDValue();
9365 SDValue ConstVec = Op->getOperand(1);
9366 if (!isa<BuildVectorSDNode>(ConstVec))
9367 return SDValue();
9369 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9370 uint32_t FloatBits = FloatTy.getSizeInBits();
9371 if (FloatBits != 32 && FloatBits != 64)
9372 return SDValue();
9374 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9375 uint32_t IntBits = IntTy.getSizeInBits();
9376 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9377 return SDValue();
9379 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9380 if (IntBits > FloatBits)
9381 return SDValue();
9383 BitVector UndefElements;
9384 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9385 int32_t Bits = IntBits == 64 ? 64 : 32;
9386 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
9387 if (C == -1 || C == 0 || C > Bits)
9388 return SDValue();
9390 MVT ResTy;
9391 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9392 switch (NumLanes) {
9393 default:
9394 return SDValue();
9395 case 2:
9396 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9397 break;
9398 case 4:
9399 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9400 break;
9403 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9404 return SDValue();
9406 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
9407 "Illegal vector type after legalization");
9409 SDLoc DL(N);
9410 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
9411 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
9412 : Intrinsic::aarch64_neon_vcvtfp2fxu;
9413 SDValue FixConv =
9414 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
9415 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
9416 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
9417 // We can handle smaller integers by generating an extra trunc.
9418 if (IntBits < FloatBits)
9419 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
9421 return FixConv;
9424 /// Fold a floating-point divide by power of two into fixed-point to
9425 /// floating-point conversion.
9426 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
9427 TargetLowering::DAGCombinerInfo &DCI,
9428 const AArch64Subtarget *Subtarget) {
9429 if (!Subtarget->hasNEON())
9430 return SDValue();
9432 SDValue Op = N->getOperand(0);
9433 unsigned Opc = Op->getOpcode();
9434 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
9435 !Op.getOperand(0).getValueType().isSimple() ||
9436 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
9437 return SDValue();
9439 SDValue ConstVec = N->getOperand(1);
9440 if (!isa<BuildVectorSDNode>(ConstVec))
9441 return SDValue();
9443 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9444 int32_t IntBits = IntTy.getSizeInBits();
9445 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
9446 return SDValue();
9448 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9449 int32_t FloatBits = FloatTy.getSizeInBits();
9450 if (FloatBits != 32 && FloatBits != 64)
9451 return SDValue();
9453 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9454 if (IntBits > FloatBits)
9455 return SDValue();
9457 BitVector UndefElements;
9458 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
9459 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
9460 if (C == -1 || C == 0 || C > FloatBits)
9461 return SDValue();
9463 MVT ResTy;
9464 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9465 switch (NumLanes) {
9466 default:
9467 return SDValue();
9468 case 2:
9469 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
9470 break;
9471 case 4:
9472 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
9473 break;
9476 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
9477 return SDValue();
9479 SDLoc DL(N);
9480 SDValue ConvInput = Op.getOperand(0);
9481 bool IsSigned = Opc == ISD::SINT_TO_FP;
9482 if (IntBits < FloatBits)
9483 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
9484 ResTy, ConvInput);
9486 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
9487 : Intrinsic::aarch64_neon_vcvtfxu2fp;
9488 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
9489 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
9490 DAG.getConstant(C, DL, MVT::i32));
9493 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9494 /// searches for and classifies those shifts.
9495 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
9496 bool &FromHi) {
9497 if (N.getOpcode() == ISD::SHL)
9498 FromHi = false;
9499 else if (N.getOpcode() == ISD::SRL)
9500 FromHi = true;
9501 else
9502 return false;
9504 if (!isa<ConstantSDNode>(N.getOperand(1)))
9505 return false;
9507 ShiftAmount = N->getConstantOperandVal(1);
9508 Src = N->getOperand(0);
9509 return true;
9512 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9513 /// registers viewed as a high/low pair. This function looks for the pattern:
9514 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9515 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9516 /// aren't independent.
9517 static SDValue tryCombineToEXTR(SDNode *N,
9518 TargetLowering::DAGCombinerInfo &DCI) {
9519 SelectionDAG &DAG = DCI.DAG;
9520 SDLoc DL(N);
9521 EVT VT = N->getValueType(0);
9523 assert(N->getOpcode() == ISD::OR && "Unexpected root");
9525 if (VT != MVT::i32 && VT != MVT::i64)
9526 return SDValue();
9528 SDValue LHS;
9529 uint32_t ShiftLHS = 0;
9530 bool LHSFromHi = false;
9531 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
9532 return SDValue();
9534 SDValue RHS;
9535 uint32_t ShiftRHS = 0;
9536 bool RHSFromHi = false;
9537 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
9538 return SDValue();
9540 // If they're both trying to come from the high part of the register, they're
9541 // not really an EXTR.
9542 if (LHSFromHi == RHSFromHi)
9543 return SDValue();
9545 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
9546 return SDValue();
9548 if (LHSFromHi) {
9549 std::swap(LHS, RHS);
9550 std::swap(ShiftLHS, ShiftRHS);
9553 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
9554 DAG.getConstant(ShiftRHS, DL, MVT::i64));
9557 static SDValue tryCombineToBSL(SDNode *N,
9558 TargetLowering::DAGCombinerInfo &DCI) {
9559 EVT VT = N->getValueType(0);
9560 SelectionDAG &DAG = DCI.DAG;
9561 SDLoc DL(N);
9563 if (!VT.isVector())
9564 return SDValue();
9566 SDValue N0 = N->getOperand(0);
9567 if (N0.getOpcode() != ISD::AND)
9568 return SDValue();
9570 SDValue N1 = N->getOperand(1);
9571 if (N1.getOpcode() != ISD::AND)
9572 return SDValue();
9574 // We only have to look for constant vectors here since the general, variable
9575 // case can be handled in TableGen.
9576 unsigned Bits = VT.getScalarSizeInBits();
9577 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
9578 for (int i = 1; i >= 0; --i)
9579 for (int j = 1; j >= 0; --j) {
9580 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
9581 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
9582 if (!BVN0 || !BVN1)
9583 continue;
9585 bool FoundMatch = true;
9586 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
9587 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
9588 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
9589 if (!CN0 || !CN1 ||
9590 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
9591 FoundMatch = false;
9592 break;
9596 if (FoundMatch)
9597 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
9598 N0->getOperand(1 - i), N1->getOperand(1 - j));
9601 return SDValue();
9604 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9605 const AArch64Subtarget *Subtarget) {
9606 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9607 SelectionDAG &DAG = DCI.DAG;
9608 EVT VT = N->getValueType(0);
9610 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9611 return SDValue();
9613 if (SDValue Res = tryCombineToEXTR(N, DCI))
9614 return Res;
9616 if (SDValue Res = tryCombineToBSL(N, DCI))
9617 return Res;
9619 return SDValue();
9622 static SDValue performANDCombine(SDNode *N,
9623 TargetLowering::DAGCombinerInfo &DCI) {
9624 SelectionDAG &DAG = DCI.DAG;
9625 SDValue LHS = N->getOperand(0);
9626 EVT VT = N->getValueType(0);
9627 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
9628 return SDValue();
9630 BuildVectorSDNode *BVN =
9631 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
9632 if (!BVN)
9633 return SDValue();
9635 // AND does not accept an immediate, so check if we can use a BIC immediate
9636 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9637 // pattern in isel, because some immediates may be lowered to the preferred
9638 // (and x, (movi imm)) form, even though an mvni representation also exists.
9639 APInt DefBits(VT.getSizeInBits(), 0);
9640 APInt UndefBits(VT.getSizeInBits(), 0);
9641 if (resolveBuildVector(BVN, DefBits, UndefBits)) {
9642 SDValue NewOp;
9644 DefBits = ~DefBits;
9645 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9646 DefBits, &LHS)) ||
9647 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9648 DefBits, &LHS)))
9649 return NewOp;
9651 UndefBits = ~UndefBits;
9652 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
9653 UndefBits, &LHS)) ||
9654 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
9655 UndefBits, &LHS)))
9656 return NewOp;
9659 return SDValue();
9662 static SDValue performSRLCombine(SDNode *N,
9663 TargetLowering::DAGCombinerInfo &DCI) {
9664 SelectionDAG &DAG = DCI.DAG;
9665 EVT VT = N->getValueType(0);
9666 if (VT != MVT::i32 && VT != MVT::i64)
9667 return SDValue();
9669 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9670 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9671 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9672 SDValue N0 = N->getOperand(0);
9673 if (N0.getOpcode() == ISD::BSWAP) {
9674 SDLoc DL(N);
9675 SDValue N1 = N->getOperand(1);
9676 SDValue N00 = N0.getOperand(0);
9677 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9678 uint64_t ShiftAmt = C->getZExtValue();
9679 if (VT == MVT::i32 && ShiftAmt == 16 &&
9680 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
9681 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9682 if (VT == MVT::i64 && ShiftAmt == 32 &&
9683 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
9684 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
9687 return SDValue();
9690 static SDValue performBitcastCombine(SDNode *N,
9691 TargetLowering::DAGCombinerInfo &DCI,
9692 SelectionDAG &DAG) {
9693 // Wait 'til after everything is legalized to try this. That way we have
9694 // legal vector types and such.
9695 if (DCI.isBeforeLegalizeOps())
9696 return SDValue();
9698 // Remove extraneous bitcasts around an extract_subvector.
9699 // For example,
9700 // (v4i16 (bitconvert
9701 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9702 // becomes
9703 // (extract_subvector ((v8i16 ...), (i64 4)))
9705 // Only interested in 64-bit vectors as the ultimate result.
9706 EVT VT = N->getValueType(0);
9707 if (!VT.isVector())
9708 return SDValue();
9709 if (VT.getSimpleVT().getSizeInBits() != 64)
9710 return SDValue();
9711 // Is the operand an extract_subvector starting at the beginning or halfway
9712 // point of the vector? A low half may also come through as an
9713 // EXTRACT_SUBREG, so look for that, too.
9714 SDValue Op0 = N->getOperand(0);
9715 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
9716 !(Op0->isMachineOpcode() &&
9717 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
9718 return SDValue();
9719 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
9720 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
9721 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
9722 return SDValue();
9723 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
9724 if (idx != AArch64::dsub)
9725 return SDValue();
9726 // The dsub reference is equivalent to a lane zero subvector reference.
9727 idx = 0;
9729 // Look through the bitcast of the input to the extract.
9730 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
9731 return SDValue();
9732 SDValue Source = Op0->getOperand(0)->getOperand(0);
9733 // If the source type has twice the number of elements as our destination
9734 // type, we know this is an extract of the high or low half of the vector.
9735 EVT SVT = Source->getValueType(0);
9736 if (!SVT.isVector() ||
9737 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
9738 return SDValue();
9740 LLVM_DEBUG(
9741 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9743 // Create the simplified form to just extract the low or high half of the
9744 // vector directly rather than bothering with the bitcasts.
9745 SDLoc dl(N);
9746 unsigned NumElements = VT.getVectorNumElements();
9747 if (idx) {
9748 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
9749 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
9750 } else {
9751 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
9752 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
9753 Source, SubReg),
9758 static SDValue performConcatVectorsCombine(SDNode *N,
9759 TargetLowering::DAGCombinerInfo &DCI,
9760 SelectionDAG &DAG) {
9761 SDLoc dl(N);
9762 EVT VT = N->getValueType(0);
9763 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
9765 // Optimize concat_vectors of truncated vectors, where the intermediate
9766 // type is illegal, to avoid said illegality, e.g.,
9767 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9768 // (v2i16 (truncate (v2i64)))))
9769 // ->
9770 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9771 // (v4i32 (bitcast (v2i64))),
9772 // <0, 2, 4, 6>)))
9773 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9774 // on both input and result type, so we might generate worse code.
9775 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9776 if (N->getNumOperands() == 2 &&
9777 N0->getOpcode() == ISD::TRUNCATE &&
9778 N1->getOpcode() == ISD::TRUNCATE) {
9779 SDValue N00 = N0->getOperand(0);
9780 SDValue N10 = N1->getOperand(0);
9781 EVT N00VT = N00.getValueType();
9783 if (N00VT == N10.getValueType() &&
9784 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
9785 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
9786 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
9787 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
9788 for (size_t i = 0; i < Mask.size(); ++i)
9789 Mask[i] = i * 2;
9790 return DAG.getNode(ISD::TRUNCATE, dl, VT,
9791 DAG.getVectorShuffle(
9792 MidVT, dl,
9793 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
9794 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
9798 // Wait 'til after everything is legalized to try this. That way we have
9799 // legal vector types and such.
9800 if (DCI.isBeforeLegalizeOps())
9801 return SDValue();
9803 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9804 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9805 // canonicalise to that.
9806 if (N0 == N1 && VT.getVectorNumElements() == 2) {
9807 assert(VT.getScalarSizeInBits() == 64);
9808 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
9809 DAG.getConstant(0, dl, MVT::i64));
9812 // Canonicalise concat_vectors so that the right-hand vector has as few
9813 // bit-casts as possible before its real operation. The primary matching
9814 // destination for these operations will be the narrowing "2" instructions,
9815 // which depend on the operation being performed on this right-hand vector.
9816 // For example,
9817 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9818 // becomes
9819 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9821 if (N1->getOpcode() != ISD::BITCAST)
9822 return SDValue();
9823 SDValue RHS = N1->getOperand(0);
9824 MVT RHSTy = RHS.getValueType().getSimpleVT();
9825 // If the RHS is not a vector, this is not the pattern we're looking for.
9826 if (!RHSTy.isVector())
9827 return SDValue();
9829 LLVM_DEBUG(
9830 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9832 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
9833 RHSTy.getVectorNumElements() * 2);
9834 return DAG.getNode(ISD::BITCAST, dl, VT,
9835 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
9836 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
9837 RHS));
9840 static SDValue tryCombineFixedPointConvert(SDNode *N,
9841 TargetLowering::DAGCombinerInfo &DCI,
9842 SelectionDAG &DAG) {
9843 // Wait until after everything is legalized to try this. That way we have
9844 // legal vector types and such.
9845 if (DCI.isBeforeLegalizeOps())
9846 return SDValue();
9847 // Transform a scalar conversion of a value from a lane extract into a
9848 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9849 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9850 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9852 // The second form interacts better with instruction selection and the
9853 // register allocator to avoid cross-class register copies that aren't
9854 // coalescable due to a lane reference.
9856 // Check the operand and see if it originates from a lane extract.
9857 SDValue Op1 = N->getOperand(1);
9858 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9859 // Yep, no additional predication needed. Perform the transform.
9860 SDValue IID = N->getOperand(0);
9861 SDValue Shift = N->getOperand(2);
9862 SDValue Vec = Op1.getOperand(0);
9863 SDValue Lane = Op1.getOperand(1);
9864 EVT ResTy = N->getValueType(0);
9865 EVT VecResTy;
9866 SDLoc DL(N);
9868 // The vector width should be 128 bits by the time we get here, even
9869 // if it started as 64 bits (the extract_vector handling will have
9870 // done so).
9871 assert(Vec.getValueSizeInBits() == 128 &&
9872 "unexpected vector size on extract_vector_elt!");
9873 if (Vec.getValueType() == MVT::v4i32)
9874 VecResTy = MVT::v4f32;
9875 else if (Vec.getValueType() == MVT::v2i64)
9876 VecResTy = MVT::v2f64;
9877 else
9878 llvm_unreachable("unexpected vector type!");
9880 SDValue Convert =
9881 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
9882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
9884 return SDValue();
9887 // AArch64 high-vector "long" operations are formed by performing the non-high
9888 // version on an extract_subvector of each operand which gets the high half:
9890 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9892 // However, there are cases which don't have an extract_high explicitly, but
9893 // have another operation that can be made compatible with one for free. For
9894 // example:
9896 // (dupv64 scalar) --> (extract_high (dup128 scalar))
9898 // This routine does the actual conversion of such DUPs, once outer routines
9899 // have determined that everything else is in order.
9900 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9901 // similarly here.
9902 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
9903 switch (N.getOpcode()) {
9904 case AArch64ISD::DUP:
9905 case AArch64ISD::DUPLANE8:
9906 case AArch64ISD::DUPLANE16:
9907 case AArch64ISD::DUPLANE32:
9908 case AArch64ISD::DUPLANE64:
9909 case AArch64ISD::MOVI:
9910 case AArch64ISD::MOVIshift:
9911 case AArch64ISD::MOVIedit:
9912 case AArch64ISD::MOVImsl:
9913 case AArch64ISD::MVNIshift:
9914 case AArch64ISD::MVNImsl:
9915 break;
9916 default:
9917 // FMOV could be supported, but isn't very useful, as it would only occur
9918 // if you passed a bitcast' floating point immediate to an eligible long
9919 // integer op (addl, smull, ...).
9920 return SDValue();
9923 MVT NarrowTy = N.getSimpleValueType();
9924 if (!NarrowTy.is64BitVector())
9925 return SDValue();
9927 MVT ElementTy = NarrowTy.getVectorElementType();
9928 unsigned NumElems = NarrowTy.getVectorNumElements();
9929 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
9931 SDLoc dl(N);
9932 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
9933 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
9934 DAG.getConstant(NumElems, dl, MVT::i64));
9937 static bool isEssentiallyExtractHighSubvector(SDValue N) {
9938 if (N.getOpcode() == ISD::BITCAST)
9939 N = N.getOperand(0);
9940 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9941 return false;
9942 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
9943 N.getOperand(0).getValueType().getVectorNumElements() / 2;
9946 /// Helper structure to keep track of ISD::SET_CC operands.
9947 struct GenericSetCCInfo {
9948 const SDValue *Opnd0;
9949 const SDValue *Opnd1;
9950 ISD::CondCode CC;
9953 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9954 struct AArch64SetCCInfo {
9955 const SDValue *Cmp;
9956 AArch64CC::CondCode CC;
9959 /// Helper structure to keep track of SetCC information.
9960 union SetCCInfo {
9961 GenericSetCCInfo Generic;
9962 AArch64SetCCInfo AArch64;
9965 /// Helper structure to be able to read SetCC information. If set to
9966 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9967 /// GenericSetCCInfo.
9968 struct SetCCInfoAndKind {
9969 SetCCInfo Info;
9970 bool IsAArch64;
9973 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9974 /// an
9975 /// AArch64 lowered one.
9976 /// \p SetCCInfo is filled accordingly.
9977 /// \post SetCCInfo is meanginfull only when this function returns true.
9978 /// \return True when Op is a kind of SET_CC operation.
9979 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
9980 // If this is a setcc, this is straight forward.
9981 if (Op.getOpcode() == ISD::SETCC) {
9982 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
9983 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
9984 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9985 SetCCInfo.IsAArch64 = false;
9986 return true;
9988 // Otherwise, check if this is a matching csel instruction.
9989 // In other words:
9990 // - csel 1, 0, cc
9991 // - csel 0, 1, !cc
9992 if (Op.getOpcode() != AArch64ISD::CSEL)
9993 return false;
9994 // Set the information about the operands.
9995 // TODO: we want the operands of the Cmp not the csel
9996 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9997 SetCCInfo.IsAArch64 = true;
9998 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9999 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10001 // Check that the operands matches the constraints:
10002 // (1) Both operands must be constants.
10003 // (2) One must be 1 and the other must be 0.
10004 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
10005 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10007 // Check (1).
10008 if (!TValue || !FValue)
10009 return false;
10011 // Check (2).
10012 if (!TValue->isOne()) {
10013 // Update the comparison when we are interested in !cc.
10014 std::swap(TValue, FValue);
10015 SetCCInfo.Info.AArch64.CC =
10016 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
10018 return TValue->isOne() && FValue->isNullValue();
10021 // Returns true if Op is setcc or zext of setcc.
10022 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
10023 if (isSetCC(Op, Info))
10024 return true;
10025 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
10026 isSetCC(Op->getOperand(0), Info));
10029 // The folding we want to perform is:
10030 // (add x, [zext] (setcc cc ...) )
10031 // -->
10032 // (csel x, (add x, 1), !cc ...)
10034 // The latter will get matched to a CSINC instruction.
10035 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
10036 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
10037 SDValue LHS = Op->getOperand(0);
10038 SDValue RHS = Op->getOperand(1);
10039 SetCCInfoAndKind InfoAndKind;
10041 // If neither operand is a SET_CC, give up.
10042 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
10043 std::swap(LHS, RHS);
10044 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
10045 return SDValue();
10048 // FIXME: This could be generatized to work for FP comparisons.
10049 EVT CmpVT = InfoAndKind.IsAArch64
10050 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
10051 : InfoAndKind.Info.Generic.Opnd0->getValueType();
10052 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
10053 return SDValue();
10055 SDValue CCVal;
10056 SDValue Cmp;
10057 SDLoc dl(Op);
10058 if (InfoAndKind.IsAArch64) {
10059 CCVal = DAG.getConstant(
10060 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
10061 MVT::i32);
10062 Cmp = *InfoAndKind.Info.AArch64.Cmp;
10063 } else
10064 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
10065 *InfoAndKind.Info.Generic.Opnd1,
10066 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
10067 CCVal, DAG, dl);
10069 EVT VT = Op->getValueType(0);
10070 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
10071 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
10074 // The basic add/sub long vector instructions have variants with "2" on the end
10075 // which act on the high-half of their inputs. They are normally matched by
10076 // patterns like:
10078 // (add (zeroext (extract_high LHS)),
10079 // (zeroext (extract_high RHS)))
10080 // -> uaddl2 vD, vN, vM
10082 // However, if one of the extracts is something like a duplicate, this
10083 // instruction can still be used profitably. This function puts the DAG into a
10084 // more appropriate form for those patterns to trigger.
10085 static SDValue performAddSubLongCombine(SDNode *N,
10086 TargetLowering::DAGCombinerInfo &DCI,
10087 SelectionDAG &DAG) {
10088 if (DCI.isBeforeLegalizeOps())
10089 return SDValue();
10091 MVT VT = N->getSimpleValueType(0);
10092 if (!VT.is128BitVector()) {
10093 if (N->getOpcode() == ISD::ADD)
10094 return performSetccAddFolding(N, DAG);
10095 return SDValue();
10098 // Make sure both branches are extended in the same way.
10099 SDValue LHS = N->getOperand(0);
10100 SDValue RHS = N->getOperand(1);
10101 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
10102 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
10103 LHS.getOpcode() != RHS.getOpcode())
10104 return SDValue();
10106 unsigned ExtType = LHS.getOpcode();
10108 // It's not worth doing if at least one of the inputs isn't already an
10109 // extract, but we don't know which it'll be so we have to try both.
10110 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
10111 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
10112 if (!RHS.getNode())
10113 return SDValue();
10115 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
10116 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
10117 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
10118 if (!LHS.getNode())
10119 return SDValue();
10121 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
10124 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
10127 // Massage DAGs which we can use the high-half "long" operations on into
10128 // something isel will recognize better. E.g.
10130 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10131 // (aarch64_neon_umull (extract_high (v2i64 vec)))
10132 // (extract_high (v2i64 (dup128 scalar)))))
10134 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
10135 TargetLowering::DAGCombinerInfo &DCI,
10136 SelectionDAG &DAG) {
10137 if (DCI.isBeforeLegalizeOps())
10138 return SDValue();
10140 SDValue LHS = N->getOperand(1);
10141 SDValue RHS = N->getOperand(2);
10142 assert(LHS.getValueType().is64BitVector() &&
10143 RHS.getValueType().is64BitVector() &&
10144 "unexpected shape for long operation");
10146 // Either node could be a DUP, but it's not worth doing both of them (you'd
10147 // just as well use the non-high version) so look for a corresponding extract
10148 // operation on the other "wing".
10149 if (isEssentiallyExtractHighSubvector(LHS)) {
10150 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
10151 if (!RHS.getNode())
10152 return SDValue();
10153 } else if (isEssentiallyExtractHighSubvector(RHS)) {
10154 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
10155 if (!LHS.getNode())
10156 return SDValue();
10159 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
10160 N->getOperand(0), LHS, RHS);
10163 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
10164 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
10165 unsigned ElemBits = ElemTy.getSizeInBits();
10167 int64_t ShiftAmount;
10168 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
10169 APInt SplatValue, SplatUndef;
10170 unsigned SplatBitSize;
10171 bool HasAnyUndefs;
10172 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
10173 HasAnyUndefs, ElemBits) ||
10174 SplatBitSize != ElemBits)
10175 return SDValue();
10177 ShiftAmount = SplatValue.getSExtValue();
10178 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
10179 ShiftAmount = CVN->getSExtValue();
10180 } else
10181 return SDValue();
10183 unsigned Opcode;
10184 bool IsRightShift;
10185 switch (IID) {
10186 default:
10187 llvm_unreachable("Unknown shift intrinsic");
10188 case Intrinsic::aarch64_neon_sqshl:
10189 Opcode = AArch64ISD::SQSHL_I;
10190 IsRightShift = false;
10191 break;
10192 case Intrinsic::aarch64_neon_uqshl:
10193 Opcode = AArch64ISD::UQSHL_I;
10194 IsRightShift = false;
10195 break;
10196 case Intrinsic::aarch64_neon_srshl:
10197 Opcode = AArch64ISD::SRSHR_I;
10198 IsRightShift = true;
10199 break;
10200 case Intrinsic::aarch64_neon_urshl:
10201 Opcode = AArch64ISD::URSHR_I;
10202 IsRightShift = true;
10203 break;
10204 case Intrinsic::aarch64_neon_sqshlu:
10205 Opcode = AArch64ISD::SQSHLU_I;
10206 IsRightShift = false;
10207 break;
10210 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
10211 SDLoc dl(N);
10212 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10213 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
10214 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
10215 SDLoc dl(N);
10216 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
10217 DAG.getConstant(ShiftAmount, dl, MVT::i32));
10220 return SDValue();
10223 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10224 // the intrinsics must be legal and take an i32, this means there's almost
10225 // certainly going to be a zext in the DAG which we can eliminate.
10226 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
10227 SDValue AndN = N->getOperand(2);
10228 if (AndN.getOpcode() != ISD::AND)
10229 return SDValue();
10231 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
10232 if (!CMask || CMask->getZExtValue() != Mask)
10233 return SDValue();
10235 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
10236 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
10239 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
10240 SelectionDAG &DAG) {
10241 SDLoc dl(N);
10242 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
10243 DAG.getNode(Opc, dl,
10244 N->getOperand(1).getSimpleValueType(),
10245 N->getOperand(1)),
10246 DAG.getConstant(0, dl, MVT::i64));
10249 static SDValue performIntrinsicCombine(SDNode *N,
10250 TargetLowering::DAGCombinerInfo &DCI,
10251 const AArch64Subtarget *Subtarget) {
10252 SelectionDAG &DAG = DCI.DAG;
10253 unsigned IID = getIntrinsicID(N);
10254 switch (IID) {
10255 default:
10256 break;
10257 case Intrinsic::aarch64_neon_vcvtfxs2fp:
10258 case Intrinsic::aarch64_neon_vcvtfxu2fp:
10259 return tryCombineFixedPointConvert(N, DCI, DAG);
10260 case Intrinsic::aarch64_neon_saddv:
10261 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
10262 case Intrinsic::aarch64_neon_uaddv:
10263 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
10264 case Intrinsic::aarch64_neon_sminv:
10265 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
10266 case Intrinsic::aarch64_neon_uminv:
10267 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
10268 case Intrinsic::aarch64_neon_smaxv:
10269 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
10270 case Intrinsic::aarch64_neon_umaxv:
10271 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
10272 case Intrinsic::aarch64_neon_fmax:
10273 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
10274 N->getOperand(1), N->getOperand(2));
10275 case Intrinsic::aarch64_neon_fmin:
10276 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
10277 N->getOperand(1), N->getOperand(2));
10278 case Intrinsic::aarch64_neon_fmaxnm:
10279 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
10280 N->getOperand(1), N->getOperand(2));
10281 case Intrinsic::aarch64_neon_fminnm:
10282 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
10283 N->getOperand(1), N->getOperand(2));
10284 case Intrinsic::aarch64_neon_smull:
10285 case Intrinsic::aarch64_neon_umull:
10286 case Intrinsic::aarch64_neon_pmull:
10287 case Intrinsic::aarch64_neon_sqdmull:
10288 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
10289 case Intrinsic::aarch64_neon_sqshl:
10290 case Intrinsic::aarch64_neon_uqshl:
10291 case Intrinsic::aarch64_neon_sqshlu:
10292 case Intrinsic::aarch64_neon_srshl:
10293 case Intrinsic::aarch64_neon_urshl:
10294 return tryCombineShiftImm(IID, N, DAG);
10295 case Intrinsic::aarch64_crc32b:
10296 case Intrinsic::aarch64_crc32cb:
10297 return tryCombineCRC32(0xff, N, DAG);
10298 case Intrinsic::aarch64_crc32h:
10299 case Intrinsic::aarch64_crc32ch:
10300 return tryCombineCRC32(0xffff, N, DAG);
10302 return SDValue();
10305 static SDValue performExtendCombine(SDNode *N,
10306 TargetLowering::DAGCombinerInfo &DCI,
10307 SelectionDAG &DAG) {
10308 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10309 // we can convert that DUP into another extract_high (of a bigger DUP), which
10310 // helps the backend to decide that an sabdl2 would be useful, saving a real
10311 // extract_high operation.
10312 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
10313 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
10314 SDNode *ABDNode = N->getOperand(0).getNode();
10315 unsigned IID = getIntrinsicID(ABDNode);
10316 if (IID == Intrinsic::aarch64_neon_sabd ||
10317 IID == Intrinsic::aarch64_neon_uabd) {
10318 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
10319 if (!NewABD.getNode())
10320 return SDValue();
10322 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
10323 NewABD);
10327 // This is effectively a custom type legalization for AArch64.
10329 // Type legalization will split an extend of a small, legal, type to a larger
10330 // illegal type by first splitting the destination type, often creating
10331 // illegal source types, which then get legalized in isel-confusing ways,
10332 // leading to really terrible codegen. E.g.,
10333 // %result = v8i32 sext v8i8 %value
10334 // becomes
10335 // %losrc = extract_subreg %value, ...
10336 // %hisrc = extract_subreg %value, ...
10337 // %lo = v4i32 sext v4i8 %losrc
10338 // %hi = v4i32 sext v4i8 %hisrc
10339 // Things go rapidly downhill from there.
10341 // For AArch64, the [sz]ext vector instructions can only go up one element
10342 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10343 // take two instructions.
10345 // This implies that the most efficient way to do the extend from v8i8
10346 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10347 // the normal splitting to happen for the v8i16->v8i32.
10349 // This is pre-legalization to catch some cases where the default
10350 // type legalization will create ill-tempered code.
10351 if (!DCI.isBeforeLegalizeOps())
10352 return SDValue();
10354 // We're only interested in cleaning things up for non-legal vector types
10355 // here. If both the source and destination are legal, things will just
10356 // work naturally without any fiddling.
10357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10358 EVT ResVT = N->getValueType(0);
10359 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
10360 return SDValue();
10361 // If the vector type isn't a simple VT, it's beyond the scope of what
10362 // we're worried about here. Let legalization do its thing and hope for
10363 // the best.
10364 SDValue Src = N->getOperand(0);
10365 EVT SrcVT = Src->getValueType(0);
10366 if (!ResVT.isSimple() || !SrcVT.isSimple())
10367 return SDValue();
10369 // If the source VT is a 64-bit vector, we can play games and get the
10370 // better results we want.
10371 if (SrcVT.getSizeInBits() != 64)
10372 return SDValue();
10374 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
10375 unsigned ElementCount = SrcVT.getVectorNumElements();
10376 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
10377 SDLoc DL(N);
10378 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
10380 // Now split the rest of the operation into two halves, each with a 64
10381 // bit source.
10382 EVT LoVT, HiVT;
10383 SDValue Lo, Hi;
10384 unsigned NumElements = ResVT.getVectorNumElements();
10385 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
10386 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
10387 ResVT.getVectorElementType(), NumElements / 2);
10389 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
10390 LoVT.getVectorNumElements());
10391 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10392 DAG.getConstant(0, DL, MVT::i64));
10393 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
10394 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
10395 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
10396 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
10398 // Now combine the parts back together so we still have a single result
10399 // like the combiner expects.
10400 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
10403 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
10404 SDValue SplatVal, unsigned NumVecElts) {
10405 assert(!St.isTruncatingStore() && "cannot split truncating vector store");
10406 unsigned OrigAlignment = St.getAlignment();
10407 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
10409 // Create scalar stores. This is at least as good as the code sequence for a
10410 // split unaligned store which is a dup.s, ext.b, and two stores.
10411 // Most of the time the three stores should be replaced by store pair
10412 // instructions (stp).
10413 SDLoc DL(&St);
10414 SDValue BasePtr = St.getBasePtr();
10415 uint64_t BaseOffset = 0;
10417 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
10418 SDValue NewST1 =
10419 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
10420 OrigAlignment, St.getMemOperand()->getFlags());
10422 // As this in ISel, we will not merge this add which may degrade results.
10423 if (BasePtr->getOpcode() == ISD::ADD &&
10424 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
10425 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
10426 BasePtr = BasePtr->getOperand(0);
10429 unsigned Offset = EltOffset;
10430 while (--NumVecElts) {
10431 unsigned Alignment = MinAlign(OrigAlignment, Offset);
10432 SDValue OffsetPtr =
10433 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10434 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
10435 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
10436 PtrInfo.getWithOffset(Offset), Alignment,
10437 St.getMemOperand()->getFlags());
10438 Offset += EltOffset;
10440 return NewST1;
10443 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10444 /// load store optimizer pass will merge them to store pair stores. This should
10445 /// be better than a movi to create the vector zero followed by a vector store
10446 /// if the zero constant is not re-used, since one instructions and one register
10447 /// live range will be removed.
10449 /// For example, the final generated code should be:
10451 /// stp xzr, xzr, [x0]
10453 /// instead of:
10455 /// movi v0.2d, #0
10456 /// str q0, [x0]
10458 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10459 SDValue StVal = St.getValue();
10460 EVT VT = StVal.getValueType();
10462 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10463 // 2, 3 or 4 i32 elements.
10464 int NumVecElts = VT.getVectorNumElements();
10465 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
10466 VT.getVectorElementType().getSizeInBits() == 64) ||
10467 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
10468 VT.getVectorElementType().getSizeInBits() == 32)))
10469 return SDValue();
10471 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
10472 return SDValue();
10474 // If the zero constant has more than one use then the vector store could be
10475 // better since the constant mov will be amortized and stp q instructions
10476 // should be able to be formed.
10477 if (!StVal.hasOneUse())
10478 return SDValue();
10480 // If the store is truncating then it's going down to i16 or smaller, which
10481 // means it can be implemented in a single store anyway.
10482 if (St.isTruncatingStore())
10483 return SDValue();
10485 // If the immediate offset of the address operand is too large for the stp
10486 // instruction, then bail out.
10487 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
10488 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
10489 if (Offset < -512 || Offset > 504)
10490 return SDValue();
10493 for (int I = 0; I < NumVecElts; ++I) {
10494 SDValue EltVal = StVal.getOperand(I);
10495 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
10496 return SDValue();
10499 // Use a CopyFromReg WZR/XZR here to prevent
10500 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10501 SDLoc DL(&St);
10502 unsigned ZeroReg;
10503 EVT ZeroVT;
10504 if (VT.getVectorElementType().getSizeInBits() == 32) {
10505 ZeroReg = AArch64::WZR;
10506 ZeroVT = MVT::i32;
10507 } else {
10508 ZeroReg = AArch64::XZR;
10509 ZeroVT = MVT::i64;
10511 SDValue SplatVal =
10512 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
10513 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10516 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10517 /// value. The load store optimizer pass will merge them to store pair stores.
10518 /// This has better performance than a splat of the scalar followed by a split
10519 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10520 /// followed by an ext.b and two stores.
10521 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
10522 SDValue StVal = St.getValue();
10523 EVT VT = StVal.getValueType();
10525 // Don't replace floating point stores, they possibly won't be transformed to
10526 // stp because of the store pair suppress pass.
10527 if (VT.isFloatingPoint())
10528 return SDValue();
10530 // We can express a splat as store pair(s) for 2 or 4 elements.
10531 unsigned NumVecElts = VT.getVectorNumElements();
10532 if (NumVecElts != 4 && NumVecElts != 2)
10533 return SDValue();
10535 // If the store is truncating then it's going down to i16 or smaller, which
10536 // means it can be implemented in a single store anyway.
10537 if (St.isTruncatingStore())
10538 return SDValue();
10540 // Check that this is a splat.
10541 // Make sure that each of the relevant vector element locations are inserted
10542 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10543 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
10544 SDValue SplatVal;
10545 for (unsigned I = 0; I < NumVecElts; ++I) {
10546 // Check for insert vector elements.
10547 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
10548 return SDValue();
10550 // Check that same value is inserted at each vector element.
10551 if (I == 0)
10552 SplatVal = StVal.getOperand(1);
10553 else if (StVal.getOperand(1) != SplatVal)
10554 return SDValue();
10556 // Check insert element index.
10557 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
10558 if (!CIndex)
10559 return SDValue();
10560 uint64_t IndexVal = CIndex->getZExtValue();
10561 if (IndexVal >= NumVecElts)
10562 return SDValue();
10563 IndexNotInserted.reset(IndexVal);
10565 StVal = StVal.getOperand(0);
10567 // Check that all vector element locations were inserted to.
10568 if (IndexNotInserted.any())
10569 return SDValue();
10571 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
10574 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
10575 SelectionDAG &DAG,
10576 const AArch64Subtarget *Subtarget) {
10578 StoreSDNode *S = cast<StoreSDNode>(N);
10579 if (S->isVolatile() || S->isIndexed())
10580 return SDValue();
10582 SDValue StVal = S->getValue();
10583 EVT VT = StVal.getValueType();
10584 if (!VT.isVector())
10585 return SDValue();
10587 // If we get a splat of zeros, convert this vector store to a store of
10588 // scalars. They will be merged into store pairs of xzr thereby removing one
10589 // instruction and one register.
10590 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
10591 return ReplacedZeroSplat;
10593 // FIXME: The logic for deciding if an unaligned store should be split should
10594 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10595 // a call to that function here.
10597 if (!Subtarget->isMisaligned128StoreSlow())
10598 return SDValue();
10600 // Don't split at -Oz.
10601 if (DAG.getMachineFunction().getFunction().hasMinSize())
10602 return SDValue();
10604 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10605 // those up regresses performance on micro-benchmarks and olden/bh.
10606 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
10607 return SDValue();
10609 // Split unaligned 16B stores. They are terrible for performance.
10610 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10611 // extensions can use this to mark that it does not want splitting to happen
10612 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10613 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10614 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
10615 S->getAlignment() <= 2)
10616 return SDValue();
10618 // If we get a splat of a scalar convert this vector store to a store of
10619 // scalars. They will be merged into store pairs thereby removing two
10620 // instructions.
10621 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
10622 return ReplacedSplat;
10624 SDLoc DL(S);
10626 // Split VT into two.
10627 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10628 unsigned NumElts = HalfVT.getVectorNumElements();
10629 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10630 DAG.getConstant(0, DL, MVT::i64));
10631 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
10632 DAG.getConstant(NumElts, DL, MVT::i64));
10633 SDValue BasePtr = S->getBasePtr();
10634 SDValue NewST1 =
10635 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
10636 S->getAlignment(), S->getMemOperand()->getFlags());
10637 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
10638 DAG.getConstant(8, DL, MVT::i64));
10639 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
10640 S->getPointerInfo(), S->getAlignment(),
10641 S->getMemOperand()->getFlags());
10644 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10645 /// post-increment LD1R.
10646 static SDValue performPostLD1Combine(SDNode *N,
10647 TargetLowering::DAGCombinerInfo &DCI,
10648 bool IsLaneOp) {
10649 if (DCI.isBeforeLegalizeOps())
10650 return SDValue();
10652 SelectionDAG &DAG = DCI.DAG;
10653 EVT VT = N->getValueType(0);
10655 unsigned LoadIdx = IsLaneOp ? 1 : 0;
10656 SDNode *LD = N->getOperand(LoadIdx).getNode();
10657 // If it is not LOAD, can not do such combine.
10658 if (LD->getOpcode() != ISD::LOAD)
10659 return SDValue();
10661 // The vector lane must be a constant in the LD1LANE opcode.
10662 SDValue Lane;
10663 if (IsLaneOp) {
10664 Lane = N->getOperand(2);
10665 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
10666 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
10667 return SDValue();
10670 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
10671 EVT MemVT = LoadSDN->getMemoryVT();
10672 // Check if memory operand is the same type as the vector element.
10673 if (MemVT != VT.getVectorElementType())
10674 return SDValue();
10676 // Check if there are other uses. If so, do not combine as it will introduce
10677 // an extra load.
10678 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
10679 ++UI) {
10680 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
10681 continue;
10682 if (*UI != N)
10683 return SDValue();
10686 SDValue Addr = LD->getOperand(1);
10687 SDValue Vector = N->getOperand(0);
10688 // Search for a use of the address operand that is an increment.
10689 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
10690 Addr.getNode()->use_end(); UI != UE; ++UI) {
10691 SDNode *User = *UI;
10692 if (User->getOpcode() != ISD::ADD
10693 || UI.getUse().getResNo() != Addr.getResNo())
10694 continue;
10696 // If the increment is a constant, it must match the memory ref size.
10697 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10698 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10699 uint32_t IncVal = CInc->getZExtValue();
10700 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
10701 if (IncVal != NumBytes)
10702 continue;
10703 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10706 // To avoid cycle construction make sure that neither the load nor the add
10707 // are predecessors to each other or the Vector.
10708 SmallPtrSet<const SDNode *, 32> Visited;
10709 SmallVector<const SDNode *, 16> Worklist;
10710 Visited.insert(Addr.getNode());
10711 Worklist.push_back(User);
10712 Worklist.push_back(LD);
10713 Worklist.push_back(Vector.getNode());
10714 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
10715 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10716 continue;
10718 SmallVector<SDValue, 8> Ops;
10719 Ops.push_back(LD->getOperand(0)); // Chain
10720 if (IsLaneOp) {
10721 Ops.push_back(Vector); // The vector to be inserted
10722 Ops.push_back(Lane); // The lane to be inserted in the vector
10724 Ops.push_back(Addr);
10725 Ops.push_back(Inc);
10727 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
10728 SDVTList SDTys = DAG.getVTList(Tys);
10729 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
10730 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
10731 MemVT,
10732 LoadSDN->getMemOperand());
10734 // Update the uses.
10735 SDValue NewResults[] = {
10736 SDValue(LD, 0), // The result of load
10737 SDValue(UpdN.getNode(), 2) // Chain
10739 DCI.CombineTo(LD, NewResults);
10740 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
10741 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
10743 break;
10745 return SDValue();
10748 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10749 /// address translation.
10750 static bool performTBISimplification(SDValue Addr,
10751 TargetLowering::DAGCombinerInfo &DCI,
10752 SelectionDAG &DAG) {
10753 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
10754 KnownBits Known;
10755 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10756 !DCI.isBeforeLegalizeOps());
10757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10758 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
10759 DCI.CommitTargetLoweringOpt(TLO);
10760 return true;
10762 return false;
10765 static SDValue performSTORECombine(SDNode *N,
10766 TargetLowering::DAGCombinerInfo &DCI,
10767 SelectionDAG &DAG,
10768 const AArch64Subtarget *Subtarget) {
10769 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
10770 return Split;
10772 if (Subtarget->supportsAddressTopByteIgnored() &&
10773 performTBISimplification(N->getOperand(2), DCI, DAG))
10774 return SDValue(N, 0);
10776 return SDValue();
10780 /// Target-specific DAG combine function for NEON load/store intrinsics
10781 /// to merge base address updates.
10782 static SDValue performNEONPostLDSTCombine(SDNode *N,
10783 TargetLowering::DAGCombinerInfo &DCI,
10784 SelectionDAG &DAG) {
10785 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10786 return SDValue();
10788 unsigned AddrOpIdx = N->getNumOperands() - 1;
10789 SDValue Addr = N->getOperand(AddrOpIdx);
10791 // Search for a use of the address operand that is an increment.
10792 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10793 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10794 SDNode *User = *UI;
10795 if (User->getOpcode() != ISD::ADD ||
10796 UI.getUse().getResNo() != Addr.getResNo())
10797 continue;
10799 // Check that the add is independent of the load/store. Otherwise, folding
10800 // it would create a cycle.
10801 SmallPtrSet<const SDNode *, 32> Visited;
10802 SmallVector<const SDNode *, 16> Worklist;
10803 Visited.insert(Addr.getNode());
10804 Worklist.push_back(N);
10805 Worklist.push_back(User);
10806 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
10807 SDNode::hasPredecessorHelper(User, Visited, Worklist))
10808 continue;
10810 // Find the new opcode for the updating load/store.
10811 bool IsStore = false;
10812 bool IsLaneOp = false;
10813 bool IsDupOp = false;
10814 unsigned NewOpc = 0;
10815 unsigned NumVecs = 0;
10816 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10817 switch (IntNo) {
10818 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10819 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
10820 NumVecs = 2; break;
10821 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
10822 NumVecs = 3; break;
10823 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
10824 NumVecs = 4; break;
10825 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
10826 NumVecs = 2; IsStore = true; break;
10827 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
10828 NumVecs = 3; IsStore = true; break;
10829 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
10830 NumVecs = 4; IsStore = true; break;
10831 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
10832 NumVecs = 2; break;
10833 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
10834 NumVecs = 3; break;
10835 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
10836 NumVecs = 4; break;
10837 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
10838 NumVecs = 2; IsStore = true; break;
10839 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
10840 NumVecs = 3; IsStore = true; break;
10841 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
10842 NumVecs = 4; IsStore = true; break;
10843 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
10844 NumVecs = 2; IsDupOp = true; break;
10845 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
10846 NumVecs = 3; IsDupOp = true; break;
10847 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
10848 NumVecs = 4; IsDupOp = true; break;
10849 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
10850 NumVecs = 2; IsLaneOp = true; break;
10851 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
10852 NumVecs = 3; IsLaneOp = true; break;
10853 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
10854 NumVecs = 4; IsLaneOp = true; break;
10855 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
10856 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
10857 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
10858 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
10859 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
10860 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
10863 EVT VecTy;
10864 if (IsStore)
10865 VecTy = N->getOperand(2).getValueType();
10866 else
10867 VecTy = N->getValueType(0);
10869 // If the increment is a constant, it must match the memory ref size.
10870 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10871 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10872 uint32_t IncVal = CInc->getZExtValue();
10873 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10874 if (IsLaneOp || IsDupOp)
10875 NumBytes /= VecTy.getVectorNumElements();
10876 if (IncVal != NumBytes)
10877 continue;
10878 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
10880 SmallVector<SDValue, 8> Ops;
10881 Ops.push_back(N->getOperand(0)); // Incoming chain
10882 // Load lane and store have vector list as input.
10883 if (IsLaneOp || IsStore)
10884 for (unsigned i = 2; i < AddrOpIdx; ++i)
10885 Ops.push_back(N->getOperand(i));
10886 Ops.push_back(Addr); // Base register
10887 Ops.push_back(Inc);
10889 // Return Types.
10890 EVT Tys[6];
10891 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
10892 unsigned n;
10893 for (n = 0; n < NumResultVecs; ++n)
10894 Tys[n] = VecTy;
10895 Tys[n++] = MVT::i64; // Type of write back register
10896 Tys[n] = MVT::Other; // Type of the chain
10897 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
10899 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
10900 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
10901 MemInt->getMemoryVT(),
10902 MemInt->getMemOperand());
10904 // Update the uses.
10905 std::vector<SDValue> NewResults;
10906 for (unsigned i = 0; i < NumResultVecs; ++i) {
10907 NewResults.push_back(SDValue(UpdN.getNode(), i));
10909 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
10910 DCI.CombineTo(N, NewResults);
10911 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10913 break;
10915 return SDValue();
10918 // Checks to see if the value is the prescribed width and returns information
10919 // about its extension mode.
10920 static
10921 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
10922 ExtType = ISD::NON_EXTLOAD;
10923 switch(V.getNode()->getOpcode()) {
10924 default:
10925 return false;
10926 case ISD::LOAD: {
10927 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
10928 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
10929 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
10930 ExtType = LoadNode->getExtensionType();
10931 return true;
10933 return false;
10935 case ISD::AssertSext: {
10936 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10937 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10938 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10939 ExtType = ISD::SEXTLOAD;
10940 return true;
10942 return false;
10944 case ISD::AssertZext: {
10945 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
10946 if ((TypeNode->getVT() == MVT::i8 && width == 8)
10947 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
10948 ExtType = ISD::ZEXTLOAD;
10949 return true;
10951 return false;
10953 case ISD::Constant:
10954 case ISD::TargetConstant: {
10955 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
10956 1LL << (width - 1);
10960 return true;
10963 // This function does a whole lot of voodoo to determine if the tests are
10964 // equivalent without and with a mask. Essentially what happens is that given a
10965 // DAG resembling:
10967 // +-------------+ +-------------+ +-------------+ +-------------+
10968 // | Input | | AddConstant | | CompConstant| | CC |
10969 // +-------------+ +-------------+ +-------------+ +-------------+
10970 // | | | |
10971 // V V | +----------+
10972 // +-------------+ +----+ | |
10973 // | ADD | |0xff| | |
10974 // +-------------+ +----+ | |
10975 // | | | |
10976 // V V | |
10977 // +-------------+ | |
10978 // | AND | | |
10979 // +-------------+ | |
10980 // | | |
10981 // +-----+ | |
10982 // | | |
10983 // V V V
10984 // +-------------+
10985 // | CMP |
10986 // +-------------+
10988 // The AND node may be safely removed for some combinations of inputs. In
10989 // particular we need to take into account the extension type of the Input,
10990 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10991 // width of the input (this can work for any width inputs, the above graph is
10992 // specific to 8 bits.
10994 // The specific equations were worked out by generating output tables for each
10995 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10996 // problem was simplified by working with 4 bit inputs, which means we only
10997 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10998 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10999 // patterns present in both extensions (0,7). For every distinct set of
11000 // AddConstant and CompConstants bit patterns we can consider the masked and
11001 // unmasked versions to be equivalent if the result of this function is true for
11002 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11004 // sub w8, w0, w1
11005 // and w10, w8, #0x0f
11006 // cmp w8, w2
11007 // cset w9, AArch64CC
11008 // cmp w10, w2
11009 // cset w11, AArch64CC
11010 // cmp w9, w11
11011 // cset w0, eq
11012 // ret
11014 // Since the above function shows when the outputs are equivalent it defines
11015 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11016 // would be expensive to run during compiles. The equations below were written
11017 // in a test harness that confirmed they gave equivalent outputs to the above
11018 // for all inputs function, so they can be used determine if the removal is
11019 // legal instead.
11021 // isEquivalentMaskless() is the code for testing if the AND can be removed
11022 // factored out of the DAG recognition as the DAG can take several forms.
11024 static bool isEquivalentMaskless(unsigned CC, unsigned width,
11025 ISD::LoadExtType ExtType, int AddConstant,
11026 int CompConstant) {
11027 // By being careful about our equations and only writing the in term
11028 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11029 // make them generally applicable to all bit widths.
11030 int MaxUInt = (1 << width);
11032 // For the purposes of these comparisons sign extending the type is
11033 // equivalent to zero extending the add and displacing it by half the integer
11034 // width. Provided we are careful and make sure our equations are valid over
11035 // the whole range we can just adjust the input and avoid writing equations
11036 // for sign extended inputs.
11037 if (ExtType == ISD::SEXTLOAD)
11038 AddConstant -= (1 << (width-1));
11040 switch(CC) {
11041 case AArch64CC::LE:
11042 case AArch64CC::GT:
11043 if ((AddConstant == 0) ||
11044 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
11045 (AddConstant >= 0 && CompConstant < 0) ||
11046 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
11047 return true;
11048 break;
11049 case AArch64CC::LT:
11050 case AArch64CC::GE:
11051 if ((AddConstant == 0) ||
11052 (AddConstant >= 0 && CompConstant <= 0) ||
11053 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
11054 return true;
11055 break;
11056 case AArch64CC::HI:
11057 case AArch64CC::LS:
11058 if ((AddConstant >= 0 && CompConstant < 0) ||
11059 (AddConstant <= 0 && CompConstant >= -1 &&
11060 CompConstant < AddConstant + MaxUInt))
11061 return true;
11062 break;
11063 case AArch64CC::PL:
11064 case AArch64CC::MI:
11065 if ((AddConstant == 0) ||
11066 (AddConstant > 0 && CompConstant <= 0) ||
11067 (AddConstant < 0 && CompConstant <= AddConstant))
11068 return true;
11069 break;
11070 case AArch64CC::LO:
11071 case AArch64CC::HS:
11072 if ((AddConstant >= 0 && CompConstant <= 0) ||
11073 (AddConstant <= 0 && CompConstant >= 0 &&
11074 CompConstant <= AddConstant + MaxUInt))
11075 return true;
11076 break;
11077 case AArch64CC::EQ:
11078 case AArch64CC::NE:
11079 if ((AddConstant > 0 && CompConstant < 0) ||
11080 (AddConstant < 0 && CompConstant >= 0 &&
11081 CompConstant < AddConstant + MaxUInt) ||
11082 (AddConstant >= 0 && CompConstant >= 0 &&
11083 CompConstant >= AddConstant) ||
11084 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
11085 return true;
11086 break;
11087 case AArch64CC::VS:
11088 case AArch64CC::VC:
11089 case AArch64CC::AL:
11090 case AArch64CC::NV:
11091 return true;
11092 case AArch64CC::Invalid:
11093 break;
11096 return false;
11099 static
11100 SDValue performCONDCombine(SDNode *N,
11101 TargetLowering::DAGCombinerInfo &DCI,
11102 SelectionDAG &DAG, unsigned CCIndex,
11103 unsigned CmpIndex) {
11104 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
11105 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
11106 unsigned CondOpcode = SubsNode->getOpcode();
11108 if (CondOpcode != AArch64ISD::SUBS)
11109 return SDValue();
11111 // There is a SUBS feeding this condition. Is it fed by a mask we can
11112 // use?
11114 SDNode *AndNode = SubsNode->getOperand(0).getNode();
11115 unsigned MaskBits = 0;
11117 if (AndNode->getOpcode() != ISD::AND)
11118 return SDValue();
11120 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
11121 uint32_t CNV = CN->getZExtValue();
11122 if (CNV == 255)
11123 MaskBits = 8;
11124 else if (CNV == 65535)
11125 MaskBits = 16;
11128 if (!MaskBits)
11129 return SDValue();
11131 SDValue AddValue = AndNode->getOperand(0);
11133 if (AddValue.getOpcode() != ISD::ADD)
11134 return SDValue();
11136 // The basic dag structure is correct, grab the inputs and validate them.
11138 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
11139 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
11140 SDValue SubsInputValue = SubsNode->getOperand(1);
11142 // The mask is present and the provenance of all the values is a smaller type,
11143 // lets see if the mask is superfluous.
11145 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
11146 !isa<ConstantSDNode>(SubsInputValue.getNode()))
11147 return SDValue();
11149 ISD::LoadExtType ExtType;
11151 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
11152 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
11153 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
11154 return SDValue();
11156 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
11157 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
11158 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
11159 return SDValue();
11161 // The AND is not necessary, remove it.
11163 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
11164 SubsNode->getValueType(1));
11165 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
11167 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
11168 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
11170 return SDValue(N, 0);
11173 // Optimize compare with zero and branch.
11174 static SDValue performBRCONDCombine(SDNode *N,
11175 TargetLowering::DAGCombinerInfo &DCI,
11176 SelectionDAG &DAG) {
11177 MachineFunction &MF = DAG.getMachineFunction();
11178 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11179 // will not be produced, as they are conditional branch instructions that do
11180 // not set flags.
11181 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
11182 return SDValue();
11184 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
11185 N = NV.getNode();
11186 SDValue Chain = N->getOperand(0);
11187 SDValue Dest = N->getOperand(1);
11188 SDValue CCVal = N->getOperand(2);
11189 SDValue Cmp = N->getOperand(3);
11191 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
11192 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
11193 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
11194 return SDValue();
11196 unsigned CmpOpc = Cmp.getOpcode();
11197 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
11198 return SDValue();
11200 // Only attempt folding if there is only one use of the flag and no use of the
11201 // value.
11202 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
11203 return SDValue();
11205 SDValue LHS = Cmp.getOperand(0);
11206 SDValue RHS = Cmp.getOperand(1);
11208 assert(LHS.getValueType() == RHS.getValueType() &&
11209 "Expected the value type to be the same for both operands!");
11210 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
11211 return SDValue();
11213 if (isNullConstant(LHS))
11214 std::swap(LHS, RHS);
11216 if (!isNullConstant(RHS))
11217 return SDValue();
11219 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
11220 LHS.getOpcode() == ISD::SRL)
11221 return SDValue();
11223 // Fold the compare into the branch instruction.
11224 SDValue BR;
11225 if (CC == AArch64CC::EQ)
11226 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11227 else
11228 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
11230 // Do not add new nodes to DAG combiner worklist.
11231 DCI.CombineTo(N, BR, false);
11233 return SDValue();
11236 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11237 // as well as whether the test should be inverted. This code is required to
11238 // catch these cases (as opposed to standard dag combines) because
11239 // AArch64ISD::TBZ is matched during legalization.
11240 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
11241 SelectionDAG &DAG) {
11243 if (!Op->hasOneUse())
11244 return Op;
11246 // We don't handle undef/constant-fold cases below, as they should have
11247 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11248 // etc.)
11250 // (tbz (trunc x), b) -> (tbz x, b)
11251 // This case is just here to enable more of the below cases to be caught.
11252 if (Op->getOpcode() == ISD::TRUNCATE &&
11253 Bit < Op->getValueType(0).getSizeInBits()) {
11254 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11257 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11258 if (Op->getOpcode() == ISD::ANY_EXTEND &&
11259 Bit < Op->getOperand(0).getValueSizeInBits()) {
11260 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11263 if (Op->getNumOperands() != 2)
11264 return Op;
11266 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11267 if (!C)
11268 return Op;
11270 switch (Op->getOpcode()) {
11271 default:
11272 return Op;
11274 // (tbz (and x, m), b) -> (tbz x, b)
11275 case ISD::AND:
11276 if ((C->getZExtValue() >> Bit) & 1)
11277 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11278 return Op;
11280 // (tbz (shl x, c), b) -> (tbz x, b-c)
11281 case ISD::SHL:
11282 if (C->getZExtValue() <= Bit &&
11283 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11284 Bit = Bit - C->getZExtValue();
11285 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11287 return Op;
11289 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11290 case ISD::SRA:
11291 Bit = Bit + C->getZExtValue();
11292 if (Bit >= Op->getValueType(0).getSizeInBits())
11293 Bit = Op->getValueType(0).getSizeInBits() - 1;
11294 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11296 // (tbz (srl x, c), b) -> (tbz x, b+c)
11297 case ISD::SRL:
11298 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
11299 Bit = Bit + C->getZExtValue();
11300 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11302 return Op;
11304 // (tbz (xor x, -1), b) -> (tbnz x, b)
11305 case ISD::XOR:
11306 if ((C->getZExtValue() >> Bit) & 1)
11307 Invert = !Invert;
11308 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
11312 // Optimize test single bit zero/non-zero and branch.
11313 static SDValue performTBZCombine(SDNode *N,
11314 TargetLowering::DAGCombinerInfo &DCI,
11315 SelectionDAG &DAG) {
11316 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11317 bool Invert = false;
11318 SDValue TestSrc = N->getOperand(1);
11319 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
11321 if (TestSrc == NewTestSrc)
11322 return SDValue();
11324 unsigned NewOpc = N->getOpcode();
11325 if (Invert) {
11326 if (NewOpc == AArch64ISD::TBZ)
11327 NewOpc = AArch64ISD::TBNZ;
11328 else {
11329 assert(NewOpc == AArch64ISD::TBNZ);
11330 NewOpc = AArch64ISD::TBZ;
11334 SDLoc DL(N);
11335 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
11336 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
11339 // vselect (v1i1 setcc) ->
11340 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
11341 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11342 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11343 // such VSELECT.
11344 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
11345 SDValue N0 = N->getOperand(0);
11346 EVT CCVT = N0.getValueType();
11348 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
11349 CCVT.getVectorElementType() != MVT::i1)
11350 return SDValue();
11352 EVT ResVT = N->getValueType(0);
11353 EVT CmpVT = N0.getOperand(0).getValueType();
11354 // Only combine when the result type is of the same size as the compared
11355 // operands.
11356 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
11357 return SDValue();
11359 SDValue IfTrue = N->getOperand(1);
11360 SDValue IfFalse = N->getOperand(2);
11361 SDValue SetCC =
11362 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
11363 N0.getOperand(0), N0.getOperand(1),
11364 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11365 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
11366 IfTrue, IfFalse);
11369 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11370 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11371 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11372 /// with a vector one followed by a DUP shuffle on the result.
11373 static SDValue performSelectCombine(SDNode *N,
11374 TargetLowering::DAGCombinerInfo &DCI) {
11375 SelectionDAG &DAG = DCI.DAG;
11376 SDValue N0 = N->getOperand(0);
11377 EVT ResVT = N->getValueType(0);
11379 if (N0.getOpcode() != ISD::SETCC)
11380 return SDValue();
11382 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11383 // scalar SetCCResultType. We also don't expect vectors, because we assume
11384 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11385 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
11386 "Scalar-SETCC feeding SELECT has unexpected result type!");
11388 // If NumMaskElts == 0, the comparison is larger than select result. The
11389 // largest real NEON comparison is 64-bits per lane, which means the result is
11390 // at most 32-bits and an illegal vector. Just bail out for now.
11391 EVT SrcVT = N0.getOperand(0).getValueType();
11393 // Don't try to do this optimization when the setcc itself has i1 operands.
11394 // There are no legal vectors of i1, so this would be pointless.
11395 if (SrcVT == MVT::i1)
11396 return SDValue();
11398 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
11399 if (!ResVT.isVector() || NumMaskElts == 0)
11400 return SDValue();
11402 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
11403 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
11405 // Also bail out if the vector CCVT isn't the same size as ResVT.
11406 // This can happen if the SETCC operand size doesn't divide the ResVT size
11407 // (e.g., f64 vs v3f32).
11408 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
11409 return SDValue();
11411 // Make sure we didn't create illegal types, if we're not supposed to.
11412 assert(DCI.isBeforeLegalize() ||
11413 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
11415 // First perform a vector comparison, where lane 0 is the one we're interested
11416 // in.
11417 SDLoc DL(N0);
11418 SDValue LHS =
11419 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
11420 SDValue RHS =
11421 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
11422 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
11424 // Now duplicate the comparison mask we want across all other lanes.
11425 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
11426 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
11427 Mask = DAG.getNode(ISD::BITCAST, DL,
11428 ResVT.changeVectorElementTypeToInteger(), Mask);
11430 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
11433 /// Get rid of unnecessary NVCASTs (that don't change the type).
11434 static SDValue performNVCASTCombine(SDNode *N) {
11435 if (N->getValueType(0) == N->getOperand(0).getValueType())
11436 return N->getOperand(0);
11438 return SDValue();
11441 // If all users of the globaladdr are of the form (globaladdr + constant), find
11442 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11443 // globaladdr as (globaladdr + constant) - constant.
11444 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
11445 const AArch64Subtarget *Subtarget,
11446 const TargetMachine &TM) {
11447 auto *GN = cast<GlobalAddressSDNode>(N);
11448 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
11449 AArch64II::MO_NO_FLAG)
11450 return SDValue();
11452 uint64_t MinOffset = -1ull;
11453 for (SDNode *N : GN->uses()) {
11454 if (N->getOpcode() != ISD::ADD)
11455 return SDValue();
11456 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
11457 if (!C)
11458 C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11459 if (!C)
11460 return SDValue();
11461 MinOffset = std::min(MinOffset, C->getZExtValue());
11463 uint64_t Offset = MinOffset + GN->getOffset();
11465 // Require that the new offset is larger than the existing one. Otherwise, we
11466 // can end up oscillating between two possible DAGs, for example,
11467 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11468 if (Offset <= uint64_t(GN->getOffset()))
11469 return SDValue();
11471 // Check whether folding this offset is legal. It must not go out of bounds of
11472 // the referenced object to avoid violating the code model, and must be
11473 // smaller than 2^21 because this is the largest offset expressible in all
11474 // object formats.
11476 // This check also prevents us from folding negative offsets, which will end
11477 // up being treated in the same way as large positive ones. They could also
11478 // cause code model violations, and aren't really common enough to matter.
11479 if (Offset >= (1 << 21))
11480 return SDValue();
11482 const GlobalValue *GV = GN->getGlobal();
11483 Type *T = GV->getValueType();
11484 if (!T->isSized() ||
11485 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
11486 return SDValue();
11488 SDLoc DL(GN);
11489 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
11490 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
11491 DAG.getConstant(MinOffset, DL, MVT::i64));
11494 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
11495 DAGCombinerInfo &DCI) const {
11496 SelectionDAG &DAG = DCI.DAG;
11497 switch (N->getOpcode()) {
11498 default:
11499 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11500 break;
11501 case ISD::ADD:
11502 case ISD::SUB:
11503 return performAddSubLongCombine(N, DCI, DAG);
11504 case ISD::XOR:
11505 return performXorCombine(N, DAG, DCI, Subtarget);
11506 case ISD::MUL:
11507 return performMulCombine(N, DAG, DCI, Subtarget);
11508 case ISD::SINT_TO_FP:
11509 case ISD::UINT_TO_FP:
11510 return performIntToFpCombine(N, DAG, Subtarget);
11511 case ISD::FP_TO_SINT:
11512 case ISD::FP_TO_UINT:
11513 return performFpToIntCombine(N, DAG, DCI, Subtarget);
11514 case ISD::FDIV:
11515 return performFDivCombine(N, DAG, DCI, Subtarget);
11516 case ISD::OR:
11517 return performORCombine(N, DCI, Subtarget);
11518 case ISD::AND:
11519 return performANDCombine(N, DCI);
11520 case ISD::SRL:
11521 return performSRLCombine(N, DCI);
11522 case ISD::INTRINSIC_WO_CHAIN:
11523 return performIntrinsicCombine(N, DCI, Subtarget);
11524 case ISD::ANY_EXTEND:
11525 case ISD::ZERO_EXTEND:
11526 case ISD::SIGN_EXTEND:
11527 return performExtendCombine(N, DCI, DAG);
11528 case ISD::BITCAST:
11529 return performBitcastCombine(N, DCI, DAG);
11530 case ISD::CONCAT_VECTORS:
11531 return performConcatVectorsCombine(N, DCI, DAG);
11532 case ISD::SELECT:
11533 return performSelectCombine(N, DCI);
11534 case ISD::VSELECT:
11535 return performVSelectCombine(N, DCI.DAG);
11536 case ISD::LOAD:
11537 if (performTBISimplification(N->getOperand(1), DCI, DAG))
11538 return SDValue(N, 0);
11539 break;
11540 case ISD::STORE:
11541 return performSTORECombine(N, DCI, DAG, Subtarget);
11542 case AArch64ISD::BRCOND:
11543 return performBRCONDCombine(N, DCI, DAG);
11544 case AArch64ISD::TBNZ:
11545 case AArch64ISD::TBZ:
11546 return performTBZCombine(N, DCI, DAG);
11547 case AArch64ISD::CSEL:
11548 return performCONDCombine(N, DCI, DAG, 2, 3);
11549 case AArch64ISD::DUP:
11550 return performPostLD1Combine(N, DCI, false);
11551 case AArch64ISD::NVCAST:
11552 return performNVCASTCombine(N);
11553 case ISD::INSERT_VECTOR_ELT:
11554 return performPostLD1Combine(N, DCI, true);
11555 case ISD::INTRINSIC_VOID:
11556 case ISD::INTRINSIC_W_CHAIN:
11557 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11558 case Intrinsic::aarch64_neon_ld2:
11559 case Intrinsic::aarch64_neon_ld3:
11560 case Intrinsic::aarch64_neon_ld4:
11561 case Intrinsic::aarch64_neon_ld1x2:
11562 case Intrinsic::aarch64_neon_ld1x3:
11563 case Intrinsic::aarch64_neon_ld1x4:
11564 case Intrinsic::aarch64_neon_ld2lane:
11565 case Intrinsic::aarch64_neon_ld3lane:
11566 case Intrinsic::aarch64_neon_ld4lane:
11567 case Intrinsic::aarch64_neon_ld2r:
11568 case Intrinsic::aarch64_neon_ld3r:
11569 case Intrinsic::aarch64_neon_ld4r:
11570 case Intrinsic::aarch64_neon_st2:
11571 case Intrinsic::aarch64_neon_st3:
11572 case Intrinsic::aarch64_neon_st4:
11573 case Intrinsic::aarch64_neon_st1x2:
11574 case Intrinsic::aarch64_neon_st1x3:
11575 case Intrinsic::aarch64_neon_st1x4:
11576 case Intrinsic::aarch64_neon_st2lane:
11577 case Intrinsic::aarch64_neon_st3lane:
11578 case Intrinsic::aarch64_neon_st4lane:
11579 return performNEONPostLDSTCombine(N, DCI, DAG);
11580 default:
11581 break;
11583 break;
11584 case ISD::GlobalAddress:
11585 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
11587 return SDValue();
11590 // Check if the return value is used as only a return value, as otherwise
11591 // we can't perform a tail-call. In particular, we need to check for
11592 // target ISD nodes that are returns and any other "odd" constructs
11593 // that the generic analysis code won't necessarily catch.
11594 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
11595 SDValue &Chain) const {
11596 if (N->getNumValues() != 1)
11597 return false;
11598 if (!N->hasNUsesOfValue(1, 0))
11599 return false;
11601 SDValue TCChain = Chain;
11602 SDNode *Copy = *N->use_begin();
11603 if (Copy->getOpcode() == ISD::CopyToReg) {
11604 // If the copy has a glue operand, we conservatively assume it isn't safe to
11605 // perform a tail call.
11606 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
11607 MVT::Glue)
11608 return false;
11609 TCChain = Copy->getOperand(0);
11610 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
11611 return false;
11613 bool HasRet = false;
11614 for (SDNode *Node : Copy->uses()) {
11615 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
11616 return false;
11617 HasRet = true;
11620 if (!HasRet)
11621 return false;
11623 Chain = TCChain;
11624 return true;
11627 // Return whether the an instruction can potentially be optimized to a tail
11628 // call. This will cause the optimizers to attempt to move, or duplicate,
11629 // return instructions to help enable tail call optimizations for this
11630 // instruction.
11631 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11632 return CI->isTailCall();
11635 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
11636 SDValue &Offset,
11637 ISD::MemIndexedMode &AM,
11638 bool &IsInc,
11639 SelectionDAG &DAG) const {
11640 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
11641 return false;
11643 Base = Op->getOperand(0);
11644 // All of the indexed addressing mode instructions take a signed
11645 // 9 bit immediate offset.
11646 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
11647 int64_t RHSC = RHS->getSExtValue();
11648 if (Op->getOpcode() == ISD::SUB)
11649 RHSC = -(uint64_t)RHSC;
11650 if (!isInt<9>(RHSC))
11651 return false;
11652 IsInc = (Op->getOpcode() == ISD::ADD);
11653 Offset = Op->getOperand(1);
11654 return true;
11656 return false;
11659 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11660 SDValue &Offset,
11661 ISD::MemIndexedMode &AM,
11662 SelectionDAG &DAG) const {
11663 EVT VT;
11664 SDValue Ptr;
11665 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11666 VT = LD->getMemoryVT();
11667 Ptr = LD->getBasePtr();
11668 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11669 VT = ST->getMemoryVT();
11670 Ptr = ST->getBasePtr();
11671 } else
11672 return false;
11674 bool IsInc;
11675 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
11676 return false;
11677 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
11678 return true;
11681 bool AArch64TargetLowering::getPostIndexedAddressParts(
11682 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
11683 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
11684 EVT VT;
11685 SDValue Ptr;
11686 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11687 VT = LD->getMemoryVT();
11688 Ptr = LD->getBasePtr();
11689 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11690 VT = ST->getMemoryVT();
11691 Ptr = ST->getBasePtr();
11692 } else
11693 return false;
11695 bool IsInc;
11696 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
11697 return false;
11698 // Post-indexing updates the base, so it's not a valid transform
11699 // if that's not the same as the load's pointer.
11700 if (Ptr != Base)
11701 return false;
11702 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
11703 return true;
11706 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
11707 SelectionDAG &DAG) {
11708 SDLoc DL(N);
11709 SDValue Op = N->getOperand(0);
11711 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
11712 return;
11714 Op = SDValue(
11715 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
11716 DAG.getUNDEF(MVT::i32), Op,
11717 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
11719 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
11720 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
11723 static void ReplaceReductionResults(SDNode *N,
11724 SmallVectorImpl<SDValue> &Results,
11725 SelectionDAG &DAG, unsigned InterOp,
11726 unsigned AcrossOp) {
11727 EVT LoVT, HiVT;
11728 SDValue Lo, Hi;
11729 SDLoc dl(N);
11730 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
11731 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
11732 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
11733 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
11734 Results.push_back(SplitVal);
11737 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
11738 SDLoc DL(N);
11739 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
11740 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
11741 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
11742 DAG.getConstant(64, DL, MVT::i64)));
11743 return std::make_pair(Lo, Hi);
11746 // Create an even/odd pair of X registers holding integer value V.
11747 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
11748 SDLoc dl(V.getNode());
11749 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
11750 SDValue VHi = DAG.getAnyExtOrTrunc(
11751 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
11752 dl, MVT::i64);
11753 if (DAG.getDataLayout().isBigEndian())
11754 std::swap (VLo, VHi);
11755 SDValue RegClass =
11756 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
11757 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
11758 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
11759 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
11760 return SDValue(
11761 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
11764 static void ReplaceCMP_SWAP_128Results(SDNode *N,
11765 SmallVectorImpl<SDValue> &Results,
11766 SelectionDAG &DAG,
11767 const AArch64Subtarget *Subtarget) {
11768 assert(N->getValueType(0) == MVT::i128 &&
11769 "AtomicCmpSwap on types less than 128 should be legal");
11771 if (Subtarget->hasLSE()) {
11772 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11773 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11774 SDValue Ops[] = {
11775 createGPRPairNode(DAG, N->getOperand(2)), // Compare value
11776 createGPRPairNode(DAG, N->getOperand(3)), // Store value
11777 N->getOperand(1), // Ptr
11778 N->getOperand(0), // Chain in
11781 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11783 unsigned Opcode;
11784 switch (MemOp->getOrdering()) {
11785 case AtomicOrdering::Monotonic:
11786 Opcode = AArch64::CASPX;
11787 break;
11788 case AtomicOrdering::Acquire:
11789 Opcode = AArch64::CASPAX;
11790 break;
11791 case AtomicOrdering::Release:
11792 Opcode = AArch64::CASPLX;
11793 break;
11794 case AtomicOrdering::AcquireRelease:
11795 case AtomicOrdering::SequentiallyConsistent:
11796 Opcode = AArch64::CASPALX;
11797 break;
11798 default:
11799 llvm_unreachable("Unexpected ordering!");
11802 MachineSDNode *CmpSwap = DAG.getMachineNode(
11803 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
11804 DAG.setNodeMemRefs(CmpSwap, {MemOp});
11806 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
11807 if (DAG.getDataLayout().isBigEndian())
11808 std::swap(SubReg1, SubReg2);
11809 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
11810 SDValue(CmpSwap, 0)));
11811 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
11812 SDValue(CmpSwap, 0)));
11813 Results.push_back(SDValue(CmpSwap, 1)); // Chain out
11814 return;
11817 auto Desired = splitInt128(N->getOperand(2), DAG);
11818 auto New = splitInt128(N->getOperand(3), DAG);
11819 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
11820 New.first, New.second, N->getOperand(0)};
11821 SDNode *CmpSwap = DAG.getMachineNode(
11822 AArch64::CMP_SWAP_128, SDLoc(N),
11823 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
11825 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
11826 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
11828 Results.push_back(SDValue(CmpSwap, 0));
11829 Results.push_back(SDValue(CmpSwap, 1));
11830 Results.push_back(SDValue(CmpSwap, 3));
11833 void AArch64TargetLowering::ReplaceNodeResults(
11834 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
11835 switch (N->getOpcode()) {
11836 default:
11837 llvm_unreachable("Don't know how to custom expand this");
11838 case ISD::BITCAST:
11839 ReplaceBITCASTResults(N, Results, DAG);
11840 return;
11841 case ISD::VECREDUCE_ADD:
11842 case ISD::VECREDUCE_SMAX:
11843 case ISD::VECREDUCE_SMIN:
11844 case ISD::VECREDUCE_UMAX:
11845 case ISD::VECREDUCE_UMIN:
11846 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
11847 return;
11849 case AArch64ISD::SADDV:
11850 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
11851 return;
11852 case AArch64ISD::UADDV:
11853 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
11854 return;
11855 case AArch64ISD::SMINV:
11856 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
11857 return;
11858 case AArch64ISD::UMINV:
11859 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
11860 return;
11861 case AArch64ISD::SMAXV:
11862 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
11863 return;
11864 case AArch64ISD::UMAXV:
11865 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
11866 return;
11867 case ISD::FP_TO_UINT:
11868 case ISD::FP_TO_SINT:
11869 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
11870 // Let normal code take care of it by not adding anything to Results.
11871 return;
11872 case ISD::ATOMIC_CMP_SWAP:
11873 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
11874 return;
11878 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11879 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
11880 return TargetLowering::useLoadStackGuardNode();
11881 return true;
11884 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11885 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11886 // reciprocal if there are three or more FDIVs.
11887 return 3;
11890 TargetLoweringBase::LegalizeTypeAction
11891 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
11892 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11893 // v4i16, v2i32 instead of to promote.
11894 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
11895 VT == MVT::v1f32)
11896 return TypeWidenVector;
11898 return TargetLoweringBase::getPreferredVectorAction(VT);
11901 // Loads and stores less than 128-bits are already atomic; ones above that
11902 // are doomed anyway, so defer to the default libcall and blame the OS when
11903 // things go wrong.
11904 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11905 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11906 return Size == 128;
11909 // Loads and stores less than 128-bits are already atomic; ones above that
11910 // are doomed anyway, so defer to the default libcall and blame the OS when
11911 // things go wrong.
11912 TargetLowering::AtomicExpansionKind
11913 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11914 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11915 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
11918 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11919 TargetLowering::AtomicExpansionKind
11920 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11921 if (AI->isFloatingPointOperation())
11922 return AtomicExpansionKind::CmpXChg;
11924 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11925 if (Size > 128) return AtomicExpansionKind::None;
11926 // Nand not supported in LSE.
11927 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
11928 // Leave 128 bits to LLSC.
11929 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
11932 TargetLowering::AtomicExpansionKind
11933 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11934 AtomicCmpXchgInst *AI) const {
11935 // If subtarget has LSE, leave cmpxchg intact for codegen.
11936 if (Subtarget->hasLSE())
11937 return AtomicExpansionKind::None;
11938 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11939 // implement cmpxchg without spilling. If the address being exchanged is also
11940 // on the stack and close enough to the spill slot, this can lead to a
11941 // situation where the monitor always gets cleared and the atomic operation
11942 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11943 if (getTargetMachine().getOptLevel() == 0)
11944 return AtomicExpansionKind::None;
11945 return AtomicExpansionKind::LLSC;
11948 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11949 AtomicOrdering Ord) const {
11950 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11951 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11952 bool IsAcquire = isAcquireOrStronger(Ord);
11954 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11955 // intrinsic must return {i64, i64} and we have to recombine them into a
11956 // single i128 here.
11957 if (ValTy->getPrimitiveSizeInBits() == 128) {
11958 Intrinsic::ID Int =
11959 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
11960 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
11962 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11963 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
11965 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11966 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11967 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11968 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11969 return Builder.CreateOr(
11970 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
11973 Type *Tys[] = { Addr->getType() };
11974 Intrinsic::ID Int =
11975 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
11976 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
11978 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
11980 const DataLayout &DL = M->getDataLayout();
11981 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
11982 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
11984 return Builder.CreateBitCast(Trunc, EltTy);
11987 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11988 IRBuilder<> &Builder) const {
11989 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11990 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
11993 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
11994 Value *Val, Value *Addr,
11995 AtomicOrdering Ord) const {
11996 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11997 bool IsRelease = isReleaseOrStronger(Ord);
11999 // Since the intrinsics must have legal type, the i128 intrinsics take two
12000 // parameters: "i64, i64". We must marshal Val into the appropriate form
12001 // before the call.
12002 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
12003 Intrinsic::ID Int =
12004 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
12005 Function *Stxr = Intrinsic::getDeclaration(M, Int);
12006 Type *Int64Ty = Type::getInt64Ty(M->getContext());
12008 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
12009 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
12010 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12011 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
12014 Intrinsic::ID Int =
12015 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
12016 Type *Tys[] = { Addr->getType() };
12017 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
12019 const DataLayout &DL = M->getDataLayout();
12020 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
12021 Val = Builder.CreateBitCast(Val, IntValTy);
12023 return Builder.CreateCall(Stxr,
12024 {Builder.CreateZExtOrBitCast(
12025 Val, Stxr->getFunctionType()->getParamType(0)),
12026 Addr});
12029 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12030 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
12031 return Ty->isArrayTy();
12034 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
12035 EVT) const {
12036 return false;
12039 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
12040 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
12041 Function *ThreadPointerFunc =
12042 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
12043 return IRB.CreatePointerCast(
12044 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
12045 Offset),
12046 IRB.getInt8PtrTy()->getPointerTo(0));
12049 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
12050 // Android provides a fixed TLS slot for the stack cookie. See the definition
12051 // of TLS_SLOT_STACK_GUARD in
12052 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12053 if (Subtarget->isTargetAndroid())
12054 return UseTlsOffset(IRB, 0x28);
12056 // Fuchsia is similar.
12057 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12058 if (Subtarget->isTargetFuchsia())
12059 return UseTlsOffset(IRB, -0x10);
12061 return TargetLowering::getIRStackGuard(IRB);
12064 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
12065 // MSVC CRT provides functionalities for stack protection.
12066 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
12067 // MSVC CRT has a global variable holding security cookie.
12068 M.getOrInsertGlobal("__security_cookie",
12069 Type::getInt8PtrTy(M.getContext()));
12071 // MSVC CRT has a function to validate security cookie.
12072 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
12073 "__security_check_cookie", Type::getVoidTy(M.getContext()),
12074 Type::getInt8PtrTy(M.getContext()));
12075 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
12076 F->setCallingConv(CallingConv::Win64);
12077 F->addAttribute(1, Attribute::AttrKind::InReg);
12079 return;
12081 TargetLowering::insertSSPDeclarations(M);
12084 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
12085 // MSVC CRT has a global variable holding security cookie.
12086 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12087 return M.getGlobalVariable("__security_cookie");
12088 return TargetLowering::getSDagStackGuard(M);
12091 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
12092 // MSVC CRT has a function to validate security cookie.
12093 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
12094 return M.getFunction("__security_check_cookie");
12095 return TargetLowering::getSSPStackGuardCheck(M);
12098 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
12099 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12100 // definition of TLS_SLOT_SAFESTACK in
12101 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12102 if (Subtarget->isTargetAndroid())
12103 return UseTlsOffset(IRB, 0x48);
12105 // Fuchsia is similar.
12106 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12107 if (Subtarget->isTargetFuchsia())
12108 return UseTlsOffset(IRB, -0x8);
12110 return TargetLowering::getSafeStackPointerLocation(IRB);
12113 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12114 const Instruction &AndI) const {
12115 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12116 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12117 // may be beneficial to sink in other cases, but we would have to check that
12118 // the cmp would not get folded into the br to form a cbz for these to be
12119 // beneficial.
12120 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
12121 if (!Mask)
12122 return false;
12123 return Mask->getValue().isPowerOf2();
12126 bool AArch64TargetLowering::
12127 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12128 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
12129 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
12130 SelectionDAG &DAG) const {
12131 // Does baseline recommend not to perform the fold by default?
12132 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12133 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
12134 return false;
12135 // Else, if this is a vector shift, prefer 'shl'.
12136 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
12139 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
12140 SDNode *N) const {
12141 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
12142 !Subtarget->isTargetWindows())
12143 return false;
12144 return true;
12147 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12148 // Update IsSplitCSR in AArch64unctionInfo.
12149 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
12150 AFI->setIsSplitCSR(true);
12153 void AArch64TargetLowering::insertCopiesSplitCSR(
12154 MachineBasicBlock *Entry,
12155 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12156 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
12157 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12158 if (!IStart)
12159 return;
12161 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
12162 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12163 MachineBasicBlock::iterator MBBI = Entry->begin();
12164 for (const MCPhysReg *I = IStart; *I; ++I) {
12165 const TargetRegisterClass *RC = nullptr;
12166 if (AArch64::GPR64RegClass.contains(*I))
12167 RC = &AArch64::GPR64RegClass;
12168 else if (AArch64::FPR64RegClass.contains(*I))
12169 RC = &AArch64::FPR64RegClass;
12170 else
12171 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12173 Register NewVR = MRI->createVirtualRegister(RC);
12174 // Create copy from CSR to a virtual register.
12175 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12176 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12177 // nounwind. If we want to generalize this later, we may need to emit
12178 // CFI pseudo-instructions.
12179 assert(Entry->getParent()->getFunction().hasFnAttribute(
12180 Attribute::NoUnwind) &&
12181 "Function should be nounwind in insertCopiesSplitCSR!");
12182 Entry->addLiveIn(*I);
12183 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12184 .addReg(*I);
12186 // Insert the copy-back instructions right before the terminator.
12187 for (auto *Exit : Exits)
12188 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12189 TII->get(TargetOpcode::COPY), *I)
12190 .addReg(NewVR);
12194 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
12195 // Integer division on AArch64 is expensive. However, when aggressively
12196 // optimizing for code size, we prefer to use a div instruction, as it is
12197 // usually smaller than the alternative sequence.
12198 // The exception to this is vector division. Since AArch64 doesn't have vector
12199 // integer division, leaving the division as-is is a loss even in terms of
12200 // size, because it will have to be scalarized, while the alternative code
12201 // sequence can be performed in vector form.
12202 bool OptSize =
12203 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
12204 return OptSize && !VT.isVector();
12207 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12208 // We want inc-of-add for scalars and sub-of-not for vectors.
12209 return VT.isScalarInteger();
12212 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
12213 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
12216 unsigned
12217 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
12218 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
12219 return getPointerTy(DL).getSizeInBits();
12221 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
12224 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
12225 MF.getFrameInfo().computeMaxCallFrameSize(MF);
12226 TargetLoweringBase::finalizeLowering(MF);
12229 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12230 bool AArch64TargetLowering::needsFixedCatchObjects() const {
12231 return false;